hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3ffb4189fcdf57cc615cceec4bec0ae1e2981eed | 5,994 | cpp | C++ | src/cgame/etj_timerun.cpp | marcel95k/etjump | 019a09f62c0dc551886ccba9a6eb419e5910d722 | [
"MIT"
] | null | null | null | src/cgame/etj_timerun.cpp | marcel95k/etjump | 019a09f62c0dc551886ccba9a6eb419e5910d722 | [
"MIT"
] | null | null | null | src/cgame/etj_timerun.cpp | marcel95k/etjump | 019a09f62c0dc551886ccba9a6eb419e5910d722 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2022 ETJump team <zero@etjump.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include <string>
#include "cg_local.h"
#include "etj_timerun.h"
#include "../game/etj_string_utilities.h"
Timerun::Timerun(int clientNum)
{
_clientNum = clientNum;
}
void Timerun::startTimerun(const std::string &runName, int startTime, int previousRecord)
{
_running = true;
_startTime = startTime;
_currentTimerun = runName;
_runningPlayerClientNum = _clientNum;
auto playerTimes = _fastestTimes.find(_clientNum);
if (playerTimes == _fastestTimes.end())
{
_fastestTimes[_clientNum] = std::map<std::string, int>();
playerTimes = _fastestTimes.find(_clientNum);
}
playerTimes->second[runName] = previousRecord;
_fastestTime = previousRecord;
}
void Timerun::startSpectatorTimerun(int clientNum, const std::string &runName, int startTime, int previousRecord)
{
if (clientNum == _clientNum)
{
return;
}
_running = true;
_currentTimerun = runName;
_startTime = startTime;
_runningPlayerClientNum = clientNum;
auto playerTimes = _fastestTimes.find(clientNum);
if (playerTimes == _fastestTimes.end())
{
_fastestTimes[clientNum] = std::map<std::string, int>();
playerTimes = _fastestTimes.find(clientNum);
}
playerTimes->second[runName] = previousRecord;
_fastestTime = previousRecord;
}
void Timerun::interrupt()
{
_running = false;
_currentTimerun = "";
_startTime = 0;
_runningPlayerClientNum = 0;
_fastestTime = -1;
}
void Timerun::stopTimerun(int completionTime)
{
_running = false;
_completionTime = completionTime;
}
void Timerun::record(int clientNum, std::string runName, int completionTime)
{
int previousTime = NO_PREVIOUS_RECORD;
auto playerTimes = _fastestTimes.find(clientNum);
if (playerTimes != _fastestTimes.end())
{
auto previousTimeIter = playerTimes->second.find(runName);
if (previousTimeIter != playerTimes->second.end())
{
previousTime = previousTimeIter->second;
}
}
std::string message = createCompletionMessage(cgs.clientinfo[clientNum], runName, completionTime, previousTime);
int shader = previousTime == NO_PREVIOUS_RECORD ?
cgs.media.stopwatchIcon : cgs.media.stopwatchIconGreen;
printMessage(message, shader);
}
void Timerun::completion(int clientNum, std::string runName, int completionTime)
{
int previousRecord = NO_PREVIOUS_RECORD;
auto playerTimes = _fastestTimes.find(clientNum);
if (playerTimes != _fastestTimes.end())
{
auto previousTimeIter = playerTimes->second.find(runName);
if (previousTimeIter != playerTimes->second.end())
{
previousRecord = previousTimeIter->second;
}
}
// if we're the player / spectating the player, print the message
if (clientNum == cg.snap->ps.clientNum)
{
std::string message = createCompletionMessage(cgs.clientinfo[clientNum], runName, completionTime, previousRecord);
printMessage(message, cgs.media.stopwatchIconRed);
}
}
void Timerun::stopSpectatorTimerun(int clientNum, int completionTime, const std::string& currentRun)
{
_running = false;
_completionTime = completionTime;
}
Timerun::Time Timerun::createTimeFromTimestamp(int timestamp)
{
int millis = timestamp;
int minutes = millis / static_cast<int>(Time::Duration::Minute);
millis -= minutes * static_cast<int>(Time::Duration::Minute);
int seconds = millis / static_cast<int>(Time::Duration::Second);
millis -= seconds * static_cast<int>(Time::Duration::Second);
return{ minutes, seconds, millis, timestamp };
}
std::string Timerun::createCompletionMessage(clientInfo_t& player, std::string& runName, int completionTime, int previousTime)
{
Time now = createTimeFromTimestamp(completionTime);
std::string who{ (player.clientNum == _clientNum) ? "You" : player.name };
std::string timeFinished{ createTimeString(now) };
std::string timeDifference{ "" };
auto postfix = '!';
if (previousTime != NO_PREVIOUS_RECORD)
{
Time diff = createTimeFromTimestamp(abs(previousTime - completionTime));
std::string timeDir;
if (previousTime > completionTime)
{
// faster
timeDir = "-^2";
}
else if (previousTime < completionTime)
{
// slower
timeDir = "+^1";
}
else
{
// tied
timeDir = "+^7";
}
timeDifference = ETJump::stringFormat("^7(%s%s^7)", timeDir, createTimeString(diff));
postfix = (previousTime > completionTime) ? '!' : '.';
}
std::string message = ETJump::stringFormat(
"^7%s ^7completed %s ^7in %s%c %s", who, runName, timeFinished, postfix, timeDifference
);
return message;
}
std::string Timerun::createTimeString(Time &time)
{
return ETJump::stringFormat("%02d:%02d.%03d", time.minutes, time.seconds, time.ms);
}
void Timerun::printMessage(std::string &message, int shaderIcon)
{
CG_AddPMItem(PM_MESSAGE, message.c_str(), shaderIcon);
}
| 29.97 | 126 | 0.712212 | marcel95k |
3ffc1aef30744d8cad04762638bff81b3339f082 | 11,617 | cpp | C++ | common/tier4_traffic_light_rviz_plugin/src/traffic_light_publish_panel.cpp | goktugyildirim/autoware.universe | b2f90a0952bf37969517f72ccd5a1ea86f253ce5 | [
"Apache-2.0"
] | 1 | 2021-11-30T02:26:07.000Z | 2021-11-30T02:26:07.000Z | common/tier4_traffic_light_rviz_plugin/src/traffic_light_publish_panel.cpp | goktugyildirim/autoware.universe | b2f90a0952bf37969517f72ccd5a1ea86f253ce5 | [
"Apache-2.0"
] | 11 | 2022-01-24T10:26:37.000Z | 2022-03-22T08:19:01.000Z | common/tier4_traffic_light_rviz_plugin/src/traffic_light_publish_panel.cpp | KeisukeShima/autoware.universe | 21d5453dfa2bf75716b8737fb7b58f3b45483e29 | [
"Apache-2.0"
] | null | null | null | //
// Copyright 2022 TIER IV, 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 "traffic_light_publish_panel.hpp"
#include <QHBoxLayout>
#include <QHeaderView>
#include <QLabel>
#include <QString>
#include <QStringList>
#include <QVBoxLayout>
#include <rviz_common/display_context.hpp>
#include <memory>
#include <string>
namespace rviz_plugins
{
TrafficLightPublishPanel::TrafficLightPublishPanel(QWidget * parent) : rviz_common::Panel(parent)
{
// Publish Rate
publishing_rate_input_ = new QSpinBox();
publishing_rate_input_->setRange(1, 100);
publishing_rate_input_->setSingleStep(1);
publishing_rate_input_->setValue(10);
publishing_rate_input_->setSuffix("Hz");
// Traffic Light ID
traffic_light_id_input_ = new QSpinBox();
traffic_light_id_input_->setRange(0, 999999);
traffic_light_id_input_->setValue(0);
// Traffic Light Confidence
traffic_light_confidence_input_ = new QDoubleSpinBox();
traffic_light_confidence_input_->setRange(0.0, 1.0);
traffic_light_confidence_input_->setSingleStep(0.1);
traffic_light_confidence_input_->setValue(1.0);
// Traffic Light Color
light_color_combo_ = new QComboBox();
light_color_combo_->addItems({"RED", "AMBER", "GREEN", "WHITE", "UNKNOWN"});
// Traffic Light Shape
light_shape_combo_ = new QComboBox();
light_shape_combo_->addItems(
{"CIRCLE", "LEFT_ARROW", "RIGHT_ARROW", "UP_ARROW", "DOWN_ARROW", "DOWN_LEFT_ARROW",
"DOWN_RIGHT_ARROW", "CROSS", "UNKNOWN"});
// Traffic Light Status
light_status_combo_ = new QComboBox();
light_status_combo_->addItems({"SOLID_ON", "SOLID_OFF", "FLASHING", "UNKNOWN"});
// Set Traffic Signals Button
set_button_ = new QPushButton("SET");
// Reset Traffic Signals Button
reset_button_ = new QPushButton("RESET");
// Publish Traffic Signals Button
publish_button_ = new QPushButton("PUBLISH");
auto vertical_header = new QHeaderView(Qt::Vertical);
vertical_header->hide();
auto horizontal_header = new QHeaderView(Qt::Horizontal);
horizontal_header->setSectionResizeMode(QHeaderView::Stretch);
traffic_table_ = new QTableWidget();
traffic_table_->setColumnCount(5);
traffic_table_->setHorizontalHeaderLabels({"ID", "Color", "Shape", "Status", "Confidence"});
traffic_table_->setVerticalHeader(vertical_header);
traffic_table_->setHorizontalHeader(horizontal_header);
connect(publishing_rate_input_, SIGNAL(valueChanged(int)), this, SLOT(onRateChanged(int)));
connect(set_button_, SIGNAL(clicked()), SLOT(onSetTrafficLightState()));
connect(reset_button_, SIGNAL(clicked()), SLOT(onResetTrafficLightState()));
connect(publish_button_, SIGNAL(clicked()), SLOT(onPublishTrafficLightState()));
auto * h_layout_1 = new QHBoxLayout;
h_layout_1->addWidget(new QLabel("Rate: "));
h_layout_1->addWidget(publishing_rate_input_);
h_layout_1->addWidget(new QLabel("ID: "));
h_layout_1->addWidget(traffic_light_id_input_);
h_layout_1->addWidget(new QLabel("Confidence: "));
h_layout_1->addWidget(traffic_light_confidence_input_);
auto * h_layout_2 = new QHBoxLayout;
h_layout_2->addWidget(new QLabel("Traffic Light Color: "), 40);
h_layout_2->addWidget(light_color_combo_, 60);
auto * h_layout_3 = new QHBoxLayout;
h_layout_3->addWidget(new QLabel("Traffic Light Shape: "), 40);
h_layout_3->addWidget(light_shape_combo_, 60);
auto * h_layout_4 = new QHBoxLayout;
h_layout_4->addWidget(new QLabel("Traffic Light Status: "), 40);
h_layout_4->addWidget(light_status_combo_, 60);
auto * v_layout = new QVBoxLayout;
v_layout->addLayout(h_layout_1);
v_layout->addLayout(h_layout_2);
v_layout->addLayout(h_layout_3);
v_layout->addLayout(h_layout_4);
v_layout->addWidget(set_button_);
v_layout->addWidget(reset_button_);
v_layout->addWidget(publish_button_);
auto * h_layout_5 = new QHBoxLayout;
h_layout_5->addLayout(v_layout);
h_layout_5->addWidget(traffic_table_);
setLayout(h_layout_5);
}
void TrafficLightPublishPanel::onSetTrafficLightState()
{
const auto traffic_light_id = traffic_light_id_input_->value();
const auto color = light_color_combo_->currentText();
const auto shape = light_shape_combo_->currentText();
const auto status = light_status_combo_->currentText();
TrafficLight traffic_light;
traffic_light.confidence = traffic_light_confidence_input_->value();
if (color == "RED") {
traffic_light.color = TrafficLight::RED;
} else if (color == "AMBER") {
traffic_light.color = TrafficLight::AMBER;
} else if (color == "GREEN") {
traffic_light.color = TrafficLight::GREEN;
} else if (color == "WHITE") {
traffic_light.color = TrafficLight::WHITE;
} else if (color == "UNKNOWN") {
traffic_light.color = TrafficLight::UNKNOWN;
}
if (shape == "CIRCLE") {
traffic_light.shape = TrafficLight::CIRCLE;
} else if (shape == "LEFT_ARROW") {
traffic_light.shape = TrafficLight::LEFT_ARROW;
} else if (shape == "RIGHT_ARROW") {
traffic_light.shape = TrafficLight::RIGHT_ARROW;
} else if (shape == "UP_ARROW") {
traffic_light.shape = TrafficLight::UP_ARROW;
} else if (shape == "DOWN_ARROW") {
traffic_light.shape = TrafficLight::DOWN_ARROW;
} else if (shape == "DOWN_LEFT_ARROW") {
traffic_light.shape = TrafficLight::DOWN_LEFT_ARROW;
} else if (shape == "DOWN_RIGHT_ARROW") {
traffic_light.shape = TrafficLight::DOWN_RIGHT_ARROW;
} else if (shape == "UNKNOWN") {
traffic_light.shape = TrafficLight::UNKNOWN;
}
if (status == "SOLID_OFF") {
traffic_light.status = TrafficLight::SOLID_OFF;
} else if (status == "SOLID_ON") {
traffic_light.status = TrafficLight::SOLID_ON;
} else if (status == "FLASHING") {
traffic_light.status = TrafficLight::FLASHING;
} else if (status == "UNKNOWN") {
traffic_light.status = TrafficLight::UNKNOWN;
}
TrafficSignal traffic_signal;
traffic_signal.lights.push_back(traffic_light);
traffic_signal.map_primitive_id = traffic_light_id;
for (auto & signal : extra_traffic_signals_.signals) {
if (signal.map_primitive_id == traffic_light_id) {
signal = traffic_signal;
return;
}
}
extra_traffic_signals_.signals.push_back(traffic_signal);
}
void TrafficLightPublishPanel::onResetTrafficLightState()
{
extra_traffic_signals_.signals.clear();
enable_publish_ = false;
publish_button_->setText("PUBLISH");
publish_button_->setStyleSheet("background-color: #FFFFFF");
}
void TrafficLightPublishPanel::onPublishTrafficLightState()
{
enable_publish_ = true;
publish_button_->setText("PUBLISHING...");
publish_button_->setStyleSheet("background-color: #FFBF00");
}
void TrafficLightPublishPanel::onInitialize()
{
raw_node_ = this->getDisplayContext()->getRosNodeAbstraction().lock()->get_raw_node();
pub_traffic_signals_ = raw_node_->create_publisher<TrafficSignalArray>(
"/perception/traffic_light_recognition/traffic_signals", rclcpp::QoS(1));
createWallTimer();
enable_publish_ = false;
}
void TrafficLightPublishPanel::onRateChanged(int new_rate)
{
(void)new_rate;
pub_timer_->cancel();
createWallTimer();
}
void TrafficLightPublishPanel::createWallTimer()
{
// convert rate from Hz to milliseconds
const auto period =
std::chrono::milliseconds(static_cast<int64_t>(1e3 / publishing_rate_input_->value()));
pub_timer_ = raw_node_->create_wall_timer(period, [&]() { onTimer(); });
}
void TrafficLightPublishPanel::onTimer()
{
if (enable_publish_) {
extra_traffic_signals_.header.stamp = rclcpp::Clock().now();
pub_traffic_signals_->publish(extra_traffic_signals_);
}
traffic_table_->setRowCount(extra_traffic_signals_.signals.size());
if (extra_traffic_signals_.signals.empty()) {
return;
}
for (size_t i = 0; i < extra_traffic_signals_.signals.size(); ++i) {
const auto & signal = extra_traffic_signals_.signals.at(i);
if (signal.lights.empty()) {
continue;
}
auto id_label = new QLabel(QString::number(signal.map_primitive_id));
id_label->setAlignment(Qt::AlignCenter);
auto color_label = new QLabel();
color_label->setAlignment(Qt::AlignCenter);
const auto & light = signal.lights.front();
switch (light.color) {
case TrafficLight::RED:
color_label->setText("RED");
color_label->setStyleSheet("background-color: #FF0000;");
break;
case TrafficLight::AMBER:
color_label->setText("AMBER");
color_label->setStyleSheet("background-color: #FFBF00;");
break;
case TrafficLight::GREEN:
color_label->setText("GREEN");
color_label->setStyleSheet("background-color: #7CFC00;");
break;
case TrafficLight::WHITE:
color_label->setText("WHITE");
color_label->setStyleSheet("background-color: #FFFFFF;");
break;
case TrafficLight::UNKNOWN:
color_label->setText("UNKNOWN");
color_label->setStyleSheet("background-color: #808080;");
break;
default:
break;
}
auto shape_label = new QLabel();
shape_label->setAlignment(Qt::AlignCenter);
switch (light.shape) {
case TrafficLight::CIRCLE:
shape_label->setText("CIRCLE");
break;
case TrafficLight::LEFT_ARROW:
shape_label->setText("LEFT_ARROW");
break;
case TrafficLight::RIGHT_ARROW:
shape_label->setText("RIGHT_ARROW");
break;
case TrafficLight::UP_ARROW:
shape_label->setText("UP_ARROW");
break;
case TrafficLight::DOWN_ARROW:
shape_label->setText("DOWN_ARROW");
break;
case TrafficLight::DOWN_LEFT_ARROW:
shape_label->setText("DOWN_LEFT_ARROW");
break;
case TrafficLight::DOWN_RIGHT_ARROW:
shape_label->setText("DOWN_RIGHT_ARROW");
break;
case TrafficLight::FLASHING:
shape_label->setText("FLASHING");
break;
case TrafficLight::UNKNOWN:
shape_label->setText("UNKNOWN");
break;
default:
break;
}
auto status_label = new QLabel();
status_label->setAlignment(Qt::AlignCenter);
switch (light.status) {
case TrafficLight::SOLID_OFF:
status_label->setText("SOLID_OFF");
break;
case TrafficLight::SOLID_ON:
status_label->setText("SOLID_ON");
break;
case TrafficLight::FLASHING:
status_label->setText("FLASHING");
break;
case TrafficLight::UNKNOWN:
status_label->setText("UNKNOWN");
break;
default:
break;
}
auto confidence_label = new QLabel(QString::number(light.confidence));
confidence_label->setAlignment(Qt::AlignCenter);
traffic_table_->setCellWidget(i, 0, id_label);
traffic_table_->setCellWidget(i, 1, color_label);
traffic_table_->setCellWidget(i, 2, shape_label);
traffic_table_->setCellWidget(i, 3, status_label);
traffic_table_->setCellWidget(i, 4, confidence_label);
}
}
} // namespace rviz_plugins
#include <pluginlib/class_list_macros.hpp>
PLUGINLIB_EXPORT_CLASS(rviz_plugins::TrafficLightPublishPanel, rviz_common::Panel)
| 32.540616 | 97 | 0.710597 | goktugyildirim |
b21c5733999bbb9d470b67e0ea151cf586d855c7 | 4,819 | cpp | C++ | src/background_sea.cpp | esohns/splot | 1577df5c06270c7239d9e721d339256269d96d5b | [
"ClArtistic"
] | null | null | null | src/background_sea.cpp | esohns/splot | 1577df5c06270c7239d9e721d339256269d96d5b | [
"ClArtistic"
] | null | null | null | src/background_sea.cpp | esohns/splot | 1577df5c06270c7239d9e721d339256269d96d5b | [
"ClArtistic"
] | null | null | null | #include "stdafx.h"
#include "background_sea.h"
#include <cmath>
#include <string>
#include "ace/OS.h"
#include "ace/OS_Memory.h"
#include "defines.h"
#include "common.h"
#include "state.h"
#include "configuration.h"
#include "background_sea_segment.h"
#include "image.h"
// init statics
GLuint Splot_BackgroundSea::texBase = 0;
//float Splot_BackgroundSea::vert[4][3] = {{ 20.5, 15.5, 0.0},
// {-20.5, 15.5, 0.0},
// { 20.5, -15.5, 0.0},
// {-20.5, -15.5, 0.0}};
Splot_BackgroundSea::Splot_BackgroundSea ()
: inherited (BACKGROUND_SEA)
, size_ (21.0)
{
loadTextures ();
float s[2] = {size_, size_};
inherited::position_[1] = size_*2.0F;
Splot_BackgroundSegment* segment = NULL;
ACE_NEW (segment,
Splot_BackgroundSeaSegment (inherited::position_, s, this));
inherited::segments_.push_back (segment);
inherited::position_[1] = 0.0;
ACE_NEW (segment,
Splot_BackgroundSeaSegment (inherited::position_, s, this));
inherited::segments_.push_back (segment);
}
Splot_BackgroundSea::~Splot_BackgroundSea ()
{
deleteTextures ();
}
bool
Splot_BackgroundSea::init ()
{
std::string path_base = ACE_TEXT_ALWAYS_CHAR (SPLOT_IMAGE_DATA_DIR);
path_base += ACE_DIRECTORY_SEPARATOR_STR;
char buffer[PATH_MAX];
ACE_OS::memset (buffer, 0, sizeof (buffer));
if (ACE_OS::sprintf (buffer, ACE_TEXT_ALWAYS_CHAR ("gndBaseSea.png")) < 0)
{
ACE_DEBUG ((LM_ERROR,
ACE_TEXT ("failed to sprintf(): \"%m\", aborting\n")));
return false;
} // end IF
std::string filename = dataLoc (path_base+buffer);
texBase =
Splot_Image::load (filename, IMG_NOMIPMAPS, IMG_ALPHA, GL_CLAMP, GL_LINEAR, GL_LINEAR);
if (!Splot_BackgroundSea::texBase)
{
ACE_DEBUG ((LM_ERROR,
ACE_TEXT ("failed to Splot_Image::load(\"%s\"), aborting\n"),
ACE_TEXT (filename.c_str ())));
return false;
} // end IF
return true;
}
void
Splot_BackgroundSea::fini ()
{
glDeleteTextures (1, &texBase);
}
void
Splot_BackgroundSea::loadTextures ()
{
#if defined (DEBUG_LAZY_LOADING) && (DEBUG_LAZY_LOADING == 1)
std::string path_base = ACE_TEXT_ALWAYS_CHAR (SPLOT_IMAGE_DATA_DIR);
path_base += ACE_DIRECTORY_SEPARATOR_STR;
char buffer[PATH_MAX];
ACE_OS::memset (buffer, 0, sizeof (buffer));
if (ACE_OS::sprintf (buffer, ACE_TEXT_ALWAYS_CHAR ("gndBaseSea.png")) < 0)
{
ACE_DEBUG ((LM_ERROR,
ACE_TEXT ("failed to sprintf(): \"%m\", returning\n")));
return;
} // end IF
std::string filename = dataLoc (path_base+buffer);
texBase =
Splot_Image::load (filename, IMG_NOMIPMAPS, IMG_ALPHA, GL_CLAMP, GL_LINEAR, GL_LINEAR);
if (!Splot_BackgroundSea::texBase)
{
ACE_DEBUG ((LM_ERROR,
ACE_TEXT ("failed to Splot_Image::load(\"%s\"), returning\n"),
ACE_TEXT (filename.c_str ())));
return;
} // end IF
#else
inherited::tex_[BACKGROUNDTEXTURE_BASE] = Splot_BackgroundSea::texBase;
#endif
}
void
Splot_BackgroundSea::deleteTextures ()
{
#if defined (DEBUG_LAZY_LOADING) && (DEBUG_LAZY_LOADING == 1)
glDeleteTextures (1, &inherited::tex_[BACKGROUNDTEXTURE_BASE]);
inherited::tex_[BACKGROUNDTEXTURE_BASE] = 0;
#endif
}
void
Splot_BackgroundSea::setVariation (int index_in)
{
ACE_UNUSED_ARG (index_in);
}
void
Splot_BackgroundSea::drawGL ()
{
State_t& state = SPLOT_STATE_SINGLETON::instance ()->get ();
glClearColor (0.15F, 0.12F, 0.1F, 1.0F);
// glClearColor(0.27451, 0.235294, 0.392157, 1.0); // web page background color
//-- draw ground segments
segmentsIterator_t iterator = inherited::segments_.begin ();
if (!state.game_pause ||
state.game_mode == GAMEMODE_MENU)
{
while (iterator != inherited::segments_.end ())
{
(*iterator)->position_[1] += state.scroll_speed;
iterator++;
} // end WHILE
} // end IF
glColor4f (0.9F, 0.9F, 0.9F, 0.7F);
float s2 = size_*2.0F;
float position[3] = {0.0, s2, 0.0};
float s[2] = {size_, size_};
Splot_BackgroundSeaSegment* segment = NULL;
iterator = inherited::segments_.begin ();
while (iterator != inherited::segments_.end ())
{
(*iterator)->drawGL ();
(*iterator)->position_[1] += state.scroll_speed;
if ((*iterator)->position_[1] >= -s2)
{
iterator++;
continue;
} // end IF
delete *iterator;
iterator = inherited::segments_.erase (iterator);
segment = NULL;
ACE_NEW_NORETURN (segment,
Splot_BackgroundSeaSegment (position, s, this));
if (!segment)
ACE_DEBUG ((LM_CRITICAL,
ACE_TEXT ("failed to allocate memory, continuing\n")));
else
inherited::segments_.push_front (segment);
break;
} // end WHILE
}
| 26.333333 | 91 | 0.640382 | esohns |
b21d378bfc96691a60410728a5e211efc77b4bc0 | 10,666 | cpp | C++ | luaopen_uv.cpp | grrrwaaa/luauv | fc74482dcf3323d03825a5c867264bf44c734ffb | [
"MIT",
"Unlicense"
] | 6 | 2015-04-03T03:00:43.000Z | 2021-03-12T06:31:17.000Z | luaopen_uv.cpp | grrrwaaa/luauv | fc74482dcf3323d03825a5c867264bf44c734ffb | [
"MIT",
"Unlicense"
] | null | null | null | luaopen_uv.cpp | grrrwaaa/luauv | fc74482dcf3323d03825a5c867264bf44c734ffb | [
"MIT",
"Unlicense"
] | 2 | 2017-04-18T01:54:05.000Z | 2020-11-06T08:34:05.000Z | /*
LuaUV
Copyright 2012 Graham Wakefield. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "luaopen_uv.h"
#include <stdlib.h>
#include <string.h>
int lua_uv_loop___tostring(lua_State * L) {
lua_pushfstring(L, "uv_loop (%p)", lua_uv_loop(L));
return 1;
}
int lua_uv_loop___gc(lua_State * L) {
dprintf("lua_uv_loop___gc\n");
lua_pushnil(L);
lua_setmetatable(L, 1);
uv_loop_delete(lua_uv_loop(L));
return 1;
}
#pragma mark buffers
uv_buf_t lua_uv_alloc(uv_handle_t *, size_t suggested_size) {
uv_buf_t buf;
buf.base = (char *)malloc(suggested_size);
buf.len = suggested_size;
return buf;
}
/*
expects an integer size on the top of the stack
allocates a userdata whose contents are
uv_buf_t, char[len]
uv_buf_t.base points to char[len]
Since this memory is managed by Lua, it is user responsibility to keep
it referenced on the stack by any callbacks that use it
*/
uv_buf_t * lua_uv_buf_init(lua_State * L, size_t len) {
uv_buf_t * buf = (uv_buf_t *)lua_newuserdata(L, sizeof(uv_buf_t) + len);
buf->base = (char *)(buf + sizeof(uv_buf_t));
buf->len = len;
luaL_getmetatable(L, classname<uv_buf_t>());
lua_setmetatable(L, -2);
return buf;
}
uv_buf_t * lua_uv_buf_init(lua_State * L, char * data, size_t len) {
uv_buf_t * buf = lua_uv_buf_init(L, len);
memcpy(buf->base, data, len);
return buf;
}
int lua_uv_buf___gc(lua_State * L) {
dprintf("buf gc\n");
return 0;
}
#pragma mark loops
//int lua_uv_loop_new(lua_State * L) {
// lua_pushlightuserdata(L, uv_loop_new());
// return 1;
//}
//
//int lua_uv_loop_delete(lua_State * L) {
// uv_loop_t * v = (uv_loop_t *)lua_touserdata(L, 1);
// uv_loop_delete(v);
// return 0;
//}
int lua_uv_run(lua_State * L) {
uv_loop_t * v = lua_uv_loop(L);
lua_pushinteger(L, uv_run(v));
return 1;
}
int lua_uv_run_once(lua_State * L) {
uv_loop_t * v = lua_uv_loop(L);
lua_pushinteger(L, uv_run_once(v));
return 1;
}
int lua_uv_now(lua_State * L) {
uv_loop_t * v = lua_uv_loop(L);
lua_pushinteger(L, uv_now(v));
return 1;
}
int lua_uv_update_time(lua_State * L) {
uv_loop_t * v = lua_uv_loop(L);
uv_update_time(v);
return 0;
}
int lua_uv_unref(lua_State * L) {
uv_loop_t * v = lua_uv_loop(L);
uv_unref(v);
return 0;
}
#pragma mark errors
bool lua_uv_check(lua_State * L, uv_err_t err) {
bool ok = err.code == 0;
lua_pushboolean(L, ok);
lua_pushstring(L, uv_strerror(err));
return ok;
}
void lua_uv_ok(lua_State * L, uv_err_t err) {
if (err.code) {
lua_pushinteger(L, err.code);
lua_pushfstring(L, "uv error (%d): %s", err.code, uv_strerror(err) );
lua_error(L);
}
}
void lua_uv_ok(lua_State * L) {
lua_uv_ok(L, uv_last_error(lua_uv_loop(L)));
}
int lua_uv_last_error(lua_State * L) {
uv_loop_t * v = lua_uv_loop(L);
uv_err_t err = uv_last_error(v);
lua_pushinteger(L, err.code);
lua_pushstring(L, uv_strerror(err));
lua_pushstring(L, uv_err_name(err));
return 3;
}
#pragma mark utils
int lua_uv_exepath(lua_State * L) {
size_t s(4096);
char path[s + 1];
uv_exepath(path, &s);
lua_pushlstring(L, path, s);
return 1;
}
int lua_uv_cwd(lua_State * L) {
size_t s(4096);
char path[s + 1];
lua_uv_ok(L, uv_cwd(path, s));
lua_pushstring(L, path);
return 1;
}
int lua_uv_chdir(lua_State * L) {
lua_uv_ok(L, uv_chdir(luaL_checkstring(L, 1)));
return 0;
}
int lua_uv_get_free_memory(lua_State * L) {
lua_pushinteger(L, uv_get_free_memory());
return 1;
}
int lua_uv_get_total_memory(lua_State * L) {
lua_pushinteger(L, uv_get_total_memory());
return 1;
}
/*
In UNIX computing, the system load is a measure of the amount of work that a computer system performs. The load average represents the average system load over a period of time. It conventionally appears in the form of three numbers which represent the system load during the last one-, five-, and fifteen-minute periods.
*/
int lua_uv_loadavg(lua_State* L) {
double avg[3];
uv_loadavg(avg);
lua_pushnumber(L, avg[0]);
lua_pushnumber(L, avg[1]);
lua_pushnumber(L, avg[2]);
return 3;
}
int lua_uv_uptime(lua_State* L) {
double uptime;
uv_uptime(&uptime);
lua_pushnumber(L, uptime);
return 1;
}
int lua_uv_cpu_info(lua_State* L) {
uv_cpu_info_t* cpu_infos;
int count;
uv_cpu_info(&cpu_infos, &count);
for (int i = 0; i < count; i++) {
lua_newtable(L);
lua_pushstring(L, (cpu_infos[i]).model);
lua_setfield(L, -2, "model");
lua_pushnumber(L, (cpu_infos[i]).speed);
lua_setfield(L, -2, "speed");
lua_newtable(L);
lua_pushnumber(L, (cpu_infos[i]).cpu_times.user);
lua_setfield(L, -2, "user");
lua_pushnumber(L, (cpu_infos[i]).cpu_times.nice);
lua_setfield(L, -2, "nice");
lua_pushnumber(L, (cpu_infos[i]).cpu_times.sys);
lua_setfield(L, -2, "sys");
lua_pushnumber(L, (cpu_infos[i]).cpu_times.idle);
lua_setfield(L, -2, "idle");
lua_pushnumber(L, (cpu_infos[i]).cpu_times.irq);
lua_setfield(L, -2, "irq");
lua_setfield(L, -2, "times");
}
uv_free_cpu_info(cpu_infos, count);
return count;
}
int lua_uv_interface_addresses(lua_State * L) {
int count;
uv_interface_address_t * addresses;
char address[INET6_ADDRSTRLEN] = "0.0.0.0";
lua_uv_check(L, uv_interface_addresses(&addresses, &count));
for (int i=0; i<count; i++) {
lua_newtable(L);
lua_pushstring(L, addresses[i].name);
lua_setfield(L, -2, "interface");
lua_pushboolean(L, addresses[i].is_internal);
lua_setfield(L, -2, "internal");
if (addresses[i].address.address4.sin_family == AF_INET) {
lua_pushstring(L, "IPv4"); lua_setfield(L, -2, "family");
uv_ip4_name(&addresses[i].address.address4, address, sizeof(address));
} else if (addresses[i].address.address4.sin_family == AF_INET6) {
lua_pushstring(L, "IPv6"); lua_setfield(L, -2, "family");
uv_ip6_name(&addresses[i].address.address6, address, sizeof(address));
}
lua_pushstring(L, address); lua_setfield(L, -2, "address");
}
uv_free_interface_addresses(addresses, count);
return count;
}
int lua_uv_hrtime(lua_State * L) {
lua_pushnumber(L, uv_hrtime());
return 1;
}
int lua_uv_get_process_title(lua_State * L) {
char buf[1024];
lua_uv_check(L, uv_get_process_title(buf, 1024));
lua_pushstring(L, buf);
return 1;
}
int lua_uv_loop_new(lua_State * L) {
struct luaL_reg loop_methods[] = {
// utilities
{ "exepath", lua_uv_exepath },
{ "cwd", lua_uv_cwd },
{ "chdir", lua_uv_chdir },
{ "interface_addresses", lua_uv_interface_addresses },
{ "get_free_memory", lua_uv_get_free_memory },
{ "get_total_memory", lua_uv_get_total_memory },
{ "loadavg", lua_uv_loadavg },
{ "uptime", lua_uv_uptime },
{ "cpu_info", lua_uv_cpu_info },
{ "hrtime", lua_uv_hrtime },
{ "get_process_title", lua_uv_get_process_title },
{ NULL, NULL },
};
// create a new uv_loop_t for this lua_State
uv_loop_t * loop = uv_loop_new();
// cache the lua_State in the loop
// (assumes that the state that calls require "uv" is the root state
// or otherwise safe to use for general callbacks)
loop->data = L;
// box it in a userdatum:
*(uv_loop_t **)lua_newuserdata(L, sizeof(uv_loop_t *)) = loop;
int loopidx = lua_gettop(L);
// bind loop as an upvalue of all the methods:
#define LUA_UV_CLOSURE(PREFIX, NAME) \
lua_pushvalue(L, loopidx); \
lua_pushcclosure(L, lua_##PREFIX##_##NAME, 1); \
lua_setfield(L, -2, #NAME);
// define uv_loop metatable
luaL_newmetatable(L, classname<uv_loop_t>());
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
LUA_UV_CLOSURE(uv_loop, __tostring);
LUA_UV_CLOSURE(uv_loop, __gc);
LUA_UV_CLOSURE(uv, now);
LUA_UV_CLOSURE(uv, update_time);
LUA_UV_CLOSURE(uv, run);
LUA_UV_CLOSURE(uv, run_once);
LUA_UV_CLOSURE(uv, unref);
LUA_UV_CLOSURE(uv, last_error);
LUA_UV_CLOSURE(uv, timer);
LUA_UV_CLOSURE(uv, tcp);
LUA_UV_CLOSURE(uv, tty);
LUA_UV_CLOSURE(uv, fs_open);
LUA_UV_CLOSURE(uv, fs_readdir);
LUA_UV_CLOSURE(uv, fs_stat);
// install the non-closure methods:
luaL_register(L, NULL, loop_methods);
// set metatable on the main loop:
lua_setmetatable(L, loopidx);
return 1;
}
uv_loop_t * lua_uv_main_loop(lua_State * L) {
lua_getfield(L, LUA_REGISTRYINDEX, "uv_main_loop");
uv_loop_t * loop = (*(uv_loop_t **)luaL_checkudata(L, -1, classname<uv_loop_t>()));
return loop;
}
int lua_uv_request___gc(lua_State * L) {
dprintf("request __gc\n");
return 0;
}
int lua_uv_request___tostring(lua_State * L) {
lua_pushfstring(L, "uv.request (%p)", lua_touserdata(L, 1));
return 1;
}
// The uv module returns a uv_loop userdatum, which has all the main
// libuv functions within it.
// This ensures that multiple independent lua_States have distinct loops,
// that the loop is properly closed when the module is garbage collected,
// and that the uv_loop_t is available as an upvalue to all functions.
extern "C" int luaopen_uv(lua_State * L) {
lua_uv_loop_new(L);
int loopidx = lua_gettop(L);
// stick this one in the registry:
lua_pushvalue(L, loopidx);
lua_setfield(L, LUA_REGISTRYINDEX, "uv_main_loop");
// define uv_buf metatable
luaL_newmetatable(L, classname<uv_buf_t>());
lua_pushvalue(L, -1);
lua_setfield(L, -2, "__index");
lua_pushcfunction(L, lua_generic___tostring<uv_buf_t>);
lua_setfield(L, -2, "__tostring");
LUA_UV_CLOSURE(uv_buf, __gc);
lua_pop(L, 1);
// order is important:
init_handle_metatable(L, loopidx);
init_stream_metatable(L, loopidx);
init_timer_metatable(L, loopidx);
init_tcp_metatable(L, loopidx);
init_tty_metatable(L, loopidx);
init_fs_metatable(L, loopidx);
luaL_newmetatable(L, "uv.request");
lua_pushcfunction(L, lua_uv_request___tostring);
lua_setfield(L, -2, "__tostring");
lua_pushcfunction(L, lua_uv_request___gc);
lua_setfield(L, -2, "__gc");
lua_pop(L, 1);
return 1;
}
| 27.348718 | 460 | 0.716295 | grrrwaaa |
b21f729764a90d86074ff4e78691e3f2c2533a35 | 5,042 | hpp | C++ | ROSE/SgUntypedNodes.hpp | OpenFortranProject/ofp-sdf | 202591cf4ac4981b21ddc38c7077f9c4d1c16f54 | [
"BSD-3-Clause"
] | 27 | 2015-03-05T14:41:39.000Z | 2021-04-22T23:51:25.000Z | ROSE/SgUntypedNodes.hpp | OpenFortranProject/ofp-sdf | 202591cf4ac4981b21ddc38c7077f9c4d1c16f54 | [
"BSD-3-Clause"
] | 33 | 2015-11-05T09:50:04.000Z | 2018-05-10T21:32:48.000Z | ROSE/SgUntypedNodes.hpp | OpenFortranProject/ofp-sdf | 202591cf4ac4981b21ddc38c7077f9c4d1c16f54 | [
"BSD-3-Clause"
] | 10 | 2015-06-24T01:22:58.000Z | 2019-06-16T06:47:15.000Z | #ifndef SG_UNTYPED_NODES_HPP
#define SG_UNTYPED_NODES_HPP
#include <string>
#include <list>
namespace sage {
class SgNode;
class SgLocatedNode;
class SgLocatedNodeSupport;
class SgUntypedNode;
class SgUntypedExpression;
class SgUntypedStatement;
class SgUntypedDeclaration;
class SgUntypedType;
class SgUntypedAttribute;
//class SgUntypedDeclarationStatement;
class SgUntypedFunctionDeclaration;
class SgUntypedScope;
class SgUntypedModuleScope;
class SgUntypedFunctionScope;
//class SgUntypedTypeUnknown;
class SgUntypedUnknown;
class SgUntypedGlobalScope;
class SgUntypedAttribute {
public:
SgUntypedAttribute(int, std::string);
};
class SgUntypedInitializedName {
public:
SgUntypedInitializedName(SgUntypedType*, std::string);
};
class SgUntypedFile
{
public:
SgUntypedFile(SgUntypedGlobalScope*);
~SgUntypedFile();
// protected:
SgUntypedGlobalScope * p_SgUntypedGlobalScope;
};
class SgUntypedDeclarationStatement;
class SgUntypedStatementList {
SgUntypedStatementList(std::list<SgUntypedStatement> *);
};
class SgUntypedDeclarationList {
SgUntypedDeclarationList(std::list<SgUntypedDeclarationStatement> *);
};
typedef std::list<SgUntypedFunctionDeclaration*> SgUntypedFunctionDeclarationList;
//class SgUntypedFunctionDeclarationList {
// SgUntypedFunctionDeclarationList(std::list<SgUntypedFunctionDeclaration> *);
//};
typedef std::list<SgUntypedInitializedName*> SgUntypedInitializedNameList;
//class SgUntypedInitializedNameList {
// SgUntypedInitializedNameList(std::list<SgUntypedInitializedName> *);
//};
class SgUntypedValueExpression {
SgUntypedValueExpression(int, std::string, SgUntypedType);
};
class SgUntypedArrayReferenceExpression {
SgUntypedArrayReferenceExpression(int);
};
class SgUntypedOtherExpression {
SgUntypedOtherExpression(int);
};
class SgUntypedFunctionCallOrArrayReferenceExpression {
SgUntypedFunctionCallOrArrayReferenceExpression(int);
};
class SgUntypedReferenceExpression {
SgUntypedReferenceExpression(int, std::string);
};
class SgUntypedAssignmentStatement {
SgUntypedAssignmentStatement(std::string, int, SgUntypedExpression, SgUntypedExpression);
};
class SgUntypedFunctionCallStatement {
SgUntypedFunctionCallStatement(std::string, int);
};
class SgUntypedNamedStatement {
SgUntypedNamedStatement(std::string, int, std::string);
};
class SgUntypedOtherStatement {
SgUntypedOtherStatement(std::string, int);
};
class SgUntypedImplicitDeclaration {
SgUntypedImplicitDeclaration(std::string, int);
};
class SgUntypedVariableDeclaration {
SgUntypedVariableDeclaration(std::string, int, SgUntypedType, SgUntypedInitializedNameList);
};
class SgUntypedModuleDeclaration {
SgUntypedModuleDeclaration(std::string, int, std::string, SgUntypedModuleScope, SgUntypedNamedStatement);
};
class SgUntypedDeclaration {
public:
SgUntypedDeclaration();
};
class SgUntypedFunctionDeclaration : public SgUntypedDeclaration {
public:
SgUntypedFunctionDeclaration();
};
class SgUntypedProgramHeaderDeclaration : public SgUntypedFunctionDeclaration {
SgUntypedProgramHeaderDeclaration(std::string, int, std::string, SgUntypedInitializedNameList, SgUntypedType, SgUntypedFunctionScope, SgUntypedNamedStatement);
};
class SgUntypedSubroutineDeclaration {
SgUntypedSubroutineDeclaration(std::string, int, std::string, SgUntypedInitializedNameList, SgUntypedType, SgUntypedFunctionScope, SgUntypedNamedStatement);
};
class SgUntypedFunctionScope {
SgUntypedFunctionScope(std::string, int, SgUntypedDeclarationList, SgUntypedStatementList, SgUntypedFunctionDeclarationList);
};
class SgUntypedModuleScope {
SgUntypedModuleScope(std::string, int, SgUntypedDeclarationList, SgUntypedStatementList, SgUntypedFunctionDeclarationList);
};
class SgUntypedGlobalScope {
public:
SgUntypedGlobalScope(std::string, int, SgUntypedDeclarationList*, SgUntypedStatementList*, SgUntypedFunctionDeclarationList*);
};
class SgUntypedArrayType {
SgUntypedArrayType(std::string, SgUntypedExpression, bool, bool, bool, bool, bool, bool, SgUntypedExpression, std::string, bool);
};
class SgUntypedTypeVoid;
class SgUntypedTypeUnknown;
class SgUntypedTypeInt {
SgUntypedTypeInt();
};
class SgUntypedTypeFloat {
SgUntypedTypeFloat();
};
class SgUntypedTypeDouble {
SgUntypedTypeDouble();
};
class SgUntypedTypeBool {
SgUntypedTypeBool();
};
class SgUntypedBlockScope {
SgUntypedBlockScope(std::string, int, SgUntypedDeclarationList, SgUntypedStatementList, SgUntypedFunctionDeclarationList);
};
class SgUntypedBlockStatement {
SgUntypedBlockStatement(std::string, int, std::string, SgUntypedBlockScope, SgUntypedNamedStatement);
};
class SgUntypedUnaryOperator {
SgUntypedUnaryOperator(int, int, std::string, SgUntypedExpression);
};
class SgUntypedBinaryOperator {
SgUntypedBinaryOperator(int, int, std::string, SgUntypedExpression, SgUntypedExpression);
};
} // namespace sage
#endif //SG_UNTYPED_NODES_HPP
| 25.989691 | 163 | 0.800873 | OpenFortranProject |
b22c9d4469cbbaf3fd46ab3853e62b8003d81c16 | 2,925 | cpp | C++ | filters/pclviewer.cpp | megadl/DiveIntoPointCloud | e1206fc245d62cab487f2501f223996455f8db95 | [
"BSD-3-Clause"
] | null | null | null | filters/pclviewer.cpp | megadl/DiveIntoPointCloud | e1206fc245d62cab487f2501f223996455f8db95 | [
"BSD-3-Clause"
] | null | null | null | filters/pclviewer.cpp | megadl/DiveIntoPointCloud | e1206fc245d62cab487f2501f223996455f8db95 | [
"BSD-3-Clause"
] | null | null | null | #include "pclviewer.h"
#include <chrono>
#include <thread>
using namespace std::chrono_literals;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
void main(int argc, char* argv[])
{
FilterType filtertype = FilterType::PassThrough;
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>);
pcl::io::loadPCDFile ("table_scene_mug_stereo_textured.pcd", *cloud);
filterPipeline(filtertype);
viewer = simpleVis(cloud);
while (!viewer.wasStopped())
{
viewer.spinOnce(100);
std::this_thread::sleep_for(100ms);
}
}
pcl::PointCloud<pcl::PointXYZ> filterPipeline(int filtertype){
pcl::PassThrough<pcl::PointXYZ> pass;
pcl::VoxelGrid<pcl::PointXYZ> sor;
pcl::StatisticalOutlierRemoval<pcl::PointXYZ> sor2;
pcl::RadiusOutlierRemoval<pcl::PointXYZ> sor3;
pcl::ConditionalRemoval<pcl::PointXYZ> sor4;
pcl::ExtractIndices<pcl::PointXYZ> sor5;
pcl::ProjectInliers<pcl::PointXYZ> sor6;
pcl::CropBox<pcl::PointXYZ> sor7;
pcl::CropHull<pcl::PointXYZ> sor8;
switch (filtertype) {
case 0:
pass.setInputCloud(cloud);
pass.setFilterFieldName("z");
pass.setFilterLimits(0.0, 1.0);
pass.filter(*cloud);
break;
case 1:
sor.setInputCloud(cloud);
sor.setLeafSize(0.01f, 0.01f, 0.01f);
sor.filter(*cloud);
break;
case 2:
sor2.setInputCloud(cloud);
sor2.setMeanK(50);
sor2.setStddevMulThresh(1.0);
sor2.filter(*cloud);
break;
case 3:
sor3.setInputCloud(cloud);
sor3.setRadiusSearch(0.05);
sor3.setMinNeighborsInRadius(50);
sor3.filter(*cloud);
break;
case 4:
case 5:
sor5.setInputCloud(cloud);
pcl::PointIndices::Ptr inliers(new pcl::PointIndices);
for (int i = 0; i < cloud->points.size(); i++) {
if (cloud->points[i].z < 0.5) {
inliers->indices.push_back(i);
}
break;
return *cloud;
}
pcl::visualization::PCLVisualizer::Ptr simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud)
{
// --------------------------------------------
// -----Open 3D viewer and add point cloud-----
// --------------------------------------------
pcl::visualization::PCLVisualizer::Ptr viewer (new pcl::visualization::PCLVisualizer ("3D Viewer"));
viewer->setBackgroundColor (0, 0, 0);
viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud");
viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud");
viewer->addCoordinateSystem (1.0);
viewer->initCameraParameters ();
return (viewer);
} | 33.62069 | 110 | 0.578803 | megadl |
b22e0af99a8ffd0b4619ccef9322a1b5dc73a098 | 728 | cpp | C++ | chapter03/ex10_operatus.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 124 | 2018-06-23T10:16:56.000Z | 2022-03-19T15:16:12.000Z | chapter03/ex10_operatus.cpp | therootfolder/stroustrup-ppp | b1e936c9a67b9205fdc9712c42496b45200514e2 | [
"MIT"
] | 23 | 2018-02-08T20:57:46.000Z | 2021-10-08T13:58:29.000Z | chapter03/ex10_operatus.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 65 | 2019-05-27T03:05:56.000Z | 2022-03-26T03:43:05.000Z | #include "../text_lib/std_lib_facilities.h"
// LOOKING BACK: Not sure why I didn't use char's for the operators..
int main()
{
// Program
cout << "Provide an operation and two values you'd like operated on:\n";
string operatus;
double val1;
double val2;
cin >> operatus >> val1 >> val2;
double result = 0;
if (operatus == "+" || operatus == "plus")
result = val1 + val2;
else if (operatus == "-" || operatus == "minus")
result = val1 - val2;
else if (operatus == "*" || operatus == "mul")
result = val1 * val2;
else if (operatus == "/" || operatus == "div")
result = val1 / val2;
cout << "The result of your operation is " << result << '\n';
}
| 28 | 76 | 0.561813 | ClassAteam |
b22f89f7e7354563840f2d7dbf3ce5c5ce2c96d4 | 4,384 | cpp | C++ | thread_supervisor.cpp | espkk/dlt-parser | 5a458b72535e816cb4c76b86b3580bbbb436f3eb | [
"MIT"
] | null | null | null | thread_supervisor.cpp | espkk/dlt-parser | 5a458b72535e816cb4c76b86b3580bbbb436f3eb | [
"MIT"
] | null | null | null | thread_supervisor.cpp | espkk/dlt-parser | 5a458b72535e816cb4c76b86b3580bbbb436f3eb | [
"MIT"
] | null | null | null | #include <thread>
#include <type_traits>
#include <cassert>
#include "thread_supervisor.h"
#include "exceptions.h"
namespace dlt {
task::task(std::unique_ptr<fs::reader> reader) : reader_(std::move(reader)) {
}
const fs::reader& task::get_reader() const {
return *reader_;
}
void task::execute() {
// if parse exception occured push corrupted record if no others in a row
// this is to be in compliance with DLT viewer
const auto parse_exception_handler = [this](const Record& record) {
// TODO: log
if(records_.size() == 0 || !records_.back().isCorrupted()) {
records_.push_back(record);
}
};
while (true) {
try {
Record record;
record.parse(*reader_, parse_exception_handler);
// we do not emplace anymore because parse may throw
records_.push_back(std::move(record));
// check if we overruned current chunk
if (reader_->get_overrun() > 0) {
throw except::eof{};
}
// if exception was raised somewhere in another thread - cancel execution
if (supervisor::exception_ptr_holder != nullptr) {
break;
}
}
catch (const except::eof&) {
break;
}
catch(...) {
supervisor::exception_ptr_holder = std::current_exception();
break;
}
}
}
std::vector<Record>& task::result() {
return records_;
}
supervisor::supervisor(fs::reader&& reader) {
// threads_num_ should be configurable defaulting to the number of cores
threads_num_ = cores_num;
auto&& readers = reader.split(threads_num_);
tasks_.reserve(threads_num_);
for (size_t i = 0; i != threads_num_; ++i) {
tasks_.emplace_back(std::move(readers[i]));
}
}
void supervisor::execute(std::vector<Record>& records) {
std::vector<std::thread> threads(threads_num_);
for (size_t i = 0; i != threads_num_; ++i) {
threads[i] = std::thread{[this, i]() { tasks_[i].execute(); }};
}
// firstly wait for all threads and store results
std::vector<std::remove_reference_t<decltype(tasks_[0].result())>> results;
results.reserve(threads_num_);
for (size_t i = 0; i != threads_num_; ++i) {
threads[i].join();
results.push_back(std::move(tasks_[i].result()));
}
// secondly store results contiguously...
records = std::move(results[0]);
// reserve enough space and then just copy into the memory
// this thing is a bit non-standard (UB)
// actually, the standard forbids accessing reserved but non-resized
// but since this memory is contigously allocated we are sure that everything goes well
// otherwise the overhead zeroing would be performed
std::size_t size{ 0 };
for (size_t i = 0; i != threads_num_; ++i) {
size += results[i].size();
}
records.reserve(size);
for(size_t i=1; i != threads_num_; ++i) {
// the whole point of this check is to determine wheter the corrupted record is
// a result of splitting into chunks or not
// if so, we just remove that corrupted record
// we also remove it if overrun is because eof for two tasks in a row
// this means that some chunks do not have any records at all. we do assert in such a case
bool skip_first_record{ false };
if (results[i].size() > 0 && results[i][0].isCorrupted()) {
const auto prev_overrun = tasks_[i - 1].get_reader().get_overrun();
const auto cur_overrun = tasks_[i].get_reader().get_overrun();
const auto cur_valid_offset = tasks_[i].get_reader().get_first_valid_offset();
if ((prev_overrun > 0 && prev_overrun == cur_valid_offset)
|| (prev_overrun == fs::reader::OVERRUN_EOF && cur_overrun == fs::reader::OVERRUN_EOF &&
(assert(results[i].size() == 1), true))) {
skip_first_record = true;
}
}
// if the first record is corrupted because it was splitted into chunks in the middle it will be skipped
// such record itself is a part of previous chunk no matter if it is correct or not
std::move(std::begin(results[i]) + (skip_first_record ? 1 : 0), std::end(results[i]), std::back_inserter(records));
}
// if exception was raised rethrow
if (exception_ptr_holder != nullptr) {
std::rethrow_exception(exception_ptr_holder);
}
}
}
| 34.519685 | 121 | 0.630703 | espkk |
b234aba9602d043d298a314d7304485a9922246c | 437 | hpp | C++ | ruin (old)/variant.hpp | AmaneTsukishiro/Ruin | f8cc84799a4c9d5b314d231a5ae86890c84bb4fb | [
"BSL-1.0"
] | 3 | 2015-01-15T14:09:53.000Z | 2016-11-17T16:21:05.000Z | ruin (old)/variant.hpp | yuishiyumeiji/Ruin | f8cc84799a4c9d5b314d231a5ae86890c84bb4fb | [
"BSL-1.0"
] | null | null | null | ruin (old)/variant.hpp | yuishiyumeiji/Ruin | f8cc84799a4c9d5b314d231a5ae86890c84bb4fb | [
"BSL-1.0"
] | null | null | null |
#ifndef RUIN_VARIANT_HPP_INCLUDED
#define RUIN_VARIANT_HPP_INCLUDED
#include "ruin/variant/apply_visitor.hpp"
#include "ruin/variant/static_visitor.hpp"
#include "ruin/variant/variant.hpp"
#include "ruin/variant/visitor_ptr.hpp"
namespace ruin
{
using ruin::variants::variant;
using ruin::variants::static_visitor;
using ruin::variants::apply_visitor;
using ruin::variants::visitor_ptr;
}
#endif // RUIN_VARIANT_HPP_INCLUDED
| 19.863636 | 42 | 0.79405 | AmaneTsukishiro |
b2386fa9f25335af25c472aac935d54c2dd25e9e | 740 | cpp | C++ | Treasure Hunt/Treasure Hunt/Treasure Hunt.cpp | IosifGabriel/TreasureHunt | fd98a931f3a3b5c017e50606b54a8f360ada79ae | [
"MIT"
] | null | null | null | Treasure Hunt/Treasure Hunt/Treasure Hunt.cpp | IosifGabriel/TreasureHunt | fd98a931f3a3b5c017e50606b54a8f360ada79ae | [
"MIT"
] | null | null | null | Treasure Hunt/Treasure Hunt/Treasure Hunt.cpp | IosifGabriel/TreasureHunt | fd98a931f3a3b5c017e50606b54a8f360ada79ae | [
"MIT"
] | null | null | null | #include "pch.h"
#include <iostream>
#include "GameMode.h"
#include <windows.h>
using namespace std;
int main()
{
GameMode Game;
int i = 0;
do
{
system("CLS");
i++;
Game.TreasureHuntMap.PrintMap();
Game.MoveAgents();
Sleep(1500);
if (Game.ReturnNumbOfTreasure() == 3)
{
cout << " ALL TREASURES HAVE BEEN FOUND " << endl;
break;
}
if (Game.NumbOfBlockedAgents >= 2)
{
cout << " More or two agents are blocked!" << endl;
break;
}
if (i == Game.ReturnNumbOfRounds())
{
cout << endl;
cout << "Do you want to play more rounds?" << endl;
Game.SetRounds();
i = 0;
}
} while (i <= Game.ReturnNumbOfRounds());
cout << " GAME OVER ";
}
| 16.086957 | 55 | 0.554054 | IosifGabriel |
b2388a2035674e1c521c6ec84ffda36293cf8c29 | 391 | cpp | C++ | unittests/src/test_TwoSidedPlane.cpp | dgough/lazy-gltf2 | 9ada92d73234c55a15acebfd0b80ec045ef75f52 | [
"Apache-2.0"
] | 12 | 2017-07-24T02:17:38.000Z | 2022-03-10T11:27:36.000Z | unittests/src/test_TwoSidedPlane.cpp | dgough/lazy-gltf2 | 9ada92d73234c55a15acebfd0b80ec045ef75f52 | [
"Apache-2.0"
] | null | null | null | unittests/src/test_TwoSidedPlane.cpp | dgough/lazy-gltf2 | 9ada92d73234c55a15acebfd0b80ec045ef75f52 | [
"Apache-2.0"
] | null | null | null | #include <lazy_gltf2.hpp>
#include <gtest/gtest.h>
#include <array>
#include "common.hpp"
using namespace gltf2;
static const char* PATH = LAZY_GLTF2_BASE_SAMPLE_DIR "/2.0/TwoSidedPlane/glTF/TwoSidedPlane.gltf";
TEST(gltf, twosided) {
Gltf gltf(PATH);
EXPECT_TRUE(gltf);
auto material = gltf.material(0);
EXPECT_TRUE(material);
EXPECT_TRUE(material.doubleSided());
} | 21.722222 | 98 | 0.723785 | dgough |
b23b628e1df47ade956d3cc5040767d578632d33 | 3,224 | cpp | C++ | deploy/files/GLRawFile.cpp | cginternals/glraw | 4c9930833e42404e74364b9b6eaf5afd98ac3096 | [
"MIT"
] | 48 | 2015-07-30T11:20:49.000Z | 2022-01-10T20:07:51.000Z | deploy/files/GLRawFile.cpp | hpicgs/glraw | 4c9930833e42404e74364b9b6eaf5afd98ac3096 | [
"MIT"
] | 3 | 2015-08-08T08:51:36.000Z | 2017-01-17T17:26:54.000Z | deploy/files/GLRawFile.cpp | cginternals/glraw | 4c9930833e42404e74364b9b6eaf5afd98ac3096 | [
"MIT"
] | 9 | 2015-07-06T15:51:22.000Z | 2019-04-24T06:23:12.000Z |
#include <algorithm>
#include <fstream>
#include <sstream>
#include <iostream>
#include <stdio.h>
#include "GLRawFile.h"
namespace
{
template<typename T>
T read(std::ifstream & stream)
{
T value;
stream.read(reinterpret_cast<char*>(&value), sizeof(value));
return value;
}
std::string readString(std::ifstream & stream)
{
std::stringstream ss;
char c;
while (stream.good())
{
stream.get(c);
if (c == '\0')
break;
ss << c;
}
return ss.str();
}
} // namespace
uint16_t GLRawFile::s_magicNumber = 0xC6F5;
GLRawFile::GLRawFile(const std::string & filePath, bool parseProperties)
: m_filePath(filePath)
, m_valid(false)
{
m_valid = readFile(parseProperties);
}
GLRawFile::~GLRawFile()
{
}
bool GLRawFile::isValid() const
{
return m_valid;
}
const char * GLRawFile::data() const
{
return m_data.data();
}
const size_t GLRawFile::size() const
{
return m_data.size();
}
const std::string & GLRawFile::stringProperty(const std::string & key) const
{
return m_stringProperties.at(key);
}
int32_t GLRawFile::intProperty(const std::string & key) const
{
return m_intProperties.at(key);
}
double GLRawFile::doubleProperty(const std::string & key) const
{
return m_doubleProperties.at(key);
}
bool GLRawFile::hasStringProperty(const std::string & key) const
{
return m_stringProperties.find(key) != m_stringProperties.end();
}
bool GLRawFile::hasIntProperty(const std::string & key) const
{
return m_intProperties.find(key) != m_intProperties.end();
}
bool GLRawFile::hasDoubleProperty(const std::string & key) const
{
return m_doubleProperties.find(key) != m_doubleProperties.end();
}
bool GLRawFile::readFile(bool parseProperties)
{
std::ifstream ifs(m_filePath, std::ios::in | std::ios::binary);
if (!ifs)
{
perror("Error");
return false;
}
uint64_t offset = 0;
if (read<uint16_t>(ifs) == s_magicNumber)
{
offset = read<uint64_t>(ifs);
if (parseProperties)
{
readProperties(ifs, offset);
}
}
else
{
ifs.seekg(0);
}
readRawData(ifs, offset);
ifs.close();
return true;
}
void GLRawFile::readProperties(std::ifstream & ifs, uint64_t offset)
{
while (ifs.tellg() < static_cast<int64_t>(offset) && ifs.good())
{
uint8_t type = read<uint8_t>(ifs);
std::string key = readString(ifs);
switch (type)
{
case IntType:
m_intProperties[key] = read<int32_t>(ifs);
break;
case DoubleType:
m_doubleProperties[key] = read<double>(ifs);
break;
case StringType:
m_stringProperties[key] = readString(ifs);
break;
default:
return;
}
}
}
void GLRawFile::readRawData(std::ifstream & ifs, uint64_t rawDataOffset)
{
ifs.seekg(0, std::ios::end);
size_t endPosition = ifs.tellg();
const size_t size = endPosition - rawDataOffset;
ifs.seekg(rawDataOffset, std::ios::beg);
m_data.resize(size);
ifs.read(m_data.data(), size);
}
| 17.812155 | 76 | 0.608561 | cginternals |
b243629a6d93d947d597d8f4016884ec6a631b1e | 3,964 | cc | C++ | slib_graphics/source/opengl/gl_stock_shaders.cc | KarlJansson/ecs_game_engine | c76b7379d8ff913cd7773d0a9f55535996abdf35 | [
"MIT"
] | 1 | 2018-05-18T10:42:35.000Z | 2018-05-18T10:42:35.000Z | slib_graphics/source/opengl/gl_stock_shaders.cc | KarlJansson/ecs_game_engine | c76b7379d8ff913cd7773d0a9f55535996abdf35 | [
"MIT"
] | null | null | null | slib_graphics/source/opengl/gl_stock_shaders.cc | KarlJansson/ecs_game_engine | c76b7379d8ff913cd7773d0a9f55535996abdf35 | [
"MIT"
] | null | null | null | #include "gl_stock_shaders.h"
#include "material_system.h"
#include "renderer.h"
namespace lib_graphics {
GlStockShaders::GlStockShaders() = default;
void GlStockShaders::ForwardShaders() {
shader_source_[MaterialSystem::kText] = {
cu::ReadFile("./content/shaders/opengl/text_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/text_fs.glsl"), ""};
shader_source_[MaterialSystem::kPbrUntextured] = {
cu::ReadFile("./content/shaders/opengl/forward_pbr_untextured_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/forward_pbr_untextured_fs.glsl"),
""};
shader_source_[MaterialSystem::kPbrTextured] = {
cu::ReadFile("./content/shaders/opengl/forward_pbr_textured_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/forward_pbr_textured_fs.glsl"),
""};
}
void GlStockShaders::DeferredShaders() {
shader_source_[MaterialSystem::kText] = {
cu::ReadFile("./content/shaders/opengl/text_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/text_fs.glsl"), ""};
shader_source_[MaterialSystem::kPbrTextured] = {
cu::ReadFile("./content/shaders/opengl/deferred_pbr_textured_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/deferred_pbr_textured_fs.glsl"),
""};
shader_source_[MaterialSystem::kPbrUntextured] = {
cu::ReadFile("./content/shaders/opengl/deferred_pbr_untextured_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/deferred_pbr_untextured_fs.glsl"),
""};
shader_source_[MaterialSystem::kDeferredLightingAmbient] = {
cu::ReadFile("./content/shaders/opengl/deferred_ambient_tonemap_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/deferred_ambient_fs.glsl"), ""};
shader_source_[MaterialSystem::kTonemapGamma] = {
cu::ReadFile("./content/shaders/opengl/deferred_ambient_tonemap_vs.glsl"),
cu::ReadFile("./content/shaders/opengl/deferred_tonemap_fs.glsl"), ""};
}
void GlStockShaders::CompileShaders(MaterialSystem *mat_mgr) {
ForwardShaders();
for (auto &p : shader_source_) {
auto it = forward_shader_ids_.find(p.first);
if (it == forward_shader_ids_.end()) {
auto shader_command = AddShaderCommand(
std::get<0>(p.second), std::get<1>(p.second), std::get<2>(p.second));
forward_shader_ids_[p.first] = shader_command.ShaderId();
issue_command(shader_command);
} else {
auto shader_command = AddShaderCommand();
shader_command.vert_shader = std::get<0>(p.second);
shader_command.frag_shader = std::get<1>(p.second);
shader_command.geom_shader = std::get<2>(p.second);
shader_command.base_id = it->second;
issue_command(shader_command);
}
}
shader_source_.clear();
DeferredShaders();
for (auto &p : shader_source_) {
auto it = deferred_shader_ids_.find(p.first);
if (it == deferred_shader_ids_.end()) {
auto shader_command = AddShaderCommand(
std::get<0>(p.second), std::get<1>(p.second), std::get<2>(p.second));
deferred_shader_ids_[p.first] = shader_command.ShaderId();
auto f_it = forward_shader_ids_.find(p.first);
if (f_it != forward_shader_ids_.end())
def_to_for_map_[shader_command.ShaderId()] = f_it->second;
issue_command(shader_command);
} else {
auto shader_command = AddShaderCommand();
shader_command.vert_shader = std::get<0>(p.second);
shader_command.frag_shader = std::get<1>(p.second);
shader_command.geom_shader = std::get<2>(p.second);
shader_command.base_id = it->second;
issue_command(shader_command);
}
}
shader_source_.clear();
}
size_t GlStockShaders::GetShaderId(MaterialSystem::ShaderType type) {
auto it = deferred_shader_ids_.find(type);
return it != deferred_shader_ids_.end() ? it->second : 0;
}
size_t GlStockShaders::DefToForId(size_t deferred_id) {
auto it = def_to_for_map_.find(deferred_id);
if (it == def_to_for_map_.end()) return 0;
return it->second;
}
} // namespace lib_graphics
| 38.862745 | 80 | 0.698789 | KarlJansson |
b245f9cfe81be789d1ba07c0313f9199016e4f5f | 118 | cpp | C++ | Collector.cpp | gaobowen/websocket | feca320de23630787d38e404a7931f8c88ebdee3 | [
"MIT"
] | 1 | 2021-12-15T03:10:55.000Z | 2021-12-15T03:10:55.000Z | Collector.cpp | gaobowen/websocket | feca320de23630787d38e404a7931f8c88ebdee3 | [
"MIT"
] | null | null | null | Collector.cpp | gaobowen/websocket | feca320de23630787d38e404a7931f8c88ebdee3 | [
"MIT"
] | null | null | null | #include "Collector.h"
namespace GWS {
tbb::concurrent_hash_map<void*, std::shared_ptr<SockHandle>> collector;
}
| 19.666667 | 75 | 0.737288 | gaobowen |
b2492ed2a07c85c6c3d0c764c9ed332256890e51 | 2,810 | cxx | C++ | matrix/bin/cpi/3dc/spelldialog.cxx | D5n9sMatrix/able | 5f135e7f6f0ba7432df6d8a756613161c7f628e2 | [
"MIT"
] | 1 | 2022-02-20T04:39:10.000Z | 2022-02-20T04:39:10.000Z | matrix/bin/cpi/3dc/spelldialog.cxx | D5n9sMatrix/able | 5f135e7f6f0ba7432df6d8a756613161c7f628e2 | [
"MIT"
] | null | null | null | matrix/bin/cpi/3dc/spelldialog.cxx | D5n9sMatrix/able | 5f135e7f6f0ba7432df6d8a756613161c7f628e2 | [
"MIT"
] | null | null | null | /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you 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 .
*/
#include<stdio.h>
#include<stdarg.h>
#include<stdlib.h>
#include<string>
#ifdef spelldialog
namespace svx {
SpellDialogChildWindow::SpellDialogChildWindow (
Window* _pParent,
sal_uInt16 nId,
SfxBindings* pBindings,
SfxChildWinInfo* /*pInfo*/)
: SfxChildWindow (_pParent, nId)
{
SvxAbstractDialogFactory* pFact = SvxAbstractDialogFactory::Create();
DBG_ASSERT(pFact, "SvxAbstractDialogFactory::Create() failed");
m_pAbstractSpellDialog = pFact->CreateSvxSpellDialog(_pParent,
pBindings,
this );
pWindow = m_pAbstractSpellDialog->GetWindow();
eChildAlignment = SFX_ALIGN_NOALIGNMENT;
SetHideNotDelete (sal_True);
}
SpellDialogChildWindow::~SpellDialogChildWindow (void)
{
}
SfxBindings& SpellDialogChildWindow::GetBindings (void) const
{
OSL_ASSERT (m_pAbstractSpellDialog != NULL);
return m_pAbstractSpellDialog->GetBindings();
}
void SpellDialogChildWindow::InvalidateSpellDialog()
{
OSL_ASSERT (m_pAbstractSpellDialog != NULL);
if(m_pAbstractSpellDialog)
m_pAbstractSpellDialog->Invalidate();
}
bool SpellDialogChildWindow::HasAutoCorrection()
{
return false;
}
void SpellDialogChildWindow::AddAutoCorrection(
const OUString& /*rOld*/,
const OUString& /*rNew*/,
LanguageType /*eLanguage*/)
{
OSL_FAIL("AutoCorrection should have been overloaded - if available");
}
bool SpellDialogChildWindow::HasGrammarChecking()
{
return false;
}
bool SpellDialogChildWindow::IsGrammarChecking()
{
OSL_FAIL("Grammar checking should have been overloaded - if available");
return false;
}
void SpellDialogChildWindow::SetGrammarChecking(bool )
{
OSL_FAIL("Grammar checking should have been overloaded - if available");
}
} // end of namespace ::svx
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
#endif // spelldialog
| 33.855422 | 79 | 0.7121 | D5n9sMatrix |
b2502d3bfee9c3f5f2728529eeaeb179ab5a694e | 1,034 | cpp | C++ | example/map_like/map_like.cpp | cmachaca/struct_mapping | 12e37346afa3cefe880f9efd0dd1475a67ad67f8 | [
"MIT"
] | 57 | 2020-06-12T23:32:57.000Z | 2022-03-19T03:19:07.000Z | example/map_like/map_like.cpp | cmachaca/struct_mapping | 12e37346afa3cefe880f9efd0dd1475a67ad67f8 | [
"MIT"
] | 10 | 2020-07-24T18:06:56.000Z | 2022-03-31T14:36:06.000Z | example/map_like/map_like.cpp | cmachaca/struct_mapping | 12e37346afa3cefe880f9efd0dd1475a67ad67f8 | [
"MIT"
] | 13 | 2020-07-15T16:24:19.000Z | 2022-02-16T08:11:56.000Z | #include "struct_mapping/struct_mapping.h"
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <unordered_map>
struct Library
{
std::unordered_map<
std::string,
std::multimap<std::string, int>> counters;
std::multimap<
std::string,
std::unordered_multimap<std::string, std::string>> books;
};
int main()
{
struct_mapping::reg(&Library::counters, "counters");
struct_mapping::reg(&Library::books, "books");
Library library;
std::istringstream json_data(R"json(
{
"counters": {
"first": {
"112": 13,
"142": 560,
"112": 0
},
"second": {
"2": 28,
"20": 411
},
"third": {
}
},
"books": {
"asd": {
"Leo": "aaa",
"Leo": "bbb",
"Mark": "ccc"
},
"wwert": {
"Gogol": "ddd",
"Tom": "eee"
}
}
}
)json");
struct_mapping::map_json_to_struct(library, json_data);
std::ostringstream out_json_data;
struct_mapping::map_struct_to_json(library, out_json_data, " ");
std::cout << out_json_data.str() << std::endl;
}
| 16.412698 | 66 | 0.601547 | cmachaca |
b25133329365c9e9946157e7f23fbc2a84df7349 | 3,629 | cc | C++ | src/math/matrix_factories_test.cc | paulmiller/glFun | 39df2c7f92b41c09d618b81e2016f1c530fb2108 | [
"Unlicense"
] | null | null | null | src/math/matrix_factories_test.cc | paulmiller/glFun | 39df2c7f92b41c09d618b81e2016f1c530fb2108 | [
"Unlicense"
] | null | null | null | src/math/matrix_factories_test.cc | paulmiller/glFun | 39df2c7f92b41c09d618b81e2016f1c530fb2108 | [
"Unlicense"
] | null | null | null | #include "matrix_factories.h"
#include "approx_object.h"
#include "util.h"
#include "vector.h"
#include "catch.h"
TEST_CASE("MatrixFromColumnVectors") {
auto actual3x3 = MatrixFromColumnVectors(
Vector3<int>{1, 2, 3},
Vector3<int>{4, 5, 6},
Vector3<int>{7, 8, 9}
);
Matrix<int,3,3> expected3x3 {{
{1, 4, 7},
{2, 5, 8},
{3, 6, 9}
}};
REQUIRE(actual3x3 == expected3x3);
auto actual4x4 = MatrixFromColumnVectors(
Vector4<int>{ 1, 2, 3, 4},
Vector4<int>{ 5, 6, 7, 8},
Vector4<int>{ 9, 10, 11, 12},
Vector4<int>{13, 14, 15, 16}
);
Matrix<int,4,4> expected4x4 {{
{1, 5, 9, 13},
{2, 6, 10, 14},
{3, 7, 11, 15},
{4, 8, 12, 16}
}};
REQUIRE(actual4x4 == expected4x4);
}
TEST_CASE("RotationMatrix4x4") {
using namespace Catch::literals;
Matrix<double,4,4> actual;
ApproxMatrix4x4d expected(Matrix4x4d{});
expected.margin(1e-10);
// quarter turns around the X axis
expected.value = Matrix4x4d {{
{ 1, 0, 0, 0},
{ 0, 0,-1, 0},
{ 0, 1, 0, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(UnitX_Vector3d, Tau_d/4);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(-UnitX_Vector3d, -Tau_d/4);
REQUIRE(actual == expected);
expected.value = Matrix4x4d {{
{ 1, 0, 0, 0},
{ 0, 0, 1, 0},
{ 0,-1, 0, 0},
{ 0, 0, 0, 1}
}};
actual = RotationMatrix4x4(UnitX_Vector3d, -Tau_d/4);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(-UnitX_Vector3d, Tau_d/4);
REQUIRE(actual == expected);
// quarter turns around the Y axis
expected.value = Matrix4x4d {{
{ 0, 0, 1, 0},
{ 0, 1, 0, 0},
{-1, 0, 0, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(UnitY_Vector3d, Tau_d/4);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(-UnitY_Vector3d, -Tau_d/4);
REQUIRE(actual == expected);
expected.value = Matrix4x4d {{
{ 0, 0,-1, 0},
{ 0, 1, 0, 0},
{ 1, 0, 0, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(UnitY_Vector3d, -Tau_d/4);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(-UnitY_Vector3d, Tau_d/4);
REQUIRE(actual == expected);
// quarter turns around the around Z axis
expected.value = Matrix4x4d {{
{ 0,-1, 0, 0},
{ 1, 0, 0, 0},
{ 0, 0, 1, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(UnitZ_Vector3d, Tau_d/4);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(-UnitZ_Vector3d, -Tau_d/4);
REQUIRE(actual == expected);
expected.value = Matrix4x4d {{
{ 0, 1, 0, 0},
{-1, 0, 0, 0},
{ 0, 0, 1, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(UnitZ_Vector3d, -Tau_d/4);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(-UnitZ_Vector3d, Tau_d/4);
REQUIRE(actual == expected);
// 1/3 turn around <1,1,1>
expected.value = Matrix4x4d {{
{ 0, 0, 1, 0},
{ 1, 0, 0, 0},
{ 0, 1, 0, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(Vector3d{1,1,1}.unit(), Tau_d/3);
REQUIRE(actual == expected);
// no-op turns around an arbitrary axis
Vector3d axis = Vector3d{1,2,3}.unit();
expected.value = Matrix4x4d {{
{ 1, 0, 0, 0},
{ 0, 1, 0, 0},
{ 0, 0, 1, 0},
{ 0, 0, 0, 1}}};
actual = RotationMatrix4x4(axis, 0);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(axis, Tau_d);
REQUIRE(actual == expected);
actual = RotationMatrix4x4(axis, -Tau_d);
REQUIRE(actual == expected);
}
TEST_CASE("ScaleMatrix4x4") {
auto actual = ScaleMatrix4x4(Vector3<int>{2,3,4});
Matrix<int,4,4> expected {{
{2, 0, 0, 0},
{0, 3, 0, 0},
{0, 0, 4, 0},
{0, 0, 0, 1}
}};
REQUIRE(actual == expected);
}
| 26.107914 | 62 | 0.583356 | paulmiller |
b25b2cb5b455e7f233f6b8709f6594d6e122506d | 8,437 | cpp | C++ | src/TriplePropertyMapWidget.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | src/TriplePropertyMapWidget.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | src/TriplePropertyMapWidget.cpp | sempr-tk/sempr-gui | ba96dca6945122a157f61fec9e41f4aa6060e3b2 | [
"BSD-3-Clause"
] | null | null | null | #include "TriplePropertyMapWidget.hpp"
#include "../ui/ui_triplepropertymap.h"
#include "CustomDataRoles.hpp"
namespace sempr { namespace gui {
TriplePropertyMapWidget::TriplePropertyMapWidget(QWidget* parent)
: SingleComponentWidget(parent), form_(new Ui::TriplePropertyMapWidget)
{
form_->setupUi(this);
connect(form_->btnRemove, &QPushButton::clicked,
this, &TriplePropertyMapWidget::remove);
connect(form_->btnAdd, &QPushButton::clicked,
this, &TriplePropertyMapWidget::add);
// update after every change of an item
connect(form_->tableWidget, &QTableWidget::cellChanged,
this, &TriplePropertyMapWidget::save);
}
TriplePropertyMapWidget::~TriplePropertyMapWidget()
{
delete form_;
}
void TriplePropertyMapWidget::remove()
{
auto rows = form_->tableWidget->selectionModel()->selectedRows();
if (rows.size() > 0)
{
form_->tableWidget->blockSignals(true);
// only remove the first selected as I guess that the oder indices get
// invalidated by this
form_->tableWidget->removeRow(rows[0].row());
form_->tableWidget->blockSignals(false);
}
else
{
QMessageBox msg( QMessageBox::Icon::Warning, "No row selected",
"Please select an entire row to delete.",
QMessageBox::Button::Ok );
msg.exec();
}
// update the model
save();
}
void TriplePropertyMapWidget::save()
{
bool okay = false;
auto map = currentPtr();
if (map)
{
// okay, got the component... clear its data!
map->map_.clear();
// then iterate over the table widget and add new data
size_t numRows = form_->tableWidget->rowCount();
for (size_t i = 0; i < numRows; i++)
{
QString key = form_->tableWidget->item(i, 0)->text();
QString value = form_->tableWidget->item(i, 1)->text();
auto cellWidget = form_->tableWidget->cellWidget(i, 2);
auto comboWidget = dynamic_cast<QComboBox*>(cellWidget);
if (comboWidget)
{
auto data = comboWidget->currentData();
// shouldn't even need to check this...
if (data.canConvert<int>()) // TriplePropertyMapEntry::Type is an enum, should be good.
{
auto type = data.value<int>();
// now, create the new entry.
if (type == TriplePropertyMapEntry::INT)
{
map->map_[key.toStdString()] = value.toInt();
}
else if (type == TriplePropertyMapEntry::FLOAT)
{
map->map_[key.toStdString()] = value.toFloat();
}
else if (type == TriplePropertyMapEntry::RESOURCE)
{
map->map_[key.toStdString()] = { value.toStdString(), true };
}
else /*if (type == TriplePropertyMapEntry::STRING)*/
{
map->map_[key.toStdString()] = value.toStdString();
}
}
else
{
// :(
throw std::exception();
}
}
else
{
// wtf?
throw std::exception();
}
}
// trigger re-computation of the json representation
okay = model_->setData(
currentIndex_,
QVariant::fromValue(std::static_pointer_cast<Component>(map)),
Role::ComponentPtrRole);
// Only set the data in the model.
// When it is actually sent to the sempr core is not our business!
}
if (!okay)
{
QMessageBox msg(QMessageBox::Icon::Critical, "Error",
"Something went wrong while trying to save the component.",
QMessageBox::Button::Ok);
msg.exec();
}
}
void TriplePropertyMapWidget::add()
{
form_->tableWidget->blockSignals(true);
form_->tableWidget->setRowCount(form_->tableWidget->rowCount()+1);
QTableWidgetItem* keyItem = new QTableWidgetItem();
QTableWidgetItem* valueItem = new QTableWidgetItem();
form_->tableWidget->setItem(form_->tableWidget->rowCount()-1, 0, keyItem);
form_->tableWidget->setItem(form_->tableWidget->rowCount()-1, 1, valueItem);
QComboBox* typeCombo = new QComboBox();
typeCombo->addItem("int", TriplePropertyMapEntry::INT);
typeCombo->addItem("float", TriplePropertyMapEntry::FLOAT);
typeCombo->addItem("string", TriplePropertyMapEntry::STRING);
typeCombo->addItem("resource", TriplePropertyMapEntry::RESOURCE);
typeCombo->setCurrentIndex(0);
// call save whenever the combo box selection changes
connect(typeCombo, &QComboBox::currentTextChanged,
this, &TriplePropertyMapWidget::save);
form_->tableWidget->setCellWidget(form_->tableWidget->rowCount()-1, 2, typeCombo);
form_->tableWidget->blockSignals(false);
// update the model
save();
}
bool TriplePropertyMapWidget::updateComponentWidget(
TriplePropertyMap::Ptr map, bool isMutable)
{
if (!map)
{
this->setEnabled(false);
return false;
}
// first, make sure that the current view is empty
form_->tableWidget->clear();
size_t numProps = map->map_.size();
form_->tableWidget->setColumnCount(3);
form_->tableWidget->setRowCount(numProps);
// block signals -- must not "save" to the model yet, that would result
// in endless recursion.
form_->tableWidget->blockSignals(true);
// then, add the entries: 3 for every property in the map.
// 1: key
// 2: value
// 3: type
int currentRow = 0;
for (auto entry : map->map_)
{
QTableWidgetItem* keyItem = new QTableWidgetItem();
keyItem->setText(QString::fromStdString(entry.first));
QTableWidgetItem* valueItem = new QTableWidgetItem();
int intVal;
float fltVal;
switch(entry.second.type()) {
case TriplePropertyMapEntry::INT:
intVal = entry.second;
valueItem->setText(QString::number(intVal));
break;
case TriplePropertyMapEntry::FLOAT:
fltVal = entry.second;
valueItem->setText(QString::number(fltVal));
break;
case TriplePropertyMapEntry::STRING:
case TriplePropertyMapEntry::RESOURCE:
{
std::string strVal = entry.second;
valueItem->setText(QString::fromStdString(strVal));
break;
}
case TriplePropertyMapEntry::INVALID:
// ???
break;
}
QComboBox* typeCombo = new QComboBox();
typeCombo->addItem("int", TriplePropertyMapEntry::INT);
typeCombo->addItem("float", TriplePropertyMapEntry::FLOAT);
typeCombo->addItem("string", TriplePropertyMapEntry::STRING);
typeCombo->addItem("resource", TriplePropertyMapEntry::RESOURCE);
switch (entry.second.type()) {
case TriplePropertyMapEntry::INT:
typeCombo->setCurrentText("int");
break;
case TriplePropertyMapEntry::FLOAT:
typeCombo->setCurrentText("float");
break;
case TriplePropertyMapEntry::STRING:
typeCombo->setCurrentText("string");
break;
case TriplePropertyMapEntry::RESOURCE:
typeCombo->setCurrentText("resource");
break;
case TriplePropertyMapEntry::INVALID:
// ???
break;
}
// call save whenever the combo box selection changes
connect(typeCombo, &QComboBox::currentTextChanged,
this, &TriplePropertyMapWidget::save);
form_->tableWidget->setItem(currentRow, 0, keyItem);
form_->tableWidget->setItem(currentRow, 1, valueItem);
form_->tableWidget->setCellWidget(currentRow, 2, typeCombo);
currentRow++;
} // end for every property in the map
form_->tableWidget->blockSignals(false);
this->setEnabled(isMutable);
return true;
}
}}
| 33.216535 | 103 | 0.573308 | sempr-tk |
b25c83d4e70ecf2c5da0f4a466ed6abbaf8e436d | 898 | hpp | C++ | 3DRadSpace/3DRadSpaceDll/ResourceCreationException.hpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 9 | 2017-01-10T11:47:06.000Z | 2021-11-27T14:32:55.000Z | 3DRadSpace/3DRadSpaceDll/ResourceCreationException.hpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | null | null | null | 3DRadSpace/3DRadSpaceDll/ResourceCreationException.hpp | NicusorN5/3D_Rad_Space | 029c52817deb08db17f46bef6246413a115d9e1d | [
"CC0-1.0"
] | 6 | 2017-07-08T23:03:43.000Z | 2022-03-08T07:47:13.000Z | #pragma once
#include "Globals.hpp"
#pragma warning(push)
#pragma warning(disable: 4275)
#pragma warning(disable: 4251)
namespace Engine3DRadSpace
{
/// <summary>
/// Represents a detailed exception thrown when resource creation and allocations fail. An alternative to std::bad_alloc.
/// </summary>
class DLLEXPORT ResourceCreationException : public std::exception
{
std::string _message;
public:
ResourceCreationException() = delete;
/// <summary>
/// Constructs a exception with the given details
/// </summary>
/// <param name="message">Custom message</param>
/// <param name="type">Type of the faulty object</param>
ResourceCreationException(const std::string& message, const std::type_info& type) :
_message(message + "Faulty type :" + std::string(type.name())) { };
const char* what() const override;
~ResourceCreationException();
};
}
#pragma warning(pop) | 28.0625 | 122 | 0.716036 | NicusorN5 |
b25d9dc344486713803f810de18f90925ad13aa4 | 1,223 | cpp | C++ | LicenseManagerAuthenticator/Authenticator.cpp | johanlantz/headsetpresenter | 39c5e9740f58d66947e689670500fd0e8b7562c3 | [
"MIT"
] | 1 | 2022-02-24T06:04:03.000Z | 2022-02-24T06:04:03.000Z | LicenseManagerAuthenticator/Authenticator.cpp | johanlantz/headsetpresenter | 39c5e9740f58d66947e689670500fd0e8b7562c3 | [
"MIT"
] | null | null | null | LicenseManagerAuthenticator/Authenticator.cpp | johanlantz/headsetpresenter | 39c5e9740f58d66947e689670500fd0e8b7562c3 | [
"MIT"
] | null | null | null | #include ".\authenticator.h"
#include "time.h"
Authenticator::Authenticator(ILicenseHandler* imyLicenseHandler)
{
myLicenseHandler = imyLicenseHandler;
myLicenseHandler->Activate(150); //licman must be activated with a secret key
CK=13291;
AuthenticateComponent();
}
Authenticator::~Authenticator(void)
{
}
/*Note: If a lib is run in debug mode with the HeadsetPresenter as target then HeadsetPresenter
must be rebuilt for any changes in the lib to be effective. It is not enough to rebuild the lib, the
lib is statically linked into HeadsetPresenter at compiletime not like the dll case where changes would be
introduces at runtime*/
bool Authenticator::AuthenticateComponent(void)
{
bool authenticationResult = false;
int response;
srand( (unsigned)time( NULL ) );
int challenge = rand();
myLicenseHandler->Authenticate(challenge,&response);
if(response == (challenge ^ CK))
{
authenticationResult = true;
}
else
{
MessageBox(NULL,"Authentication failed, the application will terminate.\n\nThis should never happen unless you are hacking the LicenceManager. Contact support if this is not the case","",MB_OK);
exit(0);
}
return authenticationResult;
} | 31.358974 | 197 | 0.743254 | johanlantz |
b25eefb363c1e45ce16162a22aed99766ea686b9 | 18,314 | cpp | C++ | mediapipe/Osc/UdpSocket.cpp | tommymitch/mediapipe2osc | 8cf5d2c0d84bc4faddeff63f907f4085825ea14d | [
"Apache-2.0"
] | 6 | 2021-06-29T18:22:48.000Z | 2022-02-09T14:25:22.000Z | mediapipe/Osc/UdpSocket.cpp | tommymitch/mediapipe2osc | 8cf5d2c0d84bc4faddeff63f907f4085825ea14d | [
"Apache-2.0"
] | null | null | null | mediapipe/Osc/UdpSocket.cpp | tommymitch/mediapipe2osc | 8cf5d2c0d84bc4faddeff63f907f4085825ea14d | [
"Apache-2.0"
] | 1 | 2021-12-29T17:15:36.000Z | 2021-12-29T17:15:36.000Z | //
// UdpSocket.cpp
// OscppTest
//
// Created by Tom Mitchell on 16/04/2021.
// Copyright © 2021 Tom Mitchell. All rights reserved.
//
#include "UdpSocket.h"
#include <atomic>
//Apple
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#if defined(_WIN64)
using juce_socklen_t = int;
using juce_recvsend_size_t = int;
using SocketHandle = SOCKET;
static const SocketHandle invalidSocket = INVALID_SOCKET;
#else
using juce_socklen_t = unsigned int; //socklen_t; //apparently this is in the SystemConfiguration framework.
using juce_recvsend_size_t = unsigned int; //socklen_t;
using SocketHandle = int;
static const SocketHandle invalidSocket = -1;
#endif
//==============================================================================
namespace SocketHelpers
{
static void initSockets()
{
#if defined(_WIN64)
static bool socketsStarted = false;
if (! socketsStarted)
{
socketsStarted = true;
WSADATA wsaData;
const WORD wVersionRequested = MAKEWORD (1, 1);
WSAStartup (wVersionRequested, &wsaData);
}
#endif
}
inline bool isValidPortNumber (int port) noexcept
{
return port > 0 && port < 65536;
}
template <typename Type>
static bool setOption (SocketHandle handle, int mode, int property, Type value) noexcept
{
return setsockopt (handle, mode, property, reinterpret_cast<const char*> (&value), sizeof (value)) == 0;
}
template <typename Type>
static bool setOption (SocketHandle handle, int property, Type value) noexcept
{
return setOption (handle, SOL_SOCKET, property, value);
}
static bool resetSocketOptions (SocketHandle handle, bool isDatagram, bool allowBroadcast) noexcept
{
return handle != invalidSocket
&& setOption (handle, SO_RCVBUF, (int) 65536)
&& setOption (handle, SO_SNDBUF, (int) 65536)
&& (isDatagram ? ((! allowBroadcast) || setOption (handle, SO_BROADCAST, (int) 1))
: setOption (handle, IPPROTO_TCP, TCP_NODELAY, (int) 1));
}
static void closeSocket (std::atomic<int>& handle, std::mutex& readLock,
bool isListener, int portNumber, std::atomic<bool>& connected) noexcept
{
const auto h = (SocketHandle) handle.load();
handle = -1;
#if JUCE_WINDOWS
ignoreUnused (portNumber, isListener, readLock);
if (h != invalidSocket || connected)
closesocket (h);
// make sure any read process finishes before we delete the socket
std::mutex::ScopedLockType lock (readLock);
connected = false;
#else
if (connected)
{
connected = false;
if (isListener)
{
// need to do this to interrupt the accept() function..
//*********************************
//StreamingSocket temp;
//temp.connect (IPAddress::local().tostd::string(), portNumber, 1000);
}
}
if (h >= 0)
{
// unblock any pending read requests
::shutdown (h, SHUT_RDWR);
::close (h);
std::lock_guard<std::mutex> lg (readLock);
}
#endif
}
static bool bindSocket (SocketHandle handle, int port, const std::string& address) noexcept
{
if (handle == invalidSocket || ! isValidPortNumber (port))
return false;
struct sockaddr_in addr;
//zerostruct (addr); // (can't use "= { 0 }" on this object because it's typedef'ed as a C struct)
memset ((void*) &addr, 0, sizeof (addr));
addr.sin_family = PF_INET;
addr.sin_port = htons ((unsigned short) port);
addr.sin_addr.s_addr = ! address.empty() ? ::inet_addr (address.c_str())
: htonl (INADDR_ANY);
return ::bind (handle, (struct sockaddr*) &addr, sizeof (addr)) >= 0;
}
static int getBoundPort (SocketHandle handle) noexcept
{
if (handle != invalidSocket)
{
struct sockaddr_in addr;
socklen_t len = sizeof (addr);
if (getsockname (handle, (struct sockaddr*) &addr, &len) == 0)
return ntohs (addr.sin_port);
}
return -1;
}
static std::string getConnectedAddress (SocketHandle handle) noexcept
{
struct sockaddr_in addr;
socklen_t len = sizeof (addr);
if (getpeername (handle, (struct sockaddr*) &addr, &len) >= 0)
return inet_ntoa (addr.sin_addr);
return "0.0.0.0";
}
static bool setSocketBlockingState (SocketHandle handle, bool shouldBlock) noexcept
{
#if defined(_WIN64)
u_long nonBlocking = shouldBlock ? 0 : (u_long) 1;
return ioctlsocket (handle, (long) FIONBIO, &nonBlocking) == 0;
#else
int socketFlags = fcntl (handle, F_GETFL, 0);
if (socketFlags == -1)
return false;
if (shouldBlock)
socketFlags &= ~O_NONBLOCK;
else
socketFlags |= O_NONBLOCK;
return fcntl (handle, F_SETFL, socketFlags) == 0;
#endif
}
#if ! defined(_WIN64)
static bool getSocketBlockingState (SocketHandle handle)
{
return (fcntl (handle, F_GETFL, 0) & O_NONBLOCK) == 0;
}
#endif
static int readSocket (SocketHandle handle,
void* destBuffer, int maxBytesToRead,
std::atomic<bool>& connected,
bool blockUntilSpecifiedAmountHasArrived,
std::mutex& readLock,
std::string* senderIP = nullptr,
int* senderPort = nullptr) noexcept
{
#if ! JUCE_WINDOWS
if (blockUntilSpecifiedAmountHasArrived != getSocketBlockingState (handle))
#endif
setSocketBlockingState (handle, blockUntilSpecifiedAmountHasArrived);
int bytesRead = 0;
while (bytesRead < maxBytesToRead)
{
long bytesThisTime = -1;
auto buffer = static_cast<char*> (destBuffer) + bytesRead;
auto numToRead = (juce_recvsend_size_t) (maxBytesToRead - bytesRead);
{
// avoid race-condition
std::unique_lock<std::mutex> lock (readLock, std::try_to_lock);
if(!lock.owns_lock())
{
if (senderIP == nullptr || senderPort == nullptr)
{
bytesThisTime = ::recv (handle, buffer, numToRead, 0);
}
else
{
sockaddr_in client;
socklen_t clientLen = sizeof (sockaddr);
bytesThisTime = ::recvfrom (handle, buffer, numToRead, 0, (sockaddr*) &client, &clientLen);
std::string temp;
*senderIP = temp.append (inet_ntoa (client.sin_addr), 16);
*senderPort = ntohs (client.sin_port);
}
}
}
if (bytesThisTime <= 0 || ! connected)
{
if (bytesRead == 0 && blockUntilSpecifiedAmountHasArrived)
bytesRead = -1;
break;
}
bytesRead = static_cast<int> (bytesRead + bytesThisTime);
if (! blockUntilSpecifiedAmountHasArrived)
break;
}
return (int) bytesRead;
}
static int waitForReadiness (std::atomic<int>& handle, std::mutex& readLock,
bool forReading, int timeoutMsecs) noexcept
{
// avoid race-condition
std::unique_lock<std::mutex> lock (readLock, std::try_to_lock);
if(!lock.owns_lock())
return -1;
auto hasErrorOccurred = [&handle]() -> bool
{
auto h = (SocketHandle) handle.load();
if (h == invalidSocket)
return true;
int opt;
juce_socklen_t len = sizeof (opt);
if (getsockopt (h, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0 || opt != 0)
return true;
return false;
};
auto h = handle.load();
#if defined(_WIN64)
struct timeval timeout;
struct timeval* timeoutp;
if (timeoutMsecs >= 0)
{
timeout.tv_sec = timeoutMsecs / 1000;
timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
timeoutp = &timeout;
}
else
{
timeoutp = nullptr;
}
fd_set rset, wset;
FD_ZERO (&rset);
FD_SET ((SOCKET) h, &rset);
FD_ZERO (&wset);
FD_SET ((SOCKET) h, &wset);
fd_set* prset = forReading ? &rset : nullptr;
fd_set* pwset = forReading ? nullptr : &wset;
// NB - need to use select() here as WSAPoll is broken on Windows
if (select ((int) h + 1, prset, pwset, nullptr, timeoutp) < 0 || hasErrorOccurred())
return -1;
return FD_ISSET (h, forReading ? &rset : &wset) ? 1 : 0;
#else
short eventsFlag = (forReading ? POLLIN : POLLOUT);
pollfd pfd { (SocketHandle) h, eventsFlag, 0 };
int result = 0;
for (;;)
{
result = poll (&pfd, 1, timeoutMsecs);
if (result >= 0 || errno != EINTR)
break;
}
if (result < 0 || hasErrorOccurred())
return -1;
return (pfd.revents & eventsFlag) != 0;
#endif
}
static addrinfo* getAddressInfo (bool isDatagram, const std::string& hostName, int portNumber)
{
struct addrinfo hints;
memset ((void*) &hints, 0, sizeof (hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = isDatagram ? SOCK_DGRAM : SOCK_STREAM;
hints.ai_flags = AI_NUMERICSERV;
struct addrinfo* info = nullptr;
if (getaddrinfo (hostName.c_str(), std::to_string(portNumber).c_str(), &hints, &info) == 0)
return info;
return nullptr;
}
static bool connectSocket (std::atomic<int>& handle,
std::mutex& readLock,
const std::string& hostName,
int portNumber,
int timeOutMillisecs) noexcept
{
bool success = false;
if (auto* info = getAddressInfo (false, hostName, portNumber))
{
for (auto* i = info; i != nullptr; i = i->ai_next)
{
auto newHandle = socket (i->ai_family, i->ai_socktype, 0);
if (newHandle != invalidSocket)
{
setSocketBlockingState (newHandle, false);
auto result = ::connect (newHandle, i->ai_addr, (socklen_t) i->ai_addrlen);
success = (result >= 0);
if (! success)
{
#if JUCE_WINDOWS
if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
#else
if (errno == EINPROGRESS)
#endif
{
std::atomic<int> cvHandle { (int) newHandle };
if (waitForReadiness (cvHandle, readLock, false, timeOutMillisecs) == 1)
success = true;
}
}
if (success)
{
handle = (int) newHandle;
break;
}
#if JUCE_WINDOWS
closesocket (newHandle);
#else
::close (newHandle);
#endif
}
}
freeaddrinfo (info);
if (success)
{
auto h = (SocketHandle) handle.load();
setSocketBlockingState (h, true);
resetSocketOptions (h, false, false);
}
}
return success;
}
static void makeReusable (int handle) noexcept
{
setOption ((SocketHandle) handle, SO_REUSEADDR, (int) 1);
}
static bool multicast (int handle, const std::string& multicastIPAddress,
const std::string& interfaceIPAddress, bool join) noexcept
{
struct ip_mreq mreq;
memset ((void*) &mreq, 0, sizeof (mreq));
mreq.imr_multiaddr.s_addr = inet_addr (multicastIPAddress.c_str());
mreq.imr_interface.s_addr = INADDR_ANY;
if (! interfaceIPAddress.empty())
mreq.imr_interface.s_addr = inet_addr (interfaceIPAddress.c_str());
return setsockopt ((SocketHandle) handle, IPPROTO_IP,
join ? IP_ADD_MEMBERSHIP
: IP_DROP_MEMBERSHIP,
(const char*) &mreq, sizeof (mreq)) == 0;
}
}
//==============================================================================
//==============================================================================
UdpSocket::UdpSocket (bool canBroadcast)
{
SocketHelpers::initSockets();
handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
if (handle >= 0)
{
SocketHelpers::resetSocketOptions ((SocketHandle) handle.load(), true, canBroadcast);
SocketHelpers::makeReusable (handle);
}
}
UdpSocket::~UdpSocket()
{
if (lastServerAddress != nullptr)
freeaddrinfo (static_cast<struct addrinfo*> (lastServerAddress));
shutdown();
}
void UdpSocket::shutdown()
{
if (handle < 0)
return;
std::atomic<int> handleCopy { handle.load() };
handle = -1;
std::atomic<bool> connected { false };
SocketHelpers::closeSocket (handleCopy, readLock, false, 0, connected);
isBound = false;
}
bool UdpSocket::bindToPort (int port)
{
return bindToPort (port, std::string());
}
bool UdpSocket::bindToPort (int port, const std::string& addr)
{
assert (SocketHelpers::isValidPortNumber (port));
if (handle < 0)
return false;
if (SocketHelpers::bindSocket ((SocketHandle) handle.load(), port, addr))
{
isBound = true;
lastBindAddress = addr;
return true;
}
return false;
}
int UdpSocket::getBoundPort() const noexcept
{
return (handle >= 0 && isBound) ? SocketHelpers::getBoundPort ((SocketHandle) handle.load()) : -1;
}
//==============================================================================
int UdpSocket::waitUntilReady (bool readyForReading, int timeoutMsecs)
{
if (handle < 0)
return -1;
return SocketHelpers::waitForReadiness (handle, readLock, readyForReading, timeoutMsecs);
}
int UdpSocket::read (void* destBuffer, int maxBytesToRead, bool shouldBlock)
{
if (handle < 0 || ! isBound)
return -1;
std::atomic<bool> connected { true };
return SocketHelpers::readSocket ((SocketHandle) handle.load(), destBuffer, maxBytesToRead,
connected, shouldBlock, readLock);
}
int UdpSocket::read (void* destBuffer, int maxBytesToRead, bool shouldBlock, std::string& senderIPAddress, int& senderPort)
{
if (handle < 0 || ! isBound)
return -1;
std::atomic<bool> connected { true };
return SocketHelpers::readSocket ((SocketHandle) handle.load(), destBuffer, maxBytesToRead, connected,
shouldBlock, readLock, &senderIPAddress, &senderPort);
}
int UdpSocket::write (const std::string& remoteHostname, int remotePortNumber,
const void* sourceBuffer, int numBytesToWrite)
{
assert (SocketHelpers::isValidPortNumber (remotePortNumber));
if (handle < 0)
return -1;
struct addrinfo*& info = reinterpret_cast<struct addrinfo*&> (lastServerAddress);
// getaddrinfo can be quite slow so cache the result of the address lookup
if (info == nullptr || remoteHostname != lastServerHost || remotePortNumber != lastServerPort)
{
if (info != nullptr)
freeaddrinfo (info);
if ((info = SocketHelpers::getAddressInfo (true, remoteHostname, remotePortNumber)) == nullptr)
return -1;
lastServerHost = remoteHostname;
lastServerPort = remotePortNumber;
}
return (int) ::sendto ((SocketHandle) handle.load(), (const char*) sourceBuffer,
(juce_recvsend_size_t) numBytesToWrite, 0,
info->ai_addr, (socklen_t) info->ai_addrlen);
}
bool UdpSocket::joinMulticast (const std::string& multicastIPAddress)
{
if (handle < 0 || ! isBound)
return false;
return SocketHelpers::multicast (handle, multicastIPAddress, lastBindAddress, true);
}
bool UdpSocket::leaveMulticast (const std::string& multicastIPAddress)
{
if (handle < 0 || ! isBound)
return false;
return SocketHelpers::multicast (handle, multicastIPAddress, lastBindAddress, false);
}
bool UdpSocket::setMulticastLoopbackEnabled (bool enable)
{
if (handle < 0 || ! isBound)
return false;
return SocketHelpers::setOption<bool> ((SocketHandle) handle.load(), IPPROTO_IP, IP_MULTICAST_LOOP, enable);
}
bool UdpSocket::setEnablePortReuse (bool enabled)
{
#if JUCE_ANDROID
ignoreUnused (enabled);
#else
if (handle >= 0)
return SocketHelpers::setOption ((SocketHandle) handle.load(),
#if JUCE_WINDOWS || JUCE_LINUX
SO_REUSEADDR, // port re-use is implied by addr re-use on these platforms
#else
SO_REUSEPORT,
#endif
(int) (enabled ? 1 : 0));
#endif
return false;
}
| 30.83165 | 123 | 0.535656 | tommymitch |
b25ff5cd74f5ee15d3cb90431682eaf5b1863d50 | 2,106 | cpp | C++ | dialogeditpatient.cpp | kushagra10025/Hospital-Registration-Portal | a68cfcba95ddaecac2f1d959cc0c82df0415fc9d | [
"Apache-2.0"
] | null | null | null | dialogeditpatient.cpp | kushagra10025/Hospital-Registration-Portal | a68cfcba95ddaecac2f1d959cc0c82df0415fc9d | [
"Apache-2.0"
] | null | null | null | dialogeditpatient.cpp | kushagra10025/Hospital-Registration-Portal | a68cfcba95ddaecac2f1d959cc0c82df0415fc9d | [
"Apache-2.0"
] | null | null | null | #include "dialogeditpatient.h"
#include "ui_dialogeditpatient.h"
DialogEditPatient::DialogEditPatient(QSqlRecord *rowEdit, QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogEditPatient)
{
ui->setupUi(this);
rowToEdit = rowEdit;
ui->txt_fullname->setText(rowToEdit->value("p_fullname").toString());
ui->txt_pno->setText(rowToEdit->value("p_pno").toString());
ui->txt_address->setText(rowToEdit->value("p_address").toString());
ui->txt_age->setText(rowToEdit->value("p_age").toString());
if(rowToEdit->value("p_gender").toString() == "M"){
ui->rb_male->setChecked(true);
}else if(rowToEdit->value("p_gender").toString() == "F"){
ui->rb_female->setChecked(true);
}
ui->date_regdate->setDate(QDate::fromString(rowToEdit->value("p_regdate").toString()));
ui->lbl_gen_reg_no->setText(rowToEdit->value("reg_no").toString());
}
DialogEditPatient::~DialogEditPatient()
{
delete ui;
}
void DialogEditPatient::on_btn_cancel_clicked()
{
this->close();
}
void DialogEditPatient::on_btn_update_clicked()
{
std::vector<QString> inputs(rowToEdit->count());
inputs[0] = ui->lbl_gen_reg_no->text();
inputs[1] = ui->txt_fullname->toPlainText();
if(ui->rb_male->isChecked()){
inputs[2] = "M";
}else if(ui->rb_female->isChecked()){
inputs[2] = "F";
}
inputs[3] = ui->txt_pno->toPlainText();
inputs[4] = ui->txt_address->toPlainText();
inputs[5] = ui->txt_age->toPlainText();
inputs[6] = ui->date_regdate->date().toString();
if(inputs[0].isEmpty() || inputs[1].isEmpty() || inputs[2].isEmpty() || inputs[3].isEmpty() || inputs[4].isEmpty() || inputs[5].isEmpty() || inputs[6].isEmpty()){
QMessageBox::information(this,"Empty Field!","Please enter some value!!");
return;
}
int cols = rowToEdit->count();
for(int i = 0;i<cols;i++){
rowToEdit->setValue(i,inputs[i]);
}
// DO ERROR CHECKING FOR SQL RULES BEFORE EMITTING SIGNAL
emit signalReady();
this->close();
}
QString DialogEditPatient::getRegNo()
{
return p_reg_no;
}
| 29.661972 | 166 | 0.644349 | kushagra10025 |
b260658d6fd8cecd25042f15bb30f63917bcd7f6 | 5,024 | cpp | C++ | DynacoeSrc/srcs/Dynacoe/Component.cpp | jcorks/Dynacoe | 2d606620e8072d8ae76aa2ecdc31512ac90362d9 | [
"Apache-2.0",
"MIT",
"Libpng",
"FTL",
"BSD-3-Clause"
] | 1 | 2015-11-06T18:10:11.000Z | 2015-11-06T18:10:11.000Z | DynacoeSrc/srcs/Dynacoe/Component.cpp | jcorks/Dynacoe | 2d606620e8072d8ae76aa2ecdc31512ac90362d9 | [
"Apache-2.0",
"MIT",
"Libpng",
"FTL",
"BSD-3-Clause"
] | 8 | 2018-01-25T03:54:32.000Z | 2018-09-17T01:55:35.000Z | DynacoeSrc/srcs/Dynacoe/Component.cpp | jcorks/Dynacoe | 2d606620e8072d8ae76aa2ecdc31512ac90362d9 | [
"Apache-2.0",
"MIT",
"Libpng",
"FTL",
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2018, Johnathan Corkery. (jcorkery@umich.edu)
All rights reserved.
This file is part of the Dynacoe project (https://github.com/jcorks/Dynacoe)
Dynacoe was released under the MIT License, as detailed below.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall
be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Dynacoe/Component.h>
#include <Dynacoe/Modules/Console.h>
using namespace Dynacoe;
Component::Component(const std::string & tag_) {
tag = tag_;
host = nullptr;
draw = true;
step = true;
InstallEvent("on-attach");
InstallEvent("on-detach");
}
void Component::SetHost(Entity * h) {
host = h;
}
void Component::Draw() {
OnDraw();
}
void Component::Step() {
OnStep();
}
bool Component::EmitEvent(const std::string & ev, Entity::ID source, const std::vector<std::string> & args) {
auto eventHandlers = handlers.find(ev);
if (eventHandlers == handlers.end()) {
Dynacoe::Console::Error() << "Component " << GetTag() << " error: cannot perform unknown signal \"" << ev << "\"\n";
return false;
}
EventSet fns = eventHandlers->second;
bool retval = true;
for(int64_t i = fns.handlers.size()-1; i >= 0; --i) {
if (!fns.handlers[i].first(fns.handlers[i].second, this, GetHostID(), source, args)) {
retval = false;
break;
}
}
for(size_t i = 0; i < fns.hooks.size(); ++i) {
fns.hooks[i].first(fns.hooks[i].second, this, GetHostID(), source, args);
}
return retval;
}
bool Component::CanHandleEvent(const std::string & s) {
return handlers.find(s) != handlers.end();
}
void Component::InstallEvent(const std::string & name, EventHandler h, void * data) {
if (handlers.find(name) != handlers.end()) {
Dynacoe::Console::Error() << "Component " << GetTag() << " error: cannot install \"" << name << "\", event is already installed.\n";
return;
}
if (h)
handlers[name].handlers.push_back({h, data});
else
handlers[name] = EventSet();
}
void Component::UninstallEvent(const std::string & name) {
handlers.erase(name);
}
std::vector<std::string> Component::GetKnownEvents() const {
std::vector<std::string> out;
for(auto i = handlers.begin(); i != handlers.end(); ++i) {
out.push_back(i->first);
}
return out;
}
void Component::InstallHandler(const std::string & name, EventHandler h, void * data) {
auto fns = handlers.find(name);
if (fns == handlers.end()) {
Dynacoe::Console::Error() << "Component " << GetTag() << " error: cannot add handler for \"" << name << "\": event is not installed.\n";
return;
}
fns->second.handlers.push_back({h, data});
}
void Component::UninstallHandler(const std::string & name, EventHandler h) {
auto localHandlers = handlers.find(name);
if (localHandlers == handlers.end()) return;
for(size_t i = 0; i < localHandlers->second.handlers.size(); ++i) {
if (localHandlers->second.handlers[i].first == h) {
localHandlers->second.handlers.erase(localHandlers->second.handlers.begin()+i);
}
}
}
void Component::InstallHook(const std::string & name, EventHandler h, void * data) {
auto fns = handlers.find(name);
if (fns == handlers.end()) {
Dynacoe::Console::Error() << "Component: cannot add hook for \"" << name << "\": event is not installed.\n";
return;
}
fns->second.hooks.push_back({h, data});
}
void Component::UninstallHook(const std::string & name, EventHandler h) {
auto localHandlers = handlers.find(name);
if (localHandlers == handlers.end()) return;
for(size_t i = 0; i < localHandlers->second.hooks.size(); ++i) {
if (localHandlers->second.hooks[i].first == h) {
localHandlers->second.hooks.erase(localHandlers->second.hooks.begin()+i);
}
}
}
void * Component::operator new(std::size_t size) {
return new char[size];
}
void Component::operator delete(void * ptr) {
delete[] (char*) ptr;
}
| 27.453552 | 144 | 0.651274 | jcorks |
b260fa95c35385b9ce7c59135a7dfee0f719a385 | 1,598 | cpp | C++ | Lab1/lab1.cpp | toniminh161200/Computational-Mathematics | f7e1a7475d001fb654e14ea23393fe8838fcfb40 | [
"MIT"
] | null | null | null | Lab1/lab1.cpp | toniminh161200/Computational-Mathematics | f7e1a7475d001fb654e14ea23393fe8838fcfb40 | [
"MIT"
] | null | null | null | Lab1/lab1.cpp | toniminh161200/Computational-Mathematics | f7e1a7475d001fb654e14ea23393fe8838fcfb40 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
double rel_error_x, rel_error_y, abs_er_x = 0.5, abs_er_y = 0.1, x = 9, y = 7.5;
cout << "x = " << x << " y = " << y<<"\n";
rel_error_x = abs_er_x / x;
rel_error_y = abs_er_y / y;
cout << "x absError = " << abs_er_x << "\n";
cout << "y absError = " << abs_er_y << "\n";
cout << "x relError = " << rel_error_x << "\n";
cout << "y relError = " << rel_error_y << "\n";
cout << "Sum: 1\nDifferent: 2\nMultiplication: 3\nDivision: 4\n";
int checker = 1;
std::cin >> checker;
switch (checker) {
case(1):
cout << "x + y = " << x + y << "\n";
cout << "x + y absError = " << abs_er_x + abs_er_y << "\n";
cout << "x + y relError = " << (abs_er_x + abs_er_y) / (x + y) << "\n";
break;
case(2):
cout << "x - y = " << x - y << "\n";
cout << "x - y absError = " << abs_er_x + abs_er_y << "\n";
cout << "x - y relError = " << (abs_er_x + abs_er_y) / (x - y) << "\n";
break;
case(3):
cout << "x * y = " << x * y << "\n";
cout << "x * y absError = " << (rel_error_x + rel_error_y) * x * y << "\n";
cout << "x * y relError = " << rel_error_x + rel_error_y << "\n";
break;
case(4):
cout << "x * y = " << x / y << "\n";
cout << "x * y absError = " << (rel_error_x + rel_error_y) * x / y << "\n";
cout << "x * y relError = " << rel_error_x + rel_error_y << "\n";
break;
}
return 0;
}
| 38.97561 | 87 | 0.426158 | toniminh161200 |
b2682343bb267a9ded8bb4bd1d28561a0e3ec0bd | 2,259 | cpp | C++ | src/engine/object/pointgizmo.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | 2 | 2019-06-22T23:29:44.000Z | 2019-07-07T18:34:04.000Z | src/engine/object/pointgizmo.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | src/engine/object/pointgizmo.cpp | dream-overflow/o3d | 087ab870cc0fd9091974bb826e25c23903a1dde0 | [
"FSFAP"
] | null | null | null | /**
* @file pointgizmo.cpp
* @brief
* @author Frederic SCHERMA (frederic.scherma@dreamoverflow.org)
* @date 2005-04-15
* @copyright Copyright (c) 2001-2017 Dream Overflow. All rights reserved.
* @details
*/
#include "o3d/engine/precompiled.h"
#include "o3d/engine/object/pointgizmo.h"
#include "o3d/engine/scene/scene.h"
#include "o3d/engine/context.h"
#include "o3d/engine/matrix.h"
#include "o3d/engine/primitive/primitivemanager.h"
using namespace o3d;
O3D_IMPLEMENT_DYNAMIC_CLASS1(PointGizmo, ENGINE_GIZMO_POINT, Gizmo)
// Get the drawing type
UInt32 PointGizmo::getDrawType() const { return Scene::DRAW_POINT_GIZMO; }
/*---------------------------------------------------------------------------------------
Constructor
---------------------------------------------------------------------------------------*/
PointGizmo::PointGizmo(BaseObject *pParent) :
Gizmo(pParent)
{
m_dim[X] = m_dim[Y] = m_dim[X] = 0;
}
/*---------------------------------------------------------------------------------------
test if a point is inside the gizmo
---------------------------------------------------------------------------------------*/
Bool PointGizmo::isInside(Vector3 pos)
{
return False;
}
/*---------------------------------------------------------------------------------------
test if the gizmo is inside the frustrum view
---------------------------------------------------------------------------------------*/
Bool PointGizmo::frustrumClip()
{
return False;
}
/*---------------------------------------------------------------------------------------
draw the gizmo
---------------------------------------------------------------------------------------*/
void PointGizmo::draw(const DrawInfo &drawInfo)
{
if (!getActivity() || !getVisibility()) {
return;
}
if ((drawInfo.pass == DrawInfo::AMBIENT_PASS/*SymbolicPass*/) && getScene()->getDrawObject(Scene::DRAW_POINT_GIZMO)) {
setUpModelView();
PrimitiveAccess primitive = getScene()->getPrimitiveManager()->access(drawInfo);
if (getScene()->getDrawObject(Scene::DRAW_LOCAL_AXIS)) {
primitive->drawLocalAxis();
}
primitive->setColor(1.f,1.f,0.f);
primitive->draw(PrimitiveManager::WIRE_CUBE1, Vector3(0.2f,0.2f,0.2f));
}
}
| 31.375 | 122 | 0.486056 | dream-overflow |
05dd4f136b6f2a03a064d9f4807ddd1e0a30c738 | 1,154 | hpp | C++ | sprout/functional/hash/hash_fwd.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | 1 | 2020-02-04T05:16:01.000Z | 2020-02-04T05:16:01.000Z | sprout/functional/hash/hash_fwd.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | null | null | null | sprout/functional/hash/hash_fwd.hpp | osyo-manga/Sprout | 8885b115f739ef255530f772067475d3bc0dcef7 | [
"BSL-1.0"
] | null | null | null | #ifndef SPROUT_FUNCTIONAL_HASH_HASH_FWD_HPP
#define SPROUT_FUNCTIONAL_HASH_HASH_FWD_HPP
#include <cstddef>
#include <sprout/config.hpp>
namespace sprout {
//
// hash
//
template<typename T>
struct hash;
//
// to_hash
//
template<typename T>
SPROUT_CONSTEXPR std::size_t to_hash(T const& v);
//
// hash_combine
//
template<typename... Args>
inline SPROUT_CONSTEXPR std::size_t
hash_combine(std::size_t seed, Args const&... args);
//
// hash_values
//
template<typename... Args>
inline SPROUT_CONSTEXPR std::size_t
hash_values(Args const&... args);
//
// hash_range
//
template<typename Iterator>
SPROUT_CONSTEXPR std::size_t hash_range(std::size_t seed, Iterator first, Iterator last);
template<typename Iterator>
SPROUT_CONSTEXPR std::size_t hash_range(Iterator first, Iterator last);
template<typename InputRange>
SPROUT_CONSTEXPR std::size_t hash_range(std::size_t seed, InputRange const& rng);
template<typename InputRange>
SPROUT_CONSTEXPR std::size_t hash_range(InputRange const& rng);
} // namespace sprout
#endif // #ifndef SPROUT_FUNCTIONAL_HASH_HASH_FWD_HPP
| 24.041667 | 91 | 0.725303 | osyo-manga |
05e0ea795856e3acaa445c1fae7a13eca102cdc0 | 696 | cpp | C++ | NikolaevaElya/6sem/BTree/BubbleSort.cpp | soomrack/MR2020 | 2de7289665dcdac4a436eb512f283780aa78cb76 | [
"MIT"
] | 4 | 2020-09-22T12:04:07.000Z | 2020-10-03T22:28:00.000Z | NikolaevaElya/6sem/BTree/BubbleSort.cpp | soomrack/MR2020 | 2de7289665dcdac4a436eb512f283780aa78cb76 | [
"MIT"
] | null | null | null | NikolaevaElya/6sem/BTree/BubbleSort.cpp | soomrack/MR2020 | 2de7289665dcdac4a436eb512f283780aa78cb76 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int swap(int *first, int *second){
int temp = *first;
*first = *second;
*second = temp;
return 0;
}
int bubbleSort(int arr[], int size) {
for(int step = 0; step < size; step++) {
for (int i = 0; i < size - 1; i++) {
if(arr[i] > arr[i+1]) {
swap(arr[i], arr[i+1]);
}
}
}
return 0;
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
cout << " " << arr[i];
}
cout << "\n";
}
int main(){
int test[] = {-3, 9, 8, -34, 99, -1};
bubbleSort(test, 6);
printArray(test, 6);
return 0;
} | 18.315789 | 45 | 0.436782 | soomrack |
05e40718ecd5a940d241abb98072c4db399a5ed4 | 778 | cpp | C++ | Algorithms and Data Structures/Homework 2/testWindGauge.cpp | Tewodros00/CS-Jacobs | 5876decf6aa6f612dc5569e50e6e5a9eb768d78b | [
"MIT"
] | 4 | 2021-04-09T08:14:58.000Z | 2021-05-17T10:42:11.000Z | Algorithms and Data Structures/Homework 2/testWindGauge.cpp | Tewodros00/Jacobs-Coursework | 5876decf6aa6f612dc5569e50e6e5a9eb768d78b | [
"MIT"
] | null | null | null | Algorithms and Data Structures/Homework 2/testWindGauge.cpp | Tewodros00/Jacobs-Coursework | 5876decf6aa6f612dc5569e50e6e5a9eb768d78b | [
"MIT"
] | null | null | null | /*
CH-231-A
hw2_p3.cpp
Tewodros Adane
tadane@jacobs-university.de
*/
#include <iostream>
#include "WindGauge.h"
int main(void) {
WindGauge windGauge;
windGauge.currentWindSpeed(15);
windGauge.currentWindSpeed(16);
windGauge.currentWindSpeed(12);
windGauge.currentWindSpeed(15);
windGauge.currentWindSpeed(15);
windGauge.dump();
std::cout << std::endl;
windGauge.currentWindSpeed(16);
windGauge.currentWindSpeed(17);
windGauge.currentWindSpeed(16);
windGauge.currentWindSpeed(16);
windGauge.currentWindSpeed(20);
windGauge.currentWindSpeed(17);
windGauge.currentWindSpeed(16);
windGauge.currentWindSpeed(15);
windGauge.currentWindSpeed(16);
windGauge.currentWindSpeed(20);
windGauge.dump();
} | 21.611111 | 35 | 0.717224 | Tewodros00 |
05ee5baff090193d40457f3b0c6e68113fa56a81 | 3,056 | cpp | C++ | samples/cps3_test/src/main.cpp | clusterpoint/cpp-client-api | 605825f0d46678c1ebdabb006bc0c138e4b0b7f3 | [
"MIT"
] | 1 | 2015-09-22T10:32:36.000Z | 2015-09-22T10:32:36.000Z | samples/cps3_test/src/main.cpp | clusterpoint/cpp-client-api | 605825f0d46678c1ebdabb006bc0c138e4b0b7f3 | [
"MIT"
] | null | null | null | samples/cps3_test/src/main.cpp | clusterpoint/cpp-client-api | 605825f0d46678c1ebdabb006bc0c138e4b0b7f3 | [
"MIT"
] | null | null | null | #include "cps/CPS_API.hpp"
#include "TestSuite.hpp"
#include "Utils.hpp"
#include <boost/program_options.hpp>
#include <iostream>
#include <cstdlib>
#include <memory>
#include <vector>
int main(int argc, char* argv[])
{
int result = EXIT_FAILURE;
try
{
namespace po = boost::program_options;
po::options_description desc("Options");
desc.add_options()
("help,h", "Print this help message")
("host,c", po::value<std::string>(), "Clusterpoint host URL")
("db,d", po::value<std::string>(), "Clusterpoint database name")
("account,a", po::value<std::string>(), "Clusterpoint account id")
("user,u", po::value<std::string>(), "User name")
("password,p", po::value<std::string>(), "User password");
po::variables_map vm;
std::vector<std::string> additionalParameters;
po::parsed_options parsed = po::command_line_parser(argc, argv).
options(desc).allow_unregistered().run();
po::store(parsed, vm);
// Handle --help option
if (vm.count("help"))
{
std::cout << "Clusterpoint test app" << std::endl
<< desc
<< std::endl;
return EXIT_SUCCESS;
}
additionalParameters = po::collect_unrecognized(parsed.options,
po::include_positional);
po::notify(vm);
if (!additionalParameters.empty())
{
throw std::runtime_error(std::string("Unrecognized option: ") + additionalParameters[0]);
}
if (!vm.count("host"))
{
throw std::runtime_error("Clusterpoint host URL must be provided");
}
if (!vm.count("db"))
{
throw std::runtime_error("Clusterpoint database name must be provided");
}
if (!vm.count("user"))
{
throw std::runtime_error("User name must be provided");
}
if (!vm.count("password"))
{
throw std::runtime_error("User password must be provided");
}
if (!vm.count("account"))
{
throw std::runtime_error("Account Id must be provided");
}
std::map<std::string, std::string> account_info;
account_info["account"] = vm["account"].as<std::string>();
std::unique_ptr<CPS::Connection> conn(new CPS::Connection(
vm["host"].as<std::string>(),
vm["db"].as<std::string>(),
vm["user"].as<std::string>(),
vm["password"].as<std::string>(),
"document",
"document/id",
account_info));
conn->setDebug(true);
conn->setSocketTimeouts(10, 60, 180);
TestSuite(*conn).run();
result = EXIT_SUCCESS;
}
catch (CPS::Exception& e)
{
if (e.getResponse())
{
// Print out errors and related document ids
print_errors(std::cout, e.getResponse()->getErrors());
}
std::cerr << e.what() << std::endl;
std::cerr << boost::diagnostic_information(e) << std::endl;
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
std::cerr << boost::diagnostic_information(e) << std::endl;
}
catch (...)
{
std::cerr << "Unhandled exception" << std::endl;
}
return result;
}
| 28.296296 | 95 | 0.595223 | clusterpoint |
05f2c5582d1dd4cd06d7339dfb96706035fe4b0e | 3,659 | cpp | C++ | src/chip/alu/alu.cpp | txf0990/LogicSimulator | 9e384b9859ab01b8b0634a75d6698dab2f75d8be | [
"MIT"
] | null | null | null | src/chip/alu/alu.cpp | txf0990/LogicSimulator | 9e384b9859ab01b8b0634a75d6698dab2f75d8be | [
"MIT"
] | null | null | null | src/chip/alu/alu.cpp | txf0990/LogicSimulator | 9e384b9859ab01b8b0634a75d6698dab2f75d8be | [
"MIT"
] | null | null | null | #include "chip/alu/alu.h"
#include "chip/adder.h"
#include "chip/left_shifter.h"
#include "chip/logic_cal.h"
#include "chip/mux.h"
#include "pin_board/pin_board.h"
#include "chip/right_shifter.h"
#include <cassert>
#include <iostream>
namespace chip {
using pin_board::PinBoard;
using pin_board::PinIndex;
using std::vector;
void Alu::CreateChip(
pin_board::PinBoard& board,
const std::vector<PinIndex>& input1_pins,
const std::vector<PinIndex>& input2_pins,
const std::vector<PinIndex>& shamt,
const std::vector<PinIndex>& func,
const std::vector<PinIndex>& output_pins) {
assert(input1_pins.size() == 32);
assert(input2_pins.size() == 32);
assert(shamt.size() == 5);
assert(func.size() == 4);
assert(output_pins.size() == 32);
AluInternalPins p;
// Setup Input and Output
p.a = input1_pins;
p.b = input2_pins;
p.shamt = shamt;
p.func = func;
p.output = output_pins;
Alu::AllocatePins(board, p);
}
void Alu::AllocatePins(PinBoard& board, AluInternalPins& p) {
// Allocate pins for alu
p.add_minus_output = board.AllocatePins(32);
p.bitwise_output = board.AllocatePins(32);
p.shift_output = board.AllocatePins(32);
p.shift_replace = board.AllocatePin();
p.shift_replace_value = board.AllocatePin();
p.shift_pre_output = board.AllocatePins(32);
p.shift_num = board.AllocatePins(32);
}
void Alu::CalculateAddMinus(
pin_board::PinBoard& board,
AluInternalPins p) {
auto xor_output = board.AllocatePins(32);
std::vector<PinIndex> f1_32(32, p.func[1]);
BitwiseChip<XorGate>::CreateChip(board, p.b, f1_32, xor_output);
auto adder_output = p.add_minus_output;
adder_output.push_back(board.AllocatePin());
chip::Adder_2::CreateChip(board, p.a, xor_output, p.func[1], adder_output);
}
void Alu::CalculateBitwise(
pin_board::PinBoard& board,
AluInternalPins p) {
auto and_or_output = board.AllocatePins(32);
auto and_output = board.AllocatePins(32);
auto or_output = board.AllocatePins(32);
Mux::CreateChip(board, and_output, or_output, p.func[0], and_or_output);
BitwiseChip<AndGate>::CreateChip(board, p.a, p.b, and_output);
BitwiseChip<OrGate>::CreateChip(board, p.a, p.b, or_output);
auto xor_nor_output = board.AllocatePins(32);
auto xor_output = board.AllocatePins(32);
auto nor_output = board.AllocatePins(32);
Mux::CreateChip(board, xor_output, nor_output, p.func[0], xor_nor_output);
BitwiseChip<XorGate>::CreateChip(board, p.a, p.b, xor_output);
BitwiseChip<NorGate>::CreateChip(board, p.a, p.b, nor_output);
Mux::CreateChip(board, and_or_output, xor_nor_output, p.func[1], p.bitwise_output);
}
void Alu::CalculateShift(
pin_board::PinBoard& board,
AluInternalPins p) {
vector<PinIndex> shift_5_bit = board.AllocatePins(5);
Mux::CreateChip(board, p.shamt, {p.a[0],p.a[1],p.a[2],p.a[3],p.a[4]}, p.func[2], shift_5_bit);
PinIndex shift_complement_value = board.AllocatePin();
AndGate::CreateChip(board, {p.func[0], p.b[31]}, {shift_complement_value});
vector<PinIndex> left_shifter_result_32_bit = board.AllocatePins(32);
vector<PinIndex> right_shifter_result_32_bit = board.AllocatePins(32);
chip::LeftShifter32::CreateChip(
board,
p.b,
shift_5_bit,
left_shifter_result_32_bit);
chip::RightShifter32::CreateChip(
board,
p.b,
shift_5_bit,
shift_complement_value,
right_shifter_result_32_bit);
Mux::CreateChip(
board,
left_shifter_result_32_bit,
right_shifter_result_32_bit,
p.func[1],
p.shift_output);
}
void Alu::CalculateOutput(
pin_board::PinBoard& board,
AluInternalPins p) {
}
} // namespace chip
| 30.491667 | 96 | 0.708937 | txf0990 |
05fe637957b51e85a5e8921486dab2036fe8d65c | 276 | hpp | C++ | include/HashSearcher.hpp | Lasar1k/LAB_07_multi | 733740aa679a8a3e626b348bbb734daa567daf57 | [
"MIT"
] | null | null | null | include/HashSearcher.hpp | Lasar1k/LAB_07_multi | 733740aa679a8a3e626b348bbb734daa567daf57 | [
"MIT"
] | null | null | null | include/HashSearcher.hpp | Lasar1k/LAB_07_multi | 733740aa679a8a3e626b348bbb734daa567daf57 | [
"MIT"
] | null | null | null | // Copyright 2021 Lasar1k <alf.ivan2002@gmail.com>
#ifndef INCLUDE_HASHSEARCHER_HPP_
#define INCLUDE_HASHSEARCHER_HPP_
#include <picosha2.h>
#include <boost/log/trivial.hpp>
class HashSearcher {
public:
static void SearchHash();
};
#endif // INCLUDE_HASHSEARCHER_HPP_
| 18.4 | 50 | 0.778986 | Lasar1k |
af00e7df727b54fd6c66b795353a82f5a03bf36f | 6,210 | hpp | C++ | test/TypeParser.hpp | scrossuk/llvm-abi | bad12c7cb1cdd271cd8804d1ace1b5d1799a2908 | [
"MIT"
] | 29 | 2016-11-14T15:58:23.000Z | 2022-01-07T13:05:39.000Z | test/TypeParser.hpp | scrossuk/llvm-abi | bad12c7cb1cdd271cd8804d1ace1b5d1799a2908 | [
"MIT"
] | null | null | null | test/TypeParser.hpp | scrossuk/llvm-abi | bad12c7cb1cdd271cd8804d1ace1b5d1799a2908 | [
"MIT"
] | 4 | 2017-12-03T15:51:24.000Z | 2020-07-31T23:32:27.000Z | #ifndef TYPEPARSER_HPP
#define TYPEPARSER_HPP
#include <string>
#include <llvm/ADT/SmallVector.h>
#include <llvm-abi/FunctionType.hpp>
#include <llvm-abi/Type.hpp>
#include <llvm-abi/TypeBuilder.hpp>
#include "TestFunctionType.hpp"
#include "TokenStream.hpp"
namespace llvm_abi {
class TypeParser {
public:
TypeParser(TokenStream& stream)
: stream_(stream) { }
std::string parseString() {
std::string text;
while (true) {
const auto next = stream_.peek();
if ((next >= 'a' && next <= 'z') ||
(next >= 'A' && next <= 'Z') ||
(next >= '0' && next <= '9')) {
text += next;
stream_.consumeOne();
} else {
break;
}
}
stream_.consumeWhitespace();
return text;
}
Type parseNamedType() {
const auto text = parseString();
assert(!text.empty());
if (text == "struct") {
return parseNamedStructType();
} else if (text == "union") {
return parseNamedUnionType();
}
if (text == "void") {
return VoidTy;
} else if (text == "ptr") {
return PointerTy;
} else if (text == "bool") {
return BoolTy;
} else if (text == "char") {
return CharTy;
} else if (text == "schar") {
return SCharTy;
} else if (text == "uchar") {
return UCharTy;
} else if (text == "short") {
return ShortTy;
} else if (text == "ushort") {
return UShortTy;
} else if (text == "int") {
return IntTy;
} else if (text == "uint") {
return UIntTy;
} else if (text == "long") {
return LongTy;
} else if (text == "ulong") {
return ULongTy;
} else if (text == "longlong") {
return LongLongTy;
} else if (text == "ulonglong") {
return ULongLongTy;
} else if (text == "float") {
return FloatTy;
} else if (text == "double") {
return DoubleTy;
} else if (text == "longdouble") {
return LongDoubleTy;
} else {
throw std::runtime_error(std::string("Unknown type '") + text + "'.");
}
}
Type parseNamedStructType() {
std::string name;
if (stream_.peek() != '{') {
name = parseString();
assert(!name.empty());
}
return parseStructType(std::move(name));
}
Type parseStructType(std::string name="") {
stream_.expect('{');
stream_.consume();
llvm::SmallVector<Type, 8> types;
while (stream_.peek() != '}') {
types.push_back(parseType());
stream_.expectAny({',', '}'});
if (stream_.peek() == ',') {
stream_.consume();
}
}
stream_.expect('}');
stream_.consume();
return typeBuilder_.getStructTy(types, std::move(name));
}
Type parseNamedUnionType() {
std::string name;
if (stream_.peek() != '{') {
name = parseString();
assert(!name.empty());
}
return parseUnionType(std::move(name));
}
Type parseUnionType(std::string name="") {
stream_.expect('{');
stream_.consume();
llvm::SmallVector<Type, 8> types;
while (stream_.peek() != '}') {
types.push_back(parseType());
stream_.expectAny({',', '}'});
if (stream_.peek() == ',') {
stream_.consume();
}
}
stream_.expect('}');
stream_.consume();
return typeBuilder_.getUnionTy(types, std::move(name));
}
std::string parseIntString() {
std::string text;
while (true) {
const auto next = stream_.peek();
if (next >= '0' && next <= '9') {
text += next;
stream_.consume();
} else {
break;
}
}
assert(!text.empty());
return text;
}
int parseInt() {
return atoi(parseIntString().c_str());
}
Type parseVectorType() {
stream_.expect('<');
stream_.consume();
const auto numElements = parseInt();
stream_.expect('x');
stream_.consume();
const auto elementType = parseType();
stream_.expect('>');
stream_.consume();
return typeBuilder_.getVectorTy(numElements, elementType);
}
Type parseArrayType() {
stream_.expect('[');
stream_.consume();
const auto numElements = parseInt();
stream_.expect('x');
stream_.consume();
const auto elementType = parseType();
stream_.expect(']');
stream_.consume();
return typeBuilder_.getArrayTy(numElements, elementType);
}
Type parseType() {
const auto next = stream_.peek();
if (next == '{') {
// Struct type.
return parseStructType();
} else if (next == '<') {
// Vector type.
return parseVectorType();
} else if (next == '[') {
// Array type.
return parseArrayType();
} else if (next >= 'a' && next <= 'z') {
// Named type.
return parseNamedType();
} else {
throw std::runtime_error("Invalid type string.");
}
}
llvm::SmallVector<Type, 8> parseVarArgsTypes() {
stream_.expect('.');
stream_.consume();
stream_.expect('.');
stream_.consume();
stream_.expect('.');
stream_.consume();
stream_.expect('(');
stream_.consume();
llvm::SmallVector<Type, 8> varArgsTypes;
while (stream_.peek() != ')') {
varArgsTypes.push_back(parseType());
stream_.expectAny({',', ')'});
if (stream_.peek() == ',') {
stream_.consume();
}
}
stream_.expect(')');
stream_.consume();
return varArgsTypes;
}
TestFunctionType parseFunctionType() {
const auto returnType = parseType();
stream_.expect('(');
stream_.consume();
llvm::SmallVector<Type, 8> argumentTypes;
while (stream_.peek() != ')' && stream_.peek() != '.') {
argumentTypes.push_back(parseType());
stream_.expectAny({',', ')'});
if (stream_.peek() == ',') {
stream_.consume();
}
}
llvm::SmallVector<Type, 8> varArgsTypes;
const bool isVarArg = (stream_.peek() == '.');
if (isVarArg) {
varArgsTypes = parseVarArgsTypes();
}
stream_.expect(')');
stream_.consume();
return TestFunctionType(FunctionType(CC_CDefault,
returnType,
argumentTypes,
isVarArg),
varArgsTypes);
}
private:
TokenStream& stream_;
TypeBuilder typeBuilder_;
};
}
#endif | 21.413793 | 74 | 0.555233 | scrossuk |
af0d0e1c092f5078afc63a76baac4e6604ed61b1 | 925 | cpp | C++ | data-plane/http1/source/ESHttpServerCommandSocket.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | data-plane/http1/source/ESHttpServerCommandSocket.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | data-plane/http1/source/ESHttpServerCommandSocket.cpp | duderino/everscale | 38388289dcce869852680a167f3dcb7e090d851c | [
"Apache-2.0"
] | null | null | null | #ifndef ES_HTTP_SERVER_COMMAND_SOCKET_H
#include <ESHttpServerCommandSocket.h>
#endif
namespace ES {
HttpServerCommandSocket::HttpServerCommandSocket(const char *namePrefix, HttpMultiplexerExtended &stack)
: HttpCommandSocket(namePrefix), _multiplexer(stack) {}
HttpServerCommandSocket::~HttpServerCommandSocket() {}
// This code runs in any thread
ESB::Error HttpServerCommandSocket::push(HttpServerCommand *command) { return pushInternal(command); }
ESB::Error HttpServerCommandSocket::runCommand(ESB::EmbeddedListElement *element) {
HttpServerCommand *command = (HttpServerCommand *)element;
ESB_LOG_DEBUG("[%s] executing command '%s'", name(), ESB_SAFE_STR(command->name()));
ESB::Error error = command->run(_multiplexer);
if (ESB_SUCCESS != error) {
ESB_LOG_WARNING_ERRNO(error, "[%s] cannot execute command '%s", name(), ESB_SAFE_STR(command->name()));
}
return error;
}
} // namespace ES
| 31.896552 | 107 | 0.758919 | duderino |
af133fe8f324e21dd72b65c0f900f95fddc897e9 | 2,310 | cpp | C++ | Source/AllProjects/Installer/CQCInst/CQCInst_SecurityPanel.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 51 | 2020-12-26T18:17:16.000Z | 2022-03-15T04:29:35.000Z | Source/AllProjects/Installer/CQCInst/CQCInst_SecurityPanel.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | null | null | null | Source/AllProjects/Installer/CQCInst/CQCInst_SecurityPanel.cpp | MarkStega/CQC | c1d0e01ec2abcaa5b8eb1899b9f0522fecee4b07 | [
"MIT"
] | 4 | 2020-12-28T07:24:39.000Z | 2021-12-29T12:09:37.000Z | //
// FILE NAME: CQCInst_SecurityPanel.cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 10/30/2004
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2020
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file implements the info panel that shows the user a reminder about
// security concerns.
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CQCInst.hpp"
// ---------------------------------------------------------------------------
// Magic macros
// ---------------------------------------------------------------------------
RTTIDecls(TInstSecurityPanel,TInstInfoPanel)
// ---------------------------------------------------------------------------
// CLASS: TInstSecurityPanel
// PREFIX: pan
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// TInstSecurityPanel: Constructors and Destructor
// ---------------------------------------------------------------------------
TInstSecurityPanel::TInstSecurityPanel( TCQCInstallInfo* const pinfoCur
, TMainFrameWnd* const pwndParent) :
TInstInfoPanel(L"Summary", pinfoCur, pwndParent)
, m_pwndText(nullptr)
{
}
TInstSecurityPanel::~TInstSecurityPanel()
{
}
// ---------------------------------------------------------------------------
// TInstSecurityPanel: Protected, inherited methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean TInstSecurityPanel::bCreated()
{
// Load up our controls
LoadDlgItems(kCQCInst::ridPan_Security);
// Get some pointers to the ones we want to interact with
CastChildWnd(*this, kCQCInst::ridPan_Secure_Text, m_pwndText);
return kCIDLib::True;
}
tCIDLib::TBoolean TInstSecurityPanel::bPanelIsVisible() const
{
// We are only visible if the install succeeded
return infoCur().eInstStatus() == tCQCInst::EInstStatus::Done;
}
| 28.170732 | 78 | 0.461039 | MarkStega |
af138497c991683194db1a8fd80305d58989137e | 8,869 | cpp | C++ | src/Output/Output_BasePowerSpectrum.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 3 | 2019-04-13T02:08:01.000Z | 2020-11-17T12:45:37.000Z | src/Output/Output_BasePowerSpectrum.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | null | null | null | src/Output/Output_BasePowerSpectrum.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 2 | 2019-11-12T02:00:20.000Z | 2019-12-09T14:52:31.000Z |
#include "DAINO.h"
#ifdef GRAVITY
#ifndef DENS
#error : ERROR : variable "DENS" is NOT defined in the function Output_BasePowerSpectrum !!
#endif
//output the dimensionless power spectrum
//#define DIMENSIONLESS_FORM
extern void GetBasePowerSpectrum( real *RhoK, const int j_start, const int dj, const int RhoK_Size, real *PS_total );
#ifdef SERIAL
extern rfftwnd_plan FFTW_Plan, FFTW_Plan_Inv;
#else
extern rfftwnd_mpi_plan FFTW_Plan, FFTW_Plan_Inv;
#endif
//-------------------------------------------------------------------------------------------------------
// Function : Output_BasePowerSpectrum
// Description : Evaluate and output the base-level power spectrum by FFT
//
// Parameter : FileName : Name of the output file
//-------------------------------------------------------------------------------------------------------
void Output_BasePowerSpectrum( const char *FileName )
{
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s (DumpID = %d) ...\n", __FUNCTION__, DumpID );
// 1. get the array indices using by FFTW
const int Nx_Padded = NX0_TOT[0]/2+1;
int local_nz, local_z_start, local_ny_after_transpose, local_y_start_after_transpose, total_local_size;
# ifdef SERIAL
local_ny_after_transpose = NULL_INT;
local_y_start_after_transpose = NULL_INT;
total_local_size = 2*Nx_Padded*NX0_TOT[1]*NX0_TOT[2];
# else
rfftwnd_mpi_local_sizes( FFTW_Plan, &local_nz, &local_z_start, &local_ny_after_transpose,
&local_y_start_after_transpose, &total_local_size);
# endif
// 2. allocate memory
real *PS_total = NULL;
real *RhoK = new real [ total_local_size ];
real *SendBuf = new real [ patch->NPatchComma[0][1]*PS1*PS1*PS1 ];
# ifdef SERIAL
real *RecvBuf = SendBuf;
# else
real *RecvBuf = new real [ NX0_TOT[0]*NX0_TOT[1]*local_nz ];
# endif
# ifdef LOAD_BALANCE
long *SendBuf_SIdx = new long [ patch->NPatchComma[0][1]*PS1 ]; // Sending MPI buffer of 1D coordinate in slab
long *RecvBuf_SIdx = new long [ NX0_TOT[0]*NX0_TOT[1]*local_nz/PS1/PS1 ];
int *List_PID [MPI_NRank]; // PID of each patch slice sent to each rank
int *List_k [MPI_NRank]; // local z coordinate of each patch slice sent to each rank
int List_NSend [MPI_NRank]; // size of data (density/potential) sent to each rank
int List_NRecv [MPI_NRank]; // size of data (density/potential) received from each rank
int List_nz [MPI_NRank]; // slab thickness of each rank in the FFTW slab decomposition
int List_z_start[MPI_NRank+1]; // starting z coordinate of each rank in the FFTW slab decomposition
// collect "local_nz" from all ranks and set the corresponding list "List_z_start"
MPI_Allgather( &local_nz, 1, MPI_INT, List_nz, 1, MPI_INT, MPI_COMM_WORLD );
List_z_start[0] = 0;
for (int r=0; r<MPI_NRank; r++) List_z_start[r+1] = List_z_start[r] + List_nz[r];
if ( List_z_start[MPI_NRank] != NX0_TOT[2] )
Aux_Error( ERROR_INFO, "List_z_start[%d] (%d) != expectation (%d) !!\n",
MPI_NRank, List_z_start[MPI_NRank], NX0_TOT[2] );
# endif // #ifdef LOAD_BALANCE
if ( MPI_Rank == 0 ) PS_total = new real [Nx_Padded];
// 3. rearrange data from cube to slice (or space-filling curve decomposition if load-balance is enabled)
# ifdef LOAD_BALANCE
LB_SFC_to_Slice( RhoK, SendBuf, RecvBuf, SendBuf_SIdx, RecvBuf_SIdx, List_PID, List_k, List_NSend, List_NRecv,
List_z_start, local_nz );
# else
Cube_to_Slice( RhoK, SendBuf, RecvBuf );
# endif
// 4. evaluate the base-level power spectrum by FFT
GetBasePowerSpectrum( RhoK, local_y_start_after_transpose, local_ny_after_transpose, total_local_size, PS_total );
// 5. output the power spectrum
if ( MPI_Rank == 0 )
{
// check if the targeted file already exists
FILE *File_Check = fopen( FileName, "r" );
if ( File_Check != NULL )
{
Aux_Message( stderr, "WARNING : the file \"%s\" already exists and will be overwritten !!\n", FileName );
fclose( File_Check );
}
// output the power spectrum
const real WaveK0 = 2.0*M_PI/patch->BoxSize[0];
FILE *File = fopen( FileName, "w" );
fprintf( File, "%13s%4s%13s\n", "k", "", "Power" );
for (int b=0; b<Nx_Padded; b++) fprintf( File, "%13.6e%4s%13.6e\n", WaveK0*b, "", PS_total[b] );
fclose( File );
} // if ( MPI_Rank == 0 )
// 6. free memory
delete [] RhoK;
delete [] SendBuf;
# ifndef SERIAL
delete [] RecvBuf;
# endif
# ifdef LOAD_BALANCE
delete [] SendBuf_SIdx;
delete [] RecvBuf_SIdx;
# endif
if ( MPI_Rank == 0 ) delete [] PS_total;
if ( MPI_Rank == 0 ) Aux_Message( stdout, "%s (DumpID = %d) ... done\n", __FUNCTION__, DumpID );
} // FUNCTION : Output_BasePowerSpectrum
//-------------------------------------------------------------------------------------------------------
// Function : GetBasePowerSpectrum
// Description : Evaluate and base-level power spectrum by FFT
//
// Note : Invoked by the function "Output_BasePowerSpectrum"
//
// Parameter : RhoK : Array storing the input density and output potential
// j_start : Starting j index
// dj : Size of array in the j (y) direction after the forward FFT
// RhoK_Size : Size of the array "RhoK"
// PS_total : Power spectrum summed over all MPI ranks
//
// Return : PS_total
//-------------------------------------------------------------------------------------------------------
void GetBasePowerSpectrum( real *RhoK, const int j_start, const int dj, const int RhoK_Size, real *PS_total )
{
// check
if ( MPI_Rank == 0 && PS_total == NULL ) Aux_Error( ERROR_INFO, "PS_total == NULL at the root rank !!\n" );
const int Nx = NX0_TOT[0];
const int Ny = NX0_TOT[1];
const int Nz = NX0_TOT[2];
const int Nx_Padded = Nx/2 + 1;
fftw_complex *cdata=NULL;
real PS_local[Nx_Padded];
long Count_local[Nx_Padded], Count_total[Nx_Padded];
int bin, bin_i[Nx_Padded], bin_j[Ny], bin_k[Nz];
// forward FFT
# ifdef SERIAL
rfftwnd_one_real_to_complex( FFTW_Plan, RhoK, NULL );
# else
rfftwnd_mpi( FFTW_Plan, 1, RhoK, NULL, FFTW_TRANSPOSED_ORDER );
# endif
// the data are now complex, so typecast a pointer
cdata = (fftw_complex*) RhoK;
// set up the dimensionless wave number coefficients according to the FFTW data format
for (int i=0; i<Nx_Padded; i++) bin_i[i] = i;
for (int j=0; j<Ny; j++) bin_j[j] = ( j <= Ny/2 ) ? j : j-Ny;
for (int k=0; k<Nz; k++) bin_k[k] = ( k <= Nz/2 ) ? k : k-Nz;
// estimate the power spectrum
int Idx;
for (int b=0; b<Nx_Padded; b++)
{
PS_local [b] = (real)0.0;
Count_local[b] = 0;
}
# ifdef SERIAL // serial mode
for (int k=0; k<Nz; k++)
{
for (int j=0; j<Ny; j++)
for (int i=0; i<Nx_Padded; i++)
{
Idx = (k*Ny + j)*Nx_Padded + i;
# else // parallel mode
int j;
for (int jj=0; jj<dj; jj++)
{
j = j_start + jj;
for (int k=0; k<Nz; k++)
for (int i=0; i<Nx_Padded; i++)
{
Idx = (jj*Nz + k)*Nx_Padded + i;
# endif // #ifdef SERIAL ... else ...
bin = int( SQRT( real( SQR(bin_i[i]) + SQR(bin_j[j]) + SQR(bin_k[k]) ) ) );
if ( bin < Nx_Padded )
{
PS_local [bin] += SQR( cdata[Idx].re ) + SQR( cdata[Idx].im );
Count_local[bin] ++;
}
} // i,j,k
} // i,j,k
// sum over all ranks
# ifdef FLOAT8
MPI_Reduce( PS_local, PS_total, Nx_Padded, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD );
# else
MPI_Reduce( PS_local, PS_total, Nx_Padded, MPI_FLOAT, MPI_SUM, 0, MPI_COMM_WORLD );
# endif
MPI_Reduce( Count_local, Count_total, Nx_Padded, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD );
// normalization: SQR(AveRho) accounts for Delta=Rho/AveRho
const real Coeff = patch->BoxSize[0]*patch->BoxSize[1]*patch->BoxSize[2] / SQR( (real)Nx*(real)Ny*(real)Nz*AveDensity );
real Norm;
# ifdef DIMENSIONLESS_FORM
const real k0 = (real)2.0*M_PI/patch->BoxSize[0]; // assuming cubic box
real WaveK;
# endif
if ( MPI_Rank == 0 )
{
for (int b=0; b<Nx_Padded; b++)
{
// average
PS_total[b] /= (real)Count_total[b];
// normalization
# ifdef DIMENSIONLESS_FORM
WaveK = b*k0;
Norm = Coeff*CUBE(WaveK)/(2.0*M_PI*M_PI); // dimensionless power spectrum
# else
Norm = Coeff; // dimensional power spectrum [Mpc^3/h^3]
# endif
PS_total[b] *= Norm;
}
}
} // FUNCTION : GetBasePowerSpectrum
#endif // #ifdef GRAVITY
| 32.018051 | 123 | 0.590709 | zhulianhua |
af16904532e64e5b1232c277a83137357adf44b3 | 893 | cpp | C++ | src/mgard-x/RuntimeX/DeviceAdapters/DeviceAdapterSerial.cpp | JieyangChen7/MGARD | acec8facae1e2767a3adff2bb3c30f3477e69bdb | [
"Apache-2.0"
] | null | null | null | src/mgard-x/RuntimeX/DeviceAdapters/DeviceAdapterSerial.cpp | JieyangChen7/MGARD | acec8facae1e2767a3adff2bb3c30f3477e69bdb | [
"Apache-2.0"
] | null | null | null | src/mgard-x/RuntimeX/DeviceAdapters/DeviceAdapterSerial.cpp | JieyangChen7/MGARD | acec8facae1e2767a3adff2bb3c30f3477e69bdb | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2022, Oak Ridge National Laboratory.
* MGARD-X: MultiGrid Adaptive Reduction of Data Portable across GPUs and CPUs
* Author: Jieyang Chen (chenj3@ornl.gov)
* Date: March 17, 2022
*/
#include "mgard-x/RuntimeX/RuntimeX.h"
namespace mgard_x {
int DeviceRuntime<SERIAL>::curr_dev_id = 0;
DeviceQueues<SERIAL> DeviceRuntime<SERIAL>::queues;
DeviceSpecification<SERIAL> DeviceRuntime<SERIAL>::DeviceSpecs;
bool DeviceRuntime<SERIAL>::SyncAllKernelsAndCheckErrors = false;
bool MemoryManager<SERIAL>::ReduceMemoryFootprint = false;
bool DeviceRuntime<SERIAL>::TimingAllKernels = false;
bool DeviceRuntime<SERIAL>::PrintKernelConfig = false;
AutoTuningTable<SERIAL> AutoTuner<SERIAL>::autoTuningTable;
bool AutoTuner<SERIAL>::ProfileKernels = false;
template <> bool deviceAvailable<SERIAL>() {
return DeviceRuntime<SERIAL>::GetDeviceCount() > 0;
}
} // namespace mgard_x | 31.892857 | 78 | 0.780515 | JieyangChen7 |
af19a8563704a530c787b974aa3af7a00b323695 | 679 | cpp | C++ | src/dna/DNAVisGroup.cpp | DarthNihilus1/OTP-Server | 8a98d20f0b16689cc116e1eee4b44e659a75e9b2 | [
"BSD-3-Clause"
] | 1 | 2022-01-18T17:17:43.000Z | 2022-01-18T17:17:43.000Z | src/dna/DNAVisGroup.cpp | DarthNihilus1/OTP-Server | 8a98d20f0b16689cc116e1eee4b44e659a75e9b2 | [
"BSD-3-Clause"
] | null | null | null | src/dna/DNAVisGroup.cpp | DarthNihilus1/OTP-Server | 8a98d20f0b16689cc116e1eee4b44e659a75e9b2 | [
"BSD-3-Clause"
] | 1 | 2022-01-31T22:07:19.000Z | 2022-01-31T22:07:19.000Z | #include "DNAVisGroup.h"
DNAVisGroup::DNAVisGroup(const std::string& name): DNAGroup(name)
{
m_vis_group = this;
}
DNAVisGroup::~DNAVisGroup()
{
}
void DNAVisGroup::add_visible(const std::string& visible)
{
m_visibles.push_back(visible);
}
bool DNAVisGroup::remove_visible(const std::string& visible)
{
std::vector<std::string>::iterator it = std::find(m_visibles.begin(), m_visibles.end(), visible);
if (it == m_visibles.end())
return false;
m_visibles.erase(it);
return true;
}
size_t DNAVisGroup::get_num_visibles()
{
return m_visibles.size();
}
std::string DNAVisGroup::get_visible(size_t index)
{
return m_visibles.at(index);
} | 19.4 | 101 | 0.698085 | DarthNihilus1 |
af22d38bbe499652ba028c4c970b57aaa9f489f6 | 1,026 | cpp | C++ | PAT (Advanced Level) Practice/1163 Dijkstra Sequence (30).cpp | vuzway/PAT | 5db8ca9295b51ad9e99c815a46e4ac764d7d06c1 | [
"MIT"
] | 5 | 2020-02-10T08:26:19.000Z | 2020-07-09T00:11:16.000Z | PAT (Advanced Level) Practice/1163 Dijkstra Sequence (30).cpp | Assassin2016/zju_data_structures_and_algorithms_in_MOOC | 5db8ca9295b51ad9e99c815a46e4ac764d7d06c1 | [
"MIT"
] | null | null | null | PAT (Advanced Level) Practice/1163 Dijkstra Sequence (30).cpp | Assassin2016/zju_data_structures_and_algorithms_in_MOOC | 5db8ca9295b51ad9e99c815a46e4ac764d7d06c1 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
const int inf = 0x2fffffff;
int e[1010][1010], dis[1010];
bool vis[1010];
int main() {
fill(e[0], e[0] + 1010 * 1010, inf);
int nv, ne, k, a, b, w;
cin >> nv >> ne;
for (int i = 0; i < ne; i++) {
scanf("%d%d%d", &a, &b, &w);
e[a][b] = e[b][a] = w;
}
cin >> k;
vector<int> seq(nv);
while (k--) {
fill(dis, dis+1010, inf);
fill(vis, vis+1010, false);
for (int i = 0; i < nv; i++) scanf("%d", &seq[i]);
dis[seq[0]] = 0;
for (int i = 1; i <= nv; i++) {
int minn = inf, u = -1;
for (int j = 1; j <= nv; j++)
if (!vis[j] && dis[j] < minn) {
minn = dis[j];
u = j;
}
if (u == -1) break;
vis[u] = true;
for (int v = 1; v <= nv; v++)
if (!vis[v] && e[u][v] != inf && dis[v] > dis[u] + e[u][v])
dis[v] = dis[u] + e[u][v];
}
int flag = 0;
for (int i = 1; i < nv; i++)
if (dis[seq[i]] < dis[seq[i-1]]) {
flag = 1;
break;
}
if (flag == 1) printf("No\n");
else printf("Yes\n");
}
return 0;
}
| 22.304348 | 63 | 0.455166 | vuzway |
af29a00f44380a153c2053df41d971e4dd4cee16 | 1,206 | hpp | C++ | third_party/libosmium/include/protozero/pbf_message.hpp | Mapotempo/osrm-backend | a62c10321c0a269e218ab4164c4ccd132048f271 | [
"BSD-2-Clause"
] | 1 | 2016-11-29T15:02:40.000Z | 2016-11-29T15:02:40.000Z | third_party/libosmium/include/protozero/pbf_message.hpp | aaronbenz/osrm-backend | 758d4023050d1f49971f919cea872a2276dafe14 | [
"BSD-2-Clause"
] | 1 | 2019-02-04T18:10:57.000Z | 2019-02-04T18:10:57.000Z | third_party/libosmium/include/protozero/pbf_message.hpp | Mapotempo/osrm-backend | a62c10321c0a269e218ab4164c4ccd132048f271 | [
"BSD-2-Clause"
] | null | null | null | #ifndef PROTOZERO_PBF_MESSAGE_HPP
#define PROTOZERO_PBF_MESSAGE_HPP
/*****************************************************************************
protozero - Minimalistic protocol buffer decoder and encoder in C++.
This file is from https://github.com/mapbox/protozero where you can find more
documentation.
*****************************************************************************/
#include <type_traits>
#include <protozero/pbf_reader.hpp>
#include <protozero/pbf_types.hpp>
namespace protozero {
template <typename T>
class pbf_message : public pbf_reader {
static_assert(std::is_same<pbf_tag_type, typename std::underlying_type<T>::type>::value, "T must be enum with underlying type protozero::pbf_tag_type");
public:
using enum_type = T;
template <typename... Args>
pbf_message(Args&&... args) noexcept :
pbf_reader(std::forward<Args>(args)...) {
}
inline bool next() {
return pbf_reader::next();
}
inline bool next(T tag) {
return pbf_reader::next(pbf_tag_type(tag));
}
inline T tag() const noexcept {
return T(pbf_reader::tag());
}
};
} // end namespace protozero
#endif // PROTOZERO_PBF_MESSAGE_HPP
| 23.647059 | 156 | 0.606965 | Mapotempo |
af2d5deddf654ec2be11387164491a0cd8b23470 | 707 | hpp | C++ | library/ATF/_POSTDATA_DB_BASE.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/_POSTDATA_DB_BASE.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/_POSTDATA_DB_BASE.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <_DELPOST_DB_BASE.hpp>
#include <_POSTSTORAGE_DB_BASE.hpp>
#include <_RETURNPOST_DB_BASE.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 1)
struct _POSTDATA_DB_BASE
{
_POSTSTORAGE_DB_BASE dbPost;
_RETURNPOST_DB_BASE dbRetPost;
_DELPOST_DB_BASE dbDelPost;
public:
void Init();
void UpdateInit();
_POSTDATA_DB_BASE();
void ctor__POSTDATA_DB_BASE();
};
#pragma pack(pop)
static_assert(ATF::checkSize<_POSTDATA_DB_BASE, 15389>(), "_POSTDATA_DB_BASE");
END_ATF_NAMESPACE
| 27.192308 | 108 | 0.708628 | lemkova |
af2fafcb0bde4bbf8f971cbe1e70ef9724c4d18e | 237 | cc | C++ | transpiler/examples/structs/return_struct.cc | birdmanhub/fully-homomorphic-encryption | 6f8e3a216ebe6911f8fa46bd0b1ce3636df8eff5 | [
"Apache-2.0"
] | 2,661 | 2021-06-14T16:27:52.000Z | 2022-03-31T14:19:39.000Z | transpiler/examples/structs/return_struct.cc | birdmanhub/fully-homomorphic-encryption | 6f8e3a216ebe6911f8fa46bd0b1ce3636df8eff5 | [
"Apache-2.0"
] | 18 | 2021-06-14T17:39:02.000Z | 2022-01-15T10:25:47.000Z | transpiler/examples/structs/return_struct.cc | birdmanhub/fully-homomorphic-encryption | 6f8e3a216ebe6911f8fa46bd0b1ce3636df8eff5 | [
"Apache-2.0"
] | 181 | 2021-06-14T17:05:57.000Z | 2022-03-26T19:08:35.000Z | #include "return_struct.h"
#pragma hls_top
ReturnStruct ConstructReturnStruct(unsigned char a, Embedded b,
unsigned char c) {
ReturnStruct ret;
ret.a = a;
ret.b = b;
ret.c = c;
return ret;
}
| 19.75 | 63 | 0.594937 | birdmanhub |
af3072766a8c332e97c02684d9b6f6f3bec19032 | 2,365 | cpp | C++ | Source/Client/Core/UnitTests/gen/Main.cpp | cppsoup/soup | 0d6e6cb730d062373724cb1c4ab092eda8d53dc2 | [
"MIT"
] | 40 | 2020-01-12T05:56:53.000Z | 2020-09-25T22:27:10.000Z | Source/Client/Core/UnitTests/gen/Main.cpp | cppsoup/soup | 0d6e6cb730d062373724cb1c4ab092eda8d53dc2 | [
"MIT"
] | 17 | 2018-03-20T05:42:36.000Z | 2020-09-19T01:42:31.000Z | Source/Client/Core/UnitTests/gen/Main.cpp | cppsoup/soup | 0d6e6cb730d062373724cb1c4ab092eda8d53dc2 | [
"MIT"
] | 1 | 2020-05-26T17:29:46.000Z | 2020-05-26T17:29:46.000Z | #include <any>
#include <chrono>
#include <fstream>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <queue>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
import Opal;
import Soup.Core;
import json11;
import Monitor.Host;
import Soup.Test.Assert;
using namespace Opal;
using namespace Opal::System;
using namespace Soup::Test;
#include "Utils/TestHelpers.h"
#include "Build/BuildEvaluateEngineTests.gen.h"
#include "Build/BuildHistoryCheckerTests.gen.h"
#include "Build/FileSystemStateTests.gen.h"
#include "Build/ProjectManagerTests.gen.h"
#include "Build/RecipeBuilderTests.gen.h"
#include "LocalUserConfig/LocalUserConfigExtensionsTests.gen.h"
#include "LocalUserConfig/LocalUserConfigTests.gen.h"
#include "OperationGraph/OperationGraphTests.gen.h"
#include "OperationGraph/OperationGraphManagerTests.gen.h"
#include "OperationGraph/OperationGraphReaderTests.gen.h"
#include "OperationGraph/OperationGraphWriterTests.gen.h"
#include "Package/PackageManagerTests.gen.h"
#include "Recipe/PackageReferenceTests.gen.h"
#include "Recipe/RecipeExtensionsTests.gen.h"
#include "Recipe/RecipeTests.gen.h"
#include "Recipe/RecipeTomlTests.gen.h"
#include "ValueTable/ValueTableManagerTests.gen.h"
#include "ValueTable/ValueTableReaderTests.gen.h"
#include "ValueTable/ValueTableWriterTests.gen.h"
int main()
{
std::cout << "Running Tests..." << std::endl;
TestState state = { 0, 0 };
state += RunBuildEvaluateEngineTests();
state += RunBuildHistoryCheckerTests();
state += RunFileSystemStateTests();
state += RunProjectManagerTests();
state += RunRecipeBuilderTests();
state += RunLocalUserConfigExtensionsTests();
state += RunLocalUserConfigTests();
state += RunOperationGraphTests();
state += RunOperationGraphManagerTests();
state += RunOperationGraphReaderTests();
state += RunOperationGraphWriterTests();
state += RunPackageManagerTests();
state += RunPackageReferenceTests();
state += RunRecipeExtensionsTests();
state += RunRecipeTests();
state += RunRecipeTomlTests();
state += RunValueTableManagerTests();
state += RunValueTableReaderTests();
state += RunValueTableWriterTests();
std::cout << state.PassCount << " PASSED." << std::endl;
std::cout << state.FailCount << " FAILED." << std::endl;
if (state.FailCount > 0)
return 1;
else
return 0;
}
| 26.277778 | 63 | 0.765328 | cppsoup |
af34aaf545720ea15ba9d8d54ad84522957abfc4 | 966 | cpp | C++ | 1st/remove_duplicates_from_sorted_list.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/remove_duplicates_from_sorted_list.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | 1st/remove_duplicates_from_sorted_list.cpp | buptlxb/leetcode | b641419de040801c4f54618d7ee26edcf10ee53c | [
"BSD-3-Clause"
] | null | null | null | #include <iostream>
using std::cout;
using std::endl;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (!head)
return NULL;
ListNode *ret = head;
ListNode *index = head;
ListNode *cur = head->next;
while (cur) {
if (index->val != cur->val) {
index->next = cur;
index = index->next;
}
cur = cur->next;
}
index->next = NULL;
return ret;
}
};
int main(void)
{
ListNode a1(1);
ListNode a2(1);
ListNode a3(2);
ListNode a4(3);
ListNode a5(3);
a1.next = &a2;
a2.next = &a3;
a3.next = &a4;
a4.next = &a5;
ListNode *ret = Solution().deleteDuplicates(&a1);
while (ret) {
cout << ret->val << endl;
ret = ret->next;
}
return 0;
}
| 18.576923 | 53 | 0.489648 | buptlxb |
af37ec68be37026a635d4e22c2f0afc0a4be409a | 664 | cpp | C++ | Axis.Mint/services/language/syntax/evaluation/NullValue.cpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.Mint/services/language/syntax/evaluation/NullValue.cpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.Mint/services/language/syntax/evaluation/NullValue.cpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | #include "NullValue.hpp"
namespace aslse = axis::services::language::syntax::evaluation;
aslse::NullValue::NullValue( void )
{
/* nothing to do here */
}
aslse::NullValue::~NullValue( void )
{
/* nothing to do here */
}
bool aslse::NullValue::IsAssignment( void ) const
{
return false;
}
bool aslse::NullValue::IsAtomic( void ) const
{
return false;
}
bool aslse::NullValue::IsNull( void ) const
{
return true;
}
bool aslse::NullValue::IsArray( void ) const
{
return false;
}
axis::String aslse::NullValue::ToString( void ) const
{
return axis::String();
}
aslse::ParameterValue& aslse::NullValue::Clone( void ) const
{
return *new NullValue();
}
| 15.090909 | 63 | 0.691265 | renato-yuzup |
af3e8df6814a6331414dc46f1412ff9dae719ccc | 1,123 | cpp | C++ | 0349 - Intersection of Two Arrays/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | 5 | 2018-10-18T06:47:19.000Z | 2020-06-19T09:30:03.000Z | 0349 - Intersection of Two Arrays/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | null | null | null | 0349 - Intersection of Two Arrays/cpp/main.cpp | xiaoswu/Leetcode | e4ae8b2f72a312ee247084457cf4e6dbcfd20e18 | [
"MIT"
] | null | null | null | //
// main.cpp
// 两个数组的交集
//
// Created by ynfMac on 2018/10/9.
// Copyright © 2018年 ynfMac. All rights reserved.
// 使用set
#include <iostream>
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
vector<int> intersect(vector<int>& nums1, vector<int>& nums2) {
set<int> nums1Set = set<int>(nums1.begin(),nums1.end());
set<int> resultSet;
for (int i = 0; i < nums2.size(); i ++) {
if (nums1Set.find(nums2[i]) != nums1Set.end()) {
resultSet.insert(nums2[i]);
}
}
return vector<int>(resultSet.begin(),resultSet.end());
}
};
void printVec(const vector<int> &vec){
for(int n: vec){
cout << n << " ";
}
cout << endl;
}
int main() {
const int nums1[] = {1,2,2,1};
const int nums2[] = {2,2};
vector<int> vec1 = vector<int>(nums1, nums1 + sizeof(nums1) / sizeof(int));
vector<int> vec2 = vector<int>(nums2, nums2 + sizeof(nums2) / sizeof(int));
printVec(Solution().intersect(vec1, vec2));
return 0;
}
| 21.596154 | 79 | 0.534283 | xiaoswu |
af44dee4658df211a3a3408885978663787ef0a2 | 794 | cpp | C++ | 1161-maximum-level-sum-of-a-binary-tree/1161-maximum-level-sum-of-a-binary-tree.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 1161-maximum-level-sum-of-a-binary-tree/1161-maximum-level-sum-of-a-binary-tree.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 1161-maximum-level-sum-of-a-binary-tree/1161-maximum-level-sum-of-a-binary-tree.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxLevelSum(TreeNode* root) {
int ans,sum=INT_MIN,level=0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int n=q.size();
int curr=0;
level++;
while(n--){
TreeNode *f=q.front();
q.pop();
curr+=f->val;
if(f->left) q.push(f->left);
if(f->right) q.push(f->right);
}
if(curr>sum)
{
sum=curr;
ans=level;
}
}
return ans;
}
}; | 20.894737 | 93 | 0.542821 | SouvikChan |
af461c0ca5a379b8f957f52f6f607382d3e1dc6f | 757 | cpp | C++ | Hackerrank/Day of the Programmer.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | 14 | 2016-02-11T09:26:13.000Z | 2022-03-27T01:14:29.000Z | Hackerrank/Day of the Programmer.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | null | null | null | Hackerrank/Day of the Programmer.cpp | SurgicalSteel/Competitive-Programming | 3662b676de94796f717b25dc8d1b93c6851fb274 | [
"MIT"
] | 7 | 2016-10-25T19:29:35.000Z | 2021-12-05T18:31:39.000Z | #include <bits/stdc++.h>
using namespace std;
string tostr(int x)
{
ostringstream ss;
ss<<x;
return ss.str();
}
int main() {
// your code goes here
int iy,d,m,v,c=0,cm=0;
string sd,sm;
bool l=false;
int lm []={31,28,31,30,31,30,31,31,30,31,30,31};
for(int i=0;i<12;i++){cm+=lm[i];}
cin>>iy;
if (iy<1918){
l=(iy%4==0);
}else{
l=((iy%400==0) || (iy%4==0 && iy%100!=0));
}
v=(256*12)/cm;
for(int i=0;i<v;i++){
c+=lm[i];
m=i+1;
}
if (l){c++;}
d=256-c;
if (iy==1918){d+=13;}
if (d>0){m++;}
sd=tostr(d);
sm=tostr(m);
if (sd.length()==1){sd="0"+sd;}
if (sm.length()==1){sm="0"+sm;}
cout<<sd<<"."<<sm<<"."<<iy<<"\n";
return 0;
}
| 19.921053 | 52 | 0.442536 | SurgicalSteel |
af473e19bd41d67214893891cb110a031b4e558b | 394 | cpp | C++ | 272.cpp | ediston/UVA | 183bbfb352561f808ab6f82c70760c89a9b5c749 | [
"Unlicense"
] | null | null | null | 272.cpp | ediston/UVA | 183bbfb352561f808ab6f82c70760c89a9b5c749 | [
"Unlicense"
] | null | null | null | 272.cpp | ediston/UVA | 183bbfb352561f808ab6f82c70760c89a9b5c749 | [
"Unlicense"
] | null | null | null | #include<iostream>
using namespace std;
int main(){
char c;
bool first=true;
while(cin >> noskipws >> c){
if(c=='"'){
if(first){
cout << "``";
}else{
cout << "''";
}
first = !first;
}else{
cout << c;
}
}
return 0;
}
| 18.761905 | 33 | 0.309645 | ediston |
af47ffa1ddcae41ccdb44babdebb53b333f5a674 | 2,246 | cpp | C++ | lib/TickerScheduler/TickerScheduler.cpp | ecrandz/IoTManager | 5d0eb71cfccccf9020b28be8c9fa5837988fb6ba | [
"MIT"
] | 37 | 2020-08-17T10:39:06.000Z | 2022-02-17T16:18:47.000Z | lib/TickerScheduler/TickerScheduler.cpp | ecrandz/IoTManager | 5d0eb71cfccccf9020b28be8c9fa5837988fb6ba | [
"MIT"
] | 11 | 2020-10-20T14:48:07.000Z | 2022-02-04T07:05:05.000Z | lib/TickerScheduler/TickerScheduler.cpp | ecrandz/IoTManager | 5d0eb71cfccccf9020b28be8c9fa5837988fb6ba | [
"MIT"
] | 43 | 2020-06-19T22:40:14.000Z | 2022-03-05T05:29:07.000Z | #include "TickerScheduler.h"
TickerScheduler::TickerScheduler(uint8_t size)
{
this->items = new TickerSchedulerItem[size];
this->size = size;
}
TickerScheduler::~TickerScheduler()
{
for (uint8_t i = 0; i < this->size; i++)
{
this->remove(i);
yield();
}
delete[] this->items;
this->items = NULL;
this->size = 0;
}
void TickerScheduler::handleTickerFlag(bool * flag)
{
if (!*flag)
*flag = true;
}
void TickerScheduler::handleTicker(tscallback_t f, void * arg, bool * flag)
{
if (*flag)
{
yield();
*flag = false;
yield();
f(arg);
yield();
}
}
bool TickerScheduler::add(uint8_t i, uint32_t period, tscallback_t f, void* arg, boolean shouldFireNow)
{
if (i >= this->size || this->items[i].is_used)
return false;
this->items[i].cb = f;
this->items[i].cb_arg = arg;
this->items[i].flag = shouldFireNow;
this->items[i].period = period;
this->items[i].is_used = true;
enable(i);
return true;
}
bool TickerScheduler::remove(uint8_t i)
{
if (i >= this->size || !this->items[i].is_used)
return false;
this->items[i].is_used = false;
this->items[i].t.detach();
this->items[i].flag = false;
this->items[i].cb = NULL;
return true;
}
bool TickerScheduler::disable(uint8_t i)
{
if (i >= this->size || !this->items[i].is_used)
return false;
this->items[i].t.detach();
return true;
}
bool TickerScheduler::enable(uint8_t i)
{
if (i >= this->size || !this->items[i].is_used)
return false;
bool * flag = &this->items[i].flag;
this->items[i].t.attach_ms(this->items[i].period, TickerScheduler::handleTickerFlag, flag);
return true;
}
void TickerScheduler::disableAll()
{
for (uint8_t i = 0; i < this->size; i++)
disable(i);
}
void TickerScheduler::enableAll()
{
for (uint8_t i = 0; i < this->size; i++)
enable(i);
}
void TickerScheduler::update()
{
for (uint8_t i = 0; i < this->size; i++)
{
if (this->items[i].is_used)
{
#ifdef ARDUINO_ARCH_AVR
this->items[i].t.Tick();
#endif
handleTicker(this->items[i].cb, this->items[i].cb_arg, &this->items[i].flag);
}
yield();
}
}
| 19.196581 | 103 | 0.588157 | ecrandz |
af4a427d2302b8c705331d8a611ffc056b2f2aeb | 7,319 | cpp | C++ | PFL_runner.cpp | KAdamek/sdp_pfl_runner | ba8121191233f018623165dec31aa60af52f5a26 | [
"MIT"
] | null | null | null | PFL_runner.cpp | KAdamek/sdp_pfl_runner | ba8121191233f018623165dec31aa60af52f5a26 | [
"MIT"
] | null | null | null | PFL_runner.cpp | KAdamek/sdp_pfl_runner | ba8121191233f018623165dec31aa60af52f5a26 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdarg.h>
#include <memory>
#include <iostream>
#include <algorithm>
// Simple function should be trivially callable
int pflSimpleFunctionA(int A, int B, int *status) {
printf("SimpleFunctionA\n");
return(A + B);
}
// Simple function acting on the array without temporary memory should be
// trivially callable.
void pflSimpleFunctionB(float *output, float *input, int A, int B, int *status) {
printf("SimpleFunctionB\n");
}
// This class will contain configuration parameters for the pflFunction together with a check of validity
// It could be also part of the pflFunctionRunner but then the check must be factored out. Then it would not be an independent entity.
class pflFunctionAConfiguration {
public:
int a;
int b;
double c;
pflFunctionAConfiguration() {
a = 0;
b = 0;
c = 0;
}
bool check() {
if (a<=0 || b<=0) return false;
// this could be more advanced with logging of specific problems
// if(A<=0) {
// log(skaloglevel::warning, "A must be non-zero and positive");
return true;
}
};
// This class could be derived from virtual class to enforce some structure
class pflFunctionA {
private: // variables
pflFunctionAConfiguration conf;
// There might be some internal configuration
float *workarea;
int initiated;
public: // methods
pflFunctionA() {
initiated = 0;
workarea = nullptr;
}
void planner(pflFunctionAConfiguration conf, int *error_status) {
if (*error_status != 0) return;
if (initiated==1) {
*error_status = 1;
return;
}
printf("Planner for function A\n");
this->conf = conf;
workarea = (float *)malloc(conf.a*conf.b*sizeof(float));
if (workarea == nullptr) {
*error_status = 1;
}
if(*error_status==0) initiated = 1;
}
void planner(pflFunctionAConfiguration conf) {
int error_status = 0;
planner(conf, &error_status);
if(error_status!=0) throw new std::exception;
}
void run(float *outputA, int *error_status) {
if (*error_status != 0) return;
if (initiated==0) {
*error_status = 1;
return;
}
printf("Running function A\n");
for (int f = 0; f<conf.a*conf.b; f++) {
float ftemp = 0;
workarea[f] = conf.c*f;
for (int i = 0; i<f; i++) {
ftemp = ftemp + workarea[i];
}
outputA[f] = ftemp;
}
}
void run(float *outputA) {
int error_status = 0;
run(outputA, &error_status);
if(error_status!=0) throw new std::exception;
}
~pflFunctionA() {
printf("Destructor for function A called.\n");
free(workarea);
}
};
// Another complex function which would used ComplexFunction0
class pflFunctionBConfiguration {
public:
int d;
int e;
pflFunctionBConfiguration() {
d = 0;
e = 0;
}
bool check() {
if (d<=0 || e<=0) return false;
return true;
}
};
// This class could be derived from virtual class to enforce some structure
class pflFunctionB {
private: // variables
pflFunctionBConfiguration conf;
// There might be some internal configuration
float *workarea;
pflFunctionAConfiguration Aconf;
pflFunctionA Afunc;
int initiated;
public: // methods
pflFunctionB() {
initiated = 0;
workarea = nullptr;
}
void planner(pflFunctionBConfiguration conf, int* error_status) {
if (*error_status != 0) return;
if (initiated==1) {
*error_status = 1;
return;
}
printf("Planner for function B\n");
this->conf = conf;
workarea = (float*)malloc(2*conf.d*2*conf.e*sizeof(float));
if (workarea == nullptr) {
*error_status = 1;
}
Aconf.a = 2*this->conf.e;
Aconf.b = 2*this->conf.d;
Aconf.c = 0.1f;
if (!Aconf.check()) {
*error_status = 2;
}
Afunc.planner(Aconf, error_status);
if(*error_status==0) initiated = 1;
}
void planner(pflFunctionBConfiguration conf) {
int error_status = 0;
planner(conf, &error_status);
if (error_status != 0) throw new std::exception;
}
void run(float *inputB, float *outputB, int *error_status) {
if (*error_status != 0) return;
if (initiated==0) {
*error_status = 1;
return;
}
printf("Running function B...\n");
Afunc.run(workarea, error_status);
for (int f = 0; f<conf.e*conf.d; f++) {
outputB[f] = inputB[f] + workarea[4*f];
}
}
void run(float *inputB, float *outputB) {
int error_status = 0;
run(inputB, outputB, &error_status);
if (error_status != 0) throw new std::exception;
}
~pflFunctionB() {
printf("Destructor for function B called.\n");
free(workarea);
}
};
extern "C" {
int pflFunctionACall(float *outputA, int A, int B, double C) {
pflFunctionAConfiguration conf;
conf.a = A;
conf.b = B;
conf.c = C;
if (conf.check()==false) return (1);
pflFunctionA runner;
// runner.planner might throw an exeption if we want to
try {
runner.planner(conf);
}
catch (...) {
return (1);
}
runner.run(outputA);
}
}
int main() {
std::cout << "Hello!\n";
printf("Configure and run function A\n");
pflFunctionAConfiguration Aconfig;
Aconfig.a = 10;
Aconfig.b = 20;
Aconfig.c = 0.1;
if (Aconfig.check()) printf("Configuration A is valid\n");
else printf("Configuration A is invalid\n");
float *outputA;
outputA = (float *)malloc(Aconfig.a*Aconfig.b*sizeof(float));
if (outputA==nullptr) printf("bad memory allocation for outputA\n");
pflFunctionA Afunc;
try {
Afunc.planner(Aconfig);
} catch (...) {
printf("Function A was not configured properly\n");
}
try {
Afunc.run(outputA);
} catch (...) {
printf("Error during execution of function A\n");
}
printf("\n");
// Function B
printf("Configure and run function B\n");
pflFunctionBConfiguration Bconfig;
Bconfig.d = 10;
Bconfig.e = 5;
if (Bconfig.check()) printf("Configuration B is valid\n");
else printf("Configuration B is invalid\n");
float *inputB, *outputB;
inputB = (float *)malloc(Bconfig.e*Bconfig.d*sizeof(float));
outputB = (float *)malloc(Bconfig.e*Bconfig.d*sizeof(float));
if (outputB==nullptr) printf("bad memory allocation for outputB\n");
if (inputB==nullptr) printf("bad memory allocation for inputB\n");
for (int f = 0; f<Bconfig.e*Bconfig.d; f++) inputB[f] = f;
pflFunctionB Bfunc;
try {
Bfunc.planner(Bconfig);
} catch (...) {
printf("Function B was not configured properly\n");
}
try {
Bfunc.run(inputB, outputB);
} catch (...) {
printf("Error during execution of function B\n");
}
free(outputA);
free(outputB);
free(inputB);
}
| 25.680702 | 134 | 0.576445 | KAdamek |
af4c308e4ffe5eccd1235695e8ea27b1502df627 | 356 | hpp | C++ | tests/test-registry.hpp | umbreensabirmain/readex-rrl | 0cb73b3a3c6948a8dbdce96c240b24d8e992c2fe | [
"BSD-3-Clause"
] | 1 | 2019-10-09T09:15:47.000Z | 2019-10-09T09:15:47.000Z | tests/test-registry.hpp | readex-eu/readex-rrl | ac8722c44f84d65668e2a60e4237ebf51b298c9b | [
"BSD-3-Clause"
] | null | null | null | tests/test-registry.hpp | readex-eu/readex-rrl | ac8722c44f84d65668e2a60e4237ebf51b298c9b | [
"BSD-3-Clause"
] | 1 | 2018-07-13T11:31:05.000Z | 2018-07-13T11:31:05.000Z | #ifndef TEST_REGISTRY_HPP
#define TEST_REGISTRY_HPP
#include <string>
void
register_test(const std::string & name, int (*test)(const std::string &));
int
run_test(const std::string & name);
#define TEST_REGISTER(name, test) \
static void __attribute__((constructor)) register_test(void) \
{ \
register_test(name, test); \
}
#endif
| 18.736842 | 74 | 0.696629 | umbreensabirmain |
af4dee6b86cd1e4d7ac63d0ee31a480d21da2069 | 10,431 | hpp | C++ | grasp_planner/test/load_perception.hpp | tanjpg/easy_manipulation_deployment | 83073fcebb25306619c4958fc98a74b1bf216141 | [
"Apache-2.0"
] | null | null | null | grasp_planner/test/load_perception.hpp | tanjpg/easy_manipulation_deployment | 83073fcebb25306619c4958fc98a74b1bf216141 | [
"Apache-2.0"
] | null | null | null | grasp_planner/test/load_perception.hpp | tanjpg/easy_manipulation_deployment | 83073fcebb25306619c4958fc98a74b1bf216141 | [
"Apache-2.0"
] | 1 | 2021-04-01T07:11:35.000Z | 2021-04-01T07:11:35.000Z | // Copyright 2020 Advanced Remanufacturing and Technology Centre
// Copyright 2020 ROS-Industrial Consortium Asia Pacific Team
//
// 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 LOAD_PERCEPTION_HPP_
#define LOAD_PERCEPTION_HPP_
#include <grasp_planning/msg/grasp_pose.hpp>
#include <epd_msgs/msg/epd_object_localization.hpp>
#include <boost/filesystem.hpp>
#include <memory>
#include <string>
#include <vector>
#include "yaml-cpp/yaml.h"
#include "perception_functions.hpp"
#include "rclcpp/rclcpp.hpp"
using std::placeholders::_1;
epd_msgs::msg::EPDObjectLocalization::SharedPtr
LoadPerception()
{
epd_msgs::msg::EPDObjectLocalization mock_perception;
YAML::Node yaml;
// Load Yaml File.
yaml = YAML::LoadFile("perception_output.yaml");
// TODO(Glenn) : add error catch if trying to create directory with same name,
// or maybe add a number to it, eg table1, table2.
for (YAML::iterator it = yaml.begin(); it != yaml.end(); ++it) {
std::string key = it->first.as<std::string>();
if (key.compare("objects") == 0) {
YAML::Node object_array = it->second;
for (YAML::iterator object_array_it = object_array.begin();
object_array_it != object_array.end();
++object_array_it)
{
epd_msgs::msg::LocalizedObject object;
object.name = object_array_it->first.as<std::string>();
YAML::Node curr_obj = object_array_it->second;
for (YAML::iterator curr_obj_it = curr_obj.begin();
curr_obj_it != curr_obj.end();
++curr_obj_it)
{
if (curr_obj_it->first.as<std::string>().compare("pos") == 0) {
YAML::Node pose = curr_obj_it->second;
for (YAML::iterator pose_it = pose.begin();
pose_it != pose.end();
++pose_it)
{
if (pose_it->first.as<std::string>().compare("position") == 0) {
YAML::Node position = pose_it->second;
for (YAML::iterator position_it = position.begin();
position_it != position.end();
++position_it)
{
if (position_it->first.as<std::string>().compare("x") == 0) {
object.pos.pose.position.x = position_it->second.as<float>();
}
if (position_it->first.as<std::string>().compare("y") == 0) {
object.pos.pose.position.y = position_it->second.as<float>();
}
if (position_it->first.as<std::string>().compare("z") == 0) {
object.pos.pose.position.z = position_it->second.as<float>();
}
}
}
if (pose_it->first.as<std::string>().compare("orientation") == 0) {
YAML::Node orientation = pose_it->second;
for (YAML::iterator orientation_it = orientation.begin();
orientation_it != orientation.end();
++orientation_it)
{
if (orientation_it->first.as<std::string>().compare("x") == 0) {
object.pos.pose.orientation.x = orientation_it->second.as<float>();
}
if (orientation_it->first.as<std::string>().compare("y") == 0) {
object.pos.pose.orientation.y = orientation_it->second.as<float>();
}
if (orientation_it->first.as<std::string>().compare("z") == 0) {
object.pos.pose.orientation.z = orientation_it->second.as<float>();
}
if (orientation_it->first.as<std::string>().compare("w") == 0) {
object.pos.pose.orientation.w = orientation_it->second.as<float>();
}
}
}
}
}
if (curr_obj_it->first.as<std::string>().compare("roi") == 0) {
YAML::Node roi = curr_obj_it->second;
for (YAML::iterator roi_it = roi.begin(); roi_it != roi.end(); ++roi_it) {
if (roi_it->first.as<std::string>().compare("x_offset") == 0) {
object.roi.x_offset = roi_it->second.as<float>();
}
if (roi_it->first.as<std::string>().compare("y_offset") == 0) {
object.roi.y_offset = roi_it->second.as<float>();
}
if (roi_it->first.as<std::string>().compare("height") == 0) {
object.roi.height = roi_it->second.as<float>();
}
if (roi_it->first.as<std::string>().compare("width") == 0) {
object.roi.width = roi_it->second.as<float>();
}
}
}
if (curr_obj_it->first.as<std::string>().compare("length") == 0) {
object.length = curr_obj_it->second.as<float>();
}
if (curr_obj_it->first.as<std::string>().compare("breadth") == 0) {
object.breadth = curr_obj_it->second.as<float>();
}
if (curr_obj_it->first.as<std::string>().compare("height") == 0) {
object.height = curr_obj_it->second.as<float>();
}
}
mock_perception.objects.push_back(object);
}
}
if (key.compare("frame_width") == 0) {
mock_perception.frame_width = it->second.as<float>();
}
if (key.compare("frame_height") == 0) {
mock_perception.frame_height = it->second.as<float>();
}
if (key.compare("num_objects") == 0) {
mock_perception.num_objects = it->second.as<float>();
}
if (key.compare("camera_info") == 0) {
YAML::Node cam_info = it->second;
sensor_msgs::msg::CameraInfo camera_info;
for (YAML::iterator cam_info_it = cam_info.begin();
cam_info_it != cam_info.end();
++cam_info_it)
{
if (cam_info_it->first.as<std::string>().compare("D") == 0) {
YAML::Node d = cam_info_it->second;
std::vector<double> d_input;
for (YAML::iterator d_it = d.begin(); d_it != d.end(); ++d_it) {
d_input.push_back(d_it->second.as<double>());
}
camera_info.d = d_input;
}
if (cam_info_it->first.as<std::string>().compare("K") == 0) {
YAML::Node k = cam_info_it->second;
std::array<double, 9> k_input;
for (YAML::iterator k_it = k.begin(); k_it != k.end(); ++k_it) {
std::string name = k_it->first.as<std::string>();
k_input[name.back() - '0'] = k_it->second.as<double>();
}
camera_info.k = k_input;
}
if (cam_info_it->first.as<std::string>().compare("R") == 0) {
YAML::Node r = cam_info_it->second;
std::array<double, 9> r_input;
for (YAML::iterator r_it = r.begin(); r_it != r.end(); ++r_it) {
std::string name = r_it->first.as<std::string>();
r_input[name.back() - '0'] = r_it->second.as<double>();
}
camera_info.r = r_input;
}
if (cam_info_it->first.as<std::string>().compare("P") == 0) {
YAML::Node p = cam_info_it->second;
std::array<double, 12> p_input;
for (YAML::iterator p_it = p.begin(); p_it != p.end(); ++p_it) {
std::string name = p_it->first.as<std::string>();
p_input[name.back() - '0'] = p_it->second.as<double>();
}
camera_info.p = p_input;
}
}
mock_perception.camera_info = camera_info;
}
if (key.compare("roi_array") == 0) {
YAML::Node roi_array = it->second;
for (YAML::iterator roi_array_it = roi_array.begin();
roi_array_it != roi_array.end();
++roi_array_it)
{
YAML::Node roi = roi_array_it->second;
sensor_msgs::msg::RegionOfInterest temp_roi;
for (YAML::iterator roi_it = roi.begin(); roi_it != roi.end(); ++roi_it) {
if (roi_it->first.as<std::string>().compare("x_offset") == 0) {
temp_roi.x_offset = roi_it->second.as<float>();
}
if (roi_it->first.as<std::string>().compare("y_offset") == 0) {
temp_roi.y_offset = roi_it->second.as<float>();
}
if (roi_it->first.as<std::string>().compare("height") == 0) {
temp_roi.height = roi_it->second.as<float>();
}
if (roi_it->first.as<std::string>().compare("width") == 0) {
temp_roi.width = roi_it->second.as<float>();
}
}
mock_perception.roi_array.push_back(temp_roi);
}
}
if (key.compare("depth_image") == 0) {
YAML::Node depth_image = it->second;
sensor_msgs::msg::Image input_image;
for (YAML::iterator depth_image_it = depth_image.begin();
depth_image_it != depth_image.end();
++depth_image_it)
{
if (depth_image_it->first.as<std::string>().compare("height") == 0) {
input_image.height = depth_image_it->second.as<float>();
}
if (depth_image_it->first.as<std::string>().compare("width") == 0) {
input_image.width = depth_image_it->second.as<float>();
}
}
mock_perception.depth_image = input_image;
}
}
std::shared_ptr<epd_msgs::msg::EPDObjectLocalization> mock_perception_ptr =
std::make_shared<epd_msgs::msg::EPDObjectLocalization>(mock_perception);
return mock_perception_ptr;
}
cv::Mat
load_depth_img()
{
cv::Mat depth_img(cv::Size(640, 480), 2);
std::ifstream infile("depth_image.yaml");
int counter_width = 0;
int counter_height = 0;
std::string line;
while (std::getline(infile, line)) {
counter_width = 0;
std::istringstream ss(line);
std::string depth_val;
while (std::getline(ss, depth_val, ',')) {
depth_img.at<ushort>(counter_width, counter_height) = std::stoi(depth_val);
counter_width++;
}
counter_height++;
}
return depth_img;
}
#endif // LOAD_PERCEPTION_HPP_
| 39.067416 | 87 | 0.560445 | tanjpg |
af4fad6c6c17c867cb8ab0dbfddd63f330f2e5b5 | 181 | hpp | C++ | src/game/process_priority.hpp | mnewhouse/tselements | bd1c6724018e862156948a680bb1bc70dd28bef6 | [
"MIT"
] | null | null | null | src/game/process_priority.hpp | mnewhouse/tselements | bd1c6724018e862156948a680bb1bc70dd28bef6 | [
"MIT"
] | null | null | null | src/game/process_priority.hpp | mnewhouse/tselements | bd1c6724018e862156948a680bb1bc70dd28bef6 | [
"MIT"
] | null | null | null | /*
* TS Elements
* Copyright 2015-2018 M. Newhouse
* Released under the MIT license.
*/
#pragma once
namespace ts
{
namespace game
{
void elevate_process_priority();
}
} | 12.066667 | 36 | 0.685083 | mnewhouse |
af54568ce52e2309c4f879a45d67728b75407162 | 770 | cpp | C++ | RubeusCore/Source/GraphicComponents/buffer_object.cpp | Rodrirokr/Rubeus | 12623b04db959b428b9eb791d3943b11d74c0532 | [
"MIT"
] | 179 | 2018-12-22T14:02:02.000Z | 2022-01-29T18:26:57.000Z | RubeusCore/Source/GraphicComponents/buffer_object.cpp | rahil627/Rubeus | dd057d23c94a0406126c32d62889ac83cba47570 | [
"MIT"
] | 56 | 2019-01-07T11:55:16.000Z | 2020-12-10T21:32:18.000Z | RubeusCore/Source/GraphicComponents/buffer_object.cpp | rahil627/Rubeus | dd057d23c94a0406126c32d62889ac83cba47570 | [
"MIT"
] | 20 | 2018-12-23T11:19:49.000Z | 2022-03-11T06:18:10.000Z | /**
* @file Source/buffer.cpp.
*
* @brief Implements the buffer class
*/
#include <buffer_object.h>
namespace Rubeus
{
namespace GraphicComponents
{
RBuffer::RBuffer(GLfloat * data, GLsizei count, GLuint elementCount)
{
m_ElementCount = elementCount;
GLCall(glGenBuffers(1, &m_BufferID));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_BufferID));
GLCall(glBufferData(GL_ARRAY_BUFFER, count * sizeof(GLfloat), data, GL_STATIC_DRAW));
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
}
RBuffer::~RBuffer()
{
GLCall(glDeleteBuffers(1, &m_BufferID));
}
void RBuffer::bindBuffer() const
{
GLCall(glBindBuffer(GL_ARRAY_BUFFER, m_BufferID));
}
void RBuffer::unbindBuffer() const
{
GLCall(glBindBuffer(GL_ARRAY_BUFFER, 0));
}
}
}
| 19.74359 | 88 | 0.705195 | Rodrirokr |
af575ec56ff4ab7e930f40be41a2b8772811ab4f | 2,890 | cpp | C++ | audio/AudioIOCallback.cpp | kovdan01/libtgvoip | 6fec40ea1acd40fddba927b049f78962507d4922 | [
"Unlicense"
] | null | null | null | audio/AudioIOCallback.cpp | kovdan01/libtgvoip | 6fec40ea1acd40fddba927b049f78962507d4922 | [
"Unlicense"
] | null | null | null | audio/AudioIOCallback.cpp | kovdan01/libtgvoip | 6fec40ea1acd40fddba927b049f78962507d4922 | [
"Unlicense"
] | null | null | null | //
// libtgvoip is free and unencumbered public domain software.
// For more information, see http://unlicense.org or the UNLICENSE file
// you should have received with this source code distribution.
//
#include "../logging.h"
#include "../VoIPController.h"
#include "AudioIOCallback.h"
#include <cstring>
using namespace tgvoip;
using namespace tgvoip::audio;
#pragma mark - IO
AudioIOCallback::AudioIOCallback()
{
m_input = new AudioInputCallback();
m_output = new AudioOutputCallback();
}
AudioIOCallback::~AudioIOCallback()
{
delete m_input;
delete m_output;
}
AudioInput* AudioIOCallback::GetInput()
{
return m_input;
}
AudioOutput* AudioIOCallback::GetOutput()
{
return m_output;
}
#pragma mark - Input
AudioInputCallback::AudioInputCallback()
{
m_thread = new Thread(std::bind(&AudioInputCallback::RunThread, this));
m_thread->SetName("AudioInputCallback");
}
AudioInputCallback::~AudioInputCallback()
{
m_running = false;
m_thread->Join();
delete m_thread;
}
void AudioInputCallback::Start()
{
if (!m_running)
{
m_running = true;
m_thread->Start();
}
m_recording = true;
}
void AudioInputCallback::Stop()
{
m_recording = false;
}
void AudioInputCallback::SetDataCallback(std::function<void(std::int16_t*, std::size_t)> dataCallback)
{
m_dataCallback = std::move(dataCallback);
}
void AudioInputCallback::RunThread()
{
std::int16_t buf[960];
while (m_running)
{
double t = VoIPController::GetCurrentTime();
std::memset(buf, 0, sizeof(buf));
m_dataCallback(buf, 960);
InvokeCallback(reinterpret_cast<std::uint8_t*>(buf), 960 * 2);
double sl = 0.02 - (VoIPController::GetCurrentTime() - t);
if (sl > 0)
Thread::Sleep(sl);
}
}
#pragma mark - Output
AudioOutputCallback::AudioOutputCallback()
{
m_thread = new Thread(std::bind(&AudioOutputCallback::RunThread, this));
m_thread->SetName("AudioOutputCallback");
}
AudioOutputCallback::~AudioOutputCallback()
{
m_running = false;
m_thread->Join();
delete m_thread;
}
void AudioOutputCallback::Start()
{
if (!m_running)
{
m_running = true;
m_thread->Start();
}
m_playing = true;
}
void AudioOutputCallback::Stop()
{
m_playing = false;
}
bool AudioOutputCallback::IsPlaying()
{
return m_playing;
}
void AudioOutputCallback::SetDataCallback(std::function<void(std::int16_t*, std::size_t)> c)
{
m_dataCallback = c;
}
void AudioOutputCallback::RunThread()
{
std::int16_t buf[960];
while (m_running)
{
double t = VoIPController::GetCurrentTime();
InvokeCallback(reinterpret_cast<std::uint8_t*>(buf), 960 * 2);
m_dataCallback(buf, 960);
double sl = 0.02 - (VoIPController::GetCurrentTime() - t);
if (sl > 0)
Thread::Sleep(sl);
}
}
| 20.20979 | 102 | 0.66436 | kovdan01 |
af58bc67b7646da96a91093a51c7db6188964f08 | 106 | cpp | C++ | RTEngine/PCG/test-high/check-pcg64_k32_fast.cpp | RootinTootinCoodin/RTEngine | 916354d8868f6eca5675390071e3ec93df497ed3 | [
"MIT"
] | 613 | 2015-01-27T09:47:36.000Z | 2022-03-17T20:26:02.000Z | third_party/pcg/test-high/check-pcg64_k32_fast.cpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | 59 | 2015-03-12T23:11:48.000Z | 2022-03-31T08:24:52.000Z | third_party/pcg/test-high/check-pcg64_k32_fast.cpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | 104 | 2015-02-24T16:25:17.000Z | 2022-03-22T09:55:51.000Z | #define RNG pcg64_k32_fast
#define TWO_ARG_INIT 0
#define AWKWARD_128BIT_CODE 1
#include "pcg-test.cpp"
| 15.142857 | 29 | 0.801887 | RootinTootinCoodin |
af5c47582b4941edcad0e06c6497b38b937323ca | 746 | cpp | C++ | src/main.cpp | unfoundbug/ESp32ControlTranciever | 35c9e527771c0d8d6edbeffaaf3fc76a16b7486e | [
"Apache-2.0"
] | null | null | null | src/main.cpp | unfoundbug/ESp32ControlTranciever | 35c9e527771c0d8d6edbeffaaf3fc76a16b7486e | [
"Apache-2.0"
] | null | null | null | src/main.cpp | unfoundbug/ESp32ControlTranciever | 35c9e527771c0d8d6edbeffaaf3fc76a16b7486e | [
"Apache-2.0"
] | null | null | null | #include <Arduino.h>
#include "globals.hpp"
#include "Core0.hpp"
#include "Core1.hpp"
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
void setup()
{
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
// let things power up
delay(500);
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 1); //enable brownout detector
Serial.begin(115200);
Serial.println("Init Globals");
// put your setup code here, to run once:
InitialiseGlobals();
Serial.println("Init Core1");
// Core 1 is responsible for communications
InitialiseCore1();
Serial.println("Init Core0");
// Core 0 is responsible for WorldIO
InitialiseCore0();
}
void loop() {
// put your main code here, to run repeatedly:
RunCore1();
} | 20.162162 | 75 | 0.703753 | unfoundbug |
af5d54d1582922cfafefb6dd225c698c9bd72793 | 7,652 | cpp | C++ | arm_components_name_manager/src/ArmJointStateSubscriber.cpp | JenniferBuehler/tools-pkgs | 8faeac8a3ecae6a35faa39463cb571ba720d6c77 | [
"BSD-3-Clause"
] | 2 | 2018-09-10T03:29:25.000Z | 2020-05-28T19:23:43.000Z | arm_components_name_manager/src/ArmJointStateSubscriber.cpp | JenniferBuehler/tools-pkgs | 8faeac8a3ecae6a35faa39463cb571ba720d6c77 | [
"BSD-3-Clause"
] | 2 | 2016-03-28T16:19:35.000Z | 2016-05-30T15:09:48.000Z | arm_components_name_manager/src/ArmJointStateSubscriber.cpp | JenniferBuehler/tools-pkgs | 8faeac8a3ecae6a35faa39463cb571ba720d6c77 | [
"BSD-3-Clause"
] | 14 | 2016-04-19T07:34:03.000Z | 2021-04-19T08:47:01.000Z | #ifdef DOXYGEN_SHOULD_SKIP_THIS
/**
Maintains up-to-date state of the arm.
Copyright (C) 2015 Jennifer Buehler
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#endif
#include <arm_components_name_manager/ArmJointStateSubscriber.h>
#define CHECK_UPDATE_RATE 50
using arm_components_name_manager::ArmJointStateSubscriber;
ArmJointStateSubscriber::ArmJointStateSubscriber(const ArmComponentsNameManager& _manager,
ros::NodeHandle& n, const std::string& joint_states_topic):
jointsManager(_manager),
node(n),
valid_arm(false),
valid_grippers(false),
// subscriber(n),
subscriberActive(false),
last_update_time(0)
{
subscriber = node.subscribe(joint_states_topic, 1000, &ArmJointStateSubscriber::callback, this);
/* subscriber.start(joint_states_topic);
update_connection = n.createTimer(ros::Duration(1.0 / CHECK_UPDATE_RATE), &ArmJointStateSubscriber::process, this);*/
}
ArmJointStateSubscriber::~ArmJointStateSubscriber() {}
void ArmJointStateSubscriber::setActive(bool flag)
{
unique_lock lock(mutex);
subscriberActive = flag;
// subscriber.setActive(flag);
}
bool ArmJointStateSubscriber::isActive() const
{
unique_lock lock(mutex);
return subscriberActive;
// return subscriber.isActive();
}
bool ArmJointStateSubscriber::waitForUpdate(float timeout, float checkStepTime) const
{
if (!isActive())
{
ROS_ERROR("Called ArmJointStateSubscriber::waitForUpdate() without calling ArmJointStateSubscriber::setActive(true) first");
return false;
}
ros::Time start_time = ros::Time::now();
float time_waited=0;
while ((getLastUpdateTime() < start_time) && ((timeout < 0) || (time_waited < timeout)))
{
ROS_INFO("ArmJointStateSubscriber: Waiting...");
// spin once so that callback() may still be called by the subscriber
// in case the node is not running in multi-threaded mode.
ros::spinOnce();
ros::Duration(checkStepTime).sleep();
ros::Time curr_time = ros::Time::now();
time_waited = (curr_time - start_time).toSec();
}
if (getLastUpdateTime() >= start_time) return true;
return false;
}
ros::Time ArmJointStateSubscriber::getLastUpdateTime() const
{
unique_lock lock(mutex);
return last_update_time;
}
std::vector<float> ArmJointStateSubscriber::armAngles(bool& valid) const
{
unique_lock lock(mutex);
valid = valid_arm;
if (!valid) ROS_WARN("Arm angles were not complete in the last joint state callback");
return arm_angles;
}
std::vector<float> ArmJointStateSubscriber::gripperAngles(bool& valid) const
{
unique_lock lock(mutex);
valid = valid_grippers;
if (!valid) ROS_WARN("Gripper angles were not complete in the last joint state callback");
return gripper_angles;
}
std::string ArmJointStateSubscriber::toString() const
{
unique_lock lock(mutex);
std::stringstream str;
str << "Arm (valid=" << valid_arm << "): ";
for (int i = 0; i < arm_angles.size(); ++i) str << arm_angles[i] << " / ";
str << " Gripper (valid=" << valid_grippers << "): ";
for (int i = 0; i < gripper_angles.size(); ++i) str << gripper_angles[i] << " / ";
return str.str();
}
void ArmJointStateSubscriber::callback(const sensor_msgs::JointState& msg)
//void ArmJointStateSubscriber::process(const ros::TimerEvent& t)
{
if (!isActive()) return;
/*
// get the newest message
sensor_msgs::JointState msg;
float rate = 1.0 / CHECK_UPDATE_RATE;
float timeout = 5 * rate;
float checkStepTime = timeout / 4.0;
bool gotMessage = subscriber.waitForNextMessage(msg, timeout, checkStepTime);
// do another thread loop, no new message has arrived so far
if (!gotMessage) return;
// ROS_INFO("Processing...");
*/
std::vector<int> idx;
// Get joint indices in msg.
// Returns 0 if all joints present, 1 if only arm joints present, and 2 if only gripper joints present.
int idxGroup = jointsManager.getJointIndices(msg.name, idx);
if (idxGroup < 0)
{
ROS_WARN("Could not obtain indices of the arm joints in joint state, skipping it.");
return;
}
int numArmJnts = jointsManager.numArmJoints();
int numGripperJnts = jointsManager.numGripperJoints();
int numJnts = numArmJnts + numGripperJnts;
if (idx.size() != numJnts)
{
ROS_ERROR("Inconsistency: joint_indices should be same size as all arm joints");
return;
}
unique_lock lock(mutex);
bool _valid_grippers = false;
bool _valid_arm = false;
if ((idxGroup == 0) || (idxGroup == 1))
{
arm_angles.assign(numArmJnts, 0);
bool allFound = true;
for (int i = 0; i < numArmJnts; ++i)
{
if (idx[i] < 0)
{
ROS_ERROR_STREAM("Arm joint "<<i<<" was not in joint state");
allFound = false;
continue;
}
if (msg.position.size() <= idx[i])
{
ROS_ERROR_STREAM("Inconsistency: position size in message is "
<<msg.position.size()<<"< tying to index "<<idx[i]);
allFound = false;
continue;
}
arm_angles[i] = msg.position[idx[i]];
}
_valid_arm = allFound;
}
if ((idxGroup == 0) || (idxGroup == 2))
{
gripper_angles.assign(numGripperJnts, 0);
bool allFound = true;
int startIt = 0;
if (idxGroup == 0) startIt = numArmJnts;
for (int i = startIt; i < numJnts; ++i)
{
if (idx[i] < 0)
{
ROS_ERROR_STREAM("Gripper joint " << (i - startIt) << " was not in joint state");
allFound = false;
continue;
}
if ((i-startIt) >= gripper_angles.size())
{
ROS_ERROR_STREAM("Consistency: index of gripper is too large. startIt="<<startIt<<", i="<<i);
allFound = false;
continue;
}
if (msg.position.size() <= idx[i])
{
ROS_ERROR_STREAM("Inconsistency: position size in message is "
<<msg.position.size()<<"< tying to index "<<idx[i]);
allFound = false;
continue;
}
// ROS_INFO_STREAM("Grippers at "<<i-startIt);
// ROS_INFO_STREAM("msg pos: "<<msg.position[idx[i]]);
gripper_angles[i-startIt] = msg.position[idx[i]];
}
_valid_grippers = allFound;
}
if (_valid_grippers || _valid_arm)
{
// Some joints were present, so assuming that we got a message related to this arm.
// Otherwise, maybe this was just a joint state from another package.
// Then, leave the current states untouched.
valid_grippers = _valid_grippers;
valid_arm = _valid_arm;
}
last_update_time = ros::Time::now();
}
| 33.858407 | 132 | 0.630685 | JenniferBuehler |
af614c3913e80c9e76c3c381039cec26b54e4df9 | 905 | cpp | C++ | atcoder/arc106/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/arc106/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/arc106/C/main.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | #include <bits/stdc++.h>
using namespace std;
vector<vector<int>> solve(int N, int M) {
if (M < 0) return {};
vector<vector<int>> ans;
if (M == 0) {
int L = 1;
for (int i = 0; i < N; ++i) {
ans.push_back({ L++, L++ });
}
return ans;
}
int L = 1;
while (M + 1 > 0) {
--M;
ans.push_back({ ++L, ++L } );
}
ans.push_back({ 1, ++L });
if (ans.size() > N) return { };
while (ans.size() < N) {
ans.push_back({ ++L, ++L });
}
return ans;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int N, M;
cin >> N >> M;
auto ans = solve(N, M);
if (ans.size() == 0) {
cout << -1 << endl;
} else {
for (int i = 0; i < ans.size(); ++i) {
cout << ans[i][0] << " " << ans[i][1] << endl;
}
}
return 0;
} | 19.673913 | 58 | 0.403315 | xirc |
af630713fdc7d28f5c471fc958c7f449a1ef4271 | 283 | cpp | C++ | c-develop/16.intro function/callFunc.cpp | GustiArsyad123/C-Language-Test | 90a2eb45d1db2b039acbe5d3499aaff0aed99f82 | [
"MIT"
] | null | null | null | c-develop/16.intro function/callFunc.cpp | GustiArsyad123/C-Language-Test | 90a2eb45d1db2b039acbe5d3499aaff0aed99f82 | [
"MIT"
] | null | null | null | c-develop/16.intro function/callFunc.cpp | GustiArsyad123/C-Language-Test | 90a2eb45d1db2b039acbe5d3499aaff0aed99f82 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
void thisFungsi()
{
cout << "This is function!\n";
}
int main()
{
thisFungsi();
thisFungsi();
thisFungsi();
return 0;
}
// In below is output from iniFungsi
// This is function!
// This is function!
// This is function! | 14.894737 | 37 | 0.632509 | GustiArsyad123 |
af713365142726494a022dcfaf9252e109951ea2 | 1,276 | cpp | C++ | src/get_parent_id.cpp | biv-tomsksoft/cis1-core-native | 6cc2fafcd382be3e21eaeeda08cc660edf000975 | [
"MIT"
] | 1 | 2019-09-02T09:13:13.000Z | 2019-09-02T09:13:13.000Z | src/get_parent_id.cpp | biv-tomsksoft/cis1-core-native | 6cc2fafcd382be3e21eaeeda08cc660edf000975 | [
"MIT"
] | 1 | 2020-02-13T07:39:51.000Z | 2020-04-16T06:44:22.000Z | src/get_parent_id.cpp | biv-tomsksoft/cis1-core-native | 6cc2fafcd382be3e21eaeeda08cc660edf000975 | [
"MIT"
] | null | null | null | /*
* TomskSoft CIS1 Core
*
* (c) 2019 TomskSoft LLC
* (c) Mokin Innokentiy [mia@tomsksoft.com]
*
*/
#include "get_parent_id.h"
#ifdef _WIN32
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
size_t get_parent_id()
{
HANDLE snapshot_handle;
PROCESSENTRY32 pe32;
DWORD pid = GetCurrentProcessId();
DWORD ppid = 0;
snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
__try
{
if(snapshot_handle == INVALID_HANDLE_VALUE)
{
__leave;
}
ZeroMemory(&pe32, sizeof(pe32));
pe32.dwSize = sizeof(pe32);
if(!Process32First(snapshot_handle, &pe32))
{
__leave;
}
do
{
if(pe32.th32ProcessID == pid)
{
ppid = pe32.th32ParentProcessID;
break;
}
}
while(Process32Next(snapshot_handle, &pe32));
}
__finally
{
if(snapshot_handle != INVALID_HANDLE_VALUE)
{
CloseHandle(snapshot_handle);
}
}
return ppid;
}
#elif defined(__linux__) || defined(__APPLE__)
#include <unistd.h>
size_t get_parent_id()
{
return getppid();
}
#else
#error "Platform not supported"
#endif
| 17.971831 | 70 | 0.564263 | biv-tomsksoft |
af797a43c50f467add919f1c2328506e4cfac732 | 570 | cpp | C++ | Sources/baba-is-auto/Agents/RandomAgent.cpp | siva-msft/baba-is-auto | 3237b5b70167130558827979bde7dcee14ef39f3 | [
"MIT"
] | 108 | 2019-09-11T06:31:35.000Z | 2022-03-28T13:02:56.000Z | Sources/baba-is-auto/Agents/RandomAgent.cpp | siva-msft/baba-is-auto | 3237b5b70167130558827979bde7dcee14ef39f3 | [
"MIT"
] | 29 | 2019-09-12T00:28:04.000Z | 2022-02-20T14:56:27.000Z | Sources/baba-is-auto/Agents/RandomAgent.cpp | utilForever/BabaIsAuto | fb444668914eb70c0a35197399d650d293b4b95f | [
"MIT"
] | 14 | 2020-02-24T05:41:43.000Z | 2022-03-28T12:43:34.000Z | // Copyright (c) 2020 Chris Ohk
// I am making my contributions/submissions to this project solely in our
// personal capacity and am not conveying any rights to any intellectual
// property of any third parties.
#include <baba-is-auto/Agents/RandomAgent.hpp>
#include <effolkronium/random.hpp>
namespace baba_is_auto
{
Direction RandomAgent::GetAction([[maybe_unused]] const Game& state)
{
using Random = effolkronium::random_static;
return static_cast<Direction>(
Random::get(0, static_cast<int>(Direction::RIGHT)));
}
} // namespace baba_is_auto | 28.5 | 73 | 0.749123 | siva-msft |
af7b3de0706c489d915c94c0969b37ef1b328d98 | 49,081 | hpp | C++ | VSUtility/VSOctaveH5Writer.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | 1 | 2018-04-17T14:03:36.000Z | 2018-04-17T14:03:36.000Z | VSUtility/VSOctaveH5Writer.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | VSUtility/VSOctaveH5Writer.hpp | sfegan/ChiLA | 916bdd95348c2df2ecc736511d5f5b2bfb4a831e | [
"BSD-3-Clause"
] | null | null | null | //-*-mode:c++; mode:font-lock;-*-
/*! \file VSOctaveH5Writer.hpp
Classes to write to structured GNU/Octave HDF5 file. Data can be
read directly into octave.
\author Stephen Fegan \n
UCLA \n
sfegan@astro.ucla.edu \n
\version 1.0
\date 05/20/2006
*/
#include"VSOctaveIO.hpp"
#ifndef VSOCTAVEH5WRITER_HPP
#define VSOCTAVEH5WRITER_HPP
#include<string>
#include<vector>
#include<set>
#include<map>
#include<vsassert>
#include<hdf5.h>
namespace VERITAS
{
// ==========================================================================
// Octave H5 writer base class
// ==========================================================================
class VSOctaveH5WriterStruct;
class VSOctaveH5WriterCellVector;
class VSOctaveH5WriterExpandableCellVector;
class VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterBase(VSOctaveH5WriterBase* parent):
m_parent(parent), m_interested_parties(), m_children()
{ /* nothing to see here */ }
virtual ~VSOctaveH5WriterBase();
virtual void flush();
void registerInterestedParty(VSOctaveH5WriterBase* x);
static unsigned defaultChunk() { return 1024; }
static unsigned defaultCache() { return defaultChunk(); }
static bool defaultCompress() { return s_default_compress; }
static bool setDefaultCompress(bool c = true)
{ bool old=s_default_compress; s_default_compress=c; return old; }
protected:
template<typename T>
void makeAttribute(hid_t id, const std::string& name, const T& value);
void makeEmptyMatrix(hid_t gid, unsigned rows, unsigned cols);
virtual void notifyOfChildDestruction(VSOctaveH5WriterBase* child);
VSOctaveH5WriterBase* m_parent;
std::set<VSOctaveH5WriterBase*> m_interested_parties;
std::set<VSOctaveH5WriterBase*> m_children;
private:
VSOctaveH5WriterBase(const VSOctaveH5WriterBase&);
VSOctaveH5WriterBase& operator=(const VSOctaveH5WriterBase&);
static bool s_default_compress;
};
// ==========================================================================
// Octave H5 writer helpers
// ==========================================================================
template<typename T> class VSOctaveH5WriterLowLevelHelper
{
public:
static inline herr_t
write_scalar(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const T& x);
static inline herr_t
write_vector(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const std::vector<T>& v);
static inline herr_t
write_matrix(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
unsigned n, const T* m);
};
template<> class VSOctaveH5WriterLowLevelHelper<bool>
{
public:
static inline herr_t
write_scalar(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const bool& x);
static inline herr_t
write_vector(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const std::vector<bool>& v);
static inline herr_t
write_matrix(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
unsigned n, const bool* m);
};
template<typename T> class VSOctaveH5WriterHelper
{
public:
static inline bool write(VSOctaveH5WriterStruct* s,
const std::string& name, const T& x);
};
template<> class VSOctaveH5WriterHelper<std::string>
{
public:
static inline bool write(VSOctaveH5WriterStruct* s,
const std::string& name, const std::string& x);
};
template<typename T> class VSOctaveH5WriterHelper<std::vector<T> >
{
public:
static inline bool write(VSOctaveH5WriterStruct* s,
const std::string& name, const std::vector<T>& x);
};
template<> class VSOctaveH5WriterHelper<std::vector<std::string> >
{
public:
static inline bool write(VSOctaveH5WriterStruct* s,
const std::string& name,
const std::vector<std::string>& x);
};
// ==========================================================================
// Octave H5 writer expandable vector
// ==========================================================================
template<typename T>
class VSOctaveH5WriterVector: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterVector(hid_t gid, VSOctaveH5WriterBase* parent,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
virtual ~VSOctaveH5WriterVector();
virtual void flush();
bool append(const T& x);
unsigned rows() const { return m_rows; }
private:
VSOctaveH5WriterVector(const VSOctaveH5WriterVector&);
VSOctaveH5WriterVector& operator=(const VSOctaveH5WriterVector&);
bool write(const T* ptr, unsigned n);
hid_t m_gid;
hid_t m_tid;
hid_t m_did;
unsigned m_rows;
unsigned m_cachesize;
unsigned m_cacheoccupancy;
T* m_cache;
unsigned m_chunksize;
bool m_compress;
};
// ==========================================================================
// Octave H5 writer expandable table (matrix)
// ==========================================================================
template<typename T>
class VSOctaveH5WriterTable: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterTable(hid_t gid, unsigned cols,
VSOctaveH5WriterBase* parent,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
virtual ~VSOctaveH5WriterTable();
bool append(const std::vector<T>& row);
unsigned rows() const { return m_rows; }
private:
VSOctaveH5WriterTable(const VSOctaveH5WriterTable&);
VSOctaveH5WriterTable& operator=(const VSOctaveH5WriterTable&);
hid_t m_gid;
hid_t m_tid;
hid_t m_did;
unsigned m_cols;
unsigned m_rows;
unsigned m_cachesize;
unsigned m_chunksize;
bool m_compress;
};
// ==========================================================================
// Octave H5 writer expandable vector for composites
// ==========================================================================
class VSOH5WCVElementWriter
{
public:
virtual ~VSOH5WCVElementWriter();
virtual bool write(const void* data,
const VSOctaveH5CompositeDefinition::Member& field) = 0;
};
template<typename T> class VSOH5WCVEWTemplate: public VSOH5WCVElementWriter
{
public:
VSOH5WCVEWTemplate(VSOctaveH5WriterVector<T>* w): m_writer(w) { }
virtual ~VSOH5WCVEWTemplate() { }
virtual bool write(const void* data,
const VSOctaveH5CompositeDefinition::Member& field)
{
return
m_writer->append(*((const T*)((const char*)(data) + field.offset)));
}
private:
VSOH5WCVEWTemplate(const VSOH5WCVEWTemplate&);
VSOH5WCVEWTemplate& operator=(const VSOH5WCVEWTemplate&);
VSOctaveH5WriterVector<T>* m_writer;
};
class VSOH5WCVEWString: public VSOH5WCVElementWriter
{
public:
VSOH5WCVEWString(VSOctaveH5WriterExpandableCellVector* ecv): m_ecv(ecv) { }
virtual ~VSOH5WCVEWString();
virtual bool write(const void* data,
const VSOctaveH5CompositeDefinition::Member& field);
private:
VSOH5WCVEWString(const VSOH5WCVEWString&);
VSOH5WCVEWString& operator=(const VSOH5WCVEWString&);
VSOctaveH5WriterExpandableCellVector* m_ecv;
};
template<typename T>
class VSOctaveH5WriterCompositeVector: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterCompositeVector(VSOctaveH5WriterBase* parent,
VSOctaveH5WriterStruct* s,
bool struct_is_my_child,
const std::string& prefix = "",
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
virtual ~VSOctaveH5WriterCompositeVector();
virtual void flush();
bool append(const T& x);
unsigned rows() const { return m_rows; }
protected:
virtual void notifyOfChildDestruction(VSOctaveH5WriterBase* child);
private:
VSOctaveH5WriterCompositeVector(const VSOctaveH5WriterCompositeVector&);
VSOctaveH5WriterCompositeVector&
operator=(const VSOctaveH5WriterCompositeVector&);
struct MemWriter
{
MemWriter(const VSOctaveH5CompositeDefinition::Member& _field,
VSOH5WCVElementWriter* _writer = 0,
VSOctaveH5WriterBase* _actual_writer = 0):
field(_field), writer(_writer), actual_writer(_actual_writer) { }
MemWriter(const MemWriter& o):
field(o.field), writer(o.writer), actual_writer(o.actual_writer) { }
MemWriter& operator=(const MemWriter& o)
{
field = o.field;
writer = o.writer;
actual_writer = o.actual_writer;
return *this;
}
VSOctaveH5CompositeDefinition::Member field;
VSOH5WCVElementWriter* writer;
VSOctaveH5WriterBase* actual_writer;
};
std::vector<MemWriter> m_members;
unsigned m_rows;
};
// ==========================================================================
// Octave H5 writer cell array - just an interface to struct
// ==========================================================================
class VSOctaveH5WriterCellArray: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterCellArray(hid_t gid, unsigned rows, unsigned cols,
VSOctaveH5WriterBase* parent);
virtual ~VSOctaveH5WriterCellArray();
virtual void flush();
bool writeEmptyMatrix(unsigned row, unsigned col);
bool writeString(unsigned row, unsigned col, const std::string& s);
template<typename T>
bool writeScalar(unsigned row, unsigned col, const T& x);
template<typename T>
bool writeVector(unsigned row, unsigned col,
const std::vector<T>& v,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T>
bool writeMatrix(unsigned row, unsigned col,
unsigned rows, unsigned cols, const T* m);
template<typename T>
bool write(unsigned row, unsigned col, const T& x);
VSOctaveH5WriterStruct* writeStruct(unsigned row, unsigned col);
VSOctaveH5WriterCellArray*
writeCellArray(unsigned row, unsigned col, unsigned rows, unsigned cols);
VSOctaveH5WriterCellVector*
writeCellVector(unsigned row, unsigned col, unsigned nel,
VSOctaveH5VecOrientation orient = VO_ROW);
VSOctaveH5WriterExpandableCellVector*
writeExpandableCellVector(unsigned row, unsigned col,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T> VSOctaveH5WriterVector<T>*
writeExpandableVector(unsigned row, unsigned col,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> VSOctaveH5WriterTable<T>*
writeExpandableTable(unsigned row, unsigned col, unsigned cols,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> bool
writeComposite(unsigned row, unsigned col, const T& x);
template<typename T> bool
writeCompositeVector(unsigned row, unsigned col,
const std::vector<T>& x);
template<typename T> VSOctaveH5WriterCompositeVector<T>*
writeCompositeExpandableVector(unsigned row, unsigned col,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
private:
VSOctaveH5WriterCellArray(const VSOctaveH5WriterCellArray&);
VSOctaveH5WriterCellArray& operator=(const VSOctaveH5WriterCellArray&);
std::string name(unsigned row, unsigned col);
VSOctaveH5WriterStruct* m_struct;
unsigned m_rows;
unsigned m_cols;
unsigned m_name_precision;
std::vector<bool> m_written;
};
// ==========================================================================
// Octave H5 writer cell vector - just an interface to struct
// ==========================================================================
class VSOctaveH5WriterCellVector: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterCellVector(hid_t gid, unsigned nel,
VSOctaveH5WriterBase* parent);
virtual ~VSOctaveH5WriterCellVector();
virtual void flush();
bool writeEmptyMatrix(unsigned iel);
bool writeString(unsigned iel, const std::string& s);
template<typename T> bool writeScalar(unsigned iel, const T& x);
template<typename T>
bool writeVector(unsigned iel, const std::vector<T>& v,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T>
bool writeMatrix(unsigned iel, unsigned rows, unsigned cols, const T* m);
template<typename T>
bool write(unsigned iel, const T& x);
VSOctaveH5WriterStruct* writeStruct(unsigned iel);
VSOctaveH5WriterCellArray*
writeCellArray(unsigned iel, unsigned rows, unsigned cols);
VSOctaveH5WriterCellVector*
writeCellVector(unsigned iel, unsigned nel,
VSOctaveH5VecOrientation orient = VO_ROW);
VSOctaveH5WriterExpandableCellVector*
writeExpandableCellVector(unsigned iel,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T> VSOctaveH5WriterVector<T>*
writeExpandableVector(unsigned iel,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> VSOctaveH5WriterTable<T>*
writeExpandableTable(unsigned iel, unsigned cols,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> bool
writeComposite(unsigned iel, const T& x);
template<typename T> bool
writeCompositeVector(unsigned iel, const std::vector<T>& x);
template<typename T> VSOctaveH5WriterCompositeVector<T>*
writeCompositeExpandableVector(unsigned iel,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
private:
VSOctaveH5WriterCellVector(const VSOctaveH5WriterCellVector&);
VSOctaveH5WriterCellVector& operator=(const VSOctaveH5WriterCellVector&);
std::string name(unsigned iel);
VSOctaveH5WriterStruct* m_struct;
unsigned m_nel;
unsigned m_name_precision;
std::vector<bool> m_written;
};
// ==========================================================================
// Octave H5 writer expandable cell vector - just an interface to struct
// ==========================================================================
class VSOctaveH5WriterExpandableCellVector: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterExpandableCellVector(hid_t gid,
VSOctaveH5WriterBase* parent,
VSOctaveH5VecOrientation orient);
virtual ~VSOctaveH5WriterExpandableCellVector();
virtual void flush();
bool appendEmptyMatrix();
bool appendString(const std::string& s);
template<typename T> bool appendScalar(const T& x);
template<typename T>
bool appendVector(const std::vector<T>& v,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T>
bool appendMatrix(unsigned rows, unsigned cols, const T* m);
template<typename T>
bool append(const T& x);
VSOctaveH5WriterStruct* appendStruct();
VSOctaveH5WriterCellArray* appendCellArray(unsigned rows, unsigned cols);
VSOctaveH5WriterCellVector*
appendCellVector(unsigned nel, VSOctaveH5VecOrientation orient = VO_ROW);
VSOctaveH5WriterExpandableCellVector*
appendExpandableCellVector(VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T> VSOctaveH5WriterVector<T>*
appendExpandableVector(unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> VSOctaveH5WriterTable<T>*
appendExpandableTable(unsigned cols,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> bool appendComposite(const T& x);
template<typename T> bool appendCompositeVector(const std::vector<T>& x);
template<typename T> VSOctaveH5WriterCompositeVector<T>*
appendCompositeExpandableVector(unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
private:
VSOctaveH5WriterExpandableCellVector
(const VSOctaveH5WriterExpandableCellVector&);
VSOctaveH5WriterExpandableCellVector& operator=
(const VSOctaveH5WriterExpandableCellVector&);
std::string name();
unsigned m_nel;
VSOctaveH5VecOrientation m_orient;
hid_t m_gid;
hid_t m_value_gid;
VSOctaveH5WriterStruct* m_struct;
};
// ==========================================================================
// Octave H5 writer struct - this is where most of the action is
// ==========================================================================
class VSOctaveH5WriterStruct: public VSOctaveH5WriterBase
{
public:
VSOctaveH5WriterStruct(const std::string& filename, bool overwrite=false,
const std::string& comment="");
VSOctaveH5WriterStruct(hid_t gid, VSOctaveH5WriterBase* parent);
virtual ~VSOctaveH5WriterStruct();
virtual void flush();
bool writeEmptyMatrix(const std::string& name);
bool writeString(const std::string& name, const std::string& s);
template<typename T>
bool writeScalar(const std::string& name, const T& x);
template<typename T>
bool writeVector(const std::string& name,
const std::vector<T>& v,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T>
bool writeMatrix(const std::string& name,
unsigned rows, unsigned cols, const T* m);
template<typename T>
bool write(const std::string& name, const T& x);
VSOctaveH5WriterStruct* writeStruct(const std::string& name);
VSOctaveH5WriterCellArray*
writeCellArray(const std::string& name, unsigned rows, unsigned cols);
template<typename T> bool
writeStructCellVector(const std::string& name, const std::vector<T>& x);
VSOctaveH5WriterCellVector*
writeCellVector(const std::string& name, unsigned nel,
VSOctaveH5VecOrientation orient = VO_ROW);
VSOctaveH5WriterExpandableCellVector*
writeExpandableCellVector(const std::string& name,
VSOctaveH5VecOrientation orient = VO_ROW);
template<typename T> VSOctaveH5WriterVector<T>*
writeExpandableVector(const std::string& name,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> VSOctaveH5WriterTable<T>*
writeExpandableTable(const std::string& name, unsigned cols,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> bool
writeCompositeHere(const T& x, const std::string& prefix = "");
template<typename T> bool
writeCompositeVectorHere(const std::vector<T>& x,
const std::string& prefix = "");
template<typename T> VSOctaveH5WriterCompositeVector<T>*
writeCompositeExpandableVectorHere(const std::string& prefix = "",
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
template<typename T> bool
writeComposite(const std::string& name, const T& x);
template<typename T> bool
writeCompositeVector(const std::string& name, const std::vector<T>& x);
template<typename T> VSOctaveH5WriterCompositeVector<T>*
writeCompositeExpandableVector(const std::string& name,
unsigned cachesize = defaultCache(),
unsigned chunksize = defaultChunk(),
bool compress = defaultCompress());
protected:
virtual void notifyOfChildDestruction(VSOctaveH5WriterBase* child);
private:
VSOctaveH5WriterStruct(const VSOctaveH5WriterStruct&);
VSOctaveH5WriterStruct& operator=(const VSOctaveH5WriterStruct&);
hid_t makeVariable(const std::string& name,
const std::string& type, const std::string& eltype="");
void registerChild(VSOctaveH5WriterBase* child, hid_t gid);
bool m_my_file;
hid_t m_gid;
std::set<std::string> m_vars;
std::map<VSOctaveH5WriterBase*, hid_t> m_gid_map;
};
typedef VSOctaveH5WriterStruct VSOctaveH5Writer;
// **************************************************************************
// **************************************************************************
// FUNCTION DEFINITIONS
// **************************************************************************
// **************************************************************************
// ==========================================================================
// BASE
// ==========================================================================
template<typename T> void VSOctaveH5WriterBase::
makeAttribute(hid_t id, const std::string& name, const T& value)
{
hid_t tid = VSOctaveH5Type<T>::h5_type();
hid_t sid = H5Screate(H5S_SCALAR);
hid_t aid = H5Acreate(id, name.c_str(), tid, sid, H5P_DEFAULT);
H5Awrite(aid, tid, &value);
H5Aclose(aid);
H5Sclose(sid);
H5Tclose(tid);
}
// ==========================================================================
// HELPER
// ==========================================================================
template<typename T> inline herr_t VSOctaveH5WriterLowLevelHelper<T>::
write_scalar(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const T& x)
{
return H5Dwrite(did, tid, core_sid, disk_sid, H5P_DEFAULT, &x);
}
template<typename T> inline herr_t VSOctaveH5WriterLowLevelHelper<T>::
write_vector(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const std::vector<T>& v)
{
return H5Dwrite(did, tid, core_sid, disk_sid, H5P_DEFAULT, &v[0]);
}
template<typename T> inline herr_t VSOctaveH5WriterLowLevelHelper<T>::
write_matrix(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
unsigned n, const T* m)
{
return H5Dwrite(did, tid, core_sid, disk_sid, H5P_DEFAULT, m);
}
herr_t inline VSOctaveH5WriterLowLevelHelper<bool>::
write_scalar(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const bool& x)
{
unsigned y = x?1:0;
return H5Dwrite(did, tid, core_sid, disk_sid, H5P_DEFAULT, &y);
}
herr_t inline VSOctaveH5WriterLowLevelHelper<bool>::
write_vector(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
const std::vector<bool>& v)
{
unsigned nv = v.size();
std::vector<unsigned> u(nv);
for(unsigned iv=0;iv<nv;iv++)u[iv]=v[iv]?1:0;
return H5Dwrite(did, tid, core_sid, disk_sid, H5P_DEFAULT, &u[0]);
}
herr_t inline VSOctaveH5WriterLowLevelHelper<bool>::
write_matrix(hid_t did, hid_t tid, hid_t core_sid, hid_t disk_sid,
unsigned n, const bool* m)
{
std::vector<unsigned> v(n);
for(unsigned im=0;im<n;im++)v[im]=m[im]?1:0;
return H5Dwrite(did, tid, core_sid, disk_sid, H5P_DEFAULT, &v[0]);
}
template<typename T> bool inline VSOctaveH5WriterHelper<T>::
write(VSOctaveH5WriterStruct* s, const std::string& name, const T& x)
{
return s->writeScalar(name,x);
};
bool inline VSOctaveH5WriterHelper<std::string>::
write(VSOctaveH5WriterStruct* s,
const std::string& name, const std::string& x)
{
return s->writeString(name,x);
};
template<typename T> bool inline VSOctaveH5WriterHelper<std::vector<T> >::
write(VSOctaveH5WriterStruct* s,
const std::string& name, const std::vector<T>& x)
{
return s->writeVector(name,x);
}
bool inline VSOctaveH5WriterHelper<std::vector<std::string> >::
write(VSOctaveH5WriterStruct* s,
const std::string& name, const std::vector<std::string>& x)
{
unsigned nstring = x.size();
VSOctaveH5WriterCellVector* c = s->writeCellVector(name,nstring);
if(c==0)return false;
for(unsigned istring=0;istring<nstring;istring++)
if(!c->writeString(istring,x[istring]))
{
delete c;
return false;
}
delete c;
return true;
}
// ==========================================================================
// VECTOR
// ==========================================================================
template<typename T> VSOctaveH5WriterVector<T>::
VSOctaveH5WriterVector(hid_t gid, VSOctaveH5WriterBase* parent,
unsigned cachesize, unsigned chunksize, bool compress)
: VSOctaveH5WriterBase(parent),
m_gid(gid), m_tid(), m_did(), m_rows(0),
m_cachesize(cachesize), m_cacheoccupancy(), m_cache(),
m_chunksize(chunksize), m_compress(compress)
{
if(cachesize)m_cache = new T[cachesize];
}
template<typename T> VSOctaveH5WriterVector<T>::
~VSOctaveH5WriterVector()
{
if(m_rows == 0)
{
makeEmptyMatrix(m_gid,1,0);
}
else
{
if(m_cacheoccupancy)write(m_cache,m_cacheoccupancy);
H5Dclose(m_did);
H5Tclose(m_tid);
}
if(m_cachesize)delete[] m_cache;
}
template<typename T> void VSOctaveH5WriterVector<T>::
VSOctaveH5WriterVector::flush()
{
if(m_cacheoccupancy)
{
write(m_cache,m_cacheoccupancy);
m_cacheoccupancy=0;
H5Fflush(m_gid,H5F_SCOPE_LOCAL);
}
}
template<typename T> bool VSOctaveH5WriterVector<T>::
append(const T& x)
{
bool status = true;
m_rows++;
if(m_cachesize == 0)
status=write(&x,1);
else
{
m_cache[m_cacheoccupancy++]=x;
if(m_cacheoccupancy==m_cachesize)
{
status=write(m_cache,m_cacheoccupancy);
m_cacheoccupancy=0;
}
}
return status;
}
template<typename T> bool VSOctaveH5WriterVector<T>::
write(const T* ptr, unsigned n)
{
unsigned nwritten = m_rows-n;
hsize_t count[2] = { n, 1 };
h5_select_hyperslab_t start[2] = { nwritten, 0 };
hsize_t dims[2] = { m_rows, 1 };
hid_t disk_sid;
if(nwritten == 0)
{
hsize_t maxdims[2] = { H5S_UNLIMITED, 1 };
m_tid = VSOctaveH5Type<T>::h5_type();
disk_sid = H5Screate_simple(2, dims, maxdims);
hsize_t chunk[2] = { m_chunksize, 1 };
hid_t pid = H5Pcreate(H5P_DATASET_CREATE);
H5Pset_layout(pid, H5D_CHUNKED);
H5Pset_chunk(pid, 2, chunk);
if(m_compress)
{
H5Pset_filter(pid, H5Z_FILTER_DEFLATE, H5Z_FLAG_OPTIONAL, 0, 0);
H5Pset_deflate(pid, 6);
}
m_did = H5Dcreate(m_gid, OCTAVE_H5_EL_VALUE, m_tid, disk_sid, pid);
if(m_did<0)
{
VSOctaveH5Exception
e(std::string("Could not create dataset: value"));
throw(e);
}
H5Pclose(pid);
}
else
{
if(H5Dextend(m_did,dims)<0)
{
VSOctaveH5Exception e(std::string("Could not extend dataset"));
throw(e);
}
disk_sid = H5Dget_space(m_did);
}
H5Sselect_hyperslab(disk_sid, H5S_SELECT_SET, start, NULL, count, NULL);
hid_t core_sid = H5Screate_simple(2, count, NULL);
if(VSOctaveH5WriterLowLevelHelper<T>::
write_matrix(m_did, m_tid, core_sid, disk_sid, n, ptr) < 0)
{
VSOctaveH5Exception
e(std::string("Could not write to dataset: value"));
throw(e);
}
H5Sclose(disk_sid);
H5Sclose(core_sid);
return true;
}
// ==========================================================================
// TABLE
// ==========================================================================
template<typename T> VSOctaveH5WriterTable<T>::
VSOctaveH5WriterTable(hid_t gid, unsigned cols,
VSOctaveH5WriterBase* parent,
unsigned cachesize, unsigned chunksize, bool compress):
VSOctaveH5WriterBase(parent),
m_gid(gid), m_tid(), m_did(), m_cols(cols), m_rows(0),
m_cachesize(cachesize), m_chunksize(chunksize), m_compress(compress)
{
// nothing to see here -- creation of HDF elements deferred to append()
}
template<typename T> VSOctaveH5WriterTable<T>::
VSOctaveH5WriterTable::~VSOctaveH5WriterTable()
{
if(m_rows == 0)
{
makeEmptyMatrix(m_gid,m_cols,0); /* meaning of cols is wrong! */
}
else
{
H5Dclose(m_did);
H5Tclose(m_tid);
}
}
template<typename T> bool VSOctaveH5WriterTable<T>::
append(const std::vector<T>& x)
{
if(x.size() != m_cols)return false;
hsize_t count[2] = { 1, m_cols };
hsize_t start[2] = { m_rows, 0 };
m_rows++;
hsize_t dims[2] = { m_rows, m_cols };
hid_t disk_sid;
if(m_rows == 1)
{
hsize_t maxdims[2] = { H5S_UNLIMITED, m_cols };
m_tid = VSOctaveH5Type<T>::h5_type();
disk_sid = H5Screate_simple(2, dims, maxdims);
hsize_t chunk[2] = { m_chunksize, 1 };
hid_t pid = H5Pcreate(H5P_DATASET_CREATE);
H5Pset_layout(pid, H5D_CHUNKED);
H5Pset_chunk(pid, 2, chunk);
if(m_compress)
{
H5Pset_filter(pid, H5Z_FILTER_DEFLATE, H5Z_FLAG_OPTIONAL, 0, 0);
H5Pset_deflate(pid, 6);
}
m_did = H5Dcreate(m_gid, OCTAVE_H5_EL_VALUE, m_tid, disk_sid, pid);
if(m_did<0)
{
VSOctaveH5Exception
e(std::string("Could not create dataset: value"));
throw(e);
}
H5Pclose(pid);
}
else
{
if(H5Dextend(m_did,dims)<0)
{
VSOctaveH5Exception e(std::string("Could not extend dataset"));
throw(e);
}
disk_sid = H5Dget_space(m_did);
}
H5Sselect_hyperslab(disk_sid, H5S_SELECT_SET, start, NULL, count, NULL);
hid_t core_sid = H5Screate_simple(2, count, NULL);
if(VSOctaveH5WriterLowLevelHelper<T>::
write_matrix(m_did, m_tid, core_sid, disk_sid, m_cols, &x[0]) < 0)
{
VSOctaveH5Exception
e(std::string("Could not write to dataset: value"));
throw(e);
}
H5Sclose(disk_sid);
H5Sclose(core_sid);
return true;
}
// ==========================================================================
// COMPOSITE VECTOR
// ==========================================================================
#define __CASENEW(t) \
if(im->type == VSOctaveH5Type<t>::int_type()) \
{ \
VSOctaveH5WriterVector<t>* vec = \
s->writeExpandableVector<t>(im->name, cachesize,chunksize,compress); \
vec->registerInterestedParty(this); \
m.writer = new VSOH5WCVEWTemplate<t>(vec); \
m.actual_writer = vec; \
m_members.push_back(m); \
continue; \
}
template<typename T> VSOctaveH5WriterCompositeVector<T>::
VSOctaveH5WriterCompositeVector(VSOctaveH5WriterBase* parent,
VSOctaveH5WriterStruct* s,
bool struct_is_my_child,
const std::string& prefix,
unsigned cachesize, unsigned chunksize,
bool compress):
VSOctaveH5WriterBase(parent), m_members(), m_rows()
{
VSOctaveH5CompositeDefinition c(prefix);
VSOctaveH5CompositeCompose<T>::compose(c);
const std::vector<VSOctaveH5CompositeDefinition::Member> m = c.members();
for(std::vector<VSOctaveH5CompositeDefinition::Member>::const_iterator
im = m.begin(); im!=m.end(); im++)
{
MemWriter m(*im,0);
__CASENEW(bool);
__CASENEW(int8_t);
__CASENEW(int16_t);
__CASENEW(int32_t);
__CASENEW(int64_t);
__CASENEW(uint8_t);
__CASENEW(uint16_t);
__CASENEW(uint32_t);
__CASENEW(uint64_t);
__CASENEW(float);
__CASENEW(double);
if(im->type == OIT_STRING)
{
VSOctaveH5WriterExpandableCellVector* cv =
s->writeExpandableCellVector(im->name);
cv->registerInterestedParty(this);
m.writer = new VSOH5WCVEWString(cv);
m.actual_writer = cv;
m_members.push_back(m);
continue;
}
vsassert(0);
}
if(struct_is_my_child)m_children.insert(s);
}
#undef __CASENEW
template<typename T> VSOctaveH5WriterCompositeVector<T>::
~VSOctaveH5WriterCompositeVector()
{
for(typename std::vector<MemWriter>::const_iterator im = m_members.begin();
im!=m_members.end(); im++)
delete im->actual_writer;
if(!m_children.empty())
{
delete *m_children.begin();
m_children.erase(*m_children.begin());
}
vsassert(m_children.empty());
}
template<typename T> void VSOctaveH5WriterCompositeVector<T>::flush()
{
for(typename std::vector<MemWriter>::const_iterator im = m_members.begin();
im!=m_members.end(); im++)
im->actual_writer->flush();
}
template<typename T> bool VSOctaveH5WriterCompositeVector<T>::
append(const T& x)
{
bool status = true;
for(typename std::vector<MemWriter>::const_iterator im = m_members.begin();
im!=m_members.end(); im++)
status &= im->writer->write(&x, im->field);
m_rows++;
return status;
}
template<typename T> void VSOctaveH5WriterCompositeVector<T>::
notifyOfChildDestruction(VSOctaveH5WriterBase* child)
{
for(typename std::vector<MemWriter>::iterator im = m_members.begin();
im!=m_members.end(); im++)
if(child == im->actual_writer)
{
delete im->writer;
im->writer = 0;
im->actual_writer = 0;
return;
}
vsassert(0);
}
// ==========================================================================
// CELL ARRAY
// ==========================================================================
template<typename T> bool VSOctaveH5WriterCellArray::
writeScalar(unsigned row, unsigned col, const T& x)
{
return m_struct->writeScalar(name(row,col), x);
}
template<typename T> bool VSOctaveH5WriterCellArray::
writeVector(unsigned row, unsigned col,
const std::vector<T>& v, VSOctaveH5VecOrientation orient)
{
return m_struct->writeVector(name(row,col), v, orient);
}
template<typename T> bool VSOctaveH5WriterCellArray::
writeMatrix(unsigned row, unsigned col,
unsigned rows, unsigned cols, const T* m)
{
return m_struct->writeMatrix(name(row,col), rows, cols, m);
}
template<typename T> bool VSOctaveH5WriterCellArray::
write(unsigned row, unsigned col, const T& x)
{
return m_struct->write(name(row,col), x);
}
template<typename T> VSOctaveH5WriterVector<T>*
VSOctaveH5WriterCellArray::
writeExpandableVector(unsigned row, unsigned col,
unsigned cachesize, unsigned chunksize, bool compress)
{
return m_struct->
writeExpandableVector<T>(name(row,col),cachesize,chunksize,compress);
}
template<typename T> VSOctaveH5WriterTable<T>*
VSOctaveH5WriterCellArray::
writeExpandableTable(unsigned row, unsigned col, unsigned cols,
unsigned cachesize, unsigned chunksize, bool compress)
{
return m_struct->
writeExpandableTable<T>(name(row,col), cols,
cachesize, chunksize, compress);
}
template<typename T> bool VSOctaveH5WriterCellArray::
writeComposite(unsigned row, unsigned col, const T& x)
{
return m_struct->writeComposite(name(row,col),x);
}
template<typename T> bool VSOctaveH5WriterCellArray::
writeCompositeVector(unsigned row, unsigned col,
const std::vector<T>& x)
{
return m_struct->writeCompositeVector(name(row,col),x);
}
template<typename T> VSOctaveH5WriterCompositeVector<T>*
VSOctaveH5WriterCellArray::
writeCompositeExpandableVector(unsigned row, unsigned col,
unsigned cachesize, unsigned chunksize,
bool compress)
{
return m_struct->
writeCompositeExpandableVector<T>(name(row,col),
cachesize, chunksize, compress);
}
// ==========================================================================
// CELL VECTOR
// ==========================================================================
template<typename T> bool VSOctaveH5WriterCellVector::
writeScalar(unsigned iel, const T& x)
{
return m_struct->writeScalar(name(iel), x);
}
template<typename T> bool VSOctaveH5WriterCellVector::
writeVector(unsigned iel,
const std::vector<T>& v, VSOctaveH5VecOrientation orient)
{
return m_struct->writeVector(name(iel), v, orient);
}
template<typename T> bool VSOctaveH5WriterCellVector::
writeMatrix(unsigned iel,
unsigned rows, unsigned cols, const T* m)
{
return m_struct->writeMatrix(name(iel), rows, cols, m);
}
template<typename T> bool VSOctaveH5WriterCellVector::
write(unsigned iel, const T& x)
{
return m_struct->write(name(iel), x);
}
template<typename T> VSOctaveH5WriterVector<T>*
VSOctaveH5WriterCellVector::
writeExpandableVector(unsigned iel,
unsigned cachesize, unsigned chunksize, bool compress)
{
return m_struct->
writeExpandableVector<T>(name(iel),cachesize,chunksize,compress);
}
template<typename T> VSOctaveH5WriterTable<T>*
VSOctaveH5WriterCellVector::
writeExpandableTable(unsigned iel, unsigned cols,
unsigned cachesize, unsigned chunksize, bool compress)
{
return m_struct->
writeExpandableTable<T>(name(iel), cols, cachesize, chunksize, compress);
}
template<typename T> bool VSOctaveH5WriterCellVector::
writeComposite(unsigned iel, const T& x)
{
return m_struct->writeComposite(name(iel),x);
}
template<typename T> bool VSOctaveH5WriterCellVector::
writeCompositeVector(unsigned iel, const std::vector<T>& x)
{
return m_struct->writeCompositeVector(name(iel),x);
}
template<typename T> VSOctaveH5WriterCompositeVector<T>*
VSOctaveH5WriterCellVector::
writeCompositeExpandableVector(unsigned iel,
unsigned cachesize, unsigned chunksize,
bool compress)
{
return m_struct->
writeCompositeExpandableVector<T>(name(iel),
cachesize, chunksize, compress);
}
// ==========================================================================
// EXPANDABLE CELL VECTOR
// ==========================================================================
template<typename T> bool VSOctaveH5WriterExpandableCellVector::
appendScalar(const T& x)
{
return m_struct->writeScalar(name(), x);
}
template<typename T> bool VSOctaveH5WriterExpandableCellVector::
appendVector(const std::vector<T>& v, VSOctaveH5VecOrientation orient)
{
return m_struct->writeVector(name(), v, orient);
}
template<typename T> bool VSOctaveH5WriterExpandableCellVector::
appendMatrix(unsigned rows, unsigned cols, const T* m)
{
return m_struct->writeMatrix(name(), rows, cols, m);
}
template<typename T> bool VSOctaveH5WriterExpandableCellVector::
append(const T& x)
{
return m_struct->write(name(), x);
}
template<typename T> VSOctaveH5WriterVector<T>*
VSOctaveH5WriterExpandableCellVector::
appendExpandableVector(unsigned cachesize, unsigned chunksize, bool compress)
{
return m_struct->
writeExpandableVector<T>(name(),cachesize,chunksize, compress);
}
template<typename T> VSOctaveH5WriterTable<T>*
VSOctaveH5WriterExpandableCellVector::
appendExpandableTable(unsigned cols,
unsigned cachesize, unsigned chunksize, bool compress)
{
return m_struct->
writeExpandableTable<T>(name(), cols, cachesize, chunksize, compress);
}
template<typename T> bool VSOctaveH5WriterExpandableCellVector::
appendComposite(const T& x)
{
return m_struct->writeComposite(name(),x);
}
template<typename T> bool VSOctaveH5WriterExpandableCellVector::
appendCompositeVector(const std::vector<T>& x)
{
return m_struct->writeCompositeVector(name(),x);
}
template<typename T> VSOctaveH5WriterCompositeVector<T>*
VSOctaveH5WriterExpandableCellVector::
appendCompositeExpandableVector(unsigned cachesize, unsigned chunksize,
bool compress)
{
return m_struct->
writeCompositeExpandableVector<T>(name(),
cachesize, chunksize, compress);
}
// ==========================================================================
// STRUCT
// ==========================================================================
template<typename T> bool VSOctaveH5WriterStruct::
writeScalar(const std::string& name, const T& x)
{
hid_t gid = makeVariable(name, OCTAVE_H5_TYPE_SCALAR,
VSOctaveH5Type<T>::oct_type());
hid_t tid = VSOctaveH5Type<T>::h5_type();
hid_t sid = H5Screate(H5S_SCALAR);
hid_t did = H5Dcreate(gid, OCTAVE_H5_EL_VALUE, tid, sid, H5P_DEFAULT);
if(did<0)
{
VSOctaveH5Exception
e(name+std::string(": could not create dataset: value"));
throw(e);
}
if(VSOctaveH5WriterLowLevelHelper<T>::
write_scalar(did, tid, H5S_ALL, H5S_ALL, x) < 0)
{
VSOctaveH5Exception
e(name+std::string(": could not write to dataset: value"));
throw(e);
}
H5Dclose(did);
H5Sclose(sid);
H5Tclose(tid);
H5Gclose(gid);
return true;
}
template<typename T> bool VSOctaveH5WriterStruct::
VSOctaveH5WriterStruct::writeVector(const std::string& name,
const std::vector<T>& v,
VSOctaveH5VecOrientation orient)
{
hid_t gid = makeVariable(name, OCTAVE_H5_TYPE_MATRIX,
VSOctaveH5Type<T>::oct_type());
if(v.size() == 0)
{
if(orient == VO_COLUMN)makeEmptyMatrix(gid,0,1);
else makeEmptyMatrix(gid,1,0);
H5Gclose(gid);
return true;
}
hid_t tid = VSOctaveH5Type<T>::h5_type();
hsize_t dims[2] = { 1, 1 };
if(orient == VO_COLUMN)dims[1] = v.size();
else dims[0] = v.size();
hid_t sid = H5Screate_simple(2, dims, NULL);
hid_t did = H5Dcreate(gid, OCTAVE_H5_EL_VALUE, tid, sid, H5P_DEFAULT);
if(did<0)
{
VSOctaveH5Exception
e(name+std::string(": could not create dataset: value"));
throw(e);
}
if(VSOctaveH5WriterLowLevelHelper<T>::
write_vector(did, tid, H5S_ALL, H5S_ALL, v) < 0)
{
VSOctaveH5Exception
e(name+std::string(": could not write to dataset: value"));
throw(e);
}
H5Dclose(did);
H5Sclose(sid);
H5Tclose(tid);
H5Gclose(gid);
return true;
}
template<typename T> bool VSOctaveH5WriterStruct::
writeMatrix(const std::string& name,
unsigned rows, unsigned cols, const T* m)
{
hid_t gid = makeVariable(name, OCTAVE_H5_TYPE_MATRIX,
VSOctaveH5Type<T>::oct_type());
if((rows == 0)||(cols == 0))
{
// This is messed up - I would hate to totally go to the
// FORTRAN standard - so I have to transpose the matrix, so that
// a nr x nc matric in C++ becomes transposed in octave
makeEmptyMatrix(gid,cols,rows);
H5Gclose(gid);
return true;
}
hid_t tid = VSOctaveH5Type<T>::h5_type();
hsize_t dims[2] = { rows, cols };
hid_t sid = H5Screate_simple(2, dims, NULL);
hid_t did = H5Dcreate(gid, OCTAVE_H5_EL_VALUE, tid, sid, H5P_DEFAULT);
if(did<0)
{
VSOctaveH5Exception
e(name+std::string(": could not create dataset: value"));
throw(e);
}
if(VSOctaveH5WriterLowLevelHelper<T>::
write_matrix(did, tid, H5S_ALL, H5S_ALL, rows*cols, m) < 0)
{
VSOctaveH5Exception
e(name+std::string(": could not write to dataset: value"));
throw(e);
}
H5Dclose(did);
H5Sclose(sid);
H5Tclose(tid);
H5Gclose(gid);
return true;
}
template<typename T> bool VSOctaveH5WriterStruct::
write(const std::string& name, const T& x)
{
return VSOctaveH5WriterHelper<T>(this,name,x);
}
template<typename T> VSOctaveH5WriterVector<T>* VSOctaveH5WriterStruct::
writeExpandableVector(const std::string& name,
unsigned cachesize, unsigned chunksize, bool compress)
{
hid_t gid = makeVariable(name, OCTAVE_H5_TYPE_MATRIX,
VSOctaveH5Type<T>::oct_type());
VSOctaveH5WriterVector<T>* v =
new VSOctaveH5WriterVector<T>(gid,this,cachesize,chunksize,compress);
registerChild(v,gid);
return v;
}
template<typename T> VSOctaveH5WriterTable<T>* VSOctaveH5WriterStruct::
writeExpandableTable(const std::string& name, unsigned cols,
unsigned cachesize, unsigned chunksize, bool compress)
{
hid_t gid = makeVariable(name, OCTAVE_H5_TYPE_MATRIX,
VSOctaveH5Type<T>::oct_type());
VSOctaveH5WriterTable<T>* m =
new VSOctaveH5WriterTable<T>(gid,cols,this,cachesize,chunksize,compress);
registerChild(m,gid);
return m;
}
#define __CASESCALAR(t,x,im) \
if(im->type == VSOctaveH5Type<t>::int_type()) \
{ \
status &= writeScalar(im->name,*((t*)((char*)(&x) + im->offset))); \
continue; \
}
template<typename T> bool VSOctaveH5WriterStruct::
writeCompositeHere(const T& x, const std::string& prefix)
{
bool status = true;
VSOctaveH5CompositeDefinition c(prefix);
VSOctaveH5CompositeCompose<T>::compose(c);
const std::vector<VSOctaveH5CompositeDefinition::Member> m = c.members();
for(std::vector<VSOctaveH5CompositeDefinition::Member>::const_iterator
im = m.begin(); im!=m.end(); im++)
{
__CASESCALAR(bool, x, im);
__CASESCALAR(int8_t, x, im);
__CASESCALAR(int16_t, x, im);
__CASESCALAR(int32_t, x, im);
__CASESCALAR(int64_t, x, im);
__CASESCALAR(uint8_t, x, im);
__CASESCALAR(uint16_t, x, im);
__CASESCALAR(uint32_t, x, im);
__CASESCALAR(uint64_t, x, im);
__CASESCALAR(float, x, im);
__CASESCALAR(double, x, im);
if(im->type == OIT_STRING)
{
status &=
writeString(im->name,*((std::string*)((char*)(&x)+im->offset)));
continue;
}
vsassert(0);
}
return status;
}
#undef __CASESCALAR
#define __CASEVECTOR(t,x,im) \
if(im->type == VSOctaveH5Type<t>::int_type()) \
{ \
unsigned nel = x.size(); \
std::vector<t> v(nel); \
for(unsigned iel=0;iel<nel;iel++) \
v[iel] = *((t*)((char*)(&x[iel]) + im->offset)); \
status &= writeVector(im->name,v); \
continue; \
}
template<typename T> bool VSOctaveH5WriterStruct::
writeStructCellVector(const std::string& name, const std::vector<T>& x)
{
bool status = true;
VSOctaveH5WriterCellVector* wc = writeCellVector(name, x.size());
for(unsigned i = 0; i < x.size(); i++)
{
VSOctaveH5WriterStruct* ws = wc->writeStruct(i);
x[i].save(ws);
delete ws;
}
delete wc;
return status;
}
template<typename T> bool VSOctaveH5WriterStruct::
writeCompositeVectorHere(const std::vector<T>& x, const std::string& prefix)
{
bool status = true;
VSOctaveH5CompositeDefinition c(prefix);
VSOctaveH5CompositeCompose<T>::compose(c);
const std::vector<VSOctaveH5CompositeDefinition::Member> m = c.members();
for(std::vector<VSOctaveH5CompositeDefinition::Member>::const_iterator
im = m.begin(); im!=m.end(); im++)
{
__CASEVECTOR(bool, x, im);
__CASEVECTOR(int8_t, x, im);
__CASEVECTOR(int16_t, x, im);
__CASEVECTOR(int32_t, x, im);
__CASEVECTOR(int64_t, x, im);
__CASEVECTOR(uint8_t, x, im);
__CASEVECTOR(uint16_t, x, im);
__CASEVECTOR(uint32_t, x, im);
__CASEVECTOR(uint64_t, x, im);
__CASEVECTOR(float, x, im);
__CASEVECTOR(double, x, im);
if(im->type == OIT_STRING)
{
unsigned nel = x.size();
VSOctaveH5WriterCellVector* cv = writeCellVector(im->name,nel);
if(cv)
{
for(unsigned iel=0;iel<nel;iel++)
status &= cv->writeString(iel,
*((std::string*)((char*)(&x[iel])+im->offset)));
delete cv;
}
continue;
}
vsassert(0);
}
return status;
}
#undef __CASEVECTOR
template<typename T>
VSOctaveH5WriterCompositeVector<T>* VSOctaveH5WriterStruct::
writeCompositeExpandableVectorHere(const std::string& prefix,
unsigned cachesize, unsigned chunksize,
bool compress)
{
VSOctaveH5WriterCompositeVector<T>* c =
new VSOctaveH5WriterCompositeVector<T>(this, this, false, prefix,
cachesize,chunksize,compress);
registerChild(c,-1);
return c;
}
template<typename T> bool VSOctaveH5WriterStruct::
writeComposite(const std::string& name, const T& x)
{
VSOctaveH5WriterStruct* s = writeStruct(name);
bool status = s->writeCompositeHere(x);
delete s;
return status;
}
template<typename T> bool VSOctaveH5WriterStruct::
writeCompositeVector(const std::string& name, const std::vector<T>& x)
{
VSOctaveH5WriterStruct* s = writeStruct(name);
bool status = s->writeCompositeVectorHere(x);
delete s;
return status;
}
template<typename T> VSOctaveH5WriterCompositeVector<T>*
VSOctaveH5WriterStruct::
writeCompositeExpandableVector(const std::string& name,
unsigned cachesize, unsigned chunksize,
bool compress)
{
hid_t gid = makeVariable(name, OCTAVE_H5_TYPE_STRUCT);
hid_t value_gid = H5Gcreate(gid, OCTAVE_H5_EL_VALUE, 0);
if(value_gid<0)
{
VSOctaveH5Exception
e(std::string("Could not create group: " OCTAVE_H5_EL_VALUE));
throw(e);
}
VSOctaveH5WriterStruct* s = new VSOctaveH5WriterStruct(value_gid,0);
VSOctaveH5WriterCompositeVector<T>* c =
new VSOctaveH5WriterCompositeVector<T>(this, s, true, "",
cachesize,chunksize,compress);
registerChild(c,gid);
return c;
}
} // namespace VERITAS
#endif // VSOCTAVEH5WRITER_HPP
| 30.675625 | 79 | 0.642204 | sfegan |
af7c794c3b4c5b35f209616e9398a62ed21b22e3 | 3,214 | cpp | C++ | Phase 1 Placement Specific/08. Arrays/8.2 Searching Algorithm/Motarack's Birthday.cpp | Tanushree-coder/CPP-DSA | 94158ed9b251789dff26862e70f46015a02b2a47 | [
"Apache-2.0"
] | 42 | 2021-01-03T17:54:59.000Z | 2022-03-26T15:57:01.000Z | Phase 1 Placement Specific/08. Arrays/8.2 Searching Algorithm/Motarack's Birthday.cpp | Tanushree-coder/CPP-DSA | 94158ed9b251789dff26862e70f46015a02b2a47 | [
"Apache-2.0"
] | 26 | 2021-04-05T07:54:21.000Z | 2021-12-10T07:35:39.000Z | Phase 1 Placement Specific/08. Arrays/8.2 Searching Algorithm/Motarack's Birthday.cpp | Tanushree-coder/CPP-DSA | 94158ed9b251789dff26862e70f46015a02b2a47 | [
"Apache-2.0"
] | 56 | 2020-12-24T17:06:33.000Z | 2022-02-06T18:21:33.000Z | /*
Dark is going to attend Motarack's birthday. Dark decided that the gift he is going to give to Motarack is an array a of n non-negative integers.
Dark created that array 1000 years ago, so some elements in that array disappeared. Dark knows that Motarack hates to see an array that has two adjacent elements with a high absolute difference between them. He doesn't have much time so he wants to choose an integer k (0≤k≤109) and replaces all missing elements in the array a with k.
Let m be the maximum absolute difference between all adjacent elements (i.e. the maximum value of |ai−ai+1| for all 1≤i≤n−1) in the array a after Dark replaces all missing elements with k.
Dark should choose an integer k so that m is minimized. Can you help him?
Input
The input consists of multiple test cases. The first line contains a single integer t (1≤t≤104) — the number of test cases. The description of the test cases follows.
The first line of each test case contains one integer n (2≤n≤105) — the size of the array a.
The second line of each test case contains n integers a1,a2,…,an (−1≤ai≤109). If ai=−1, then the i-th integer is missing. It is guaranteed that at least one integer is missing in every test case.
It is guaranteed, that the sum of n for all test cases does not exceed 4⋅105.
Output
Print the answers for each test case in the following format:
You should print two integers, the minimum possible value of m and an integer k (0≤k≤109) that makes the maximum absolute difference between adjacent elements in the array a equal to m.
Make sure that after replacing all the missing elements with k, the maximum absolute difference between adjacent elements becomes m.
If there is more than one possible k, you can print any of them.
Example input:
7
5
-1 10 -1 12 -1
5
-1 40 35 -1 35
6
-1 -1 9 -1 3 -1
2
-1 -1
2
0 -1
4
1 -1 3 -1
7
1 -1 7 5 2 -1 5
Output:
1 11
5 35
3 6
0 42
0 0
1 2
3 4
Note:
In the first test case after replacing all missing elements with 11 the array becomes [11,10,11,12,11]. The absolute difference between any adjacent elements is 1. It is impossible to choose a value of k, such that the absolute difference between any adjacent element will be ≤0. So, the answer is 1.
In the third test case after replacing all missing elements with 6 the array becomes [6,6,9,6,3,6].
|a1−a2|=|6−6|=0;
|a2−a3|=|6−9|=3;
|a3−a4|=|9−6|=3;
|a4−a5|=|6−3|=3;
|a5−a6|=|3−6|=3.
So, the maximum difference between any adjacent elements is 3.
*/
#include <bits/stdc++.h>
using namespace std;
#define oo 1000000010
#define mod 1000000007
const int N = 300010;
int n , arr[N] ;
void solve(){
int mn = oo , mx = -oo;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&arr[i]);
}
for(int i = 0;i<n;i++){
if(i > 0 && arr[i] == -1 && arr[i - 1] != -1)
mn = min(mn , arr[i - 1]) , mx = max(mx , arr[i - 1]);
if(i < n - 1 && arr[i] == - 1 && arr[i + 1] != -1)
mn = min(mn , arr[i + 1]) , mx = max(mx , arr[i + 1]);
}
int res = (mx + mn) / 2;
int ans = 0;
for(int i=0;i<n;i++){
if(arr[i] == -1)
arr[i] = res;
if(i)
ans = max(ans,abs(arr[i] - arr[i - 1]));
}
printf("%d %d\n",ans,res);
}
int main(){
int t;
cin >> t;
while(t--){
solve();
}
return 0;
} | 30.609524 | 335 | 0.679527 | Tanushree-coder |
af7dd489968727b1cbb22051808480f056fd3ba2 | 3,636 | cpp | C++ | Love-Babbar-450-In-CPPTest/08_greedy/03_huffman_coding.cpp | harshanu11/Love-Babbar-450-In-CSharp | 0dc3bef3e66e30abbc04f7bbf21c7319b41803e1 | [
"MIT"
] | null | null | null | Love-Babbar-450-In-CPPTest/08_greedy/03_huffman_coding.cpp | harshanu11/Love-Babbar-450-In-CSharp | 0dc3bef3e66e30abbc04f7bbf21c7319b41803e1 | [
"MIT"
] | null | null | null | Love-Babbar-450-In-CPPTest/08_greedy/03_huffman_coding.cpp | harshanu11/Love-Babbar-450-In-CSharp | 0dc3bef3e66e30abbc04f7bbf21c7319b41803e1 | [
"MIT"
] | null | null | null | /*
link: https://practice.geeksforgeeks.org/problems/huffman-encoding3345/1
video (just to understand): https://youtu.be/co4_ahEDCho
*/
// ----------------------------------------------------------------------------------------------------------------------- //
/*
Time complexity: O(nlogn) where n is the number of unique characters. If there are n nodes, extractMin() is called 2*(n – 1) times. extractMin() takes O(logn) time as it calles minHeapify(). So, overall complexity is O(nlogn).
If the input array is sorted, there exists a linear time algorithm. We will soon be discussing in our next post.
Applications of Huffman Coding:
1. They are used for transmitting fax and text.
2. They are used by conventional compression formats like PKZIP, GZIP, etc.
It is useful in cases where there is a series of frequently occurring characters.
*/
// C++ program for Huffman Coding with STL
#include "CppUnitTest.h"
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <unordered_set>
#include <set>
#include <unordered_map>
#include <queue>
#include <stack>
using namespace std;
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace LoveBabbar450InCPPTest
{
// TEST_CLASS(BTSort)
// {
// public:
// TEST_METHOD(Test)
// {
// std::string charM = "harhs";
// int age = 14;
// age = 55;
// std::string lastName = "<<charM <<singh";
// }
// };
}
using namespace std;
// A Huffman tree node
struct MinHeapNode {
// One of the input characters
char data;
// Frequency of the character
unsigned freq;
// Left and right child
MinHeapNode* left, * right;
MinHeapNode(char data, unsigned freq)
{
left = right = NULL;
this->data = data;
this->freq = freq;
}
};
// For comparison of
// two heap nodes (needed in min heap)
struct compare {
bool operator()(MinHeapNode* l, MinHeapNode* r)
{
return (l->freq > r->freq);
}
};
// Prints huffman codes from
// the root of Huffman Tree.
void printCodes(struct MinHeapNode* root, string str, vector<string>& v)
{
if (!root)
return;
if (root->data != '$') v.push_back(str);
printCodes(root->left, str + "0", v);
printCodes(root->right, str + "1", v);
}
// The main function that builds a Huffman Tree and
// print codes by traversing the built Huffman Tree
vector<string> HuffmanCodes(char data[], int freq[], int size)
{
vector<string> v;
struct MinHeapNode* left, * right, * top;
// Create a min heap & inserts all characters of data[]
priority_queue<MinHeapNode*, vector<MinHeapNode*>, compare> minHeap;
for (int i = 0; i < size; ++i)
minHeap.push(new MinHeapNode(data[i], freq[i]));
// Iterate while size of heap doesn't become 1
while (minHeap.size() != 1) {
// Extract the two minimum
// freq items from min heap
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
// Create a new internal node with
// frequency equal to the sum of the
// two nodes frequencies. Make the
// two extracted node as left and right children
// of this new node. Add this node
// to the min heap '$' is a special value
// for internal nodes, not used
top = new MinHeapNode('$', left->freq + right->freq);
top->left = left;
top->right = right;
minHeap.push(top);
}
// Print Huffman codes using
// the Huffman tree built above
printCodes(minHeap.top(), "", v);
return v;
}
// Driver Code
int main39()
{
char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
int freq[] = { 5, 9, 12, 13, 16, 45 };
int size = sizeof(arr) / sizeof(arr[0]);
HuffmanCodes(arr, freq, size);
return 0;
}
| 22.867925 | 227 | 0.642464 | harshanu11 |
5030e363458db75da5913da2d97a97546a6228e3 | 6,204 | cc | C++ | proxy/http2/Http2ConnectionState.cc | sc0ttbeardsley/trafficserver | 5b77907f5d9b8ac82b983dab2f5417bb7579eef9 | [
"Apache-2.0"
] | null | null | null | proxy/http2/Http2ConnectionState.cc | sc0ttbeardsley/trafficserver | 5b77907f5d9b8ac82b983dab2f5417bb7579eef9 | [
"Apache-2.0"
] | null | null | null | proxy/http2/Http2ConnectionState.cc | sc0ttbeardsley/trafficserver | 5b77907f5d9b8ac82b983dab2f5417bb7579eef9 | [
"Apache-2.0"
] | null | null | null | /** @file
Http2ConnectionState.
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 "P_Net.h"
#include "Http2ConnectionState.h"
#include "Http2ClientSession.h"
#define DebugHttp2Ssn(fmt, ...) \
DebugSsn("http2_cs", "[%" PRId64 "] " fmt, this->con_id, __VA_ARGS__)
typedef Http2ErrorCode (*http2_frame_dispatch)(Http2ClientSession&, Http2ConnectionState&, const Http2Frame&);
static const int buffer_size_index[HTTP2_FRAME_TYPE_MAX] =
{
-1, // HTTP2_FRAME_TYPE_DATA
-1, // HTTP2_FRAME_TYPE_HEADERS
-1, // HTTP2_FRAME_TYPE_PRIORITY
-1, // HTTP2_FRAME_TYPE_RST_STREAM
BUFFER_SIZE_INDEX_128, // HTTP2_FRAME_TYPE_SETTINGS
-1, // HTTP2_FRAME_TYPE_PUSH_PROMISE
-1, // HTTP2_FRAME_TYPE_PING
BUFFER_SIZE_INDEX_128, // HTTP2_FRAME_TYPE_GOAWAY
-1, // HTTP2_FRAME_TYPE_WINDOW_UPDATE
-1, // HTTP2_FRAME_TYPE_CONTINUATION
-1, // HTTP2_FRAME_TYPE_ALTSVC
-1, // HTTP2_FRAME_TYPE_BLOCKED
};
static Http2ErrorCode
rcv_settings_frame(Http2ClientSession& cs, Http2ConnectionState& cstate, const Http2Frame& frame)
{
Http2SettingsParameter param;
char buf[HTTP2_SETTINGS_PARAMETER_LEN];
unsigned nbytes = 0;
char * end;
// 6.5 The stream identifier for a SETTINGS frame MUST be zero.
if (frame.header().streamid != 0) {
return HTTP2_ERROR_PROTOCOL_ERROR;
}
// 6.5 Receipt of a SETTINGS frame with the ACK flag set and a
// length field value other than 0 MUST be treated as a connection
// error of type FRAME_SIZE_ERROR.
if (frame.header().flags & HTTP2_FLAGS_SETTINGS_ACK) {
return frame.header().length == 0 ? HTTP2_ERROR_NO_ERROR : HTTP2_ERROR_FRAME_SIZE_ERROR;
}
while (nbytes < frame.header().length) {
end = frame.reader()->memcpy(buf, sizeof(buf), nbytes);
nbytes += (end - buf);
if (!http2_parse_settings_parameter(make_iovec(buf, end - buf), param)) {
return HTTP2_ERROR_PROTOCOL_ERROR;
}
if (!http2_settings_parameter_is_valid(param)) {
return param.id == HTTP2_SETTINGS_INITIAL_WINDOW_SIZE
? HTTP2_ERROR_FLOW_CONTROL_ERROR : HTTP2_ERROR_PROTOCOL_ERROR;
}
DebugSsn(&cs, "http2_cs", "[%" PRId64 "] setting param=%d value=%u",
cs.connection_id(), param.id, param.value);
cstate.client_settings.set((Http2SettingsIdentifier)param.id, param.value);
}
// 6.5 Once all values have been applied, the recipient MUST immediately emit a
// SETTINGS frame with the ACK flag set.
Http2Frame ackFrame(HTTP2_FRAME_TYPE_SETTINGS, 0, HTTP2_FLAGS_SETTINGS_ACK);
cstate.ua_session->handleEvent(HTTP2_SESSION_EVENT_XMIT, &ackFrame);
return HTTP2_ERROR_NO_ERROR;
}
static const http2_frame_dispatch frame_handlers[HTTP2_FRAME_TYPE_MAX] =
{
NULL, // HTTP2_FRAME_TYPE_DATA
NULL, // HTTP2_FRAME_TYPE_HEADERS
NULL, // HTTP2_FRAME_TYPE_PRIORITY
NULL, // HTTP2_FRAME_TYPE_RST_STREAM
rcv_settings_frame, // HTTP2_FRAME_TYPE_SETTINGS
NULL, // HTTP2_FRAME_TYPE_PUSH_PROMISE
NULL, // HTTP2_FRAME_TYPE_PING
NULL, // HTTP2_FRAME_TYPE_GOAWAY
NULL, // HTTP2_FRAME_TYPE_WINDOW_UPDATE
NULL, // HTTP2_FRAME_TYPE_CONTINUATION
NULL, // HTTP2_FRAME_TYPE_ALTSVC
NULL, // HTTP2_FRAME_TYPE_BLOCKED
};
int
Http2ConnectionState::main_event_handler(int event, void * edata)
{
if (event == HTTP2_SESSION_EVENT_INIT) {
ink_assert(this->ua_session == NULL);
this->ua_session = (Http2ClientSession *)edata;
// 3.5 HTTP/2 Connection Preface. Upon establishment of a TCP connection and
// determination that HTTP/2 will be used by both peers, each endpoint MUST
// send a connection preface as a final confirmation ... The server connection
// preface consists of a potentially empty SETTINGS frame.
Http2Frame settings(HTTP2_FRAME_TYPE_SETTINGS, 0, 0);
this->ua_session->handleEvent(HTTP2_SESSION_EVENT_XMIT, &settings);
return 0;
}
if (event == HTTP2_SESSION_EVENT_FINI) {
this->ua_session = NULL;
SET_HANDLER(&Http2ConnectionState::state_closed);
return 0;
}
if (event == HTTP2_SESSION_EVENT_RECV) {
Http2Frame * frame = (Http2Frame *)edata;
Http2ErrorCode error;
// The session layer should have validated the frame already.
ink_assert(frame->header().type < countof(frame_handlers));
if (frame_handlers[frame->header().type]) {
error = frame_handlers[frame->header().type](*this->ua_session, *this, *frame);
} else {
error = HTTP2_ERROR_INTERNAL_ERROR;
}
if (error != HTTP2_ERROR_NO_ERROR) {
Http2Frame frame(HTTP2_FRAME_TYPE_GOAWAY, 0, 0);
Http2Goaway goaway;
goaway.last_streamid = 0;
goaway.error_code = error;
frame.alloc(buffer_size_index[HTTP2_FRAME_TYPE_GOAWAY]);
http2_write_goaway(goaway, frame.write());
frame.finalize(HTTP2_GOAWAY_LEN);
this->ua_session->handleEvent(HTTP2_SESSION_EVENT_XMIT, &frame);
eventProcessor.schedule_imm(this->ua_session, ET_NET, VC_EVENT_ERROR);
// XXX We need to think a bit harder about how to coordinate the client session and the
// protocol connection. At this point, the protocol is shutting down, but there's no way
// to tell that to the client session. Perhaps this could be solved by implementing the
// half-closed state ...
SET_HANDLER(&Http2ConnectionState::state_closed);
}
return 0;
}
return 0;
}
int
Http2ConnectionState::state_closed(int /* event */, void * /* edata */)
{
return 0;
}
| 34.466667 | 110 | 0.72695 | sc0ttbeardsley |
5034a3a3871614fdfe8b64fbc70a457f939a06ca | 2,823 | cpp | C++ | juicer-1.1.0/src/md5class.cpp | DerDudemeister046/Juicer_Reborn | 3a84c3fd1c1ebd0b7f497c1d6277363d5f061f45 | [
"BSD-2-Clause"
] | null | null | null | juicer-1.1.0/src/md5class.cpp | DerDudemeister046/Juicer_Reborn | 3a84c3fd1c1ebd0b7f497c1d6277363d5f061f45 | [
"BSD-2-Clause"
] | null | null | null | juicer-1.1.0/src/md5class.cpp | DerDudemeister046/Juicer_Reborn | 3a84c3fd1c1ebd0b7f497c1d6277363d5f061f45 | [
"BSD-2-Clause"
] | null | null | null | // md5class.cpp: implementation of the CMD5 class.
//See internet RFC 1321, "The MD5 Message-Digest Algorithm"
//
//Use this code as you see fit. It is provided "as is"
//without express or implied warranty of any kind.
//////////////////////////////////////////////////////////////////////
#include "md5class.h"
#include "md5.h" //declarations from RFC 1321
#include <string.h>
#include <stdio.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMD5::CMD5()
{
m_digestValid = false; //we don't have a plaintext string yet
m_digestString[32]=0; //the digest string is always 32 characters, so put a null in position 32
}
CMD5::~CMD5()
{
}
CMD5::CMD5(const char* plainText)
{
m_plainText = const_cast<char*>(plainText); //get a pointer to the plain text. If casting away the const-ness worries you,
//you could make a local copy of the plain text string.
m_digestString[32]=0;
m_digestValid = calcDigest();
}
//////////////////////////////////////////////////////////////////////
// Implementation
//////////////////////////////////////////////////////////////////////
void CMD5::setPlainText(const char* plainText)
{
//set plaintext with a mutator, it's ok to
//to call this multiple times. If casting away the const-ness of plainText
//worries you, you could either make a local copy of the plain
//text string instead of just pointing at the user's string, or
//modify the RFC 1321 code to take 'const' plaintext, see example below.
m_plainText = const_cast<char*>(plainText);
m_digestValid = calcDigest();
}
/* Use a function of this type with your favorite string class
if casting away the const-ness of the user's text buffer violates you
coding standards.
void CMD5::setPlainText(CString& strPlainText)
{
static CString plaintext(strPlainText);
m_plainText = strPlainText.GetBuffer();
m_digestValid = calcDigest();
}
*/
const char* CMD5::getMD5Digest()
{ //access message digest (aka hash), return 0 if plaintext has not been set
if(m_digestValid)
{
return m_digestString;
} else return 0;
}
bool CMD5::calcDigest()
{
//See RFC 1321 for details on how MD5Init, MD5Update, and MD5Final
//calculate a digest for the plain text
MD5_CTX context;
MD5Init(&context);
//the alternative to these ugly casts is to go into the RFC code and change the declarations
MD5Update(&context, reinterpret_cast<unsigned char *>(m_plainText), ::strlen(m_plainText));
MD5Final(reinterpret_cast <unsigned char *>(m_digest),&context);
//make a string version of the numeric digest value
int p=0;
for (int i = 0; i<16; i++)
{
::sprintf(&m_digestString[p],"%02x", m_digest[i]);
p+=2;
}
return true;
}
| 28.806122 | 125 | 0.623096 | DerDudemeister046 |
503a9e84c26c2c204fb56de08729d28e57e279d1 | 8,108 | cpp | C++ | TUIO SETUP/npTuioClient-old/src/plugin.cpp | alfanhui/graph_visualiser_honours_project | 0496c22af39cda12ce791f15766795bac24386c9 | [
"MIT"
] | null | null | null | TUIO SETUP/npTuioClient-old/src/plugin.cpp | alfanhui/graph_visualiser_honours_project | 0496c22af39cda12ce791f15766795bac24386c9 | [
"MIT"
] | 29 | 2018-03-23T12:58:24.000Z | 2018-04-20T16:05:25.000Z | TUIO SETUP/npTuioClient-old/src/plugin.cpp | alfanhui/graph_visualiser_honours_project | 0496c22af39cda12ce791f15766795bac24386c9 | [
"MIT"
] | null | null | null | //
// Copyright (C) 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#include "plugin.h"
#include <cstring>
#include <iostream>
#include <sstream>
#define D(s) /*std::cerr << s << std::endl;*/
#include <set>
#define MIME_TYPES_HANDLED "application/x-tuio"
// The name must be this value to get flash movies that check the
// plugin version to load.
#define PLUGIN_NAME "TUIO Client"
#define MIME_TYPES_DESCRIPTION MIME_TYPES_HANDLED":tuio:"PLUGIN_NAME
#define PLUGIN_DESCRIPTION "TUIO Client plugin"
extern NPNetscapeFuncs NPNFuncs;
NPBool plugInitialized = FALSE;
static std::set<nsPluginInstance*> instances;
void tuio_callback(TuioEventData data)
{
std::set<nsPluginInstance*>::iterator iter;
for (iter = instances.begin(); iter != instances.end(); iter++) {
(*iter)->event(data);
}
}
void
PR_CALLBACK Destructor(void * /* data */)
{
#if 0
/*
* We don't actually free the storage since it's actually allocated
* on the stack. Normally, this would not be the case and this is
* the opportunity to free whatever.
*/
PR_Free(data);
#endif
}
/// \brief Return the MIME Type description for this plugin.
char*
NPP_GetMIMEDescription(void)
{
return const_cast<char *>(MIME_TYPES_DESCRIPTION);
}
//
// general initialization and shutdown
//
/// \brief Initialize the plugin
///
/// This C++ function gets called once when the plugin is loaded,
/// regardless of how many instantiations there is actually playing
/// movies. So this is where all the one time only initialization
/// stuff goes.
NPError
NS_PluginInitialize()
{
if ( plugInitialized )
{
return NPERR_NO_ERROR;
}
plugInitialized = TRUE;
tuio_start(3333);
return NPERR_NO_ERROR;
}
/// \brief Shutdown the plugin
///
/// This C++ function gets called once when the plugin is being
/// shutdown, regardless of how many instantiations actually are
/// playing movies. So this is where all the one time only
/// shutdown stuff goes.
void
NS_PluginShutdown()
{
#if 0
if (!plugInitialized)
{
#if GNASH_PLUGIN_DEBUG > 1
std::cout << "Plugin already shut down" << std::endl;
#endif
return;
}
plugInitialized = FALSE;
#endif
tuio_stop();
}
/// \brief Retrieve values from the plugin for the Browser
///
/// This C++ function is called by the browser to get certain
/// information is needs from the plugin. This information is the
/// plugin name, a description, etc...
NPError
NS_PluginGetValue(NPPVariable aVariable, void *aValue)
{
NPError err = NPERR_NO_ERROR;
switch (aVariable)
{
case NPPVpluginNameString:
*static_cast<const char **> (aValue) = PLUGIN_NAME;
break;
// This becomes the description field you see below the opening
// text when you type about:plugins and in
// navigator.plugins["Shockwave Flash"].description, used in
// many flash version detection scripts.
case NPPVpluginDescriptionString:
*static_cast<const char **>(aValue) = PLUGIN_DESCRIPTION;
break;
case NPPVpluginNeedsXEmbed:
*(int*)aValue = PR_TRUE;
break;
case NPPVpluginTimerInterval:
case NPPVpluginKeepLibraryInMemory:
default:
err = NPERR_INVALID_PARAM;
break;
}
return err;
}
/// \brief construct our plugin instance object
///
/// This instantiates a new object via a C++ function used by the
/// browser.
nsPluginInstanceBase *
NS_NewPluginInstance(nsPluginCreateData * aCreateDataStruct)
{
if(!aCreateDataStruct) return NULL;
return new nsPluginInstance(aCreateDataStruct);
}
/// \brief destroy our plugin instance object
///
/// This destroys our instantiated object via a C++ function used by the
/// browser.
void
NS_DestroyPluginInstance(nsPluginInstanceBase* aPlugin)
{
delete static_cast<nsPluginInstance *> (aPlugin);
}
//
// nsPluginInstance class implementation
//
/// \brief Constructor
nsPluginInstance::nsPluginInstance(nsPluginCreateData* data)
:
nsPluginInstanceBase(),
_instance(data->instance),
_port(3333),
_callback("tuio_callback")
{
for (size_t i=0, n=data->argc; i<n; ++i)
{
std::string name, val;
if (data->argn[i])
{
name = data->argn[i];
}
if (data->argv[i])
{
val = data->argv[i];
}
else if ( ! strstr(name.c_str(), "callback") )
{
_callback = val;
}
else if ( ! strstr(name.c_str(), "port") )
{
_port = atoi(val.c_str());
}
}
instances.insert(this);
}
/// \brief Destructor
nsPluginInstance::~nsPluginInstance()
{
instances.erase(this);
}
/// \brief Initialize an instance of the plugin object
///
/// This methods initializes the plugin object, and is called for
/// every movie that gets played. This is where the movie playing
/// specific initialization goes.
NPBool
nsPluginInstance::init(NPWindow* aWindow)
{
D("[ns] init");
return TRUE;
}
/// \brief Shutdown an instantiated object
///
/// This shuts down an object, and is called for every movie that gets
/// played. This is where the movie playing specific shutdown code
/// goes.
void
nsPluginInstance::shut()
{
D("[ns] shut");
}
NPError
nsPluginInstance::SetWindow(NPWindow* aWindow)
{
D("[ns] SetWindow");
if(!aWindow)
{
return NPERR_INVALID_PARAM;
}
return NPERR_NO_ERROR;
}
NPError
nsPluginInstance::GetValue(NPPVariable aVariable, void *aValue)
{
return NS_PluginGetValue(aVariable, aValue);
}
/// \brief Write a status message
///
/// This writes a status message to the status line at the bottom of
/// the browser window and the console firefox was started from.
NPError
nsPluginInstance::WriteStatus(const char *msg) const
{
NPN_Status(_instance, msg);
std::cout << msg << std::endl;
return NPERR_NO_ERROR;
}
NPError
nsPluginInstance::NewStream(NPMIMEType /*type*/, NPStream* stream,
NPBool /*seekable*/, uint16* /*stype*/)
{
D("[ns] NewStream");
return NPERR_NO_ERROR;
}
NPError
nsPluginInstance::DestroyStream(NPStream* /*stream*/, NPError /*reason*/)
{
D("[ns] DestroyStream");
return NPERR_NO_ERROR;
}
int32_t
nsPluginInstance::WriteReady(NPStream* /* stream */ )
{
D("[ns] WriteReady");
return 0x0fffffff;
}
int32_t
nsPluginInstance::Write(NPStream* /*stream*/, int32_t /*offset*/, int32_t len,
void* buffer)
{
D("[ns] Write: len=" << len);
return len;
}
typedef struct {
NPP instance;
TuioEventData data;
} Event;
void test(void* ev)
{
D("ev=" << ev);
Event* event = (Event*)ev;
D("event=" << event);
std::stringstream ss;
ss << "javascript:tuio_callback(";
ss << event->data.type << ", ";
ss << event->data.sid << ", ";
ss << event->data.fid << ", ";
ss << event->data.x << ", ";
ss << event->data.y << ", ";
ss << event->data.a << ");";
NPN_GetURL(event->instance, ss.str().c_str(), "_self");
delete event;
}
void nsPluginInstance::event(TuioEventData data)
{
D("[event] callback: type=" << data.type
<< ", sid=" << data.sid << ", fid=" << data.fid
<< ", x=" << data.x << ", y=" << data.y << ", a=" << data.a);
Event* ev = new Event();
ev->instance = _instance;
ev->data = data;
NPN_PluginThreadAsyncCall(_instance, test, ev);
}
// Local Variables:
// mode: C++
// indent-tabs-mode: t
// End:
| 23.034091 | 78 | 0.665392 | alfanhui |
5041dc368c1a141cdc2cb0b612bfdbdbb380829f | 1,620 | hpp | C++ | lib/inc/tetra/behavior/BehaviorList.hpp | projectTetra/tetra-creative | 011c0ba1b288b9e2534cf9446949f55078ea265b | [
"MIT"
] | null | null | null | lib/inc/tetra/behavior/BehaviorList.hpp | projectTetra/tetra-creative | 011c0ba1b288b9e2534cf9446949f55078ea265b | [
"MIT"
] | null | null | null | lib/inc/tetra/behavior/BehaviorList.hpp | projectTetra/tetra-creative | 011c0ba1b288b9e2534cf9446949f55078ea265b | [
"MIT"
] | null | null | null | #pragma once
#ifndef BEHAVIOR_LIST_HPP
#define BEHAVIOR_LIST_HPP
#include <memory>
#include <list>
namespace tetra
{
class Behavior;
using OwnedBehavior = std::unique_ptr<Behavior>;
/**
* The BehaviorList is a collection of behaviors which are executed each time
* run() is invoked.
*/
class BehaviorList
{
public:
/**
* Insert the owned behavior before the here pointer.
* If the 'here' pointer cannot be found then the behavior is inserted at the
* end of the list.
*/
Behavior* insertBefore(const Behavior* here, OwnedBehavior&& action);
/**
* Insert the owned behavior after the 'here' pointer.
* If the 'here' pointer cannot be found in the behavior list then the provided
* behavior is inserted at the end of the list.
*/
Behavior* insertAfter(const Behavior* here, OwnedBehavior&& action);
/**
* Push the provided behavior onto the front of the behavior list.
*/
Behavior* pushFront(OwnedBehavior&& action);
/**
* Execute the behaviors in the behavior list, stopping at the end of the list
* or after the first blocking Behavior executes.
*/
void run(double dt);
/**
* Returns true as long as there are any behaviors which have not completed.
*/
bool running() const;
private:
using BehaviorCollection = std::list<OwnedBehavior>;
BehaviorCollection behaviors;
/**
* Insert the action at a location, set the parentList, and call onStart.
*/
Behavior* insertAt(BehaviorCollection::iterator location, OwnedBehavior&& action);
};
}; /* namespace tetra */
#endif
| 25.714286 | 86 | 0.682099 | projectTetra |
5043a9dc2cf7d9afd50e4a8a0c6ae566a98411fa | 407 | cpp | C++ | 04. Arrays/13 Maximum Difference/13b Maximum Difference.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 190 | 2021-02-10T17:01:01.000Z | 2022-03-20T00:21:43.000Z | 04. Arrays/13 Maximum Difference/13b Maximum Difference.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | null | null | null | 04. Arrays/13 Maximum Difference/13b Maximum Difference.cpp | VivekYadav105/Data-Structures-and-Algorithms | 7287912da8068c9124e0bb89c93c4d52aa48c51f | [
"MIT"
] | 27 | 2021-03-26T11:35:15.000Z | 2022-03-06T07:34:54.000Z | #include<bits/stdc++.h>
using namespace std;
int maxDiff(int *a,int n)//time comp. O(n)
{
int res=a[1]-a[0];
int minVal=a[0];
for(int i=1;i<n;i++)
{
res=max(res,a[i]-minVal);
minVal=min(minVal,a[i]);
}
return res;
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<maxDiff(a,n);
return 0;
} | 13.129032 | 42 | 0.471744 | VivekYadav105 |
504853a094b84ec84c4214bbce7686777d0957a8 | 678 | cpp | C++ | source/cli/Main.cpp | sienkiewiczkm/shabui | 1304d55d7bcefb8b199e4d4a89b0839d6ff02872 | [
"MIT"
] | null | null | null | source/cli/Main.cpp | sienkiewiczkm/shabui | 1304d55d7bcefb8b199e4d4a89b0839d6ff02872 | [
"MIT"
] | 3 | 2017-02-28T10:22:23.000Z | 2017-02-28T15:10:50.000Z | source/cli/Main.cpp | sienkiewiczkm/shabui | 1304d55d7bcefb8b199e4d4a89b0839d6ff02872 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstdlib>
#include <iostream>
#include <string>
#include <sstream>
#include "shabui/GLSLLoader.hpp"
int main(int argc, char **argv)
{
if (argc == 1)
{
std::cout << "usage: " << argv[0] << " shaderfile";
return EXIT_FAILURE;
}
sb::GLSLLoaderFileDependencyResolver resolver{argv[1]};
sb::GLSLLoader loader{resolver};
auto result = loader.loadFile(argv[1]);
std::cerr << "Vertex Shader Output:" << std::endl;
std::cerr << result.vertexShaderCode << std::endl;
std::cerr << "Fragment Shader Output:" << std::endl;
std::cerr << result.fragmentShaderCode << std::endl;
return EXIT_SUCCESS;
}
| 24.214286 | 59 | 0.632743 | sienkiewiczkm |
50548af311095bbf2bc68baf9d1587005d8c3a42 | 5,777 | cpp | C++ | lib/Transforms/Passes/BlockSeparatorPass.cpp | compor/Atrox | d6e893f0c91764c58e198ccf316096b0ec9f7d90 | [
"MIT"
] | null | null | null | lib/Transforms/Passes/BlockSeparatorPass.cpp | compor/Atrox | d6e893f0c91764c58e198ccf316096b0ec9f7d90 | [
"MIT"
] | null | null | null | lib/Transforms/Passes/BlockSeparatorPass.cpp | compor/Atrox | d6e893f0c91764c58e198ccf316096b0ec9f7d90 | [
"MIT"
] | null | null | null | //
//
//
#include "Atrox/Config.hpp"
#include "Atrox/Util.hpp"
#include "Atrox/Debug.hpp"
#include "Atrox/Transforms/Passes/BlockSeparatorPass.hpp"
#include "Atrox/Transforms/BlockSeparator.hpp"
#include "private/PDGUtils.hpp"
#include "private/ITRUtils.hpp"
#include "private/PassCommandLineOptions.hpp"
#include "llvm/Pass.h"
// using llvm::RegisterPass
#include "llvm/IR/Instruction.h"
// using llvm::Instruction
#include "llvm/IR/Function.h"
// using llvm::Function
#include "llvm/IR/LegacyPassManager.h"
// using llvm::PassManagerBase
#include "llvm/IR/Dominators.h"
// using llvm::DominatorTree
#include "llvm/Analysis/LoopInfo.h"
// using llvm::LoopInfo
#include "llvm/Analysis/MemoryDependenceAnalysis.h"
// using llvm::MemoryDependenceResults
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
// using llvm::PassManagerBuilder
// using llvm::RegisterStandardPasses
#include "llvm/ADT/SmallPtrSet.h"
// using llvm::SmallPtrSet
#include "llvm/Support/CommandLine.h"
// using llvm::cl::opt
// using llvm::cl::desc
// using llvm::cl::init
// using llvm::cl::ParseEnvironmentOptions
// using llvm::cl::ResetAllOptionOccurrences
#include "llvm/Support/Debug.h"
// using LLVM_DEBUG macro
// using llvm::dbgs
#include <algorithm>
// using std::find
#include <fstream>
// using std::ifstream
#include <string>
// using std::string
#define DEBUG_TYPE ATROX_BLOCKSEPARATOR_PASS_NAME
#define PASS_CMDLINE_OPTIONS_ENVVAR "BLOCKSEPARATOR_CMDLINE_OPTIONS"
// plugin registration for opt
char atrox::BlockSeparatorLegacyPass::ID = 0;
static llvm::RegisterPass<atrox::BlockSeparatorLegacyPass>
X(DEBUG_TYPE, PRJ_CMDLINE_DESC("block separator pass"), false, false);
// plugin registration for clang
// the solution was at the bottom of the header file
// 'llvm/Transforms/IPO/PassManagerBuilder.h'
// create a static free-floating callback that uses the legacy pass manager to
// add an instance of this pass and a static instance of the
// RegisterStandardPasses class
static void
registerBlockSeparatorLegacyPass(const llvm::PassManagerBuilder &Builder,
llvm::legacy::PassManagerBase &PM) {
PM.add(new atrox::BlockSeparatorLegacyPass());
return;
}
static llvm::RegisterStandardPasses RegisterBlockSeparatorLegacyPass(
llvm::PassManagerBuilder::EP_EarlyAsPossible,
registerBlockSeparatorLegacyPass);
//
namespace atrox {
// new passmanager pass
BlockSeparatorPass::BlockSeparatorPass() {
llvm::cl::ResetAllOptionOccurrences();
llvm::cl::ParseEnvironmentOptions(DEBUG_TYPE, PASS_CMDLINE_OPTIONS_ENVVAR);
}
bool BlockSeparatorPass::perform(llvm::Function &F, llvm::DominatorTree *DT,
llvm::LoopInfo *LI,
llvm::MemoryDependenceResults *MDR) {
llvm::SmallVector<std::string, 32> AtroxFunctionWhiteList;
if (AtroxFunctionWhiteListFile.getPosition()) {
std::ifstream wlFile{AtroxFunctionWhiteListFile};
std::string funcName;
while (wlFile >> funcName) {
AtroxFunctionWhiteList.push_back(funcName);
}
}
auto not_in = [](const auto &C, const auto &E) {
return C.end() == std::find(std::begin(C), std::end(C), E);
};
if (F.isDeclaration() ||
(AtroxFunctionWhiteListFile.getPosition() &&
not_in(AtroxFunctionWhiteList, std::string{F.getName()}))) {
return false;
}
LLVM_DEBUG(llvm::dbgs() << "processing func: " << F.getName() << '\n';);
auto itrInfo = BuildITRInfo(*LI, *BuildPDG(F, MDR));
// NOTE
// this does not update the iterator info with the uncond branch instruction
// that might be added by block splitting
// however that instruction can acquire the mode of its immediately
// preceding instruction
bool hasChanged = false;
for (auto *curLoop : LI->getLoopsInPreorder()) {
LLVM_DEBUG(llvm::dbgs() << "processing loop with header: "
<< curLoop->getHeader()->getName() << '\n';);
BlockModeChangePointMapTy modeChanges;
BlockModeMapTy blockModes;
auto infoOrError = itrInfo->getIteratorInfoFor(curLoop);
if (!infoOrError) {
continue;
}
auto &info = *infoOrError;
bool found = FindPartitionPoints(*curLoop, info, blockModes, modeChanges);
LLVM_DEBUG(llvm::dbgs() << "partition points found: " << modeChanges.size()
<< '\n';);
if (found) {
SplitAtPartitionPoints(modeChanges, blockModes, DT, LI);
hasChanged = true;
}
}
return hasChanged;
}
llvm::PreservedAnalyses
BlockSeparatorPass::run(llvm::Function &F, llvm::FunctionAnalysisManager &FAM) {
auto *DT = &FAM.getResult<llvm::DominatorTreeAnalysis>(F);
auto *LI = &FAM.getResult<llvm::LoopAnalysis>(F);
auto &MDR = FAM.getResult<llvm::MemoryDependenceAnalysis>(F);
bool hasChanged = perform(F, DT, LI, &MDR);
if (!hasChanged) {
return llvm::PreservedAnalyses::all();
}
llvm::PreservedAnalyses PA;
PA.preserve<llvm::DominatorTreeAnalysis>();
PA.preserve<llvm::LoopAnalysis>();
return PA;
}
// legacy passmanager pass
void BlockSeparatorLegacyPass::getAnalysisUsage(llvm::AnalysisUsage &AU) const {
AU.addRequired<llvm::DominatorTreeWrapperPass>();
AU.addRequired<llvm::LoopInfoWrapperPass>();
AU.addRequired<llvm::MemoryDependenceWrapperPass>();
AU.addPreserved<llvm::DominatorTreeWrapperPass>();
AU.addPreserved<llvm::LoopInfoWrapperPass>();
}
bool BlockSeparatorLegacyPass::runOnFunction(llvm::Function &F) {
BlockSeparatorPass pass;
auto *DT = &getAnalysis<llvm::DominatorTreeWrapperPass>().getDomTree();
auto *LI = &getAnalysis<llvm::LoopInfoWrapperPass>().getLoopInfo();
auto &MDR = getAnalysis<llvm::MemoryDependenceWrapperPass>().getMemDep();
return pass.perform(F, DT, LI, &MDR);
}
} // namespace atrox
| 26.869767 | 80 | 0.712134 | compor |
50579e9ad0faa463500c7f6d04f72809095805a5 | 7,018 | hxx | C++ | Modules/Components/Elastix/include/selxMonolithicElastixComponent.hxx | FBerendsen/SuperElastix-1 | 69d97589e34f6f2109621e917792ce18e32442fe | [
"Apache-2.0"
] | null | null | null | Modules/Components/Elastix/include/selxMonolithicElastixComponent.hxx | FBerendsen/SuperElastix-1 | 69d97589e34f6f2109621e917792ce18e32442fe | [
"Apache-2.0"
] | null | null | null | Modules/Components/Elastix/include/selxMonolithicElastixComponent.hxx | FBerendsen/SuperElastix-1 | 69d97589e34f6f2109621e917792ce18e32442fe | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Leiden University Medical Center, Erasmus University Medical
* Center and contributors
*
* 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.txt
*
* 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 "selxMonolithicElastixComponent.h"
#include "selxCheckTemplateProperties.h"
namespace selx
{
template< int Dimensionality, class TPixel >
MonolithicElastixComponent< Dimensionality, TPixel >::MonolithicElastixComponent( const std::string & name,
LoggerImpl & logger ) : Superclass( name, logger )
{
m_elastixFilter = ElastixFilterType::New();
// TODO: Due to some issues with Criteria being propagated as elastix settings, I need to empty the selxparameterObject.
elxParameterObjectPointer elxParameterObject = elxParameterObjectType::New();
typename elxParameterObjectType::ParameterMapType defaultParameters = elxParameterObject->GetDefaultParameterMap( "rigid" );
elxParameterObject->SetParameterMap( defaultParameters );
m_elastixFilter->SetParameterObject( elxParameterObject );
m_elastixFilter->LogToConsoleOn();
m_elastixFilter->LogToFileOff();
m_elastixFilter->SetOutputDirectory( "." );
}
template< int Dimensionality, class TPixel >
MonolithicElastixComponent< Dimensionality, TPixel >::~MonolithicElastixComponent()
{
}
template< int Dimensionality, class TPixel >
int
MonolithicElastixComponent< Dimensionality, TPixel >::Accept( typename itkImageFixedInterface< Dimensionality, TPixel >::Pointer component )
{
auto fixedImage = component->GetItkImageFixed();
// connect the itk pipeline
this->m_elastixFilter->SetFixedImage( fixedImage );
return 0;
}
template< int Dimensionality, class TPixel >
int
MonolithicElastixComponent< Dimensionality, TPixel >::Accept( typename itkImageMovingInterface< Dimensionality, TPixel >::Pointer component )
{
auto movingImage = component->GetItkImageMoving();
// connect the itk pipeline
this->m_elastixFilter->SetMovingImage( movingImage );
return 0;
}
template< int Dimensionality, class TPixel >
int
MonolithicElastixComponent< Dimensionality, TPixel >::Accept(typename itkImageFixedMaskInterface< Dimensionality, unsigned char >::Pointer component)
{
auto fixedMaskImage = component->GetItkImageFixedMask();
// connect the itk pipeline
this->m_elastixFilter->SetFixedMask(fixedMaskImage);
return 0;
}
template< int Dimensionality, class TPixel >
int
MonolithicElastixComponent< Dimensionality, TPixel >::Accept(typename itkImageMovingMaskInterface< Dimensionality, unsigned char >::Pointer component)
{
auto movingMaskImage = component->GetItkImageMovingMask();
// connect the itk pipeline
this->m_elastixFilter->SetMovingMask(movingMaskImage);
return 0;
}
template< int Dimensionality, class TPixel >
typename MonolithicElastixComponent< Dimensionality, TPixel >::ItkImagePointer
MonolithicElastixComponent< Dimensionality, TPixel >::GetItkImage()
{
return this->m_elastixFilter->GetOutput();
}
template< int Dimensionality, class TPixel >
typename MonolithicElastixComponent< Dimensionality,
TPixel >::elastixTransformParameterObject * MonolithicElastixComponent< Dimensionality, TPixel >::GetTransformParameterObject()
{
return this->m_elastixFilter->GetTransformParameterObject();
}
template< int Dimensionality, class TPixel >
void
MonolithicElastixComponent< Dimensionality, TPixel >::Update( void )
{
this->m_elastixFilter->Update();
}
template< int Dimensionality, class TPixel >
bool
MonolithicElastixComponent< Dimensionality, TPixel >
::MeetsCriterion( const CriterionType & criterion )
{
bool hasUndefinedCriteria( false );
bool meetsCriteria( false );
auto status = CheckTemplateProperties( this->TemplateProperties(), criterion );
if( status == CriterionStatus::Satisfied )
{
return true;
}
else if( status == CriterionStatus::Failed )
{
return false;
} // else: CriterionStatus::Unknown
else if( criterion.first == "RegistrationPreset" ) //Supports this?
{
// Temporary solution: RegistrationPreset: rigid, nonrigid, etc overwrite the current selxparameterObject.
// Warning: the order of Criteria matters, since selxparameterObject may be overwritten
// Warning: this probably fails because the Criteria map entries are processed in arbitrary order.
elxParameterObjectPointer elxParameterObject = elxParameterObjectType::New();
meetsCriteria = true;
for( auto const & presetName : criterion.second ) // auto&& preferred?
{
typename elxParameterObjectType::ParameterMapType presetParameters = elxParameterObject->GetDefaultParameterMap( presetName );
elxParameterObject->SetParameterMap( presetParameters );
try
{
this->m_elastixFilter->SetParameterObject( elxParameterObject );
}
catch( itk::ExceptionObject & err )
{
this->Error( err.what() );
meetsCriteria = false;
}
}
}
else
{
// temporary solution: pass all SuperMonolithicElastixComponent parameters as is to elastix. This should be defined in deeper hierarchy of the criteria, but for now we have a flat mapping only.
elxParameterObjectPointer elxParameterObject = this->m_elastixFilter->GetParameterObject();
typename elxParameterObjectType::ParameterMapType newParameterMap = elxParameterObject->GetParameterMap( 0 ); //copy const paramtermap to a non const map
newParameterMap[ criterion.first ] = criterion.second; //overwrite element
elxParameterObjectPointer newParameterObject = elxParameterObjectType::New();
newParameterObject->SetParameterMap( newParameterMap );
this->m_elastixFilter->SetParameterObject( newParameterObject );
meetsCriteria = true;
}
return meetsCriteria;
}
template< int Dimensionality, class TPixel >
bool
MonolithicElastixComponent< Dimensionality, TPixel >
::ConnectionsSatisfied()
{
// This function overrides the default behavior, in which all accepting interfaces must be set.
// Only Fixed and Moving images are required
// TODO: see I we can reduce the amount of code with helper (meta-)functions
if (!this->InterfaceAcceptor< itkImageFixedInterface< Dimensionality, TPixel >>::GetAccepted())
{
return false;
}
if (!this->InterfaceAcceptor< itkImageMovingInterface< Dimensionality, TPixel >>::GetAccepted())
{
return false;
}
return true;
}
} //end namespace selx
| 36.743455 | 197 | 0.742092 | FBerendsen |
5070721eb6409dfa69ec0c51f81932cef0b1fab8 | 4,415 | cpp | C++ | src/init.cpp | andreili/STM32F4 | 9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc | [
"MIT"
] | 6 | 2019-04-16T11:38:45.000Z | 2020-12-12T16:55:03.000Z | src/init.cpp | andreili/STM32F4 | 9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc | [
"MIT"
] | 1 | 2020-12-15T10:45:53.000Z | 2021-02-22T11:59:19.000Z | src/init.cpp | andreili/STM32F4 | 9054d699ec1f65e7de8aa5dd7d3ee0522dad18dc | [
"MIT"
] | 2 | 2019-05-23T03:08:25.000Z | 2020-10-10T12:43:06.000Z | #include "stm32_inc.h"
#include "init.h"
#ifdef STM32_FATFS_USE
#include "sddriver.h"
#endif
int main();
/* #define VECT_TAB_SRAM */
#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
extern volatile uint32_t _FLASH_START;
// base initialization
void base_init()
{
/* FPU settings ------------------------------------------------------------*/
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
CORTEX::FPU::CPACR::set_CP10_CP11(CORTEX::FPU::CPACR::ECP::FULL_ACCESS); /* set CP10 and CP11 Full Access */
#endif
STM32::RCC::deinit_cold();
#if defined (DATA_IN_ExtSDRAM)
if (STM32_SDRAM::init() != STM32_RESULT_OK)
Error_Handler();
#endif
/* Configure the Vector Table location add offset address ------------------*/
#ifdef VECT_TAB_SRAM
CORTEX::SCB::VTOR::set(SRAM_BASE | VECT_TAB_OFFSET); /* Vector Table Relocation in Internal SRAM */
#else
CORTEX::SCB::VTOR::set(uint32_t(&_FLASH_START) | VECT_TAB_OFFSET); /* Vector Table Relocation in Internal FLASH */
#endif
}
#ifndef STM32_TIMEBASE_SYSTICK
void timebase_cb(STM32_TIM* tim, uint32_t ch)
{
UNUSED(tim);
UNUSED(ch);
STM32::SYSTICK::on_tick();
}
#endif //STM32_TIMEBASE_SYSTICK
void timebase_init()
{
#ifdef STM32_TIMEBASE_SYSTICK
STM32_SYSTICK::init();
#else
STM32::SYSTICK::deinit();
STM32_TIM::TimerBaseInit_t tim14_init;
tim14_init.period = (1000000/STM32_TIMEBASE_FREQ_HZ) - 1;
tim14_init.prescaler = ((2 * STM32::RCC::get_PCLK1_freq()) / 1000000) - 1; // (2*PCLK1Freq/1000000 - 1) to have a 1MHz counter clock.
tim14_init.clk_div = STM32_TIM::EClkDiv::DIV_1;
tim14_init.counter_mode = STM32_TIM::ECounterMode::UP;
STM32::NVIC::enable_and_set_prior_IRQ(STM32::IRQn::TIM8_TRG_COM_TIM14, 0, 0);
STM32::RCC::enable_clk_TIM14();
tim14.set_cb_period_elapsed(timebase_cb);
tim14.init(&tim14_init);
tim14.start_IT();
#endif //STM32_TIMEBASE_SYSTICK
}
void PeriphInit()
{
STM32::RCC::update_clock();
/* Other IO and peripheral initializations */
STM32_GPIO::init_all();
#ifdef STM32_USE_UART
STM32_UART::init_all();
#endif
#ifdef STM32_USE_SPI
STM32_SPI::init_all();
#endif
#ifdef STM32_USE_RTC
STM32_RTC::init();
#endif
#ifdef STM32_USE_DMA
STM32_DMA::init_all();
#endif
#ifdef STM32_USE_TIM
STM32_TIM::init_all();
#endif
timebase_init();
}
void SystemInit()
{
base_init();
// system initialization
STM32::RCC::init();
PeriphInit();
/* Initialize interrupt vectors for a peripheral */
STM32::NVIC::init_vectors();
STM32::RCC::update_clock();
#ifdef INSTRUCTION_CACHE_ENABLE
STM32::FLASH::set_instruction_cache_enable(true);
#endif
#ifdef DATA_CACHE_ENABLE
STM32::FLASH::set_data_cache_enable(true);
#endif
#ifdef PREFETCH_ENABLE
STM32::FLASH::set_prefetch_enable(true);
#endif
STM32::NVIC::init();
}
#define INIT_SP() \
{ \
__ASM volatile("ldr sp, =_estack\n\r" : : ); \
} \
static inline void __initialize_data (uint32_t* from, uint32_t* region_begin, uint32_t* region_end)
{
// Iterate and copy word by word.
// It is assumed that the pointers are word aligned.
uint32_t *p = region_begin;
while (p < region_end)
*p++ = *from++;
}
static inline void __initialize_bss (uint32_t* region_begin, uint32_t* region_end)
{
// Iterate and clear word by word.
// It is assumed that the pointers are word aligned.
uint32_t *p = region_begin;
while (p < region_end)
*p++ = 0;
}
static inline void __initalize_classes(uint32_t* ctors_begin, uint32_t* ctors_end)
{
for (uint32_t* ctor=ctors_begin ; ctor<ctors_end ; ++ctor)
reinterpret_cast<void(*)(void)>(*ctor)();
}
extern uint32_t __textdata__;
extern uint32_t __data_start__;
extern uint32_t __data_end__;
extern uint32_t __bss_start__;
extern uint32_t __bss_end__;
extern uint32_t __ctors_start__;
extern uint32_t __ctors_end__;
void ISR::Reset()
{
SystemInit();
INIT_SP();
__initialize_bss(&__bss_start__, &__bss_end__);
__initialize_data(&__textdata__, &__data_start__, &__data_end__);
__initalize_classes(&__ctors_start__, &__ctors_end__);
PeriphInit();
CMSIS::enable_fault_irq();
CMSIS::enable_irq();
main();
}
| 26.920732 | 137 | 0.66795 | andreili |
507122dc3d2252d61a97ba041be9dcaeedf0730e | 600 | cpp | C++ | src/pe_structures/clr/Signature.cpp | secnary/pepper | 802ad055c15a6fba350f9aac08fb3f9e9770c78f | [
"Unlicense"
] | null | null | null | src/pe_structures/clr/Signature.cpp | secnary/pepper | 802ad055c15a6fba350f9aac08fb3f9e9770c78f | [
"Unlicense"
] | null | null | null | src/pe_structures/clr/Signature.cpp | secnary/pepper | 802ad055c15a6fba350f9aac08fb3f9e9770c78f | [
"Unlicense"
] | null | null | null | #include <pe_structures/DataDirectoryEntry.h>
#include <pe_structures/clr/Signature.h>
using namespace Pepper;
ClrSignature::ClrSignature(const PeFile& pe, const FileBytes& fbytes, const DataDirectoryEntry& dde)
: IDirectory(pe, fbytes, dde)
, m_length(dde.size())
{}
const char* ClrSignature::getFieldName(const int index)
{
switch (index) {
default: return "<UNKNOWN>";
}
}
const void* ClrSignature::getFieldPtr(const int index) const
{
const size_t uindex = static_cast<size_t>(index);
return (uindex < length())
? &getStructPtr()[uindex]
: nullptr;
}
| 23.076923 | 100 | 0.7 | secnary |
5072c34b3cf77328e1d006a8bb0e4eac2caee41d | 7,075 | cpp | C++ | src/pcl/src/testing.cpp | Malikmal/Learning-Pointcloud | 956ccc79e006f41ceac3af4f3ad7c41051125f19 | [
"MIT"
] | 3 | 2020-09-12T03:00:46.000Z | 2021-08-11T11:12:57.000Z | src/pcl/src/testing.cpp | Malikmal/Learning-Pointcloud | 956ccc79e006f41ceac3af4f3ad7c41051125f19 | [
"MIT"
] | 2 | 2020-09-11T17:04:40.000Z | 2020-09-12T05:51:22.000Z | src/pcl/src/testing.cpp | Malikmal/Learning-Pointcloud | 956ccc79e006f41ceac3af4f3ad7c41051125f19 | [
"MIT"
] | 2 | 2021-01-31T22:16:27.000Z | 2021-08-11T11:13:00.000Z | #include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/common.h>
#include <pcl/common/transforms.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/console/parse.h>
#include <pcl/console/print.h>
#include <pcl/io/pcd_io.h>
#include <iostream>
#include <flann/flann.h>
#include <flann/io/hdf5.h>
#include <boost/filesystem.hpp>
typedef std::pair<
std::string,
std::vector <float>
> VfhModel;
bool
loadHist (const boost::filesystem::path &path, VfhModel &vfh)
{
int vfh_idx;
// Load the file as a PCD
try
{
pcl::PCLPointCloud2 cloud;
int version;
Eigen::Vector4f origin;
Eigen::Quaternionf orientation;
pcl::PCDReader r;
int type; unsigned int idx;
r.readHeader (path.string (), cloud, origin, orientation, version, type, idx);
vfh_idx = pcl::getFieldIndex (cloud, "vfh");
if (vfh_idx == -1)
return (false);
if ((int)cloud.width * cloud.height != 1)
return (false);
}
catch (const pcl::InvalidConversionException&)
{
return (false);
}
// Treat the VFH signature as a single Point Cloud
pcl::PointCloud <pcl::VFHSignature308> point;
pcl::io::loadPCDFile (path.string (), point);
vfh.second.resize (308);
std::vector <pcl::PCLPointField> fields;
pcl::getFieldIndex<pcl::VFHSignature308> ("vfh", fields);
for (std::size_t i = 0; i < fields[vfh_idx].count; ++i)
{
vfh.second[i] = point[0].histogram[i];
}
vfh.first = path.string ();
return (true);
}
inline void
nearestKSearch (flann::Index<flann::ChiSquareDistance<float> > &index, const VfhModel &model,
int k, flann::Matrix<int> &indices, flann::Matrix<float> &distances)
{
// Query point
flann::Matrix<float> p = flann::Matrix<float>(new float[model.second.size ()], 1, model.second.size ());
memcpy (&p.ptr ()[0], &model.second[0], p.cols * p.rows * sizeof (float));
indices = flann::Matrix<int>(new int[k], 1, k);
distances = flann::Matrix<float>(new float[k], 1, k);
index.knnSearch (p, indices, distances, k, flann::SearchParams (512));
delete[] p.ptr ();
}
int main(int argc, char** argv)
{ int k = 16;
double thresh = DBL_MAX;
std::string extension(".pcd");
transform(extension.begin(), extension.end(), extension.begin(), (int(*)(int))tolower);
//load the test histogram
std::vector<int> pcdIndices = pcl::console::parse_file_extension_argument(argc, argv, ".pcd");
VfhModel histogram;
if(!loadHist(argv[pcdIndices.at(0)], histogram))
{
pcl::console::print_error("Cannot load test file %s\n", argv[pcdIndices.at(0)]);
return -1;
}
std::string idxFile = "kdtree.idx";
std::string h5File = "training_data.h5";
std::string listFile = "training_data.list";
std::vector<VfhModel> models;
flann::Matrix<int> kIndices;
flann::Matrix<float> kDistances;
flann::Matrix<float> data;
if(!boost::filesystem::exists(h5File) || !boost::filesystem::exists(listFile))
{
pcl::console::print_error("could not find kd-tree index in file %s!", idxFile.c_str());
return -1;
}else{
flann::Index<flann::ChiSquareDistance<float>> index (data, flann::SavedIndexParams("kdtree.idx"));
index.buildIndex();
nearestKSearch(index, histogram, k, kIndices, kDistances);
}
//output the result on screen
pcl::console::print_highlight("The closest %d neighbors for %s are : \n", k, argv[pcdIndices[0]]);
for(int i = 0; i < k; i++)
{
pcl::console::print_info("%d - $s (%d) with a distance of : %f\n",
i, models.at(kIndices[0][i]).first.c_str(), kIndices[0][i], kDistances[0][i]);
}
//load the result
pcl::visualization::PCLVisualizer p (argc, argv, "VFH Cluster Classifier");
int ys = (int )std::floor(sqrt((double)k));
int xs = ys + (int) std::ceil((k/(double)ys) - ys);
double xstep = (double)(1/(double)xs);
double ystep = (double)(1/(double)ys);
pcl::console::print_highlight ("Preparing to load ");
pcl::console::print_value ("%d", k);
pcl::console::print_info (" files (");
pcl::console::print_value ("%d", xs);
pcl::console::print_info ("x");
pcl::console::print_value ("%d", ys);
pcl::console::print_info (" / ");
pcl::console::print_value ("%f", xstep);
pcl::console::print_info ("x");
pcl::console::print_value ("%f", ystep);
pcl::console::print_info (")\n");
int viewport = 0, l=0, m=0;
for(int i =0; i<k; ++i)
{
std::string cloud_name = models.at(kIndices[0][i]).first;
boost::replace_last(cloud_name, "_vfh", "");
p.createViewPort(l*xstep, m*ystep, (l+1) * xstep, (m+1)* ystep, viewport);
l++;
if(l >= xs)
{
l=0;
m++;
}
pcl::PCLPointCloud2 cloud;
pcl::console::print_highlight(stderr, "Loading ");
pcl::console::print_value(stderr, "%s ", cloud_name.c_str());
if(pcl::io::loadPCDFile(cloud_name, cloud) == -1)
{
break;
}
//convert from blob to pointlcloud
pcl::PointCloud<pcl::PointXYZ> cloud_xyz;
pcl::fromPCLPointCloud2(cloud, cloud_xyz);
if(cloud_xyz.size() == 0)
{
break;
}
pcl::console::print_info ("[done, ");
pcl::console::print_value ("%zu", static_cast<std::size_t>(cloud_xyz.size ()));
pcl::console::print_info (" points]\n");
pcl::console::print_info ("Available dimensions: ");
pcl::console::print_value ("%s\n", pcl::getFieldsList (cloud).c_str ());
// Demean the cloud
Eigen::Vector4f centroid;
pcl::compute3DCentroid (cloud_xyz, centroid);
pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_xyz_demean (new pcl::PointCloud<pcl::PointXYZ>);
pcl::demeanPointCloud<pcl::PointXYZ> (cloud_xyz, centroid, *cloud_xyz_demean);
// Add to renderer*
p.addPointCloud (cloud_xyz_demean, cloud_name, viewport);
// Check if the model found is within our inlier tolerance
std::stringstream ss;
ss << kDistances[0][i];
if (kDistances[0][i] > thresh)
{
p.addText (ss.str (), 20, 30, 1, 0, 0, ss.str (), viewport); // display the text with red
// Create a red line
pcl::PointXYZ min_p, max_p;
pcl::getMinMax3D (*cloud_xyz_demean, min_p, max_p);
std::stringstream line_name;
line_name << "line_" << i;
p.addLine (min_p, max_p, 1, 0, 0, line_name.str (), viewport);
p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_LINE_WIDTH, 5, line_name.str (), viewport);
}
else
p.addText (ss.str (), 20, 30, 0, 1, 0, ss.str (), viewport);
// Increase the font size for the score*
p.setShapeRenderingProperties (pcl::visualization::PCL_VISUALIZER_FONT_SIZE, 18, ss.str (), viewport);
// Add the cluster name
p.addText (cloud_name, 20, 10, cloud_name, viewport);
}
// Add coordianate systems to all viewports
p.addCoordinateSystem (0.1, "global", 0);
p.spin ();
return (0);
} | 33.530806 | 115 | 0.618375 | Malikmal |
50731772a4dcae6a7bb451488250081156fc27e9 | 31,440 | cpp | C++ | vision-normal-fusion/libs/D3D/src/d3d_stereo/cudaPlaneSweep.cpp | kunal71091/Depth_Normal_Fusion | 407e204abfbd6c8efe2f98a07415bd623ad84422 | [
"MIT"
] | 1 | 2019-10-23T06:32:40.000Z | 2019-10-23T06:32:40.000Z | vision-normal-fusion/libs/D3D/src/d3d_stereo/cudaPlaneSweep.cpp | kunal71091/Depth_Normal_Fusion | 407e204abfbd6c8efe2f98a07415bd623ad84422 | [
"MIT"
] | null | null | null | vision-normal-fusion/libs/D3D/src/d3d_stereo/cudaPlaneSweep.cpp | kunal71091/Depth_Normal_Fusion | 407e204abfbd6c8efe2f98a07415bd623ad84422 | [
"MIT"
] | 1 | 2021-09-23T03:35:30.000Z | 2021-09-23T03:35:30.000Z | #include "cudaPlaneSweep.h"
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <d3d_base/exception.h>
#include <d3d_cudaBase/cudaCommon.h>
#include <d3d_cudaBase/deviceImage.h>
using std::cerr;
using std::cout;
using std::endl;
using std::vector;
using std::string;
using std::stringstream;
using namespace cv;
using namespace D3D;
using namespace D3D_CUDA::CudaPlaneSweepDeviceCode;
using namespace D3D_CUDA;
CudaPlaneSweep::CudaPlaneSweep()
{
nextId = 0;
// set invalid default values
nearZ = -1;
farZ = -1;
matchWindowHeight = -1;
matchWindowWidth = -1;
matchWindowRadiusX = -1;
matchWindowRadiusY = -1;
// set default parameters
occlusionMode = PLANE_SWEEP_OCCLUSION_NONE;
occlusionBestK = 1;
scale = 1;
planeGenerationMode = PLANE_SWEEP_PLANEMODE_UNIFORM_DEPTH;
outputBestDepthEnabled = true;
outputBestCostsEnabled = false;
colorMatchingEnabled = false;
outputCostVolumeEnabled = false;
outputUniquenessRatioEnabled = false;
subPixelEnabled = true;
subPixelInterpMode = PLANE_SWEEP_SUB_PIXEL_INTERP_INVERSE;
boxFilterBeforeOcclusion = true;
matchingCosts = PLANE_SWEEP_SAD;
// init cuda textures
planeSweepInitTexturing();
}
CudaPlaneSweep::~CudaPlaneSweep()
{
// delete all the images from the gpu
for (map<int, CudaPlaneSweepImage>::iterator it = images.begin(); it != images.end(); it++)
{
it->second.devImg.deallocate();
}
deallocateBuffers();
}
int CudaPlaneSweep::addImage(Mat image, CameraMatrix<double>& cam)
{
CudaPlaneSweepImage cPSI;
cPSI.cam = cam;
if (scale != 1)
{
// scale image
Mat scaledImage;
if (scale < 1)
resize(image, scaledImage, Size(0,0), scale, scale, INTER_AREA);
else
resize(image, scaledImage, Size(0,0) , scale, scale, INTER_LINEAR);
image = scaledImage;
// cv::imshow("image", image);
// cv::waitKey(500);
// scale cam
cPSI.cam.scaleK(scale, scale);
}
if (colorMatchingEnabled && image.channels() == 4)
{
// copy rgba data
cPSI.devImg.allocatePitchedAndUpload(image);
}
else if (colorMatchingEnabled && image.channels() == 3)
{
// add alpha channel first
Mat corrImg;
cvtColor(image, corrImg, CV_BGR2BGRA);
cPSI.devImg.allocatePitchedAndUpload(corrImg);
}
else if (!colorMatchingEnabled && image.channels() == 3)
{
// convert to grayscale
Mat corrImg;
cvtColor(image, corrImg, CV_BGR2GRAY);
cPSI.devImg.allocatePitchedAndUpload(corrImg);
}
else if(!colorMatchingEnabled && image.channels() == 1)
{
// copy inensity data
cPSI.devImg.allocatePitchedAndUpload(image);
}
else
{
D3D_THROW_EXCEPTION("Image format not supported for current color mode.");
}
int id = nextId++;
images[id] = cPSI;
return id;
}
int CudaPlaneSweep::addDeviceImage(DeviceImage& devImage, CameraMatrix<double>& cam)
{
CudaPlaneSweepImage cPSI;
cPSI.devImg = devImage;
cPSI.cam = cam;
int id = nextId++;
images[id] = cPSI;
return id;
}
void CudaPlaneSweep::deleteImage(int id)
{
CudaPlaneSweepImage img;
if (images.count(id) == 1)
{
img = images[id];
}
else
{
stringstream strstream;
strstream << "Image with ID " << id << " does not exist.";
D3D_THROW_EXCEPTION(strstream.str().c_str());
}
// delete image on the device
img.devImg.deallocate();
// delete image form the map
images.erase(id);
}
void CudaPlaneSweep::setZRange(double nearZ, double farZ)
{
this->nearZ = nearZ;
this->farZ = farZ;
}
void CudaPlaneSweep::setMatchWindowSize(int w, int h)
{
this->matchWindowHeight = h;
this->matchWindowWidth = w;
this->matchWindowRadiusX = w/2;
this->matchWindowRadiusY = h/2;
}
void CudaPlaneSweep::setNumPlanes(int num)
{
this->numPlanes = num;
}
void CudaPlaneSweep::setOcclusionMode(PlaneSweepOcclusionMode occlusionMode)
{
this->occlusionMode = occlusionMode;
}
void CudaPlaneSweep::setOcclusionBestK(int bestK)
{
occlusionBestK = bestK;
}
double CudaPlaneSweep::largestBaseline(const CudaPlaneSweepImage& refImg)
{
double lBaseline = 0;
Matrix<double, 3, 1> refC = refImg.cam.getC();
for (map<int, CudaPlaneSweepImage>::iterator it = images.begin(); it != images.end(); it++)
{
if (refImg.devImg.getAddr() == it->second.devImg.getAddr())
{
continue;
}
// compute baseline
Matrix<double, 3, 1> thisC = it->second.cam.getC();
double baseline = (refC-thisC).norm();
if (baseline > lBaseline)
lBaseline = baseline;
}
return lBaseline;
}
void CudaPlaneSweep::process(int refImgId, Grid<Vector4d> &planes)
{
int numPlanes = planes.getWidth();
//this->planes = planes;
// check if values are set
if (!(matchWindowHeight > 0 && matchWindowWidth > 0 &&
numPlanes > 0))
{
D3D_THROW_EXCEPTION("Parameters not set properly")
}
CudaPlaneSweepImage refImg;
if (images.count(refImgId) == 1)
{
refImg = images[refImgId] ;
}
else
{
stringstream strstream;
strstream << "Image with ID " << refImgId << " does not exist.";
D3D_THROW_EXCEPTION(strstream.str().c_str());
}
refImgCam = refImg.cam;
if (outputCostVolumeEnabled)
{
costVolume = Grid<float>(refImg.devImg.getWidth(), refImg.devImg.getHeight(), numPlanes);
}
// allocate the warping buffer on the gpu
// planeSweepCreateImage(refImg.w, refImg.h, colorMatchingEnabled, this->warpingBuffer.imgAddr, this->warpingBuffer.pitch);
// allocate the costs buffer on the gpu
// planeSweepCreateCostBuffer(refImg.w, refImg.h, this->costBuffer.addr, this->costBuffer.pitch);
// allocate a cost buffer to store the results of the first box filter pass
boxFilterTempBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
// allocate the cost accum buffer on the gpu
costAccumBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
// planeSweepCreateFloatBuffer(refImg.w, refImg.h, this->costAccumBuffer.addr, this->costAccumBuffer.pitch);
if (subPixelEnabled)
{
subPixelCostAccumBufferPrev1.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
subPixelCostAccumBufferPrev2.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
subPixelPlaneOffsetsBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
subPixelPlaneOffsetsBuffer.clear(0.0f);
}
if (outputUniquenessRatioEnabled)
{
secondBestPlaneCostBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
secondBestPlaneCostBuffer.clear(1e6);
}
if (outputBestDepthEnabled || outputUniquenessRatioEnabled)
{
// allocate best plane buffer
bestPlaneBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
// initialize to zero,
// this is necessary because the buffer on the gpu can be bigger than the actual image and we need to have valid plane indices everywhere
// for the best depth computation
bestPlaneBuffer.clear(0);
// allocate best plane cost buffer
bestPlaneCostBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
// initialize to big value
bestPlaneCostBuffer.clear(1e6);
}
if (occlusionMode == PLANE_SWEEP_OCCLUSION_BEST_K)
{
// allocate buffers for the matching costs
costBuffers.resize(images.size()-1);
for (unsigned int i = 0; i < costBuffers.size(); i++)
{
costBuffers[i].reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
}
// allocate buffers to find the best K
bestKBuffer0.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
bestKBuffer1.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
}
else if (occlusionMode == PLANE_SWEEP_OCCLUSION_REF_SPLIT)
{
// allocate buffers for accumulated matching costs
costAccumBeforeBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
costAccumAfterBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
}
double accumScale0 = 0, accumScale1 = 0;
if (occlusionMode == PLANE_SWEEP_OCCLUSION_NONE)
{
accumScale0 = (double)1 / (double) (images.size()-1);
}
else if (occlusionMode == PLANE_SWEEP_OCCLUSION_REF_SPLIT)
{
int numBefore = 0;
int numAfter = 0;
for(map<int, CudaPlaneSweepImage>::iterator it = images.begin(); it != images.end(); it++)
{
if (it->first < refImgId)
{
numBefore++;
}
else if (it->first > refImgId)
{
numAfter++;
}
}
if (numBefore == 0 || numAfter == 0)
{
D3D_THROW_EXCEPTION( "Reference Image cannot be at the border of the sequence with PLANE_SWEEP_OCCLUSION_REF_SPLIT" )
}
accumScale0 = (double) 1 / (double) numBefore;
accumScale1 = (double) 1 / (double) numAfter;
}
else if (occlusionMode == PLANE_SWEEP_OCCLUSION_BEST_K)
{
accumScale0 = (double) 1 / (double) occlusionBestK;
}
if (matchingCosts == PLANE_SWEEP_ZNCC)
{
// the matching cost is NCC so we need to allocate some more buffers
refImgBoxFilterBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
otherImgBoxFilterBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
refImgSqrBoxFilterBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
otherImgSqrBoxFilterBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
imgProdBoxFilterBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
boxFilterSqrTempBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
boxFilterProdTempBuffer.reallocatePitched(refImg.devImg.getWidth(), refImg.devImg.getHeight());
// the box filtering only dependant on the reference image can be done only once before entering the main loop
planeSweepBoxFilterImageAndSqrImage(refImg.devImg, refImgBoxFilterBuffer, refImgSqrBoxFilterBuffer,
matchWindowRadiusX, matchWindowRadiusY);
}
for (int i = 0; i < numPlanes; i++)
{
if (occlusionMode == PLANE_SWEEP_OCCLUSION_NONE)
{
costAccumBuffer.clear(0);
}
else if (occlusionMode == PLANE_SWEEP_OCCLUSION_REF_SPLIT)
{
costAccumBeforeBuffer.clear(0);
costAccumAfterBuffer.clear(0);
}
int j = 0;
for (map<int, CudaPlaneSweepImage>::iterator it = images.begin(); it != images.end(); it++)
{
if (it->first == refImgId)
continue;
// match the image
switch(occlusionMode)
{
case PLANE_SWEEP_OCCLUSION_NONE:
{
float H[9];
planeHomography(planes(i,0), refImg.cam, it->second.cam, H);
switch(matchingCosts)
{
case PLANE_SWEEP_SAD:
planeSweepWarpADAccum(it->second.devImg, colorMatchingEnabled, H,
refImg.devImg, (float) accumScale0, costAccumBuffer);
break;
case PLANE_SWEEP_ZNCC:
planeSweepWarpZNCCAccum(it->second.devImg, H, refImg.devImg,
refImgBoxFilterBuffer, refImgSqrBoxFilterBuffer,
(float) accumScale0, costAccumBuffer, matchWindowRadiusX, matchWindowRadiusY);
break;
}
break;
}
case PLANE_SWEEP_OCCLUSION_BEST_K:
{
matchImage(refImg, it->second, planes(i,0), costBuffers[j]);
if (boxFilterBeforeOcclusion && matchingCosts != PLANE_SWEEP_ZNCC)
{
planeSweepBoxFilterCosts(costBuffers[j], boxFilterTempBuffer, matchWindowRadiusX, matchWindowRadiusY);
DeviceBuffer<float> temp = boxFilterTempBuffer;
boxFilterTempBuffer = costBuffers[j]; // swap buffers
costBuffers[j] = temp;
}
break;
}
case PLANE_SWEEP_OCCLUSION_REF_SPLIT:
{
float H[9];
planeHomography(planes(i,0), refImg.cam, it->second.cam, H);
switch (matchingCosts)
{
case PLANE_SWEEP_SAD:
if (it->first < refImgId)
{
planeSweepWarpADAccum(it->second.devImg, colorMatchingEnabled, H,
refImg.devImg, (float) accumScale0, costAccumBeforeBuffer);
}
else
{
planeSweepWarpADAccum(it->second.devImg, colorMatchingEnabled, H,
refImg.devImg, (float) accumScale1, costAccumAfterBuffer);
}
break;
case PLANE_SWEEP_ZNCC:
if (it->first < refImgId)
{
planeSweepWarpZNCCAccum(it->second.devImg, H, refImg.devImg,
refImgBoxFilterBuffer, refImgSqrBoxFilterBuffer,
(float) accumScale0, costAccumBeforeBuffer, matchWindowRadiusX, matchWindowRadiusY);
}
else
{
planeSweepWarpZNCCAccum(it->second.devImg, H, refImg.devImg,
refImgBoxFilterBuffer, refImgSqrBoxFilterBuffer,
(float) accumScale1, costAccumAfterBuffer, matchWindowRadiusX, matchWindowRadiusY);
}
break;
}
break;
}
}
j++;
}
if (occlusionMode == PLANE_SWEEP_OCCLUSION_BEST_K)
{
// accumulate the best K
DeviceBuffer<float> best = bestKBuffer0;
DeviceBuffer<float> bestMin = bestKBuffer1;
const float bestMax = 1e6;
costAccumBuffer.clear(0);
best.clear(bestMax);
bestMin.clear(0);
for (int k = 0; k < this->occlusionBestK; k++)
{
for (unsigned int j = 0; j < costBuffers.size(); j++)
{
updateBestK(costBuffers[j], best, bestMin);
}
// accumulate best
planeSweepAccumCostBestK(costAccumBuffer, best, bestMin, bestMax, (float) accumScale0);
// swap buffers
DeviceBuffer<float> temp = bestMin;
bestMin = best;
best = temp;
best.clear(bestMax);
}
}
else if (occlusionMode == PLANE_SWEEP_OCCLUSION_REF_SPLIT)
{
if (boxFilterBeforeOcclusion && matchingCosts != PLANE_SWEEP_ZNCC)
{
planeSweepBoxFilterCosts(costAccumBeforeBuffer, boxFilterTempBuffer, matchWindowRadiusX, matchWindowRadiusY);
DeviceBuffer<float> temp = boxFilterTempBuffer;
boxFilterTempBuffer = costAccumBeforeBuffer;
costAccumBeforeBuffer = temp;
planeSweepBoxFilterCosts(costAccumAfterBuffer, boxFilterTempBuffer, matchWindowRadiusX, matchWindowRadiusY);
temp = boxFilterTempBuffer;
boxFilterTempBuffer = costAccumAfterBuffer;
costAccumAfterBuffer = temp;
}
// take the minimum of the two buffers
planeSweepMinFloat(costAccumBeforeBuffer, costAccumAfterBuffer, costAccumBuffer);
}
// box filter
if ((occlusionMode == PLANE_SWEEP_OCCLUSION_NONE || !boxFilterBeforeOcclusion) && matchingCosts != PLANE_SWEEP_ZNCC)
{
planeSweepBoxFilterCosts(costAccumBuffer, boxFilterTempBuffer, matchWindowRadiusX, matchWindowRadiusY);
DeviceBuffer<float> temp = boxFilterTempBuffer;
boxFilterTempBuffer = costAccumBuffer; // swap buffers
costAccumBuffer = temp;
}
if (outputCostVolumeEnabled)
{
costAccumBuffer.download((float*)&costVolume(0,0,i), costVolume.getWidth()*sizeof(float));
}
if (subPixelEnabled && i >= 2)
{
if (outputBestDepthEnabled || outputUniquenessRatioEnabled)
{
if (outputUniquenessRatioEnabled)
{
planeSweepUpdateBestAndSecondBestPlaneSubPixel(costAccumBuffer, subPixelCostAccumBufferPrev1, subPixelCostAccumBufferPrev2, refImg.devImg.getWidth(), refImg.devImg.getHeight(), i-1,
bestPlaneCostBuffer, secondBestPlaneCostBuffer, bestPlaneBuffer, subPixelPlaneOffsetsBuffer);
}
else
{
planeSweepUpdateBestPlaneSubPixel(costAccumBuffer, subPixelCostAccumBufferPrev1, subPixelCostAccumBufferPrev2, refImg.devImg.getWidth(), refImg.devImg.getHeight(), i-1,
bestPlaneCostBuffer, bestPlaneBuffer, subPixelPlaneOffsetsBuffer);
}
}
}
if (!subPixelEnabled || (i == 0 || i == numPlanes-1))
{
if (outputBestDepthEnabled || outputUniquenessRatioEnabled)
{
if (outputUniquenessRatioEnabled)
{
planeSweepUpdateBestAndSecondBestPlane(costAccumBuffer, refImg.devImg.getWidth(), refImg.devImg.getHeight(), i,
bestPlaneCostBuffer, secondBestPlaneCostBuffer, bestPlaneBuffer);
}
else
{
planeSweepUpdateBestPlane(costAccumBuffer, refImg.devImg.getWidth(), refImg.devImg.getHeight(), i,
bestPlaneCostBuffer, bestPlaneBuffer);
}
}
}
if (subPixelEnabled)
{
// rotate buffers
D3D_CUDA::DeviceBuffer<float> temp = subPixelCostAccumBufferPrev2;
subPixelCostAccumBufferPrev2 = subPixelCostAccumBufferPrev1;
subPixelCostAccumBufferPrev1 = costAccumBuffer;
costAccumBuffer = temp;
}
}
if (outputBestDepthEnabled)
{
// store planes in a vector to upload them to gpu
vector<float> planesVec;
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < numPlanes; i++)
{
planesVec.push_back((float) planes(i,0)(j));
}
}
// get inverse ref camera matrix
Matrix<double, 3, 3> KrefInv = refImg.cam.getK().inverse();
vector<float> KrefInvVec;
for (int i=0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
KrefInvVec.push_back((float) KrefInv(i,j));
}
}
bestDepth = DepthMap<float, double>(refImg.devImg.getWidth(), refImg.devImg.getHeight(), refImg.cam);
if (subPixelEnabled)
{
switch(subPixelInterpMode)
{
case PLANE_SWEEP_SUB_PIXEL_INTERP_INVERSE:
planeSweepComputeBestDepthsSubPixelInverse(bestPlaneBuffer, subPixelPlaneOffsetsBuffer, numPlanes, planesVec,
bestDepth.getDataPtr(), bestDepth.getWidth()*sizeof(float), KrefInvVec);
break;
case PLANE_SWEEP_SUB_PIXEL_INTERP_DIRECT:
planeSweepComputeBestDepthsSubPixelDirect(bestPlaneBuffer, subPixelPlaneOffsetsBuffer, numPlanes, planesVec,
bestDepth.getDataPtr(), bestDepth.getWidth()*sizeof(float), KrefInvVec);
break;
}
}
else
{
planeSweepComputeBestDepths(bestPlaneBuffer, numPlanes, planesVec,
bestDepth.getDataPtr(), bestDepth.getWidth()*sizeof(float), KrefInvVec);
}
}
if (outputBestCostsEnabled)
{
bestCosts = Grid<float>(bestPlaneCostBuffer.getWidth(), bestPlaneCostBuffer.getHeight());
bestPlaneCostBuffer.download(bestCosts.getDataPtr(), bestCosts.getWidth()*sizeof(float));
}
if (outputUniquenessRatioEnabled)
{
computeUniquenessRatio(bestPlaneCostBuffer, secondBestPlaneCostBuffer, secondBestPlaneCostBuffer);
uniqunessRatios = Grid<float>(bestPlaneCostBuffer.getWidth(), bestPlaneCostBuffer.getHeight());
secondBestPlaneCostBuffer.download(uniqunessRatios.getDataPtr(), uniqunessRatios.getWidth()*sizeof(float));
}
// costAccumBuffer.deallocate();
// boxFilterTempBuffer.deallocate();
// if (subPixelEnabled)
// {
// subPixelCostAccumBufferPrev1.deallocate();
// subPixelCostAccumBufferPrev2.deallocate();
// subPixelPlaneOffsetsBuffer.deallocate();
// }
// if (outputBestDepthEnabled || outputUniquenessRatioEnabled)
// {
// bestPlaneBuffer.deallocate();
// bestPlaneCostBuffer.deallocate();
// }
// if (occlusionMode == PLANE_SWEEP_OCCLUSION_BEST_K)
// {
// for (unsigned int i = 0; i < costBuffers.size(); i++)
// {
// costBuffers[i].deallocate();
// }
// // allocate buffers to find the best K
// bestKBuffer0.deallocate();
// bestKBuffer1.deallocate();
// }
// else if (occlusionMode == PLANE_SWEEP_OCCLUSION_REF_SPLIT)
// {
// costAccumBeforeBuffer.deallocate();
// costAccumAfterBuffer.deallocate();
// }
// if (matchingCosts == PLANE_SWEEP_ZNCC)
// {
// refImgBoxFilterBuffer.deallocate();
// otherImgBoxFilterBuffer.deallocate();
// refImgSqrBoxFilterBuffer.deallocate();
// otherImgSqrBoxFilterBuffer.deallocate();
// imgProdBoxFilterBuffer.deallocate();
// boxFilterSqrTempBuffer.deallocate();
// boxFilterProdTempBuffer.deallocate();
// }
// if (outputUniquenessRatioEnabled)
// {
// secondBestPlaneCostBuffer.deallocate();
// }
}
void CudaPlaneSweep::process(int refImgId)
{
// check if values are set
if (!(nearZ > 0 && farZ > 0 && numPlanes > 0))
{
D3D_THROW_EXCEPTION("Parameters not set properly")
}
CudaPlaneSweepImage refImg;
if (images.count(refImgId) == 1)
{
refImg = images[refImgId] ;
}
else
{
stringstream strstream;
strstream << "Image with ID " << refImgId << " does not exist.";
D3D_THROW_EXCEPTION(strstream.str().c_str());
}
planes = Grid<Vector4d>(numPlanes,1);
switch(planeGenerationMode)
{
case PLANE_SWEEP_PLANEMODE_UNIFORM_DEPTH:
{
double step = (farZ - nearZ)/(numPlanes-1);
for (int i = 0; i < numPlanes; i++)
{
planes(i,0).setZero();
planes(i,0)(2) = -1;
planes(i,0)(3) = nearZ + i*step;
}
break;
}
case PLANE_SWEEP_PLANEMODE_UNIFORM_DISPARITY:
{
double maxB = largestBaseline(refImg);
double avgF = (refImg.cam.getK()(0,0)+refImg.cam.getK()(1,1))/2.0;
double minD = maxB*avgF/farZ;
double maxD = maxB*avgF/nearZ;
double dStep = (maxD - minD)/(numPlanes-1);
for (int i = 0; i < numPlanes; i++)
{
planes(i,0).setZero();
planes(i,0)(2) = -1;
planes(i,0)(3) = maxB*avgF/(maxD - i*dStep);
}
break;
}
}
process(refImgId, planes);
}
void CudaPlaneSweep::planeHomography(const Matrix<double, 4, 1>& plane, const CameraMatrix<double> &refCam, const CameraMatrix<double> &otherCam, float* H)
{
const Matrix<double, 3, 3> kRef = refCam.getK();
const Matrix<double, 3, 3> kOther = otherCam.getK();
const Matrix<double, 3, 3> rRef = refCam.getR();
const Matrix<double, 3, 3> rOther = otherCam.getR();
const Matrix<double, 3, 1> tRef = refCam.getT();
const Matrix<double, 3, 1> tOther = otherCam.getT();
const Matrix<double, 3, 1> n = plane.head(3);
const Matrix<double, 3, 3> rRel = rOther*rRef.transpose();
const Matrix<double, 3, 1> tRel = rRel*tRef - tOther;
Matrix<double, 3, 3> Hmat = kOther*(rRel + ((double) 1)/plane(3) * tRel*n.transpose())*kRef.inverse();
H[0] = (float) Hmat(0,0); H[1] = (float) Hmat(0,1); H[2] = (float) Hmat(0,2);
H[3] = (float) Hmat(1,0); H[4] = (float) Hmat(1,1); H[5] = (float) Hmat(1,2);
H[6] = (float) Hmat(2,0); H[7] = (float) Hmat(2,1); H[8] = (float) Hmat(2,2);
}
void CudaPlaneSweep::enableOutputBestDepth(bool enabled)
{
outputBestDepthEnabled = enabled;
}
void CudaPlaneSweep::enableOutputBestCosts(bool enabled)
{
outputBestCostsEnabled = enabled;
}
DepthMap<float, double> CudaPlaneSweep::getBestDepth()
{
return bestDepth;
}
CameraMatrix<double> CudaPlaneSweep::getRefImgCam()
{
return refImgCam;
}
Grid<float> CudaPlaneSweep::getBestCosts()
{
return bestCosts;
}
// if color matching was previously disabled all images will be deleted
void CudaPlaneSweep::enableColorMatching(bool enabled)
{
if (enabled && matchingCosts == PLANE_SWEEP_ZNCC)
{
D3D_THROW_EXCEPTION( "NCC not supported with color matching" )
}
if (colorMatchingEnabled != enabled)
{
// delete all images
vector<int> idsToDelete;
for (map<int, CudaPlaneSweepImage>::iterator it = images.begin(); it != images.end(); it++)
{
idsToDelete.push_back(it->first);
}
for (size_t i=0; i < idsToDelete.size(); i++)
{
deleteImage(idsToDelete[i]);
}
colorMatchingEnabled = enabled;
}
}
void CudaPlaneSweep::matchImage(const CudaPlaneSweepImage &refImg, const CudaPlaneSweepImage &otherImg, const Matrix<double, 4, 1> &plane, DeviceBuffer<float>& costBuffer)
{
float H[9];
planeHomography(plane, refImg.cam, otherImg.cam, H);
switch(matchingCosts)
{
case PLANE_SWEEP_SAD:
planeSweepWarpAD(otherImg.devImg, colorMatchingEnabled, H, refImg.devImg, costBuffer);
break;
case PLANE_SWEEP_ZNCC:
planeSweepWarpZNCC(otherImg.devImg, H, refImg.devImg,
refImgBoxFilterBuffer, refImgSqrBoxFilterBuffer,
costBuffer, matchWindowRadiusX, matchWindowRadiusY);
break;
}
}
void CudaPlaneSweep::setPlaneGenerationMode(PlaneSweepPlaneGenerationMode planeGenerationMode)
{
this->planeGenerationMode = planeGenerationMode;
}
void CudaPlaneSweep::enableBoxFilterBeforeOcclusion(bool enabled)
{
this->boxFilterBeforeOcclusion = enabled;
}
void CudaPlaneSweep::setMatchingCosts(PlaneSweepMatchingCosts matchingCosts)
{
if (colorMatchingEnabled && matchingCosts == PLANE_SWEEP_ZNCC)
{
D3D_THROW_EXCEPTION( "ZNCC not supported with color matching" )
}
this->matchingCosts = matchingCosts;
}
void CudaPlaneSweep::setScale(double scale)
{
this->scale = scale;
}
void CudaPlaneSweep::enableOuputUniquenessRatio(bool enabled)
{
this->outputUniquenessRatioEnabled = enabled;
}
Grid<float> CudaPlaneSweep::getUniquenessRatios()
{
return uniqunessRatios;
}
void CudaPlaneSweep::enableOutputCostVolume(bool enabled)
{
this->outputCostVolumeEnabled = enabled;
}
Grid<float> CudaPlaneSweep::getCostVolume()
{
return costVolume;
}
Grid<Vector4d> CudaPlaneSweep::getPlanes()
{
return planes;
}
void CudaPlaneSweep::setSubPixelInterpolationMode(PlaneSweepSubPixelInterpMode interpMode)
{
subPixelInterpMode = interpMode;
}
void CudaPlaneSweep::enableSubPixel(bool enabled)
{
this->subPixelEnabled = enabled;
}
void CudaPlaneSweep::updateCameraMatrix(int id, CameraMatrix<double>& cam)
{
if (images.count(id) != 1)
{
stringstream strstream;
strstream << "Image with ID " << id << " does not exist.";
D3D_THROW_EXCEPTION(strstream.str().c_str());
}
images[id].cam = cam;
}
cv::Mat CudaPlaneSweep::downloadImage(int id)
{
if (images.count(id) != 1)
{
std::stringstream errorMsg;
errorMsg << "Cannot download image with ID " << id << ". ID invalid.";
D3D_THROW_EXCEPTION(errorMsg.str().c_str());
}
cv::Mat image;
images[id].devImg.download(image);
return image;
}
void CudaPlaneSweep::deallocateBuffers()
{
if (costAccumBuffer.getAddr() != 0)
costAccumBuffer.deallocate();
if (subPixelCostAccumBufferPrev1.getAddr() != 0)
subPixelCostAccumBufferPrev1.deallocate();
if (subPixelCostAccumBufferPrev2.getAddr() != 0)
subPixelCostAccumBufferPrev2.deallocate();
if (subPixelPlaneOffsetsBuffer.getAddr() != 0)
subPixelPlaneOffsetsBuffer.deallocate();
if (boxFilterTempBuffer.getAddr() != 0)
boxFilterTempBuffer.deallocate();
if (bestPlaneBuffer.getAddr() != 0)
bestPlaneBuffer.deallocate();
if (bestPlaneCostBuffer.getAddr() != 0)
bestPlaneCostBuffer.deallocate();
if (secondBestPlaneCostBuffer.getAddr() != 0)
secondBestPlaneCostBuffer.deallocate();
for (unsigned int i = 0; i < costBuffers.size(); i++)
{
if (costBuffers[i].getAddr() != 0)
costBuffers[i].deallocate();
}
if (bestKBuffer0.getAddr() != 0)
bestKBuffer0.deallocate();
if (bestKBuffer1.getAddr() != 0)
bestKBuffer1.deallocate();
if (costAccumBeforeBuffer.getAddr() != 0)
costAccumBeforeBuffer.deallocate();
if (costAccumAfterBuffer.getAddr() != 0)
costAccumAfterBuffer.deallocate();
if (refImgBoxFilterBuffer.getAddr() != 0)
refImgBoxFilterBuffer.deallocate();
if (otherImgBoxFilterBuffer.getAddr() != 0)
otherImgBoxFilterBuffer.deallocate();
if (refImgSqrBoxFilterBuffer.getAddr() != 0)
refImgSqrBoxFilterBuffer.deallocate();
if (otherImgSqrBoxFilterBuffer.getAddr() != 0)
otherImgSqrBoxFilterBuffer.deallocate();
if (imgProdBoxFilterBuffer.getAddr() != 0)
imgProdBoxFilterBuffer.deallocate();
if (boxFilterSqrTempBuffer.getAddr() != 0)
boxFilterSqrTempBuffer.deallocate();
if (boxFilterProdTempBuffer.getAddr() != 0)
boxFilterProdTempBuffer.deallocate();
}
| 31.629779 | 201 | 0.611101 | kunal71091 |
50733456d054c748b2ad3d318361539a2a3c5e39 | 1,098 | cc | C++ | plus-one.cc | sonald/leetcode | 3c34e2779a736acc880876f4244f1becd7b199ed | [
"MIT"
] | null | null | null | plus-one.cc | sonald/leetcode | 3c34e2779a736acc880876f4244f1becd7b199ed | [
"MIT"
] | null | null | null | plus-one.cc | sonald/leetcode | 3c34e2779a736acc880876f4244f1becd7b199ed | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <random>
#include <map>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> plusOne(vector<int>& digits) {
reverse(digits.begin(), digits.end());
auto sz = digits.size();
vector<int> v(sz+1);
int carry = 1;
for (int i = 0; i < sz; ++i) {
auto d = (digits[i] + carry);
carry = d-9>0?1:0;
v[i] = carry? d - 10 : d;
}
if (carry) {
v[sz] = 1;
} else {
v.resize(sz);
}
::reverse(v.begin(), v.end());
return v;
}
};
ostream& operator<<(ostream& os, const vector<int>& v)
{
::for_each(v.begin(), v.end(), [&](int x) { os << x; });
return os;
}
int main(int argc, char *argv[])
{
Solution sol;
vector<int> v{1,3,7};
cout << sol.plusOne(v) << endl;
v = {9};
cout << sol.plusOne(v) << endl;
v = {9, 9};
cout << sol.plusOne(v) << endl;
}
| 19.607143 | 60 | 0.445355 | sonald |
5073f03840c6e6f2830a3d618d87a21fa85a1282 | 2,501 | cpp | C++ | viewify/src/main/Model/ButtonModel.cpp | ii887522/viewify | 2bd8ef48a63abeaeca73f7f532992ffb6122c76e | [
"MIT"
] | 1 | 2021-07-13T00:56:09.000Z | 2021-07-13T00:56:09.000Z | viewify/src/main/Model/ButtonModel.cpp | ii887522/viewify | 2bd8ef48a63abeaeca73f7f532992ffb6122c76e | [
"MIT"
] | null | null | null | viewify/src/main/Model/ButtonModel.cpp | ii887522/viewify | 2bd8ef48a63abeaeca73f7f532992ffb6122c76e | [
"MIT"
] | null | null | null | // Copyright ii887522
#include "ButtonModel.h"
#include <nitro/nitro.h>
#include <functional>
#include <stdexcept>
#include "../Struct/Rect.h"
#include "../Any/constants.h"
using std::function;
using std::runtime_error;
using ii887522::nitro::AnimationController;
namespace ii887522::viewify {
ButtonModel::Builder::Builder(AnimationController*const animationController, const Rect<int>& rect) : animationController{ animationController }, rect{ rect },
a{ static_cast<unsigned int>(MAX_COLOR.a) }, aDuration{ 0u }, hasSetADuration{ false }, lightnessDuration{ 0u }, hasSetLightnessDuration{ false }, hasSetOnMouseMove{ false },
hasSetOnMouseOver{ false }, hasSetOnMouseOut{ false }, hasSetOnClick{ false } { }
ButtonModel::Builder& ButtonModel::Builder::setOnMouseMove(const function<void()>& value) {
onMouseMove = value;
hasSetOnMouseMove = true;
return *this;
}
ButtonModel::Builder& ButtonModel::Builder::setOnMouseOver(const function<void()>& value) {
onMouseOver = value;
hasSetOnMouseOver = true;
return *this;
}
ButtonModel::Builder& ButtonModel::Builder::setOnMouseOut(const function<void()>& value) {
onMouseOut = value;
hasSetOnMouseOut = true;
return *this;
}
ButtonModel::Builder& ButtonModel::Builder::setOnClick(const function<void()>& value) {
onClick = value;
hasSetOnClick = true;
return *this;
}
ButtonModel ButtonModel::Builder::build() {
if (!hasSetADuration) throw runtime_error{ "ButtonModel alpha duration is required!" };
if (!hasSetLightnessDuration) throw runtime_error{ "ButtonModel lightness duration is required!" };
if (!hasSetOnMouseMove) throw runtime_error{ "ButtonModel onMouseMove is required!" };
if (!hasSetOnMouseOver) throw runtime_error{ "ButtonModel onMouseOver is required!" };
if (!hasSetOnMouseOut) throw runtime_error{ "ButtonModel onMouseOut is required!" };
if (!hasSetOnClick) throw runtime_error{ "ButtonModel onClick is required!" };
return ButtonModel{ *this };
}
ButtonModel::ButtonModel(const Builder& builder) : rect{ builder.rect },
state{ State::INITIAL }, lightness{ AnimatedAny<float>::Builder{ builder.animationController, 1.f }.setDuration(builder.lightnessDuration).build() },
a{ AnimatedAny<int>::Builder{ builder.animationController, static_cast<int>(builder.a) }.setDuration(builder.aDuration).build() }, onMouseMove{ builder.onMouseMove },
onMouseOver{ builder.onMouseOver }, onMouseOut{ builder.onMouseOut }, onClick{ builder.onClick } { }
} // namespace ii887522::viewify
| 41.683333 | 176 | 0.753299 | ii887522 |
50834fe3af291dc4428f09f1282e515a1cbec97e | 9,643 | cpp | C++ | src/StackAllocator.cpp | richsposato/Memwa | 36e6a729b47656db2fc4bb3b9dad9c8d4dd94b2d | [
"MIT"
] | 1 | 2018-12-13T14:07:05.000Z | 2018-12-13T14:07:05.000Z | src/StackAllocator.cpp | richsposato/Memwa | 36e6a729b47656db2fc4bb3b9dad9c8d4dd94b2d | [
"MIT"
] | null | null | null | src/StackAllocator.cpp | richsposato/Memwa | 36e6a729b47656db2fc4bb3b9dad9c8d4dd94b2d | [
"MIT"
] | null | null | null |
#include "StackAllocator.hpp"
#include "LockGuard.hpp"
#include "StackBlock.hpp"
#include "BlockInfo.hpp"
#include "ManagerImpl.hpp"
#include <new>
#include <algorithm>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <cassert>
namespace memwa
{
// ----------------------------------------------------------------------------
StackAllocator::StackAllocator( unsigned int initialBlocks, std::size_t blockSize, std::size_t alignment ) :
Allocator(),
info_( initialBlocks, blockSize, alignment )
{
}
// ----------------------------------------------------------------------------
StackAllocator::~StackAllocator()
{
}
// ----------------------------------------------------------------------------
void StackAllocator::Destroy()
{
info_.Destroy();
}
// ----------------------------------------------------------------------------
void * StackAllocator::Allocate( std::size_t size, const void * hint )
{
if ( info_.blockSize_ < size )
{
throw std::invalid_argument( "Requested allocation size must be smaller than the memory block size." );
}
void * p = info_.Allocate( size, hint );
return p;
}
// ----------------------------------------------------------------------------
#if __cplusplus > 201402L
void * StackAllocator::Allocate( std::size_t size, std::align_val_t alignment, const void * hint )
#else
void * StackAllocator::Allocate( std::size_t size, std::size_t alignment, const void * hint )
#endif
{
if ( alignment > info_.alignment_ )
{
throw std::invalid_argument( "Requested alignment size must be less than or equal to initial alignment size." );
}
void * p = StackAllocator::Allocate( size, hint );
if ( nullptr != p )
{
return p;
}
if ( info_.TrimEmptyBlocks() )
{
p = StackAllocator::Allocate( size, hint );
if ( nullptr != p )
{
return p;
}
}
memwa::impl::ManagerImpl::GetManager()->TrimEmptyBlocks( this );
p = StackAllocator::Allocate( size, hint );
if ( nullptr == p )
{
throw std::bad_alloc();
}
return p;
}
// ----------------------------------------------------------------------------
bool StackAllocator::Release( void * place, std::size_t size )
{
if ( nullptr == place )
{
return false;
}
const bool success = info_.Release( place, size );
return success;
}
// ----------------------------------------------------------------------------
#if __cplusplus > 201402L
bool StackAllocator::Release( void * place, std::size_t size, std::align_val_t alignment )
#else
bool StackAllocator::Release( void * place, std::size_t size, std::size_t alignment )
#endif
{
if ( nullptr == place )
{
return false;
}
if ( alignment > info_.alignment_ )
{
throw std::invalid_argument( "Requested alignment size must be less than or equal to initial alignment size." );
}
const bool success = info_.Release( place, size );
return success;
}
// ----------------------------------------------------------------------------
#if __cplusplus > 201402L
bool StackAllocator::Resize( void * place, std::size_t oldSize, std::size_t newSize, std::align_val_t alignment )
#else
bool StackAllocator::Resize( void * place, std::size_t oldSize, std::size_t newSize, std::size_t alignment )
#endif
{
if ( alignment > info_.alignment_ )
{
throw std::invalid_argument( "Requested alignment size must be less than or equal to initial alignment size." );
}
const bool success = StackAllocator::Resize( place, oldSize, newSize );
return success;
}
// ----------------------------------------------------------------------------
bool StackAllocator::Resize( void * place, std::size_t oldSize, std::size_t newSize )
{
if ( nullptr == place )
{
throw std::invalid_argument( "Unable to resize if pointer is nullptr." );
}
if ( info_.blockSize_ < newSize )
{
throw std::invalid_argument( "Requested allocation size must be smaller than the memory block size." );
}
if ( oldSize == newSize )
{
return true;
}
if ( 0 == newSize )
{
return info_.Release( place, oldSize );
}
const bool success = info_.Resize( place, oldSize, newSize );
return success;
}
// ----------------------------------------------------------------------------
unsigned long long StackAllocator::GetMaxSize( std::size_t objectSize ) const
{
const unsigned long long bytesAvailable = memwa::impl::GetTotalAvailableMemory();
const unsigned long long maxPossibleObjects = bytesAvailable / objectSize;
return maxPossibleObjects;
}
// ----------------------------------------------------------------------------
bool StackAllocator::HasAddress( void * place ) const
{
const bool hasIt = info_.HasAddress( place );
return hasIt;
}
// ----------------------------------------------------------------------------
bool StackAllocator::TrimEmptyBlocks()
{
const bool trimmed = info_.TrimEmptyBlocks();
return trimmed;
}
// ----------------------------------------------------------------------------
bool StackAllocator::IsCorrupt() const
{
assert( nullptr != this );
const bool corrupt = info_.IsCorrupt();
return corrupt;
}
// ----------------------------------------------------------------------------
float StackAllocator::GetFragmentationPercent() const
{
std::size_t blockCount = 0;
std::size_t excessBlocks = 0;
info_.GetBlockCounts( blockCount, excessBlocks );
if ( 0 == blockCount )
{
return 0.0F;
}
const float percent = (float)excessBlocks / (float)blockCount;
return percent;
}
// ----------------------------------------------------------------------------
#ifdef MEMWA_DEBUGGING_ALLOCATORS
void StackAllocator::OutputContents() const
{
std::cout << "This StackAllocator: " << this
<< '\t' << " Fragmentation: " << GetFragmentationPercent()
<< std::endl;
for ( unsigned int ii = 0; ii < alignmentCount; ++ii )
{
StackBlockInfo * info = info_[ ii ];
if ( info != nullptr )
{
info_.OutputContents();
}
}
}
#endif
// ----------------------------------------------------------------------------
ThreadSafeStackAllocator::ThreadSafeStackAllocator( unsigned int initialBlocks, std::size_t blockSize, std::size_t alignment ) :
StackAllocator( initialBlocks, blockSize, alignment ),
mutex_()
{
}
// ----------------------------------------------------------------------------
ThreadSafeStackAllocator::~ThreadSafeStackAllocator()
{
}
// ----------------------------------------------------------------------------
void * ThreadSafeStackAllocator::Allocate( std::size_t size, const void * hint )
{
LockGuard guard( mutex_ );
return StackAllocator::Allocate( size );
}
// ----------------------------------------------------------------------------
#if __cplusplus > 201402L
void * ThreadSafeStackAllocator::Allocate( std::size_t size, std::align_val_t alignment, const void * hint )
#else
void * ThreadSafeStackAllocator::Allocate( std::size_t size, std::size_t alignment, const void * hint )
#endif
{
LockGuard guard( mutex_ );
return StackAllocator::Allocate( size, alignment, hint );
}
// ----------------------------------------------------------------------------
bool ThreadSafeStackAllocator::Release( void * place, std::size_t size )
{
LockGuard guard( mutex_ );
return StackAllocator::Release( place, size );
}
// ----------------------------------------------------------------------------
#if __cplusplus > 201402L
bool ThreadSafeStackAllocator::Release( void * place, std::size_t size, std::align_val_t alignment )
#else
bool ThreadSafeStackAllocator::Release( void * place, std::size_t size, std::size_t alignment )
#endif
{
LockGuard guard( mutex_ );
return StackAllocator::Release( place, size, alignment );
}
// ----------------------------------------------------------------------------
#if __cplusplus > 201402L
bool ThreadSafeStackAllocator::Resize( void * place, std::size_t oldSize, std::size_t newSize, std::align_val_t alignment )
#else
bool ThreadSafeStackAllocator::Resize( void * place, std::size_t oldSize, std::size_t newSize, std::size_t alignment )
#endif
{
LockGuard guard( mutex_ );
return StackAllocator::Resize( place, oldSize, newSize, alignment );
}
// ----------------------------------------------------------------------------
bool ThreadSafeStackAllocator::Resize( void * place, std::size_t oldSize, std::size_t newSize )
{
LockGuard guard( mutex_ );
return StackAllocator::Resize( place, oldSize, newSize );
}
// ----------------------------------------------------------------------------
bool ThreadSafeStackAllocator::HasAddress( void * place ) const
{
LockGuard guard( mutex_ );
return StackAllocator::HasAddress( place );
}
// ----------------------------------------------------------------------------
bool ThreadSafeStackAllocator::TrimEmptyBlocks()
{
LockGuard guard( mutex_ );
return StackAllocator::TrimEmptyBlocks();
}
// ----------------------------------------------------------------------------
bool ThreadSafeStackAllocator::IsCorrupt() const
{
LockGuard guard( mutex_ );
return StackAllocator::IsCorrupt();
}
// ----------------------------------------------------------------------------
float ThreadSafeStackAllocator::GetFragmentationPercent() const
{
LockGuard guard( mutex_ );
return StackAllocator::GetFragmentationPercent();
}
// ----------------------------------------------------------------------------
} // end project namespace
| 28.195906 | 129 | 0.528259 | richsposato |
5087ebfff25e60efe17c4cd15c7250142e204835 | 605 | hpp | C++ | include/GTGE/GUI/GUIEventCodes.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | include/GTGE/GUI/GUIEventCodes.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | include/GTGE/GUI/GUIEventCodes.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE file.
#ifndef GT_GUIGameEventCodes
#define GT_GUIGameEventCodes
namespace GT
{
enum GUIEventCode
{
GUIEventCode_Unknown = 0,
GUIEventCode_Null = 0,
GUIEventCode_OnSize,
GUIEventCode_OnMove,
GUIEventCode_OnKeyPressed,
GUIEventCode_OnKeyDown,
GUIEventCode_OnKeyUp,
GUIEventCode_OnMouseMove,
GUIEventCode_OnMouseWheel,
GUIEventCode_OnMouseButtonDown,
GUIEventCode_OnMouseButtonUp,
GUIEventCode_OnMouseButtonDoubleClick,
};
}
#endif | 23.269231 | 67 | 0.695868 | mackron |
508cb54975ad33a85f3058aef14ee81768e2fb9b | 864 | cpp | C++ | Engine/Graphics/Color.cpp | artur-kink/nhns | bc1ccef4e4a9cba9047051d73202ee2b1482066f | [
"Apache-2.0"
] | null | null | null | Engine/Graphics/Color.cpp | artur-kink/nhns | bc1ccef4e4a9cba9047051d73202ee2b1482066f | [
"Apache-2.0"
] | null | null | null | Engine/Graphics/Color.cpp | artur-kink/nhns | bc1ccef4e4a9cba9047051d73202ee2b1482066f | [
"Apache-2.0"
] | null | null | null | #include "Color.hpp"
Color Color::Black = Color(0.0f, 0.0f, 0.0f, 1.0f);
Color Color::Blue = Color(0.0f, 0.0f, 1.0f, 1.0f);
Color Color::Green = Color(0.0f, 1.0f, 0.0f, 1.0f);
Color Color::Red = Color(1.0f, 0.0f, 0.0f, 1.0f);
Color Color::White = Color(1.0f, 1.0f, 1.0f, 1.0f);
Color Color::Transparent = Color(1.0f, 1.0f, 1.0f, 0.0f);
/**
* Create default black color.
*/
Color::Color(){
Color(0, 0, 0, 1);
}
/**
* Create color with given values, no transparency.
*/
Color::Color(float r, float g, float b){
Color(r, g, b, 1.0f);
}
/**
* Create color with all values supplied.
*/
Color::Color(float r, float g, float b, float a){
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
#ifdef _PC_
/**
* Color to SFML::Color conversion.
*/
Color::operator sf::Color(){
return sf::Color(255*r, 255*g, 255*b, 255*a);
}
#endif | 21.073171 | 57 | 0.590278 | artur-kink |
508d00969a74f56aa3d593575309147b53c19f9c | 8,491 | cpp | C++ | src/lapel_line.cpp | cjhdev/lapel | 9fd86ba900ff3f83154e8ebd1cb8634e58c3ca75 | [
"MIT"
] | null | null | null | src/lapel_line.cpp | cjhdev/lapel | 9fd86ba900ff3f83154e8ebd1cb8634e58c3ca75 | [
"MIT"
] | null | null | null | src/lapel_line.cpp | cjhdev/lapel | 9fd86ba900ff3f83154e8ebd1cb8634e58c3ca75 | [
"MIT"
] | null | null | null | /* Copyright 2022 Cameron Harper
*
* */
#include "lapel_line.h"
#include "lapel_tty.h"
#include "lapel_control_codes.h"
#include "lapel_debug.h"
#include "lapel_decoder.h"
#include "lapel_encoder.h"
#include <string.h>
using namespace Lapel;
static const char Tag[] = "Line";
Line::Line(size_t max, TTY &tty)
:
state(STATE_IDLE),
tty(tty),
cursor(0),
display_cursor(0),
end(0),
max((max > 0) ? (max-1) : 0),
cols(80),
prompt(nullptr),
prompt_size(0),
mode(MODE_SESSION)
{
buffer = new char[max];
clear_buffer();
}
Line::~Line()
{
delete buffer;
}
void
Line::refresh()
{
do_full_refresh();
}
Line::Event
Line::process(const DecoderSymbol &symbol)
{
event = EVENT_NONE;
State next_state;
do{
process_pending = false;
switch(state){
default:
case STATE_IDLE:
next_state = process_idle(symbol);
break;
case STATE_TAB:
next_state = process_tab(symbol);
break;
}
state = next_state;
}
while(process_pending);
return event;
}
Line::State
Line::process_idle(const DecoderSymbol &symbol)
{
State retval = state;
switch(symbol.type){
default:
break;
case DecoderSymbol::TYPE_CHAR:
do_insert(symbol.c);
break;
case DecoderSymbol::TYPE_SOH:
do_home();
break;
case DecoderSymbol::TYPE_STX:
do_back();
break;
case DecoderSymbol::TYPE_ENQ:
do_end();
break;
case DecoderSymbol::TYPE_ACK:
do_forward();
break;
case DecoderSymbol::TYPE_BS:
do_backspace();
break;
case DecoderSymbol::TYPE_VT:
do_delete_from_cursor();
break;
case DecoderSymbol::TYPE_FF:
this->event = EVENT_CLEAR;
break;
case DecoderSymbol::TYPE_CR:
this->event = EVENT_EXEC;
break;
case DecoderSymbol::TYPE_SO:
this->event = EVENT_HISTORY_DOWN;
break;
case DecoderSymbol::TYPE_DLE:
this->event = EVENT_HISTORY_UP;
break;
case DecoderSymbol::TYPE_NAK:
do_delete_line();
break;
case DecoderSymbol::TYPE_ETB:
do_delete_prev_word();
break;
case DecoderSymbol::TYPE_DEL:
do_backspace();
break;
case DecoderSymbol::TYPE_UP:
this->event = EVENT_HISTORY_UP;
break;
case DecoderSymbol::TYPE_DOWN:
this->event = EVENT_HISTORY_DOWN;
break;
case DecoderSymbol::TYPE_LEFT:
do_back();
break;
case DecoderSymbol::TYPE_RIGHT:
do_forward();
break;
case DecoderSymbol::TYPE_PAGE_UP:
break;
case DecoderSymbol::TYPE_PAGE_DOWN:
break;
case DecoderSymbol::TYPE_HOME:
do_home();
break;
case DecoderSymbol::TYPE_END:
do_end();
break;
case DecoderSymbol::TYPE_HT:
this->event = EVENT_COMPLETE_1;
retval = STATE_TAB;
break;
case DecoderSymbol::TYPE_CPR:
break;
}
return retval;
}
Line::State
Line::process_tab(const DecoderSymbol &symbol)
{
State retval = state;
switch(symbol.type){
default:
retval = STATE_IDLE;
process_pending = true;
break;
case DecoderSymbol::TYPE_HT:
this->event = EVENT_COMPLETE_2;
break;
}
return retval;
}
void
Line::do_backspace()
{
if(cursor > 0){
(void)memmove(&buffer[cursor-1], &buffer[cursor], end - cursor);
cursor--;
end--;
buffer[end] = 0;
do_refresh_from_cursor();
}
}
void
Line::do_delete()
{
if((end > 0) && (cursor < end)){
(void)memmove(&buffer[cursor], &buffer[cursor+1], end - (cursor + 1));
end--;
do_refresh_from_cursor();
}
}
void
Line::do_home()
{
cursor = 0;
do_refresh_from_cursor();
}
void
Line::do_end()
{
cursor = end;
do_refresh_from_cursor();
}
void
Line::do_back()
{
if(cursor > 0){
cursor--;
do_refresh_from_cursor();
}
}
void
Line::do_forward()
{
if(cursor != end){
cursor++;
do_refresh_from_cursor();
}
}
void
Line::clear_buffer()
{
(void)memset(buffer, 0, max+1);
end = 0;
cursor = 0;
}
void
Line::clear_buffer_from_end()
{
(void)memset(&buffer[end], 0, max-end);
}
bool
Line::character_is_allowed(char c)
{
bool retval;
switch(mode){
default:
case MODE_SESSION:
retval = true;
break;
case MODE_USERNAME:
retval =
(c >= '0' && c <= '9')
||
(c >= 'a' && c <= 'z')
||
(c >= 'A' && c <= 'Z');
break;
case MODE_PASSWORD:
retval = (c != ' ');
break;
}
return retval;
}
void
Line::do_insert(char c)
{
if(character_is_allowed(c)){
if(end != max){
if(cursor != end){
(void)memmove(&buffer[cursor+1], &buffer[cursor], end - cursor);
}
end++;
buffer[cursor] = c;
buffer[end] = 0;
cursor++;
do_refresh_from_cursor();
}
}
}
void
Line::do_delete_from_cursor()
{
end = cursor;
do_refresh_from_cursor();
}
void
Line::do_delete_prev_word()
{
}
void
Line::do_delete_line()
{
cursor = 0;
end = 0;
do_refresh_from_cursor();
}
void
Line::set_size(uint32_t cols)
{
this->cols = cols;
}
uint32_t
Line::get_size()
{
return cols;
}
void
Line::clear()
{
clear_buffer();
}
void
Line::do_refresh_from_cursor()
{
do_refresh(true);
}
void
Line::do_full_refresh()
{
do_refresh(false);
}
void
Line::do_refresh(bool from_cursor)
{
size_t i = 0;
Decoder decoder;
Encoder encoder(tty);
DecoderSymbol symbol;
if(from_cursor){
if(get_cursor_line() < get_display_line()){
encoder.put_cuu();
i = get_cursor_line() * cols;
}
else{
i = get_display_line() * cols;
}
}
else{
encoder.put_cuu(get_display_line());
}
tty.put_char(CR);
encoder.put_ed_right();
for(size_t n = i, m = 0; get_raw_char(m) > 0; m++){
char c = get_raw_char(m);
if(decoder.process(c, symbol) && (symbol.type == DecoderSymbol::TYPE_CHAR)){
if(n > 0){
n--;
}
else{
tty.put_char(c);
i++;
if((i % cols) == 0){
tty.put_char(CR);
tty.put_char(LF);
}
}
}
else if(n == 0){
tty.put_char(c);
}
}
encoder.put_cuu(get_last_line() - get_cursor_line());
tty.put_char(CR);
encoder.put_cuf(get_cursor() % cols);
tty.flush();
display_cursor = cursor;
}
void
Line::set_prompt(const char *prompt)
{
this->prompt = prompt;
prompt_size = (prompt != nullptr) ? strlen(prompt) : 0;
}
size_t
Line::get_prompt_size()
{
size_t retval = 0;
Decoder decoder;
DecoderSymbol symbol;
for(size_t i=0; prompt && (i < strlen(prompt)); i++){
if(decoder.process(prompt[i], symbol) && (symbol.type = DecoderSymbol::TYPE_CHAR)){
retval++;
}
}
return retval;
}
size_t
Line::get_cursor()
{
return get_prompt_size() + cursor;
}
size_t
Line::get_line_size()
{
return get_prompt_size() + end;
}
size_t
Line::get_last_line()
{
return get_line_size() / cols;
}
size_t
Line::get_cursor_line()
{
return (get_prompt_size() + cursor) / cols;
}
size_t
Line::get_display_line()
{
return (get_prompt_size() + display_cursor) / cols;
}
char
Line::get_raw_char(size_t offset)
{
char retval;
if(offset < prompt_size){
retval = prompt[offset];
}
else if(offset < (prompt_size + end)){
retval = (mode == MODE_PASSWORD) ? '*' : buffer[offset - prompt_size];
}
else{
retval = 0;
}
return retval;
}
void
Line::set_mode(Mode mode)
{
this->mode = mode;
}
Line::Mode
Line::get_mode()
{
return mode;
}
void
Line::read_buffer(char *buffer, size_t max)
{
strncpy(buffer, this->buffer, max);
}
void
Line::write_buffer(const char *buffer)
{
strncpy(this->buffer, buffer, max);
end = (strlen(buffer) > max) ? max : strlen(buffer);
this->buffer[end] = 0;
cursor = end;
clear_buffer_from_end();
}
| 15.841418 | 91 | 0.556354 | cjhdev |
5091216d51a496241faba50772bcf2bc63090bd8 | 1,710 | cpp | C++ | src/Set.cpp | leiradel/CheevosTool | a7d0145c7617caf63d42b134a831707f10c1d27b | [
"MIT"
] | null | null | null | src/Set.cpp | leiradel/CheevosTool | a7d0145c7617caf63d42b134a831707f10c1d27b | [
"MIT"
] | null | null | null | src/Set.cpp | leiradel/CheevosTool | a7d0145c7617caf63d42b134a831707f10c1d27b | [
"MIT"
] | null | null | null | #include "Set.h"
#include <algorithm>
Set::Set(std::vector<uint32_t>&& elements) : _elements(std::move(elements)) {
std::sort(_elements.begin(), _elements.end(), [](uint32_t const& a, uint32_t const& b) -> bool {
return a < b;
});
}
Set::Set(Set&& other) : _elements(std::move(other._elements)) {}
bool Set::contains(uint32_t element) const
{
return std::binary_search(_elements.begin(), _elements.end(), element);
}
Set Set::union_(const Set& other)
{
Set result;
result._elements.reserve(_elements.size() + other._elements.size());
std::set_union(_elements.begin(),
_elements.end(),
other._elements.begin(),
other._elements.end(),
std::inserter(result._elements, result._elements.begin()));
result._elements.shrink_to_fit();
return result;
}
Set Set::intersection(const Set& other)
{
Set result;
result._elements.reserve(std::min(_elements.size(), other._elements.size()));
std::set_intersection(_elements.begin(),
_elements.end(),
other._elements.begin(),
other._elements.end(),
std::inserter(result._elements, result._elements.begin()));
result._elements.shrink_to_fit();
return result;
}
Set Set::subtraction(const Set& other)
{
Set result;
result._elements.reserve(_elements.size());
std::set_difference(_elements.begin(),
_elements.end(),
other._elements.begin(),
other._elements.end(),
std::inserter(result._elements, result._elements.begin()));
result._elements.shrink_to_fit();
return result;
}
| 27.580645 | 98 | 0.608772 | leiradel |
5099cf0ca7a29075bb45006d9fe89eff33fa757f | 1,133 | cpp | C++ | RPC/Server/GpApiTypeDetectorJson.cpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | RPC/Server/GpApiTypeDetectorJson.cpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | RPC/Server/GpApiTypeDetectorJson.cpp | ITBear/GpApi | fcf114acf28b37682919c9a634d8a2ae3860409b | [
"Apache-2.0"
] | null | null | null | #include "GpApiTypeDetectorJson.hpp"
#include "../../../GpJson/GpJsonToStruct.hpp"
namespace GPlatform::API::RPC {
GpApiTypeDetectorJson::GpApiTypeDetectorJson
(
const GpApiMethodsManager& aApiManager,
const GpBytesArray& aData
) noexcept:
iApiManager(aApiManager),
iData(aData)
{
}
GpApiTypeDetectorJson::~GpApiTypeDetectorJson (void) noexcept
{
}
const GpTypeStructInfo& GpApiTypeDetectorJson::DetectTypeInfo (void) const
{
rapidjson::Document jsonDOM;
rapidjson::Document::ConstObject jsonObject = GpJsonToStruct::SParseJsonDom(iData, jsonDOM);
rapidjson::Document::ConstMemberIterator mit = jsonObject.FindMember("method");
THROW_GPE_COND
(
mit != jsonObject.MemberEnd(),
"Json member 'method' was not found"_sv
);
const auto& mitVal = mit->value;
std::string_view methodName = {mitVal.GetString(), mitVal.GetStringLength()};
GpApiMethod::SP method = iApiManager.Find(methodName);
return method->RqTypeInfo();
}
}//namespace GPlatform::API::RPC
| 28.325 | 109 | 0.660194 | ITBear |
509cc14c7d44ded4d84760fb474d27f71680359e | 3,314 | hpp | C++ | include/codegen/include/GlobalNamespace/BloomPrePassBGLight.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/BloomPrePassBGLight.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/BloomPrePassBGLight.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: UnityEngine.Color
#include "UnityEngine/Color.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Collections::Generic
namespace System::Collections::Generic {
// Forward declaring type: List`1<T>
template<typename T>
class List_1;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: BloomPrePassBGLight
class BloomPrePassBGLight : public UnityEngine::MonoBehaviour {
public:
// private System.Single _intensity
// Offset: 0x18
float intensity;
// private System.Single _minAlpha
// Offset: 0x1C
float minAlpha;
// private System.Single _grayscaleFactor
// Offset: 0x20
float grayscaleFactor;
// private UnityEngine.Color _color
// Offset: 0x24
UnityEngine::Color color;
// Get static field: static private System.Collections.Generic.List`1<BloomPrePassBGLight> _bloomBGLightList
static System::Collections::Generic::List_1<GlobalNamespace::BloomPrePassBGLight*>* _get__bloomBGLightList();
// Set static field: static private System.Collections.Generic.List`1<BloomPrePassBGLight> _bloomBGLightList
static void _set__bloomBGLightList(System::Collections::Generic::List_1<GlobalNamespace::BloomPrePassBGLight*>* value);
// static public System.Collections.Generic.List`1<BloomPrePassBGLight> get_bloomBGLightList()
// Offset: 0x1826234
static System::Collections::Generic::List_1<GlobalNamespace::BloomPrePassBGLight*>* get_bloomBGLightList();
// public UnityEngine.Color get_color()
// Offset: 0x182629C
UnityEngine::Color get_color();
// public System.Void set_color(UnityEngine.Color value)
// Offset: 0x18262A8
void set_color(UnityEngine::Color value);
// public UnityEngine.Color get_bgColor()
// Offset: 0x18262B4
UnityEngine::Color get_bgColor();
// static private System.Void NoDomainReloadInit()
// Offset: 0x1826340
static void NoDomainReloadInit();
// protected System.Void OnEnable()
// Offset: 0x18263D0
void OnEnable();
// protected System.Void OnDisable()
// Offset: 0x1826454
void OnDisable();
// public System.Void .ctor()
// Offset: 0x18264D8
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
static BloomPrePassBGLight* New_ctor();
// static private System.Void .cctor()
// Offset: 0x18264F4
// Implemented from: UnityEngine.Object
// Base method: System.Void Object::.cctor()
static void _cctor();
}; // BloomPrePassBGLight
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::BloomPrePassBGLight*, "", "BloomPrePassBGLight");
#pragma pack(pop)
| 40.414634 | 123 | 0.714243 | Futuremappermydud |
509d293d85bb97a6433e9b07e9656d4649d17fac | 1,194 | cpp | C++ | HemeraCore/hemerafakehardwareidoperation.cpp | rbino/astarte-device-sdk-qt5 | a3c3feea8f77e6e52fd7bac0c9cdaeebd7444291 | [
"Apache-2.0"
] | 4 | 2018-12-14T00:22:07.000Z | 2021-09-29T08:13:26.000Z | HemeraCore/hemerafakehardwareidoperation.cpp | rbino/astarte-device-sdk-qt5 | a3c3feea8f77e6e52fd7bac0c9cdaeebd7444291 | [
"Apache-2.0"
] | 7 | 2020-11-05T11:37:25.000Z | 2022-03-01T16:39:40.000Z | HemeraCore/hemerafakehardwareidoperation.cpp | rbino/astarte-device-sdk-qt5 | a3c3feea8f77e6e52fd7bac0c9cdaeebd7444291 | [
"Apache-2.0"
] | 9 | 2020-01-22T14:15:15.000Z | 2022-02-23T10:52:59.000Z | /*
* This file is part of Astarte.
*
* Copyright 2017 Ispirata Srl
*
* 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 "hemerafakehardwareidoperation.h"
namespace Hemera {
QByteArray FakeHardwareIDOperation::s_fakeHardwareID = QByteArray();
FakeHardwareIDOperation::FakeHardwareIDOperation(QObject *parent)
: ByteArrayOperation(parent)
{
}
FakeHardwareIDOperation::~FakeHardwareIDOperation()
{
}
QByteArray FakeHardwareIDOperation::result() const
{
return s_fakeHardwareID;
}
void FakeHardwareIDOperation::setHardwareId(const QByteArray &hardwareId)
{
s_fakeHardwareID = hardwareId;
}
void FakeHardwareIDOperation::startImpl()
{
setFinished();
}
}
| 23.88 | 75 | 0.759631 | rbino |
509fa3a09d73a48b5f393abf9fd2687ce909a8d5 | 4,516 | cpp | C++ | frameworks/input/plugins/rules/dmzInputPluginChannelRules.cpp | shillcock/dmz | 02174b45089e12cd7f0840d5259a00403cd1ccff | [
"MIT"
] | 2 | 2015-11-05T03:03:40.000Z | 2016-02-03T21:50:40.000Z | frameworks/input/plugins/rules/dmzInputPluginChannelRules.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | frameworks/input/plugins/rules/dmzInputPluginChannelRules.cpp | dmzgroup/dmz | fc2d9ddcb04ed71f4106b8d33539529807b3dea6 | [
"MIT"
] | null | null | null | #include <dmzInputEventMasks.h>
#include <dmzInputModule.h>
#include "dmzInputPluginChannelRules.h"
#include <dmzRuntimeConfigToTypesBase.h>
#include <dmzRuntimePluginFactoryLinkSymbol.h>
#include <dmzRuntimePluginInfo.h>
#include <dmzRuntimeConfig.h>
#include <dmzTypesDeleteListTemplate.h>
/*!
\class dmz::InputPluginChannelRules
\ingroup Input
\brief Keeps only one channel in a list active at a time.
\details
If a channel in the list becomes active, every other channel in the list that was active will be deactivated. This ensures only one channel in the list is ever active. If all channels in the list become deactivated, the default channel will be activated.
\code
<scope>
<channel name="String" default="Boolean"/>
<channel name="String" default="Boolean"/>
<!-- ... -->
<channel name="String" default="Boolean"/>
</scope>
\endcode
- \b channel.name A string containing the channels name
- \b channel.default A boolean indicated if the channel is the default in the list. The last channel set as default will be the default channel if multiple channels are set to true.
*/
//! \cond
dmz::InputPluginChannelRules::InputPluginChannelRules (
const PluginInfo &Info,
Config &local) :
Plugin (Info),
InputObserverUtil (Info, local),
_log (Info),
_active (0),
_channelList (0),
_defaultChannel (0),
_input (0) {
_init (local);
}
dmz::InputPluginChannelRules::~InputPluginChannelRules () {
delete_list (_channelList);
}
// Plugin Interface
void
dmz::InputPluginChannelRules::update_plugin_state (
const PluginStateEnum State,
const UInt32 Level) {
if (State == PluginStateInit) {
}
else if (State == PluginStateStart) {
}
else if (State == PluginStateStop) {
}
else if (State == PluginStateShutdown) {
}
}
void
dmz::InputPluginChannelRules::discover_plugin (
const PluginDiscoverEnum Mode,
const Plugin *PluginPtr) {
if (Mode == PluginDiscoverAdd) {
if (!_input) {
_input = InputModule::cast (PluginPtr, _inputModuleName);
if (_input) {
ChannelStruct *current (_channelList);
while (current) {
_input->create_channel (current->Channel);
_input->register_input_observer (
current->Channel,
InputEventChannelStateMask,
*this);
current = current->next;
}
_input->set_channel_state (_defaultChannel, True);
}
}
}
else if (Mode == PluginDiscoverRemove) {
if (_input && (_input == InputModule::cast (PluginPtr, _inputModuleName))) {
_input = 0;
}
}
}
// Input Observer Interface
void
dmz::InputPluginChannelRules::update_channel_state (
const Handle Channel,
const Boolean State) {
_active += (State ? 1 : -1);
if (_active == 0 && _defaultChannel && _input) {
_input->set_channel_state (_defaultChannel, True);
}
else if (_channelList && _input && State) {
ChannelStruct *current (_channelList);
while (current) {
if (current->Channel != Channel) {
_input->set_channel_state (current->Channel, False);
}
current = current->next;
}
}
}
// InputPluginChannelRules Interface
void
dmz::InputPluginChannelRules::_init (Config &local) {
Definitions defs (get_plugin_runtime_context (), &_log);
_inputModuleName = config_to_string ("module.input.name", local);
Config channelList;
if (local.lookup_all_config ("channel", channelList)) {
ConfigIterator it;
Config cd;
ChannelStruct *current (0);
while (channelList.get_next_config (it, cd)) {
const String Name (config_to_string ("name", cd));
if (Name) {
ChannelStruct *next (new ChannelStruct (defs.create_named_handle (Name)));
if (next) {
if (config_to_boolean ("default", cd, False)) {
_defaultChannel = next->Channel;
}
if (current) { current->next = next; current = next; }
else { _channelList = current = next; }
}
}
}
}
}
//! \endcond
extern "C" {
DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin *
create_dmzInputPluginChannelRules (
const dmz::PluginInfo &Info,
dmz::Config &local,
dmz::Config &global) {
return new dmz::InputPluginChannelRules (Info, local);
}
};
| 22.808081 | 254 | 0.633747 | shillcock |
50a26275442c38aff5d3dc4e516020ae7cc4fa3d | 236 | cpp | C++ | ThirdsEngine/main.cpp | OlisProgramming/ThirdsEngine | 0f44ae9e96f47d69222a57f43c1744cd89995e44 | [
"Apache-2.0"
] | null | null | null | ThirdsEngine/main.cpp | OlisProgramming/ThirdsEngine | 0f44ae9e96f47d69222a57f43c1744cd89995e44 | [
"Apache-2.0"
] | 2 | 2016-09-29T17:26:24.000Z | 2016-10-02T08:37:57.000Z | ThirdsEngine/main.cpp | OlisProgramming/ThirdsEngine | 0f44ae9e96f47d69222a57f43c1744cd89995e44 | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include "GameManager.h"
#undef main
using namespace te;
int main() {
// GameManager does nothing until run is called.
GameManager manager;
manager.setWindow(new Window(800, 600));
manager.run();
return 0;
} | 14.75 | 49 | 0.711864 | OlisProgramming |
50a9fac1125595ddf868bd83734e7d9489c2eb0d | 5,616 | cpp | C++ | SourceCode/balance_flows_at_reservoirs.cpp | ChristinaB/Topnet-WM | abfed11a3792a43ad23000cbf3b2cb9161f19218 | [
"MIT"
] | null | null | null | SourceCode/balance_flows_at_reservoirs.cpp | ChristinaB/Topnet-WM | abfed11a3792a43ad23000cbf3b2cb9161f19218 | [
"MIT"
] | 17 | 2018-03-19T17:26:04.000Z | 2019-06-06T00:15:35.000Z | SourceCode/balance_flows_at_reservoirs.cpp | ChristinaB/Topnet-WM | abfed11a3792a43ad23000cbf3b2cb9161f19218 | [
"MIT"
] | 2 | 2018-03-25T01:55:20.000Z | 2019-05-09T22:12:50.000Z | /* Copyright 2017 Lambert Rubash
This file is part of TopNetCpp, a translation and enhancement of
Fortran TopNet.
TopNetCpp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
TopNetCpp 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 TopNetCpp. If not, see <http://www.gnu.org/licenses/>.
*/
#include "topnet.hh"
using namespace constant_definitions;
using namespace input_structures;
using namespace other_structures;
using namespace std;
int remove_element(valarray<int> &j_out, int &nj_out, const int iFound);
int BalanceFlowsAtReservoirs(const int NumNode, const int NumLink, const int NumUser, const int NumReservoir, vector<double> &ReservoirNetStorage)
{
vector<int> j_in(1000);
int m, n, isn, nj_in, nj_out, i, k, j_release, j_found, iuser, jret;
int nfound;// *ifound;
vector<int> ifound;
double flow_in, flow_taken, flow_released;
#if TRACE
static int ncalls = 0;
double tm0 = static_cast<double>(clock())/static_cast<double>(CLOCKS_PER_SEC);
string save_caller = caller;
if (ncalls < MAX_TRACE) {
traceFile << setw(30) << caller << " -> BalanceFlowsAtReservoirs(" << ncalls << ")" << std::endl;
}
caller = "BalanceFlowsAtReservoirs";
#endif
//Calculate storage in all reservoir nodes, and if there is overflow, update
//flows in outflow link as required
for (i = 1; i <= NumReservoir; i++) {
// call find2(Node%Type,ReservoirNodeCode,Node%SelfID,i,NumNode);
// isn=ifound(1) !problem if nfound<>1
// call find1(Link%DSNode,isn,NumLink); allocate (j_in(nfound));
// j_in=ifound; nj_in=nfound
// call find1(Link%USNode,isn,NumLink); allocate (j_out(nfound));
// j_out=ifound; nj_out=nfound
isn = Reservoir[i-1].isn;
nj_in = Reservoir[i-1].n_in;
for (n = 0; n < nj_in; n++) {
j_in[n] = Reservoir[i-1].ifound_in[n];
}
nj_out = Reservoir[i-1].n_taken;
valarray<int> j_out(nj_out);
for (n = 0; n < nj_out; n++) {
j_out[n] = Reservoir[i-1].ifound_taken[n];
}
//find the link going to the user node of Type=ReservoirReleaseUseCode that takes reservoir overflows from this reservoir
ifound.assign(NumUser*nj_out,0); // initialized to 0
if (Reservoir[i-1].InOffStream == InStreamReservoirCode) {
// find1()
nfound = 0; //none found
for (n = 0; n < NumUser; n++) {
for (m = 0; m < nj_out; m++) {
if (User[Node[Link[j_out[m]-1].DSNode-1].SelfID-1].UsersType == InStreamReservoirReleaseUseCode) {
nfound++;
ifound[nfound-1] = n+1;
}
}
}
} else if (Reservoir[i-1].InOffStream == OffStreamReservoirCode) {
// find1()
nfound = 0; //none found
for (n = 0; n < NumUser; n++) {
for (m = 0; m < nj_out; m++) {
if (User[Node[Link[j_out[m]-1].DSNode-1].SelfID-1].UsersType == OffStreamReservoirReleaseUseCode) {
nfound++;
ifound[nfound-1] = n+1;
}
}
}
}
j_release = j_out[ifound[0]-1]; //problem if nfound<>1
// find1()
nfound = 0; //none found
ifound.assign(nj_out,0); // initialized to 0
for (n = 0; n < nj_out; n++) {
if (j_out[n] == j_release) {
nfound++;
ifound[nfound-1] = n+1;
}
}
j_found = ifound[0]; //problem if nfound<>1
remove_element(j_out, nj_out, j_found);
flow_in = 0.0;
for (k = 1; k <= nj_in; k++) {
flow_in += Link[j_in[k-1]-1].Flow;
}
flow_taken = 0.0;
for (k = 1; k <= nj_out; k++) {
flow_taken += Link[j_out[k-1]-1].Flow;
}
flow_released = Link[j_release-1].Flow;
Node[isn-1].Store = Node[isn-1].StoreOld + flow_in - flow_taken - flow_released;
if (Node[isn-1].Store > Reservoir[i-1].StoreMax) {
Link[j_release-1].Flow += Node[isn-1].Store-Reservoir[i-1].StoreMax;
Node[isn-1].Store = Reservoir[i-1].StoreMax;
iuser = Link[j_release-1].DSNode; // This is the user identifier of the dummy user that effects reservoir release
// Need to find the return flow link associated with this user so that the corresponding return flow can also be
// adjusted by the additional flow in this link.
// find2()
nfound = 0; //none found
ifound.assign(NumLink,0); // initialized to 0
for (n = 0; n < NumLink; n++) {
if (Link[n].LinkCode == ReturnFlowLinkCode && Link[n].USNode == iuser) {
nfound++;
ifound[nfound-1] = n+1;
}
}
jret = ifound[0]; //problem if nfound<>1
Link[jret-1].Flow += Link[j_release-1].Flow; //no consumption at this usernode
// Logically the line above would be better implemented by
// Link(jret)%Flow=Link(j_release)%Flow
// Did not do this because DGT did not want to change code and Ross says will not change result.
}
ReservoirNetStorage[i-1] = Node[isn-1].Store - Reservoir[i-1].StoreMin;
}
#if TRACE
double tm1 = static_cast<double>(clock())/static_cast<double>(CLOCKS_PER_SEC);
caller = save_caller;
if (ncalls < MAX_TRACE) {
traceFile << setw(30) << caller << " <- Leaving BalanceFlowsAtReservoirs(" << ncalls << ") ";
traceFile << tm1 - tm0 << " seconds\n\n";
}
ncalls++;
#endif
return 0;
}
int remove_element(valarray<int> &j_out, int &nj_out, const int iFound)
{
int i;
for (i = iFound; i <= nj_out-1; i++) {
j_out[i-1] = j_out[i];
}
nj_out--;
return 0;
}
| 33.428571 | 146 | 0.657942 | ChristinaB |
27063abb862f1822da9e286bd30393dd1b462bfd | 935 | cpp | C++ | base/src/System/Net/Sockets/UdpClient.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 7 | 2019-07-11T02:05:32.000Z | 2020-11-01T18:57:51.000Z | base/src/System/Net/Sockets/UdpClient.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 3 | 2019-02-26T15:59:03.000Z | 2019-06-04T10:46:07.000Z | base/src/System/Net/Sockets/UdpClient.cpp | djdron/gamesparks-cpp-base | 00b8af5dc2b58b7954cfa5d99c5ea7ded7115af8 | [
"Apache-2.0"
] | 6 | 2019-03-18T19:14:04.000Z | 2019-06-25T11:55:44.000Z | #include "./UdpClient.hpp"
//#include <mbedtls/net.h>
namespace System { namespace Net { namespace Sockets {
UdpClient::UdpClient()
:client(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp)
{
}
void UdpClient::BeginConnect(
const IPEndPoint& endpoint,
const AsyncCallback& requestCallback
)
{
return client.BeginConnect(endpoint, requestCallback);
}
/*void UdpClient::Connect(const IPEndPoint &endpoint) {
client.Connect(endpoint);
}*/
void UdpClient::EnableBroadcast(bool /*value*/) {
//TODO: check if not needed
}
void UdpClient::ExclusiveAddressUse(bool /*value*/) {
//TODO: check if not needed
}
void UdpClient::MulticastLoopback(bool /*value*/) {
//TODO: check if not needed
}
Socket &UdpClient::Client() {
return client;
}
Failable<void> UdpClient::Send(const Bytes &dgram, int bytes) {
return client.Send(dgram, 0, bytes);
}
}}} /* namespace System.Net.Sockets */
| 20.777778 | 74 | 0.706952 | djdron |
270734a3c5dc0b702052928f4941484a1c9e6262 | 575 | hpp | C++ | include/imu/MadgwickFilter.hpp | medium-endian/multipid | 41ab0c810de04fc48923edf31e3c971826abbaf3 | [
"MIT"
] | 15 | 2018-06-25T23:06:57.000Z | 2022-03-31T06:00:35.000Z | include/imu/MadgwickFilter.hpp | medium-endian/multipid | 41ab0c810de04fc48923edf31e3c971826abbaf3 | [
"MIT"
] | 3 | 2017-11-20T23:00:03.000Z | 2018-01-19T16:22:39.000Z | include/imu/MadgwickFilter.hpp | medium-endian/multipid | 41ab0c810de04fc48923edf31e3c971826abbaf3 | [
"MIT"
] | 1 | 2020-08-24T13:24:39.000Z | 2020-08-24T13:24:39.000Z | #ifndef MADGWICK_FILTER_H
#define MADGWICK_FILTER_H
#include <math.h>
#include "SoftwareIMU.hpp"
#include "axis.hpp"
class MadgwickFilter : public SoftwareIMU {
private:
float beta = 0.0f;
float zeta = 0.0f;
/* integration interval */
float deltat = 0.0f;
float sum = 0.0f;
axis_t angular_rates;
axis_t acceleration;
axis_t magnetization;
public:
MadgwickFilter(RawIMU& rawIMU, float gyroMeasError, float gyroMeasDrift);
void update(float q[4]);
};
#endif // MADGWICK_FILTER_H
| 18.548387 | 81 | 0.638261 | medium-endian |
270996af510dc2fd9ed3b1ec0b02331f0e9687c1 | 2,379 | cpp | C++ | tests/test_client_examplecom.cpp | lpcvoid/cpp-net-lib | e9961392b847cb39143d6b08dd2406361aff027c | [
"MIT"
] | 10 | 2021-11-25T09:53:30.000Z | 2022-03-04T07:21:38.000Z | tests/test_client_examplecom.cpp | lpcvoid/cpp-net-lib | e9961392b847cb39143d6b08dd2406361aff027c | [
"MIT"
] | 1 | 2021-11-24T10:49:21.000Z | 2021-11-24T10:49:21.000Z | tests/test_client_examplecom.cpp | lpcvoid/cpp-net-lib | e9961392b847cb39143d6b08dd2406361aff027c | [
"MIT"
] | 2 | 2021-11-27T02:57:18.000Z | 2021-11-28T08:55:14.000Z | #include "../doctest/doctest/doctest.h"
#include "../src/netlib.hpp"
static const std::string basic_get = R"(GET / HTTP/1.1\r\nHost: example.com\r\n\r\n)";
using namespace std::chrono_literals;
TEST_CASE("Client example.com async")
{
netlib::client client;
auto connect_future =
client.connect_async("example.com", static_cast<uint16_t>(80), netlib::AddressFamily::IPv4, netlib::AddressProtocol::TCP, 10000ms);
while (connect_future.wait_for(10ms) != std::future_status::ready) {
}
CHECK_FALSE(connect_future.get().value());
auto send_future = client.send_async({basic_get.begin(), basic_get.end()}, 1000ms);
while (send_future.wait_for(10ms) != std::future_status::ready) {
}
auto send_result = send_future.get();
CHECK_FALSE(send_result.second);
CHECK_EQ(send_result.first, basic_get.size());
auto recv_future = client.recv_async(2048, 3000ms);
auto recv_result = recv_future.get();
CHECK_EQ(recv_result.second,
std::errc::connection_aborted); // the server terminates connection
// after sending site
CHECK_GT(recv_result.first.size(), basic_get.size());
std::string website(recv_result.first.begin(), recv_result.first.end());
CHECK_NE(website.find("HTTP Version Not Supported"),
std::string::npos); // 1.1 is way too old
}
TEST_CASE("Client example.com")
{
netlib::client client;
std::error_condition connect_result =
client.connect("example.com", "http", netlib::AddressFamily::IPv4, netlib::AddressProtocol::TCP, 1000ms);
CHECK_FALSE(connect_result);
std::pair<std::size_t, std::error_condition> send_result = client.send({basic_get.begin(), basic_get.end()}, 1000ms);
CHECK_FALSE(send_result.second);
CHECK_EQ(send_result.first, basic_get.size());
std::pair<std::vector<uint8_t>, std::error_condition> recv_result = client.recv(2048, 3000ms);
CHECK_EQ(recv_result.second,
std::errc::connection_aborted); // the server terminates connection
// after sending site
CHECK_GT(recv_result.first.size(), basic_get.size());
std::string website(recv_result.first.begin(), recv_result.first.end());
CHECK_NE(website.find("HTTP Version Not Supported"),
std::string::npos); // 1.1 is way too old
} | 38.370968 | 139 | 0.670029 | lpcvoid |
270a59ac8c7ecea0aed1e1bb884d6a9461297564 | 950 | hpp | C++ | include/equal/prefab/scene/blank.hpp | equal-games/equal | acaf0d456d7b996dd2a6bc23150cd45ddf618296 | [
"BSD-2-Clause",
"Apache-2.0"
] | 7 | 2019-08-07T21:27:27.000Z | 2020-11-27T16:33:16.000Z | include/equal/prefab/scene/blank.hpp | equal-games/equal | acaf0d456d7b996dd2a6bc23150cd45ddf618296 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | include/equal/prefab/scene/blank.hpp | equal-games/equal | acaf0d456d7b996dd2a6bc23150cd45ddf618296 | [
"BSD-2-Clause",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2019 Equal Games
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <equal/core/scene.hpp>
namespace eq {
/**
* @ingroup scenes
* @brief Default empty scene
*/
class BlankScene : public Scene {
public:
void start() override;
void update(Ref<World> &world, const Timestep ×tep);
void fixed_update(Ref<World> &world, const Timestep ×tep);
void end() override;
};
} // namespace eq
| 27.941176 | 75 | 0.724211 | equal-games |
270e0169d634c50584bd032ddd200725ff5bacfc | 4,064 | cpp | C++ | lib/UserInput/Button.cpp | andhieSetyabudi/continuous_8bit | d3382a8799cd963dbde1833af74e07f5210628df | [
"FSFAP"
] | null | null | null | lib/UserInput/Button.cpp | andhieSetyabudi/continuous_8bit | d3382a8799cd963dbde1833af74e07f5210628df | [
"FSFAP"
] | null | null | null | lib/UserInput/Button.cpp | andhieSetyabudi/continuous_8bit | d3382a8799cd963dbde1833af74e07f5210628df | [
"FSFAP"
] | null | null | null | #define LIBCALL_ENABLEINTERRUPT
#include "Config.h"
#include "UserInput.h"
#include <EnableInterrupt.h>
bool UserInput::Button::sleep = false;
bool UserInput::Button::sleepBuffer = false;
volatile bool UserInput::Button::interruptPressed = false;
bool UserInput::Button::pressed = false;
bool UserInput::Button::longPressed = false;
volatile bool UserInput::Button::interruptCalibrationPressed = false;
#if CALIBRATION_BUTTON_ENABLE == true
bool UserInput::Button::calibrationPressed = false;
bool UserInput::Button::calibrationLongPressed = false;
#endif
void UserInput::Button::setup(void) {
unsigned char port = BUTTON_PIN_PORT;
unsigned char bit = BUTTON_PIN_BIT;
#if CALIBRATION_BUTTON_ENABLE == true
unsigned char calibrationPort = CALIBRATION_BUTTON_PIN_PORT;
unsigned char calibrationBit = CALIBRATION_BUTTON_PIN_BIT;
#endif
*portModeRegister(port) &= ~bit;
*portOutputRegister(port) |= bit;
#if CALIBRATION_BUTTON_ENABLE == true
*portModeRegister(calibrationPort) &= ~calibrationBit;
*portOutputRegister(calibrationPort) |= calibrationBit;
#endif
enableInterrupt(BUTTON_PIN, UserInput::Button::onButtonPressed, FALLING);
#if CALIBRATION_BUTTON_ENABLE == true
enableInterrupt(CALIBRATION_BUTTON_PIN, UserInput::Button::onCalibrationButtonPressed, FALLING);
#endif
}
void UserInput::Button::loop(void) {
wdt_reset();
static bool interruptEnabled = false;
static bool interruptCalibrationEnabled = false;
if (interruptPressed || interruptCalibrationPressed) {
sleep = false;
} else if (sleepBuffer != sleep) {
if (!interruptEnabled) {
enableInterrupt(BUTTON_PIN, UserInput::Button::onButtonPressed, FALLING);
interruptEnabled = true;
}
#if CALIBRATION_BUTTON_ENABLE == true
if (!interruptCalibrationEnabled) {
enableInterrupt(CALIBRATION_BUTTON_PIN, UserInput::Button::onCalibrationButtonPressed, FALLING);
interruptCalibrationEnabled = true;
}
#endif
sleep = sleepBuffer;
}
static unsigned long pressedMillis = 0;
static unsigned long calibrationPressedMillis = 0;
if (interruptPressed) {
interruptPressed = false;
pressed = true;
pressedMillis = millis();
disableInterrupt(BUTTON_PIN);
interruptEnabled = false;
} else if ((*portInputRegister(BUTTON_PIN_PORT) & BUTTON_PIN_BIT) == LOW) {
if (longPressed) {
longPressed = false;
pressedMillis = millis();
} else if (millis() - pressedMillis > 1500) {
longPressed = true;
}
} else if (millis() - pressedMillis > 50) {
enableInterrupt(BUTTON_PIN, UserInput::Button::onButtonPressed, FALLING);
interruptEnabled = true;
pressed = false;
longPressed = false;
}
#if CALIBRATION_BUTTON_ENABLE == true
if (interruptCalibrationPressed) {
interruptCalibrationPressed = false;
calibrationPressed = true;
calibrationPressedMillis = millis();
disableInterrupt(CALIBRATION_BUTTON_PIN);
interruptCalibrationEnabled = false;
} else if ((*portInputRegister(CALIBRATION_BUTTON_PIN_PORT) & CALIBRATION_BUTTON_PIN_BIT) == LOW) {
if (calibrationLongPressed) {
calibrationLongPressed = false;
calibrationPressedMillis = millis();
} else if (millis() - calibrationPressedMillis > 1500) {
calibrationLongPressed = true;
}
} else if (millis() - calibrationPressedMillis > 50) {
enableInterrupt(CALIBRATION_BUTTON_PIN, UserInput::Button::onCalibrationButtonPressed, FALLING);
interruptCalibrationEnabled = true;
calibrationPressed = false;
calibrationLongPressed = false;
}
#endif
wdt_reset();
}
bool UserInput::Button::isSleep(void) {
return sleep;
}
bool UserInput::Button::isGoingToSleep(void) {
return sleepBuffer & !sleep;
}
void UserInput::Button::setSleep(bool sleep) {
sleepBuffer = sleep;
}
/**
* Interrupt Routine
*/
void UserInput::Button::onButtonPressed(void) {
interruptPressed = true;
wdt_reset();
}
#if CALIBRATION_BUTTON_ENABLE == true
void UserInput::Button::onCalibrationButtonPressed(void) {
interruptCalibrationPressed = true;
wdt_reset();
}
#endif | 30.787879 | 102 | 0.740404 | andhieSetyabudi |
270eda5646c1bbbea4ba0a8077d1da80a37c911e | 1,936 | cpp | C++ | examples/Standard/Roguelike/Components/Destructible.cpp | ptrefall/propcomp | 35a751ae0717e5c35621200f64deb373b29341a0 | [
"MIT"
] | 2 | 2018-10-18T12:06:15.000Z | 2019-06-13T20:41:31.000Z | examples/Standard/Roguelike/Components/Destructible.cpp | ptrefall/propcomp | 35a751ae0717e5c35621200f64deb373b29341a0 | [
"MIT"
] | null | null | null | examples/Standard/Roguelike/Components/Destructible.cpp | ptrefall/propcomp | 35a751ae0717e5c35621200f64deb373b29341a0 | [
"MIT"
] | null | null | null | #include "Destructible.h"
#include "../Engine.h"
#include "../Systems/RenderSystem.h"
#include <iostream>
Destructible::Destructible(const EntityWPtr &owner, const RenderSystemPtr &system)
: Totem::Component<Destructible, PropertyUserData>("Destructible"), owner(owner), system(system)
{
user_data.entity = owner;
user_data.component = this;
ch = owner.lock()->add<int>("Character", '@');
col = owner.lock()->add<TCODColor>("Color", TCODColor::white);
blocks = owner.lock()->add<bool>("Blocks", true);
dead = owner.lock()->add<bool>("Dead", false);
defense = owner.lock()->add<float>("Defense", 1);
maxHp = owner.lock()->add<float>("MaxHP", 1);
hp = owner.lock()->add<float>("HP", 1);
corpseName = owner.lock()->add<std::string>("CorpseName", "corpse");
owner.lock()->registerToEvent1<float>("TakeDamage").connect(this, &Destructible::takeDamage);
owner.lock()->registerToEvent1<float>("Heal").connect(this, &Destructible::heal);
}
Destructible::~Destructible()
{
//std::cout << "Destructible is being destroyed!" << std::endl;
}
void Destructible::takeDamage(float damage) {
damage -= defense;
if ( damage > 0 ) {
hp -= damage;
if ( hp <= 0 ) {
die();
}
} else {
damage=0;
}
}
void Destructible::die() {
if(owner.lock()->hasEvent("Dying", 0))
owner.lock()->sendEvent0("Dying");
// transform the actor into a corpse!
ch='%';
col=TCODColor::darkRed;
owner.lock()->updateName(corpseName.get());
blocks=false;
dead = true;
// make sure corpses are drawn before living actors
system->add(owner);
if(owner.lock()->hasEvent("Dead", 0))
owner.lock()->sendEvent0("Dead");
}
void Destructible::heal(float amount)
{
hp += amount;
if ( hp.get() > maxHp.get() ) {
hp=maxHp.get();
}
else if ( hp <= 0 ) {
die();
}
}
| 25.813333 | 97 | 0.596591 | ptrefall |
27177f39b59435d67494997ea35736d18a7e26fb | 717 | hpp | C++ | src/player.hpp | Sirflankalot/Bomberman | 7f2fa5cf657672e070e8850233c9a36a0b480b2f | [
"Apache-2.0"
] | null | null | null | src/player.hpp | Sirflankalot/Bomberman | 7f2fa5cf657672e070e8850233c9a36a0b480b2f | [
"Apache-2.0"
] | null | null | null | src/player.hpp | Sirflankalot/Bomberman | 7f2fa5cf657672e070e8850233c9a36a0b480b2f | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <GL/glew.h>
#include "controller.hpp"
#include <array>
#include <cstddef>
namespace players {
struct player_info {
enum class direction : uint8_t { up = 0, left = 1, down = 2, right = 3 };
std::size_t loc_x, loc_y;
std::size_t last_x, last_y;
float factor = 1.0;
direction dir;
bool animated = false;
bool active = false;
enum class powerup : uint8_t { none = 0, trap, bomb };
powerup power = powerup::none;
uint8_t ammo_count = 1;
};
extern std::array<player_info, 4> player_list;
void initialize();
void update_players(const control::movement_report_type&, float time_elapsed);
void render(GLuint world_matrix_uniform);
void respawn(std::size_t player_index);
} | 24.724138 | 79 | 0.707113 | Sirflankalot |
271b4a4bc011154a03033eb7bdb3fd124a627e6f | 126 | cpp | C++ | src/test_gui/test_lab.cpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | src/test_gui/test_lab.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | src/test_gui/test_lab.cpp | lib1256/zpublic | 64c2be9ef1abab878288680bb58122dcc25df81d | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | #include "stdafx.h"
#include "test_lab.h"
#include "lab1.h"
#include "lab2.h"
void test_lab()
{
//Lab1();
//Lab2();
} | 12.6 | 21 | 0.587302 | wohaaitinciu |
27210af3b8587e5bf55303c787c45d307d8bd970 | 952 | hpp | C++ | libs/swm/src/load/LoadV1.hpp | deathcleaver/swizzle | 1a1cc114841ea7de486cf94c6cafd9108963b4da | [
"MIT"
] | 2 | 2020-02-10T07:58:21.000Z | 2022-03-15T19:13:28.000Z | libs/swm/src/load/LoadV1.hpp | deathcleaver/swizzle | 1a1cc114841ea7de486cf94c6cafd9108963b4da | [
"MIT"
] | null | null | null | libs/swm/src/load/LoadV1.hpp | deathcleaver/swizzle | 1a1cc114841ea7de486cf94c6cafd9108963b4da | [
"MIT"
] | null | null | null | #ifndef SWM_MODEL_V1_LOAD_HPP
#define SWM_MODEL_V1_LOAD_HPP
/* Include files */
#include <swm/Swm.hpp>
#include <utils/BufferReader.hpp>
#include <string>
#include <vector>
/* Defines */
#define MESH_FLAGS_V1_UV_BIT 0x00
#define MESH_FLAGS_V1_NORMAL_BIT 0x01
#define MESH_FLAGS_V1_COLOR_BIT 0x02
/* Typedefs/enums */
/* Forward Declared Structs/Classes */
/* Struct Declaration */
namespace swm_v1
{
struct Mesh_v1
{
std::string mName;
U16 mMeshFlags = 0u;
std::vector<swm::Vertex> mVertices;
std::vector<swm::Uv> mUvs;
std::vector<swm::Vertex> mNormals;
std::vector<swm::Color> mColors;
std::vector<swm::Triangle> mTriangles;
};
}
/* Class Declaration */
/* Function Declaration */
namespace swm_v1
{
swm::LoadResult LoadV1(U16 minorVer, utils::BufferReader& br, swm::Model& mdl);
swm::LoadResult LoadMeshV1(utils::BufferReader& br, Mesh_v1& mesh);
}
#endif | 17.962264 | 83 | 0.680672 | deathcleaver |
27281a041626627abdeddd061b5103e678c5616c | 1,254 | cpp | C++ | src/hash/test/src/HashTest.cpp | karz0n/algorithms | b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8 | [
"MIT"
] | 1 | 2020-04-18T14:34:16.000Z | 2020-04-18T14:34:16.000Z | src/hash/test/src/HashTest.cpp | karz0n/algorithms | b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8 | [
"MIT"
] | null | null | null | src/hash/test/src/HashTest.cpp | karz0n/algorithms | b2a08ba990c7e4f078eb7bf3c90d050eb38de9d8 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <Hash.hpp>
#include <functional>
static algorithms::hash<std::string> stringHasher;
static algorithms::hash<double> doubleHasher;
TEST(HashTest, String)
{
std::string v1{"Hello world!"};
std::string v2{"Hello World!"};
EXPECT_EQ(stringHasher(v1), stringHasher(v1));
EXPECT_NE(stringHasher(v1), stringHasher(v2));
}
TEST(HashTest, Double)
{
double v1{0.01};
double v2{0.02};
EXPECT_EQ(doubleHasher(v1), doubleHasher(v1));
EXPECT_NE(doubleHasher(v1), doubleHasher(v2));
}
TEST(HashTest, Combine)
{
using namespace algorithms;
std::string v1{"Hello world!"};
double v2{0.01};
int v3{10};
EXPECT_EQ(combine(v1, v2), combine(v1, v2));
EXPECT_NE(combine(v1, v2), combine(v1, v3));
}
TEST(HashTest, Collision)
{
std::hash<std::string> trueStringHasher;
//! We have a collision with our simple hash method, it's very bad.
EXPECT_EQ(stringHasher("Aa"), stringHasher("BB"));
EXPECT_EQ(stringHasher("AaAaAaAa"), stringHasher("BBBBBBBB"));
//! We don't have a collision with STL hash method, so use it.
EXPECT_NE(trueStringHasher("Aa"), trueStringHasher("BB"));
EXPECT_NE(trueStringHasher("AaAaAaAa"), trueStringHasher("BBBBBBBB"));
}
| 24.115385 | 74 | 0.681021 | karz0n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.