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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4a194049b6d19720ba1bf16da44ae734487318ef | 1,020 | cpp | C++ | kernel/arch/x86_64/com.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | 1 | 2021-03-27T13:40:21.000Z | 2021-03-27T13:40:21.000Z | kernel/arch/x86_64/com.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | kernel/arch/x86_64/com.cpp | jasonwer/WingOS | 1e3b8b272bc93542fda48ed1cf3226e63c923f39 | [
"BSD-2-Clause"
] | null | null | null | #include <arch.h>
#include <com.h>
#include <kernel.h>
#include <process.h>
#include <stdarg.h>
#include <utility.h>
char temp_buffer[17];
uint64_t last_count = 17;
bool com_device::echo_out(const char *data, uint64_t data_length)
{
for (uint64_t i = 0; i < data_length; i++)
{
write(data[i]);
}
return true;
}
bool com_device::echo_out(const char *data)
{
uint64_t i = 0;
while (data[i] != 0)
{
write(data[i]);
i++;
}
return true;
}
void com_device::init(COM_PORT this_port)
{
port = this_port;
outb(port + 2, 0);
outb(port + 3, 1 << 7);
outb(port + 0, 3);
outb(port + 1, 0);
outb(port + 3, 0x03);
outb(port + 2, 0xC7);
outb(port + 4, 0x0B);
add_device(this);
}
void com_device::wait() const
{
int timeout = 0;
while ((inb(port + 5) & 0x20) == 0)
{
if (timeout++ > 10000)
{
break;
}
}
}
inline void com_device::write(char c) const
{
wait();
outb(port, c);
}
| 17 | 65 | 0.545098 | jasonwer |
4a1cf84fdc287c42f1dad8fa81015e3bc12e2db8 | 13,119 | cpp | C++ | src/Private/Resources/PlayingHudResource.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | src/Private/Resources/PlayingHudResource.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | src/Private/Resources/PlayingHudResource.cpp | heltena/KYEngine | 4ccb89d0b20683feb245ffe85dd34b6ffdc42c8e | [
"MIT"
] | null | null | null | #include <KYEngine/AddFaceViewParam.h>
#include <KYEngine/AddMapViewParam.h>
#include <KYEngine/AddProgressViewParam.h>
#include <KYEngine/AddJoystickButtonParam.h>
#include <KYEngine/AddPushButtonParam.h>
#include <KYEngine/Core.h>
#include <KYEngine/Private/Resources/PlayingHudResource.h>
#include <KYEngine/Utility/TiXmlHelper.h>
#include <iostream>
#include <stdexcept>
const std::string PlayingHudResource::XML_NODE = "playing-hud";
PlayingHudResource::PlayingHudResource()
: m_listener(NULL)
, m_layer(NULL)
{
}
PlayingHudResource::~PlayingHudResource()
{
}
PlayingHudResource* PlayingHudResource::readFromXml(TiXmlElement* node)
{
PlayingHudResource* result = new PlayingHudResource();
const std::string name = TiXmlHelper::readString(node, "name", true);
const std::string layerName = TiXmlHelper::readString(node, "layer-name", true);
double zOrder = TiXmlHelper::readDouble(node, "z-order", true);
result->setName(name);
result->setLayerName(layerName);
result->setZOrder(zOrder);
TiXmlElement* curr = node->FirstChildElement();
while (curr) {
std::string prefix = Core::resourceManager().prefixOfNode(curr);
Core::resourceManager().factory(prefix)->readFromXml(prefix, curr, result);
curr = curr->NextSiblingElement();
}
return result;
}
void PlayingHudResource::preload()
{
}
void PlayingHudResource::unloadFromPreloaded()
{
}
void PlayingHudResource::load()
{
for(std::list<AddFaceViewParam*>::const_iterator it = m_faceViewParams.begin(); it != m_faceViewParams.end(); it++) {
AddFaceViewParam* faceViewParam = *it;
HudFaceView* view = faceViewParam->generateFaceView();
addFaceView(faceViewParam->id(), view);
}
for(std::list<AddMapViewParam*>::const_iterator it = m_mapViewParams.begin(); it != m_mapViewParams.end(); it++) {
AddMapViewParam* mapViewParam = *it;
HudMapView* view = mapViewParam->generateMapView();
addMapView(mapViewParam->id(), view);
}
for(std::list<AddProgressViewParam*>::const_iterator it = m_progressViewParams.begin(); it != m_progressViewParams.end(); it++) {
AddProgressViewParam* progressViewParam = *it;
HudProgressView* view = progressViewParam->generateProgressView();
addProgressView(progressViewParam->id(), view);
}
for(std::list<AddJoystickButtonParam*>::const_iterator it = m_joystickButtonParams.begin(); it != m_joystickButtonParams.end(); it++) {
AddJoystickButtonParam* joystickButtonParam = *it;
HudJoystickButton* button = joystickButtonParam->generateJoystickButton();
addJoystickButton(joystickButtonParam->id(), button);
}
for(std::list<AddPushButtonParam*>::const_iterator it = m_pushButtonParams.begin(); it != m_pushButtonParams.end(); it++) {
AddPushButtonParam* pushButtonParam = *it;
HudPushButton* button = pushButtonParam->generatePushButton();
addPushButton(pushButtonParam->id(), button);
}
for(std::list<AddTextLabelParam*>::const_iterator it = m_textLabelParams.begin(); it != m_textLabelParams.end(); it++) {
AddTextLabelParam* textLabelParam = *it;
HudTextLabel* textLabel = textLabelParam->generateTextLabel();
addTextLabel(textLabelParam->id(), textLabel);
}
}
void PlayingHudResource::unload()
{
m_listener = NULL;
if (m_layer) {
Core::renderManager().removeLayer(m_layerName);
m_layer = NULL;
}
for(std::map<int, HudFaceView*>::const_iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++)
delete it->second;
m_faceViews.clear();
for(std::map<int, HudMapView*>::const_iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++)
delete it->second;
m_joystickButtons.clear();
for(std::map<int, HudProgressView*>::const_iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++)
delete it->second;
m_mapViews.clear();
for(std::map<int, HudJoystickButton*>::const_iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++)
delete it->second;
m_progressViews.clear();
for(std::map<int, HudPushButton*>::const_iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++)
delete it->second;
m_pushButtons.clear();
for(std::map<int, HudTextLabel*>::const_iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++)
delete it->second;
m_textLabels.clear();
}
void PlayingHudResource::appear(PlayingHudListener* listener)
{
if (m_layer == NULL)
m_layer = Core::renderManager().createLayer(m_layerName, m_zOrder);
m_listener = listener;
for (std::map<int, HudFaceView*>::iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) {
it->second->appear();
m_layer->addEntity(it->second);
}
for (std::map<int, HudMapView*>::iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) {
it->second->appear();
m_layer->addEntity(it->second);
}
for (std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) {
it->second->appear(NULL);
m_layer->addEntity(it->second);
}
for (std::map<int, HudProgressView*>::iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) {
it->second->appear();
m_layer->addEntity(it->second);
}
for (std::map<int, HudPushButton*>::iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) {
it->second->appear(this);
m_layer->addEntity(it->second);
}
for(std::map<int, HudTextLabel*>::iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) {
it->second->appear();
m_layer->addEntity(it->second);
}
}
bool PlayingHudResource::isAppeared() const
{
for (std::map<int, HudFaceView*>::const_iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) {
if (! it->second->isAppeared())
return false;
}
for (std::map<int, HudMapView*>::const_iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) {
if (! it->second->isAppeared())
return false;
}
for (std::map<int, HudJoystickButton*>::const_iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) {
if (! it->second->isAppeared())
return false;
}
for (std::map<int, HudProgressView*>::const_iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) {
if (! it->second->isAppeared())
return false;
}
for (std::map<int, HudPushButton*>::const_iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) {
if (! it->second->isAppeared())
return false;
}
for(std::map<int, HudTextLabel*>::const_iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) {
if (! it->second->isAppeared())
return false;
}
return true;
}
void PlayingHudResource::disappear()
{
m_listener = NULL;
for (std::map<int, HudFaceView*>::iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) {
it->second->disappear();
}
for (std::map<int, HudMapView*>::iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) {
it->second->disappear();
}
for (std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) {
it->second->disappear();
}
for (std::map<int, HudProgressView*>::iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) {
it->second->disappear();
}
for (std::map<int, HudPushButton*>::iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) {
it->second->disappear();
}
for(std::map<int, HudTextLabel*>::iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) {
it->second->disappear();
}
m_listener = NULL;
}
bool PlayingHudResource::isDisappeared() const
{
for (std::map<int, HudFaceView*>::const_iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++) {
if (! it->second->isDisappeared())
return false;
}
for (std::map<int, HudMapView*>::const_iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++) {
if (! it->second->isDisappeared())
return false;
}
for (std::map<int, HudJoystickButton*>::const_iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++) {
if (! it->second->isDisappeared())
return false;
}
for (std::map<int, HudProgressView*>::const_iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++) {
if (! it->second->isDisappeared())
return false;
}
for (std::map<int, HudPushButton*>::const_iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++) {
if (! it->second->isDisappeared())
return false;
}
for(std::map<int, HudTextLabel*>::const_iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++) {
if (! it->second->isDisappeared())
return false;
}
return true;
}
void PlayingHudResource::abort()
{
if (m_layer != NULL) {
Core::renderManager().removeLayer(m_layerName);
m_layer = NULL;
}
}
void PlayingHudResource::setListener(PlayingHudListener* listener)
{
m_listener = listener;
}
const Vector4 PlayingHudResource::direction(int id)
{
std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.find(id);
if (it == m_joystickButtons.end())
return Vector4();
return it->second->direction();
}
void PlayingHudResource::setFaceValue(int id, double value)
{
std::map<int, HudFaceView*>::iterator it = m_faceViews.find(id);
if (it == m_faceViews.end())
throw std::runtime_error("PlayingHud: faceView not found " + id);
it->second->setCurrentValue(value);
}
void PlayingHudResource::setMapItems(int id, const std::list<HudMapViewItem>& items)
{
std::map<int, HudMapView*>::iterator it = m_mapViews.find(id);
if (it == m_mapViews.end())
throw std::runtime_error("PlayingHud: mapView not found " + id);
it->second->setItems(items);
}
void PlayingHudResource::setProgressValue(int id, double value)
{
std::map<int, HudProgressView*>::iterator it = m_progressViews.find(id);
if (it == m_progressViews.end())
throw std::runtime_error("PlayingHud: progressView not found " + id);
it->second->setCurrentValue(value);
}
void PlayingHudResource::setTextLabel(int id, const std::string& value)
{
std::map<int, HudTextLabel*>::iterator it = m_textLabels.find(id);
if (it == m_textLabels.end())
throw std::runtime_error("PlayingHud: textLabel not found " + id);
it->second->setText(value);
}
void PlayingHudResource::update(const double elapsedTime)
{
if (m_layer == NULL)
return;
if (isDisappeared()) {
if (m_layer != NULL) {
Core::renderManager().removeLayer(m_layerName);
m_layer = NULL;
}
} else {
for (std::map<int, HudFaceView*>::iterator it = m_faceViews.begin(); it != m_faceViews.end(); it++)
it->second->update(elapsedTime);
for (std::map<int, HudMapView*>::iterator it = m_mapViews.begin(); it != m_mapViews.end(); it++)
it->second->update(elapsedTime);
for (std::map<int, HudJoystickButton*>::iterator it = m_joystickButtons.begin(); it != m_joystickButtons.end(); it++)
it->second->update(elapsedTime);
for (std::map<int, HudProgressView*>::iterator it = m_progressViews.begin(); it != m_progressViews.end(); it++)
it->second->update(elapsedTime);
for (std::map<int, HudPushButton*>::iterator it = m_pushButtons.begin(); it != m_pushButtons.end(); it++)
it->second->update(elapsedTime);
for (std::map<int, HudTextLabel*>::iterator it = m_textLabels.begin(); it != m_textLabels.end(); it++)
it->second->update(elapsedTime);
}
}
void PlayingHudResource::addFaceView(int id, HudFaceView* view)
{
m_faceViews[id] = view;
}
void PlayingHudResource::addJoystickButton(int id, HudJoystickButton* button)
{
m_joystickButtons[id] = button;
}
void PlayingHudResource::addMapView(int id, HudMapView* view)
{
m_mapViews[id] = view;
}
void PlayingHudResource::addProgressView(int id, HudProgressView* view)
{
m_progressViews[id] = view;
}
void PlayingHudResource::addPushButton(int id, HudPushButton* button)
{
m_pushButtons[id] = button;
}
void PlayingHudResource::addTextLabel(int id, HudTextLabel* textLabel)
{
m_textLabels[id] = textLabel;
}
void PlayingHudResource::hudButtonPressed(int id)
{
if (m_listener)
m_listener->hudButtonPressed(direction(), id);
}
void PlayingHudResource::hudButtonReleased(int id)
{
if (m_listener)
m_listener->hudButtonReleased(direction(), id);
}
| 35.649457 | 139 | 0.647991 | heltena |
4a211385c55ec7464c20bc86d74449970d0c0d31 | 217 | cpp | C++ | CC/hello_world.cpp | MrRobo24/Codes | 9513f42b61e898577123d5b996e43ba7a067a019 | [
"MIT"
] | 1 | 2020-10-12T08:03:20.000Z | 2020-10-12T08:03:20.000Z | CC/hello_world.cpp | MrRobo24/Codes | 9513f42b61e898577123d5b996e43ba7a067a019 | [
"MIT"
] | null | null | null | CC/hello_world.cpp | MrRobo24/Codes | 9513f42b61e898577123d5b996e43ba7a067a019 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main() {
long long a = 2992;
long long b = 192;
int prod = a * b;
cout << "Product of " << a <<" and " << b << " is = " << prod << "\n";
return 0;
} | 24.111111 | 74 | 0.488479 | MrRobo24 |
4a2904fda2c70d52ed7767a3317284c589584fdb | 782 | cpp | C++ | leetcode/src/0142-detectCycle.cpp | Wasikowska/go-typebyname | 460c50de881508f340c4785c18cee47232095a50 | [
"MIT"
] | null | null | null | leetcode/src/0142-detectCycle.cpp | Wasikowska/go-typebyname | 460c50de881508f340c4785c18cee47232095a50 | [
"MIT"
] | null | null | null | leetcode/src/0142-detectCycle.cpp | Wasikowska/go-typebyname | 460c50de881508f340c4785c18cee47232095a50 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_set>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if (!head) {
return nullptr;
}
// floyd's cycle finding algorithm
ListNode* n1{head};
ListNode* n2{head->next};
while (n1 && n2) {
if (n1 == n2) {
// find a cycle
std::unordered_set<ListNode*> cycle;
while (n1) {
if (cycle.find(n1) != cycle.end()) {
break;
}
cycle.insert(n1);
n1 = n1->next;
}
ListNode* n{head};
while (n) {
if (cycle.find(n) != cycle.end()) {
return n;
}
n = n->next;
}
}
n1 = n1->next;
n2 = n2->next ? n2->next->next : nullptr;
}
return nullptr;
}
};
| 16.291667 | 47 | 0.543478 | Wasikowska |
4a2bf58675380c45030695db57d420ccd8cd67f1 | 2,286 | cpp | C++ | src/tests/test_rdtree_select.cpp | rvianello/chemicalite | 0feb0d122e2f38730e2033e76681699c12eb1b23 | [
"BSD-3-Clause"
] | 29 | 2015-03-07T14:40:35.000Z | 2022-02-05T21:17:42.000Z | src/tests/test_rdtree_select.cpp | rvianello/chemicalite | 0feb0d122e2f38730e2033e76681699c12eb1b23 | [
"BSD-3-Clause"
] | 3 | 2015-11-18T05:04:48.000Z | 2020-12-16T22:37:25.000Z | src/tests/test_rdtree_select.cpp | rvianello/chemicalite | 0feb0d122e2f38730e2033e76681699c12eb1b23 | [
"BSD-3-Clause"
] | 3 | 2020-05-13T19:02:07.000Z | 2021-08-02T10:45:32.000Z | #include "test_common.hpp"
TEST_CASE("rdtree select", "[rdtree]")
{
sqlite3 * db = nullptr;
test_db_open(&db);
int rc = sqlite3_exec(
db,
"CREATE VIRTUAL TABLE xyz USING rdtree(id integer primary key, s bits(1024))",
NULL, NULL, NULL);
REQUIRE(rc == SQLITE_OK);
// insert some binary fingerprints
sqlite3_stmt *pStmt = nullptr;
rc = sqlite3_prepare(db, "INSERT INTO xyz(id, s) VALUES(?1, bfp_dummy(1024, ?2))", -1, &pStmt, 0);
REQUIRE(rc == SQLITE_OK);
for (int i=0; i < 256; ++i) {
rc = sqlite3_bind_int(pStmt, 1, i+1);
REQUIRE(rc == SQLITE_OK);
rc = sqlite3_bind_int(pStmt, 2, i);
REQUIRE(rc == SQLITE_OK);
rc = sqlite3_step(pStmt);
REQUIRE(rc == SQLITE_DONE);
rc = sqlite3_reset(pStmt);
REQUIRE(rc == SQLITE_OK);
}
SECTION("select matching simple subset constraints") {
// if we use 0x01 as subset match constraint, it will return all the dummy bfp
// records generated by an odd number. we therefore expect the number of these
// records to be a half of the total
test_select_value(
db,
"SELECT COUNT(*) FROM xyz WHERE id MATCH rdtree_subset(bfp_dummy(1024, 1))", 128);
// if we instead use 0x0f, the fingerprints matching this pattern as subset are those
// that vary in value of the more significant nibble (0x0f, 0x1f, ... 0xff). there should
// be 16 such fingerprints
test_select_value(
db,
"SELECT COUNT(*) FROM xyz WHERE id MATCH rdtree_subset(bfp_dummy(1024, 0x0f))", 16);
}
SECTION("select matching simple similarity constraints") {
// if we use 0x01 as similarity match constraint, with a threshold of at least 0.5
// we should get 0x01 (perfect match) and the bfps with two bits set per byte where
// one of the bits is 0x01 (7 more values). the expected number of returned values
// is therefore 8
test_select_value(
db,
"SELECT COUNT(*) FROM xyz WHERE bfp_tanimoto(bfp_dummy(1024, 1), s) >= 0.5", 8);
test_select_value(
db,
"SELECT COUNT(*) FROM xyz WHERE id MATCH rdtree_tanimoto(bfp_dummy(1024, 1), .5)", 8);
}
sqlite3_finalize(pStmt);
rc = sqlite3_exec(db, "DROP TABLE xyz", NULL, NULL, NULL);
REQUIRE(rc == SQLITE_OK);
test_db_close(db);
}
| 31.75 | 100 | 0.653981 | rvianello |
4a30d03c7eb0777c467f15599aebad9a2b02e6eb | 2,894 | cpp | C++ | src/graphics/ressources/buffers.cpp | guillaume-haerinck/learn-vulkan | 30acd5b477866f7454a3c89bf10a7bfffc11c9a1 | [
"MIT"
] | null | null | null | src/graphics/ressources/buffers.cpp | guillaume-haerinck/learn-vulkan | 30acd5b477866f7454a3c89bf10a7bfffc11c9a1 | [
"MIT"
] | null | null | null | src/graphics/ressources/buffers.cpp | guillaume-haerinck/learn-vulkan | 30acd5b477866f7454a3c89bf10a7bfffc11c9a1 | [
"MIT"
] | null | null | null | #include "buffers.h"
#include <chrono>
#include <glm/gtc/matrix_transform.hpp>
#include "graphics/setup/devices.h"
VertexBuffer::VertexBuffer(LogicalDevice& device, MemoryAllocator& memoryAllocator, const std::vector<Vertex>& vertices)
: m_vertices(vertices), IBuffer(device, memoryAllocator)
{
vk::BufferCreateInfo info(
vk::BufferCreateFlags(),
sizeof(m_vertices.at(0)) * m_vertices.size(),
vk::BufferUsageFlagBits::eVertexBuffer,
vk::SharingMode::eExclusive
);
m_buffers.push_back(m_device.get().createBufferUnique(info));
m_bufferMemories.push_back(m_memoryAllocator.allocateAndBindBuffer(*this));
}
IndexBuffer::IndexBuffer(LogicalDevice& device, MemoryAllocator& memoryAllocator, const Model& model)
: IBuffer(device, memoryAllocator)
{
m_elementCount = model.indicesCount;
m_byteSize = sizeof(model.indicesData.at(0)) * model.indicesData.size();
m_indices_data = model.indicesData;
vk::BufferCreateInfo info(
vk::BufferCreateFlags(),
m_byteSize,
vk::BufferUsageFlagBits::eIndexBuffer,
vk::SharingMode::eExclusive
);
m_buffers.push_back(m_device.get().createBufferUnique(info));
m_bufferMemories.push_back(m_memoryAllocator.allocateAndBindBuffer(*this));
}
UniformBuffer::UniformBuffer(LogicalDevice& device, MemoryAllocator& memoryAllocator, unsigned int swapChainImagesCount)
: IBuffer(device, memoryAllocator)
{
m_ubo.world = glm::mat4(1);
m_ubo.viewProj = glm::mat4(1);
vk::DeviceSize bufferSize = sizeof(PerFrameUB);
vk::BufferCreateInfo info(
vk::BufferCreateFlags(),
bufferSize,
vk::BufferUsageFlagBits::eUniformBuffer,
vk::SharingMode::eExclusive
);
for (size_t i = 0; i < swapChainImagesCount; i++)
{
m_buffers.push_back(m_device.get().createBufferUnique(info));
m_bufferMemories.push_back(m_memoryAllocator.allocateAndBindBuffer(*this, i));
}
}
UniformBuffer::~UniformBuffer()
{
}
void UniformBuffer::updateBuffer(unsigned int currentImage, const glm::mat4x4& viewProj)
{
static auto startTime = std::chrono::high_resolution_clock::now();
auto currentTime = std::chrono::high_resolution_clock::now();
float time = std::chrono::duration<float, std::chrono::seconds::period>(currentTime - startTime).count();
// m_ubo.world = glm::rotate(glm::mat4(1), time * glm::radians(90.0f), glm::vec3(0, 0, 1));
m_ubo.viewProj = viewProj;
// Copy data
vk::MemoryRequirements memoryRequirements = m_device.get().getBufferMemoryRequirements(m_buffers.at(currentImage).get());
unsigned int* pData = static_cast<unsigned int*>(m_device.get().mapMemory(m_bufferMemories.at(currentImage).get(), 0, memoryRequirements.size));
memcpy(pData, &m_ubo, sizeof(m_ubo));
m_device.get().unmapMemory(m_bufferMemories.at(currentImage).get());
}
| 35.728395 | 148 | 0.715619 | guillaume-haerinck |
4a3198d1b97e8de48fe4a53eea560a25f3d8c27f | 1,565 | cpp | C++ | Algorithm important/search in almost sorted array.cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | 3 | 2020-12-03T14:52:23.000Z | 2021-12-19T09:26:50.000Z | Algorithm important/search in almost sorted array.cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | null | null | null | Algorithm important/search in almost sorted array.cpp | shauryauppal/Algo-DS-StudyMaterial | 1c481f066d21b33ec2533156e75f45fa9b6a7606 | [
"Apache-2.0"
] | null | null | null | /*Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1].
For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position.
Example:
Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40
Output: 2
Output is index of 40 in given array
Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90
Output: -1
-1 is returned to indicate element is not present
*/
#include <bits/stdc++.h>
using namespace std;
int binarysearch(int A[],int n,int key)
{
int low=0,high=n-1,mid;
while(low<=high)
{
mid=(low+high)/2;
if(A[mid]==key)
return mid;
if(A[mid+1]==key )
return mid+1;
if(A[mid-1]==key)
return mid-1;
if(key>A[mid])
{
low=mid+2;
}
else high=mid-2;
}
return -1;
}
int main()
{
int n;
cout<<"\nEnter number of elements->";
cin>>n;
int A[n];
for(int i=0;i<n;i++)
cin>>A[i];
int key;
cout<<"\nEnter the element u want to search->";
cin>>key;
int index=binarysearch(A,n,key);
if(index==-1)
{
cout<<"\nNot found!!!!!!";
exit(0);
}
cout<<'\n'<<key<<"Found at->"<<index;
return 0;
}
| 26.083333 | 313 | 0.53738 | shauryauppal |
4a32688bc6ba34f96da03103f07dc211f948f8b8 | 529 | cpp | C++ | aula10092020/retangulo.cpp | imdcode/imd0030_t02_2020 | 9c08e159752fa3d1169518fcc4a1046c045d7cec | [
"MIT"
] | 3 | 2020-09-23T00:59:43.000Z | 2020-10-06T22:27:00.000Z | aula10092020/retangulo.cpp | imdcode/imd0030_t02_2020 | 9c08e159752fa3d1169518fcc4a1046c045d7cec | [
"MIT"
] | null | null | null | aula10092020/retangulo.cpp | imdcode/imd0030_t02_2020 | 9c08e159752fa3d1169518fcc4a1046c045d7cec | [
"MIT"
] | 4 | 2020-10-05T05:36:25.000Z | 2020-12-08T02:47:32.000Z | #include <iostream>
#include "retangulo.hpp"
using std::cout;
using std::endl;
int Retangulo::getLargura() {
return largura;
}
void Retangulo::setLargura(int largura_) {
if (largura_ < 0) {
cout << "O valor da largura deve ser maior ou igual a zero." << endl;
} else {
largura = largura_;
}
}
int Retangulo::getAltura() {
return altura;
}
void Retangulo::setAltura(int altura_) {
altura = altura_;
}
int Retangulo::area() {
return altura*largura;
}
int Retangulo::perimetro() {
return (2*altura + 2*largura);
} | 16.53125 | 71 | 0.678639 | imdcode |
4a37d96cf9d056243d71c788eb078d88ef78a570 | 497 | hpp | C++ | src/loader/mod_package_loader.hpp | LeoCodes21/ModLoader | be2827f52390d77d7bf01b5f345092761b8f234d | [
"MIT"
] | 4 | 2020-07-05T15:13:35.000Z | 2021-02-04T00:03:01.000Z | src/loader/mod_package_loader.hpp | LeoCodes21/ModLoader | be2827f52390d77d7bf01b5f345092761b8f234d | [
"MIT"
] | 1 | 2020-11-25T03:14:37.000Z | 2020-11-25T03:14:37.000Z | src/loader/mod_package_loader.hpp | LeoCodes21/ModLoader | be2827f52390d77d7bf01b5f345092761b8f234d | [
"MIT"
] | 5 | 2020-03-22T19:22:27.000Z | 2021-02-21T15:22:58.000Z | //
// Created by coder on 3/17/2020.
//
#ifndef MODLOADER_MOD_PACKAGE_LOADER_HPP
#define MODLOADER_MOD_PACKAGE_LOADER_HPP
#include <filesystem>
#include "mod_package.hpp"
namespace fs = std::filesystem;
class mod_package_loader {
public:
mod_package_loader(std::string &server_id, fs::path &path);
~mod_package_loader() = default;
std::shared_ptr<mod_package> load();
private:
fs::path &m_path_;
std::string &m_server_id_;
};
#endif //MODLOADER_MOD_PACKAGE_LOADER_HPP
| 17.75 | 63 | 0.738431 | LeoCodes21 |
4a3997dd491fbc0f82d3a9540674e0dde872efae | 6,512 | hpp | C++ | libs/Core/include/argos-Core/Support/SyntaxPool.hpp | henrikfroehling/argos | 821ea18335838bcb2e88187adc12b59c51cd3522 | [
"MIT"
] | null | null | null | libs/Core/include/argos-Core/Support/SyntaxPool.hpp | henrikfroehling/argos | 821ea18335838bcb2e88187adc12b59c51cd3522 | [
"MIT"
] | 2 | 2022-02-16T23:58:02.000Z | 2022-03-16T20:53:15.000Z | libs/Core/include/argos-Core/Support/SyntaxPool.hpp | henrikfroehling/argos | 821ea18335838bcb2e88187adc12b59c51cd3522 | [
"MIT"
] | null | null | null | #ifndef ARGOS_CORE_SUPPORT_SYNTAXPOOL_H
#define ARGOS_CORE_SUPPORT_SYNTAXPOOL_H
#include <memory>
#include <unordered_map>
#include <vector>
#include "argos-Core/argos_global.hpp"
#include "argos-Core/Syntax/ISyntaxNode.hpp"
#include "argos-Core/Syntax/ISyntaxToken.hpp"
#include "argos-Core/Syntax/ISyntaxTrivia.hpp"
#include "argos-Core/Syntax/ISyntaxTriviaList.hpp"
#include "argos-Core/Syntax/SyntaxMissingToken.hpp"
#include "argos-Core/Syntax/SyntaxToken.hpp"
#include "argos-Core/Syntax/SyntaxTrivia.hpp"
#include "argos-Core/Syntax/SyntaxTriviaList.hpp"
#include "argos-Core/Types.hpp"
namespace argos::Core::Support
{
/**
* @brief Storage container for all created syntax elements.
*/
class ARGOS_CORE_API SyntaxPool final
{
public:
/**
* @brief Creates a <code>SyntaxPool</code> instance.
*/
SyntaxPool() noexcept = default;
/**
* @brief Creates a new <code>ISyntaxToken</code> with the given arguments.
* @param args The arguments for the <code>ISyntaxToken</code>s constructor.
*/
template <typename... TokenArgs>
const Syntax::ISyntaxToken* createSyntaxToken(TokenArgs&&... args) noexcept;
/**
* @brief Creates a new <code>ISyntaxMissingToken</code> with the given arguments.
* @param args The arguments for the <code>ISyntaxMissingToken</code>s constructor.
*/
template <typename... TokenArgs>
const Syntax::ISyntaxToken* createMissingSyntaxToken(TokenArgs&&... args) noexcept; // TODO Change return type to ISyntaxMissingToken
/**
* @brief Creates a new leading <code>ISyntaxTrivia</code> with the given arguments.
* @param args The arguments for the leading <code>ISyntaxTrivia</code>s constructor.
*/
template <typename... TriviaArgs>
const Syntax::ISyntaxTrivia* createLeadingTrivia(TriviaArgs&&... args) noexcept;
/**
* @brief Creates a new trailing <code>ISyntaxTrivia</code> with the given arguments.
* @param args The arguments for the trailing <code>ISyntaxTrivia</code>s constructor.
*/
template <typename... TriviaArgs>
const Syntax::ISyntaxTrivia* createTrailingTrivia(TriviaArgs&&... args) noexcept;
/**
* @brief Creates a new leading <code>ISyntaxTriviaList</code> for the <code>Token</code> at the given <code>tokenIndex</code>.
* @param tokenIndex The index of the <code>Token</code> for which the leading <code>ISyntaxTriviaList</code> will be created.
* @param args The arguments for the leading <code>ISyntaxTriviaList</code>s constructor.
*/
template <typename... TriviaListArgs>
void createLeadingTriviaList(argos_size tokenIndex,
TriviaListArgs&&... args) noexcept;
/**
* @brief Creates a new trailing <code>ISyntaxTriviaList</code> for the <code>Token</code> at the given <code>tokenIndex</code>.
* @param tokenIndex The index of the <code>Token</code> for which the trailing <code>ISyntaxTriviaList</code> will be created.
* @param args The arguments for the trailing <code>ISyntaxTriviaList</code>s constructor.
*/
template <typename... TriviaListArgs>
void createTrailingTriviaList(argos_size tokenIndex,
TriviaListArgs&&... args) noexcept;
/**
* @brief Creates a new <code>ISyntaxNode</code> with the given arguments.
* @param args The arguments for the <code>ISyntaxNode</code>s constructor.
*/
template <typename NodeType,
typename... NodeTypeArgs>
const NodeType* createSyntaxNode(NodeTypeArgs&&... args) noexcept;
const Syntax::ISyntaxTriviaList* leadingTriviaList(argos_size tokenIndex) const noexcept;
const Syntax::ISyntaxTriviaList* trailingTriviaList(argos_size tokenIndex) const noexcept;
private:
std::vector<std::shared_ptr<Syntax::ISyntaxToken>> _syntaxTokens{};
std::vector<std::shared_ptr<Syntax::ISyntaxNode>> _syntaxNodes{};
std::vector<std::shared_ptr<Syntax::ISyntaxTrivia>> _leadingSyntaxTrivia{};
std::vector<std::shared_ptr<Syntax::ISyntaxTrivia>> _trailingSyntaxTrivia{};
std::unordered_map<argos_size, std::shared_ptr<Syntax::ISyntaxTriviaList>> _leadingSyntaxTriviaLists{};
std::unordered_map<argos_size, std::shared_ptr<Syntax::ISyntaxTriviaList>> _trailingSyntaxTriviaLists{};
};
template <typename... TokenArgs>
const Syntax::ISyntaxToken* SyntaxPool::createSyntaxToken(TokenArgs&&... args) noexcept
{
_syntaxTokens.emplace_back(std::make_shared<Syntax::SyntaxToken>(std::forward<TokenArgs>(args)...));
return _syntaxTokens.back().get();
}
template <typename... TokenArgs>
const Syntax::ISyntaxToken* SyntaxPool::createMissingSyntaxToken(TokenArgs&&... args) noexcept
{
_syntaxTokens.emplace_back(std::make_shared<Syntax::SyntaxMissingToken>(std::forward<TokenArgs>(args)...));
return _syntaxTokens.back().get();
}
template <typename... TriviaArgs>
const Syntax::ISyntaxTrivia* SyntaxPool::createLeadingTrivia(TriviaArgs&&... args) noexcept
{
_leadingSyntaxTrivia.emplace_back(std::make_shared<Syntax::SyntaxTrivia>(std::forward<TriviaArgs>(args)...));
return _leadingSyntaxTrivia.back().get();
}
template <typename... TriviaArgs>
const Syntax::ISyntaxTrivia* SyntaxPool::createTrailingTrivia(TriviaArgs&&... args) noexcept
{
_trailingSyntaxTrivia.emplace_back(std::make_shared<Syntax::SyntaxTrivia>(std::forward<TriviaArgs>(args)...));
return _trailingSyntaxTrivia.back().get();
}
template <typename... TriviaListArgs>
void SyntaxPool::createLeadingTriviaList(argos_size tokenIndex,
TriviaListArgs&&... args) noexcept
{
_leadingSyntaxTriviaLists.try_emplace(tokenIndex, std::make_shared<Syntax::SyntaxTriviaList>(std::forward<TriviaListArgs>(args)...));
}
template <typename... TriviaListArgs>
void SyntaxPool::createTrailingTriviaList(argos_size tokenIndex,
TriviaListArgs&&... args) noexcept
{
_trailingSyntaxTriviaLists.try_emplace(tokenIndex, std::make_shared<Syntax::SyntaxTriviaList>(std::forward<TriviaListArgs>(args)...));
}
template <typename NodeType,
typename... NodeTypeArgs>
const NodeType* SyntaxPool::createSyntaxNode(NodeTypeArgs&&... args) noexcept
{
auto syntaxNode = std::make_shared<NodeType>(std::forward<NodeTypeArgs>(args)...);
auto returnValue = syntaxNode.get();
_syntaxNodes.push_back(std::move(syntaxNode));
return returnValue;
}
} // end namespace argos::Core::Support
#endif // ARGOS_CORE_SUPPORT_SYNTAXPOOL_H
| 42.285714 | 138 | 0.724355 | henrikfroehling |
6654c3d3a8690609b115e250c82c4b8bfa8c4ef1 | 7,848 | cpp | C++ | src/base64.cpp | abbyssoul/libsolace | 390c3094af1837715787c33297720bf514f04710 | [
"Apache-2.0"
] | 18 | 2016-05-30T23:46:27.000Z | 2022-01-11T18:20:28.000Z | src/base64.cpp | abbyssoul/libsolace | 390c3094af1837715787c33297720bf514f04710 | [
"Apache-2.0"
] | 4 | 2017-09-12T13:32:28.000Z | 2019-10-21T10:36:18.000Z | src/base64.cpp | abbyssoul/libsolace | 390c3094af1837715787c33297720bf514f04710 | [
"Apache-2.0"
] | 5 | 2017-11-24T19:34:06.000Z | 2019-10-18T14:24:12.000Z | /*
* Copyright 2017 Ivan Ryabov
*
* 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.
*/
/*******************************************************************************
* libSolace
* @file base64.cpp
* @brief Implementation of Base64 encoder and decoder.
******************************************************************************/
#include "solace/base64.hpp"
#include "solace/posixErrorDomain.hpp"
#include <climits>
using namespace Solace;
static constexpr byte kBase64Alphabet[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static constexpr byte kBase64UrlAlphabet[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
Result<void, Error>
base64encode(ByteWriter& dest, MemoryView const& src, byte const alphabet[65]) {
MemoryView::size_type i = 0;
for (; i + 2 < src.size(); i += 3) {
byte const encoded[] = {
alphabet[ (src[i] >> 2) & 0x3F],
alphabet[((src[i] & 0x3) << 4) | (static_cast<int>(src[i + 1] & 0xF0) >> 4)],
alphabet[((src[i + 1] & 0xF) << 2) | (static_cast<int>(src[i + 2] & 0xC0) >> 6)],
alphabet[ src[i + 2] & 0x3F]
};
auto res = dest.write(wrapMemory(encoded));
if (!res)
return res.moveError();
}
if (i < src.size()) {
byte encoded[4];
encoded[0] = alphabet[(src[i] >> 2) & 0x3F];
if (i + 1 == src.size()) {
encoded[1] = alphabet[((src[i] & 0x3) << 4)];
encoded[2] = '=';
} else {
encoded[1] = alphabet[((src[i] & 0x3) << 4) | (static_cast<int>(src[i + 1] & 0xF0) >> 4)];
encoded[2] = alphabet[((src[i + 1] & 0xF) << 2)];
}
encoded[3] = '=';
auto res = dest.write(wrapMemory(encoded));
if (!res)
return res.moveError();
}
return Ok();
}
/* aaaack but it's fast and const should make it shared text page. */
static const byte pr2six[256] = {
/* ASCII table */
// 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 00..0F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 10..1F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, 64, 63, // 20..2F
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 30..3F
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40..4F
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 64, // 50..5F
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60..6F
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 70..7F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 80..8F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 90..9F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // A0..AF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // B0..BF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // C0..CF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // D0..DF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // E0..EF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 // F0..FF
};
static const byte prUrl2six[256] = {
/* ASCII table */
// 00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 0A, 0B, 0C, 0D, 0E, 0F,
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 00..0F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 10..1F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 62, 64, 64, // 20..2F
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 64, 64, 64, 64, 64, // 30..3F
64, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, // 40..4F
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 64, 64, 64, 63, // 50..5F
64, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, // 60..6F
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 64, 64, 64, 64, 64, // 70..7F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 80..8F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 90..9F
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // A0..AF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // B0..BF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // C0..CF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // D0..DF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // E0..EF
64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64 // F0..FF
};
Result<void, Error>
base64decode(ByteWriter& dest, MemoryView src, byte const* decodingTable) {
if (src.empty()) {
return makeError(SystemErrors::NODATA, "base64decode");
}
byte const* bufin = src.begin();
while (decodingTable[*(bufin++)] <= 63) // Count decodable bytes
{}
auto nprbytes = (bufin - src.begin()) - 1;
bufin = src.begin();
while (nprbytes > 4) {
byte const encoded[] = {
static_cast<byte>(decodingTable[bufin[0]] << 2 | decodingTable[bufin[1]] >> 4),
static_cast<byte>(decodingTable[bufin[1]] << 4 | decodingTable[bufin[2]] >> 2),
static_cast<byte>(decodingTable[bufin[2]] << 6 | decodingTable[bufin[3]])
};
auto res = dest.write(wrapMemory(encoded));
if (!res)
return res.moveError();
bufin += 4;
nprbytes -= 4;
}
/* Note: (nprbytes == 1) would be an error, so just ingore that case */
if (nprbytes > 1) {
auto res = dest.write(static_cast<byte>(decodingTable[bufin[0]] << 2 | decodingTable[bufin[1]] >> 4));
if (!res)
return res.moveError();
}
if (nprbytes > 2) {
auto res = dest.write(static_cast<byte>(decodingTable[bufin[1]] << 4 | decodingTable[bufin[2]] >> 2));
if (!res)
return res.moveError();
}
if (nprbytes > 3) {
auto res = dest.write(static_cast<byte>(decodingTable[bufin[2]] << 6 | decodingTable[bufin[3]]));
if (!res)
return res.moveError();
}
return Ok();
}
Base64Encoder::size_type
Base64Encoder::encodedSize(size_type len) {
return ((4 * len / 3) + 3) & ~3;
}
Base64Decoder::size_type
Base64Decoder::decodedSize(MemoryView data) {
if (data.empty()) {
return 0;
}
if (data.size() % 4) {
return 0; // FIXME: Probably throw!
}
size_type nprbytes = 0;
for (const auto& b : data) {
if (pr2six[b] <= 63) {
++nprbytes;
} else {
break;
}
}
return (nprbytes * 3 / 4);
}
Base64Decoder::size_type
Base64Decoder::encodedSize(MemoryView data) const {
return decodedSize(data);
}
Result<void, Error>
Base64Encoder::encode(MemoryView src) {
return base64encode(*getDestBuffer(), src, kBase64Alphabet);
}
Result<void, Error>
Base64UrlEncoder::encode(MemoryView src) {
return base64encode(*getDestBuffer(), src, kBase64UrlAlphabet);
}
Result<void, Error>
Base64Decoder::encode(MemoryView src) {
return base64decode(*getDestBuffer(), src, pr2six);
}
Result<void, Error>
Base64UrlDecoder::encode(MemoryView src) {
return base64decode(*getDestBuffer(), src, prUrl2six);
}
| 35.192825 | 114 | 0.541157 | abbyssoul |
665a99b19c8f938f1889a8d7480d84add7512067 | 1,413 | cpp | C++ | src/omplapp/graphics/RenderGeometry.cpp | SZanlongo/omplapp | c56679337e2a71d266359450afbe63d700c0a666 | [
"BSD-3-Clause"
] | null | null | null | src/omplapp/graphics/RenderGeometry.cpp | SZanlongo/omplapp | c56679337e2a71d266359450afbe63d700c0a666 | [
"BSD-3-Clause"
] | null | null | null | src/omplapp/graphics/RenderGeometry.cpp | SZanlongo/omplapp | c56679337e2a71d266359450afbe63d700c0a666 | [
"BSD-3-Clause"
] | 1 | 2019-07-01T09:30:45.000Z | 2019-07-01T09:30:45.000Z | /*********************************************************************
* Rice University Software Distribution License
*
* Copyright (c) 2010, Rice University
* All Rights Reserved.
*
* For a full description see the file named LICENSE.
*
*********************************************************************/
/* Author: Ioan Sucan */
#include "omplapp/graphics/RenderGeometry.h"
#include "omplapp/graphics/detail/assimpGUtil.h"
#include "omplapp/graphics/detail/RenderPlannerData.h"
int ompl::app::RenderGeometry::renderEnvironment(void) const
{
const GeometrySpecification &gs = rbg_.getGeometrySpecification();
return scene::assimpRender(gs.obstacles, gs.obstaclesShift);
}
int ompl::app::RenderGeometry::renderRobot(void) const
{
const GeometrySpecification &gs = rbg_.getGeometrySpecification();
return scene::assimpRender(gs.robot, gs.robotShift);
}
int ompl::app::RenderGeometry::renderRobotPart(unsigned int index) const
{
const GeometrySpecification &gs = rbg_.getGeometrySpecification();
if (index >= gs.robot.size())
return 0;
return scene::assimpRender(gs.robot[index], gs.robotShift.size() > index ? gs.robotShift[index] : aiVector3D(0.0, 0.0, 0.0));
}
int ompl::app::RenderGeometry::renderPlannerData(const base::PlannerData &pd) const
{
return RenderPlannerData(pd, aiVector3D(0.0, 0.0, 0.0), rbg_.getMotionModel(), se_, rbg_.getLoadedRobotCount());
}
| 34.463415 | 129 | 0.669498 | SZanlongo |
6662d1f125d58e10c0535921002a78a797923a68 | 1,147 | cpp | C++ | BTTH05/01/PS.cpp | MiMi-Yup/sharing | 1a04a4fdd5e179bd5491725004931d0f71923262 | [
"BSD-4-Clause-UC"
] | null | null | null | BTTH05/01/PS.cpp | MiMi-Yup/sharing | 1a04a4fdd5e179bd5491725004931d0f71923262 | [
"BSD-4-Clause-UC"
] | null | null | null | BTTH05/01/PS.cpp | MiMi-Yup/sharing | 1a04a4fdd5e179bd5491725004931d0f71923262 | [
"BSD-4-Clause-UC"
] | null | null | null | #include "PS.h"
PS::PS(int tuso, int mauso) {
this->tuso = tuso;
this->mauso = mauso;
}
PS::PS(const PS& ps) {
this->tuso = ps.tuso;
this->mauso = ps.mauso;
}
int PS::UCLN(int a, int b) {
while (a * b != 0) {
if (a > b) {
a %= b;
}
else {
b %= a;
}
}
return a + b;
}
istream& operator>>(istream& is, PS& ps) {
do {
cout << "Nhap tu so: ";
is >> ps.tuso;
cout << "Nhap mau so khac 0: ";
is >> ps.mauso;
if (ps.mauso == 0)cout << "Phan so khong hop le, nhap lai.\n";
} while (ps.mauso == 0);
return is;
}
ostream& operator<<(ostream& os, PS ps) {
os << ps.getTu() << "/" << ps.getMau() << "\n";
return os;
}
int PS::getTu() {
return this->tuso;
}
int PS::getMau() {
return this->mauso;
}
void PS::setTu(int tuso) {
this->tuso = tuso;
}
void PS::setMau(int tuso) {
if (tuso != 0) {
this->tuso = tuso;
}
else {
cout << "Cap nhap that bai.\n";
}
}
void PS::Shorter() {
int uc = UCLN(tuso, mauso);
tuso /= uc;
mauso /= uc;
}
PS& PS::operator++() {
this->tuso += mauso;
this->Shorter();
return *this;
}
PS PS::operator++(int) {
PS temp(*this);
this->tuso += mauso;
this->Shorter();
return temp;
} | 16.867647 | 64 | 0.543156 | MiMi-Yup |
6665430965fdfd0db578199d98aacd16a0af9933 | 3,211 | hpp | C++ | fon9/io/SocketConfig.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 21 | 2019-01-29T14:41:46.000Z | 2022-03-11T00:22:56.000Z | fon9/io/SocketConfig.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | null | null | null | fon9/io/SocketConfig.hpp | fonwin/Plan | 3bfa9407ab04a26293ba8d23c2208bbececb430e | [
"Apache-2.0"
] | 9 | 2019-01-27T14:19:33.000Z | 2022-03-11T06:18:24.000Z | /// \file fon9/io/SocketConfig.hpp
/// \author [email protected]
#ifndef __fon9_io_SocketConfig_hpp__
#define __fon9_io_SocketConfig_hpp__
#include "fon9/io/IoBase.hpp"
#include "fon9/io/SocketAddress.hpp"
namespace fon9 { namespace io {
fon9_WARN_DISABLE_PADDING;
/// \ingroup io
/// Socket 基本參數.
struct fon9_API SocketOptions {
/// 使用 "TcpNoDelay=N" 關閉 TCP_NODELAY.
/// 預設為 Y.
int TCP_NODELAY_;
/// 使用 "SNDBUF=size" 設定.
/// SO_SNDBUF_ < 0: 使用系統預設值, 否則使用 SO_SNDBUF_ 的設定.
int SO_SNDBUF_;
/// 使用 "RCVBUF=size" 設定.
/// SO_RCVBUF_ < 0: 使用系統預設值, 否則使用 SO_RCVBUF_ 的設定.
int SO_RCVBUF_;
/// 使用 "ReuseAddr=Y" 設定: 請參閱 SO_REUSEADDR 的說明.
int SO_REUSEADDR_;
/// 使用 "ReusePort=Y" 設定: 請參閱 SO_REUSEPORT 的說明 (Windows沒有此選項).
int SO_REUSEPORT_;
/// 請參閱 SO_LINGER 的說明.
/// 使用 "Linger=N" 設定(開啟linger,但等候0秒): Linger_.l_onoff=1; Linger_.l_linger=0; 避免 TIME_WAIT.
/// |Linger_.l_onoff | Linger_.l_linger |
/// |:--------------:|:--------------------------------------------------------|
/// | 0 | 系統預設, close()立即返回, 但仍盡可能將剩餘資料送給對方.|
/// | 非0 | 0: 放棄未送出的資料,並送RST給對方,可避免 TIME_WAIT 狀態 |
/// | 非0 | 非0: close()等候秒數,或所有資料已送給對方,且正常結束連線|
struct linger Linger_;
/// 使用 "KeepAlive=n" 設定.
/// - <=0: 不使用 KEEPALIVE 選項(預設).
/// - ==1: 使用 SO_KEEPALIVE 設為 true, 其餘(間隔時間)為系統預設值.
/// - >1: TCP_KEEPIDLE,TCP_KEEPINTVL 的間隔秒數, 此時 TCP_KEEPCNT 一律設為 3.
int KeepAliveInterval_;
void SetDefaults();
ConfigParser::Result OnTagValue(StrView tag, StrView& value);
};
/// \ingroup io
/// Socket 設定.
struct fon9_API SocketConfig {
/// 綁定的 local address.
/// - Tcp Server: listen address & port.
/// - Tcp Client: local address & port.
SocketAddress AddrBind_;
/// 目的地位置.
/// - Tcp Server: 一般無此參數, 若有提供[專用Server]則可設定此參數, 收到連入連線後判斷是否是正確的來源.
/// - Tcp Client: 遠端Server的 address & port.
SocketAddress AddrRemote_;
SocketOptions Options_;
/// 取得 Address family: 透過 AddrBind_ 的 sa_family.
AddressFamily GetAF() const {
return static_cast<AddressFamily>(AddrBind_.Addr_.sa_family);
}
void SetDefaults();
/// - 如果沒有設定 AddrBind_ family 則使用 AddrRemote_ 的 sa_family;
/// - 如果沒有設定 AddrRemote_ family 則使用 AddrBind_ 的 sa_family;
void SetAddrFamily();
/// - "Bind=address:port" or "Bind=port"
/// - "Remote=address:port"
/// - 其餘轉給 this->Options_ 處理.
ConfigParser::Result OnTagValue(StrView tag, StrView& value);
struct fon9_API Parser : public ConfigParser {
fon9_NON_COPY_NON_MOVE(Parser);
SocketConfig& Owner_;
SocketAddress* AddrDefault_;
Parser(SocketConfig& owner, SocketAddress& addrDefault)
: Owner_(owner)
, AddrDefault_{&addrDefault} {
}
/// 解構時呼叫 this->Owner_.SetAddrFamily();
~Parser();
/// - 第一個沒有「=」的欄位(value.IsNull()): 將該值填入 *this->AddrDefault_;
/// 然後將 this->AddrDefault_ = nullptr;
/// 也就是只有第一個沒有「=」的欄位會填入 *this->AddrDefault_, 其餘視為錯誤.
/// - 其餘轉給 this->Owner_.OnTagValue() 處理.
Result OnTagValue(StrView tag, StrView& value) override;
};
};
fon9_WARN_POP;
} } // namespaces
#endif//__fon9_io_SocketConfig_hpp__
| 32.434343 | 93 | 0.628153 | fonwin |
6669dc244a2317eda8e4323d4e94150abb79e048 | 12,095 | cpp | C++ | Source/spells.cpp | nomdenom/devilution | 98a0692d14f338dc8f509c8424cab1ee6067a950 | [
"Unlicense"
] | 4 | 2018-09-24T17:02:21.000Z | 2021-05-27T08:42:50.000Z | Source/spells.cpp | nomdenom/devilution | 98a0692d14f338dc8f509c8424cab1ee6067a950 | [
"Unlicense"
] | null | null | null | Source/spells.cpp | nomdenom/devilution | 98a0692d14f338dc8f509c8424cab1ee6067a950 | [
"Unlicense"
] | null | null | null | //HEADER_GOES_HERE
#include "../types.h"
SpellData spelldata[MAX_SPELLS] = {
{ 0, 0, 0, NULL, NULL, 0, 0, FALSE, FALSE, 0, 0, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_FIREBOLT, 6, STYPE_FIRE, "Firebolt", "Firebolt", 1, 1, TRUE, FALSE, 15, IS_CAST2, { MIS_FIREBOLT, 0, 0 }, 1, 3, 40, 80, 1000, 50 },
{ SPL_HEAL, 5, STYPE_MAGIC, "Healing", NULL, 1, 1, FALSE, TRUE, 17, IS_CAST8, { MIS_HEAL, 0, 0 }, 3, 1, 20, 40, 1000, 50 },
{ SPL_LIGHTNING, 10, STYPE_LIGHTNING, "Lightning", NULL, 4, 3, TRUE, FALSE, 20, IS_CAST4, { MIS_LIGHTCTRL, 0, 0 }, 1, 6, 20, 60, 3000, 150 },
{ SPL_FLASH, 30, STYPE_LIGHTNING, "Flash", NULL, 5, 4, FALSE, FALSE, 33, IS_CAST4, { MIS_FLASH, MIS_FLASH2, 0 }, 2, 16, 20, 40, 7500, 500 },
{ SPL_IDENTIFY, 13, STYPE_MAGIC, "Identify", "Identify", -1, -1, FALSE, TRUE, 23, IS_CAST6, { MIS_IDENTIFY, 0, 0 }, 2, 1, 8, 12, 0, 100 },
{ SPL_FIREWALL, 28, STYPE_FIRE, "Fire Wall", NULL, 3, 2, TRUE, FALSE, 27, IS_CAST2, { MIS_FIREWALLC, 0, 0 }, 2, 16, 8, 16, 6000, 400 },
{ SPL_TOWN, 35, STYPE_MAGIC, "Town Portal", NULL, 3, 3, TRUE, FALSE, 20, IS_CAST6, { MIS_TOWN, 0, 0 }, 3, 18, 8, 12, 3000, 200 },
{ SPL_STONE, 60, STYPE_MAGIC, "Stone Curse", NULL, 6, 5, TRUE, FALSE, 51, IS_CAST2, { MIS_STONE, 0, 0 }, 3, 40, 8, 16, 12000, 800 },
{ SPL_INFRA, 40, STYPE_MAGIC, "Infravision", NULL, -1, -1, FALSE, FALSE, 36, IS_CAST8, { MIS_INFRA, 0, 0 }, 5, 20, 0, 0, 0, 600 },
{ SPL_RNDTELEPORT, 12, STYPE_MAGIC, "Phasing", NULL, 7, 6, FALSE, FALSE, 39, IS_CAST2, { MIS_RNDTELEPORT, 0, 0 }, 2, 4, 40, 80, 3500, 200 },
{ SPL_MANASHIELD, 33, STYPE_MAGIC, "Mana Shield", NULL, 6, 5, FALSE, FALSE, 25, IS_CAST2, { MIS_MANASHIELD, 0, 0 }, 0, 33, 4, 10, 16000, 1200 },
{ SPL_FIREBALL, 16, STYPE_FIRE, "Fireball", NULL, 8, 7, TRUE, FALSE, 48, IS_CAST2, { MIS_FIREBALL, 0, 0 }, 1, 10, 40, 80, 8000, 300 },
{ SPL_GUARDIAN, 50, STYPE_FIRE, "Guardian", NULL, 9, 8, TRUE, FALSE, 61, IS_CAST2, { MIS_GUARDIAN, 0, 0 }, 2, 30, 16, 32, 14000, 950 },
{ SPL_CHAIN, 30, STYPE_LIGHTNING, "Chain Lightning", NULL, 8, 7, FALSE, FALSE, 54, IS_CAST2, { MIS_CHAIN, 0, 0 }, 1, 18, 20, 60, 11000, 750 },
{ SPL_WAVE, 35, STYPE_FIRE, "Flame Wave", NULL, 9, 8, TRUE, FALSE, 54, IS_CAST2, { MIS_WAVE, 0, 0 }, 3, 20, 20, 40, 10000, 650 },
{ SPL_DOOMSERP, 0, STYPE_LIGHTNING, "Doom Serpents", NULL, -1, -1, FALSE, FALSE, 0, IS_CAST2, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_BLODRIT, 0, STYPE_MAGIC, "Blood Ritual", NULL, -1, -1, FALSE, FALSE, 0, IS_CAST2, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_NOVA, 60, STYPE_MAGIC, "Nova", NULL, -1, 10, FALSE, FALSE, 87, IS_CAST4, { MIS_NOVA, 0, 0 }, 3, 35, 16, 32, 21000, 1300 },
{ SPL_INVISIBIL, 0, STYPE_MAGIC, "Invisibility", NULL, -1, -1, FALSE, FALSE, 0, IS_CAST2, { 0, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_FLAME, 11, STYPE_FIRE, "Inferno", NULL, 3, 2, TRUE, FALSE, 20, IS_CAST2, { MIS_FLAMEC, 0, 0 }, 1, 6, 20, 40, 2000, 100 },
{ SPL_GOLEM, 100, STYPE_FIRE, "Golem", NULL, 11, 9, FALSE, FALSE, 81, IS_CAST2, { MIS_GOLEM, 0, 0 }, 6, 60, 16, 32, 18000, 1100 },
{ SPL_BLODBOIL, 0, STYPE_LIGHTNING, "Blood Boil", NULL, -1, -1, TRUE, FALSE, 0, IS_CAST8, { 0, 0, 0 }, 0, 0, 0, 0, 0, 0 },
{ SPL_TELEPORT, 35, STYPE_MAGIC, "Teleport", NULL, 14, 12, TRUE, FALSE, 105, IS_CAST6, { MIS_TELEPORT, 0, 0 }, 3, 15, 16, 32, 20000, 1250 },
{ SPL_APOCA, 150, STYPE_FIRE, "Apocalypse", NULL, -1, 15, FALSE, FALSE, 149, IS_CAST2, { MIS_APOCA, 0, 0 }, 6, 90, 8, 12, 30000, 2000 },
{ SPL_ETHEREALIZE, 100, STYPE_MAGIC, "Etherealize", NULL, -1, -1, FALSE, FALSE, 93, IS_CAST2, { MIS_ETHEREALIZE, 0, 0 }, 0, 100, 2, 6, 26000, 1600 },
{ SPL_REPAIR, 0, STYPE_MAGIC, "Item Repair", "Item Repair", -1, -1, FALSE, TRUE, -1, IS_CAST6, { MIS_REPAIR, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_RECHARGE, 0, STYPE_MAGIC, "Staff Recharge", "Staff Recharge", -1, -1, FALSE, TRUE, -1, IS_CAST6, { MIS_RECHARGE, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_DISARM, 0, STYPE_MAGIC, "Trap Disarm", "Trap Disarm", -1, -1, FALSE, FALSE, -1, IS_CAST6, { MIS_DISARM, 0, 0 }, 0, 0, 40, 80, 0, 0 },
{ SPL_ELEMENT, 35, STYPE_FIRE, "Elemental", NULL, 8, 6, FALSE, FALSE, 68, IS_CAST2, { MIS_ELEMENT, 0, 0 }, 2, 20, 20, 60, 10500, 700 },
{ SPL_CBOLT, 6, STYPE_LIGHTNING, "Charged Bolt", NULL, 1, 1, TRUE, FALSE, 25, IS_CAST2, { MIS_CBOLT, 0, 0 }, 1, 6, 40, 80, 1000, 50 },
{ SPL_HBOLT, 7, STYPE_MAGIC, "Holy Bolt", NULL, 1, 1, TRUE, FALSE, 20, IS_CAST2, { MIS_HBOLT, 0, 0 }, 1, 3, 40, 80, 1000, 50 },
{ SPL_RESURRECT, 20, STYPE_MAGIC, "Resurrect", NULL, -1, 5, FALSE, TRUE, 30, IS_CAST8, { MIS_RESURRECT, 0, 0 }, 0, 20, 4, 10, 4000, 250 },
{ SPL_TELEKINESIS, 15, STYPE_MAGIC, "Telekinesis", NULL, 2, 2, FALSE, FALSE, 33, IS_CAST2, { MIS_TELEKINESIS, 0, 0 }, 2, 8, 20, 40, 2500, 200 },
{ SPL_HEALOTHER, 5, STYPE_MAGIC, "Heal Other", NULL, 1, 1, FALSE, TRUE, 17, IS_CAST8, { MIS_HEALOTHER, 0, 0 }, 3, 1, 20, 40, 1000, 50 },
{ SPL_FLARE, 25, STYPE_MAGIC, "Blood Star", NULL, 14, 13, FALSE, FALSE, 70, IS_CAST2, { MIS_FLARE, 0, 0 }, 2, 14, 20, 60, 27500, 1800 },
{ SPL_BONESPIRIT, 24, STYPE_MAGIC, "Bone Spirit", NULL, 9, 7, FALSE, FALSE, 34, IS_CAST2, { MIS_BONESPIRIT, 0, 0 }, 1, 12, 20, 60, 11500, 800 }
};
int __fastcall GetManaAmount(int id, int sn)
{
int i; // "raw" mana cost
int ma; // mana amount
// mana adjust
int adj = 0;
// spell level
int sl = plr[id]._pSplLvl[sn] + plr[id]._pISplLvlAdd - 1;
if (sl < 0) {
sl = 0;
}
if (sl > 0) {
adj = sl * spelldata[sn].sManaAdj;
}
if (sn == SPL_FIREBOLT) {
adj >>= 1;
}
if (sn == SPL_RESURRECT && sl > 0) {
adj = sl * (spelldata[SPL_RESURRECT].sManaCost / 8);
}
if (spelldata[sn].sManaCost == 255) // TODO: check sign
{
i = (BYTE)plr[id]._pMaxManaBase;
} else {
i = spelldata[sn].sManaCost;
}
ma = (i - adj) << 6;
if (sn == SPL_HEAL) {
ma = (spelldata[SPL_HEAL].sManaCost + 2 * plr[id]._pLevel - adj) << 6;
}
if (sn == SPL_HEALOTHER) {
ma = (spelldata[SPL_HEAL].sManaCost + 2 * plr[id]._pLevel - adj) << 6;
}
if (plr[id]._pClass == PC_ROGUE) {
ma -= ma >> 2;
}
if (spelldata[sn].sMinMana > ma >> 6) {
ma = spelldata[sn].sMinMana << 6;
}
return ma * (100 - plr[id]._pISplCost) / 100;
}
void __fastcall UseMana(int id, int sn)
{
int ma; // mana cost
if (id == myplr) {
switch (plr[id]._pSplType) {
case RSPLTYPE_SPELL:
#ifdef _DEBUG
if (!debug_mode_key_inverted_v) {
#endif
ma = GetManaAmount(id, sn);
plr[id]._pMana -= ma;
plr[id]._pManaBase -= ma;
drawmanaflag = TRUE;
#ifdef _DEBUG
}
#endif
break;
case RSPLTYPE_SCROLL:
RemoveScroll(id);
break;
case RSPLTYPE_CHARGES:
UseStaffCharge(id);
break;
}
}
}
BOOL __fastcall CheckSpell(int id, int sn, BYTE st, BOOL manaonly)
{
#ifdef _DEBUG
if (debug_mode_key_inverted_v)
return TRUE;
#endif
BOOL result = TRUE;
if (!manaonly && pcurs != 1) {
result = FALSE;
} else {
if (st != RSPLTYPE_SKILL) {
if (GetSpellLevel(id, sn) <= 0) {
result = FALSE;
} else {
result = plr[id]._pMana >= GetManaAmount(id, sn);
}
}
}
return result;
}
void __fastcall CastSpell(int id, int spl, int sx, int sy, int dx, int dy, BOOL caster, int spllvl)
{
int dir; // missile direction
// ugly switch, but generates the right code
switch (caster) {
case TRUE:
dir = monster[id]._mdir;
break;
case FALSE:
// caster must be 0 already in this case, but oh well,
// it's needed to generate the right code
caster = 0;
dir = plr[id]._pdir;
if (spl == SPL_FIREWALL) {
dir = plr[id]._pVar3;
}
break;
}
for (int i = 0; spelldata[spl].sMissiles[i] != MIS_ARROW && i < 3; i++) {
AddMissile(sx, sy, dx, dy, dir, spelldata[spl].sMissiles[i], caster, id, 0, spllvl);
}
if (spelldata[spl].sMissiles[0] == MIS_TOWN) {
UseMana(id, SPL_TOWN);
}
if (spelldata[spl].sMissiles[0] == MIS_CBOLT) {
UseMana(id, SPL_CBOLT);
for (int i = 0; i < (spllvl >> 1) + 3; i++) {
AddMissile(sx, sy, dx, dy, dir, MIS_CBOLT, caster, id, 0, spllvl);
}
}
}
// pnum: player index
// rid: target player index
void __fastcall DoResurrect(int pnum, int rid)
{
if ((char)rid != -1) {
AddMissile(plr[rid].WorldX, plr[rid].WorldY, plr[rid].WorldX, plr[rid].WorldY, 0, MIS_RESURRECTBEAM, 0, pnum, 0, 0);
}
if (pnum == myplr) {
NewCursor(CURSOR_HAND);
}
if ((char)rid != -1 && plr[rid]._pHitPoints == 0) {
if (rid == myplr) {
deathflag = FALSE;
gamemenu_off();
drawhpflag = TRUE;
drawmanaflag = TRUE;
}
ClrPlrPath(rid);
plr[rid].destAction = ACTION_NONE;
plr[rid]._pInvincible = 0;
PlacePlayer(rid);
int hp = 640;
if (plr[rid]._pMaxHPBase < 640) {
hp = plr[rid]._pMaxHPBase;
}
SetPlayerHitPoints(rid, hp);
plr[rid]._pMana = 0;
plr[rid]._pHPBase = plr[rid]._pHitPoints + (plr[rid]._pMaxHPBase - plr[rid]._pMaxHP);
plr[rid]._pManaBase = plr[rid]._pMaxManaBase - plr[rid]._pMaxMana;
CalcPlrInv(rid, TRUE);
if (plr[rid].plrlevel == currlevel) {
StartStand(rid, plr[rid]._pdir);
} else {
plr[rid]._pmode = 0;
}
}
}
void __fastcall PlacePlayer(int pnum)
{
int nx;
int ny;
if (plr[pnum].plrlevel == currlevel) {
for (DWORD i = 0; i < 8; i++) {
nx = plr[pnum].WorldX + plrxoff2[i];
ny = plr[pnum].WorldY + plryoff2[i];
if (PosOkPlayer(pnum, nx, ny)) {
break;
}
}
if (!PosOkPlayer(pnum, nx, ny)) {
BOOL done = FALSE;
for (int max = 1, min = -1; min > -50 && !done; max++, min--) {
for (int y = min; y <= max && !done; y++) {
ny = plr[pnum].WorldY + y;
for (int x = min; x <= max && !done; x++) {
nx = plr[pnum].WorldX + x;
if (PosOkPlayer(pnum, nx, ny)) {
done = TRUE;
}
}
}
}
}
plr[pnum].WorldX = nx;
plr[pnum].WorldY = ny;
dPlayer[nx][ny] = pnum + 1;
if (pnum == myplr) {
ViewX = nx;
ViewY = ny;
}
}
}
void __fastcall DoHealOther(int pnum, int rid)
{
if (pnum == myplr) {
NewCursor(CURSOR_HAND);
}
if ((char)rid != -1 && (plr[rid]._pHitPoints >> 6) > 0) {
int hp = (random(57, 10) + 1) << 6;
for (int i = 0; i < plr[pnum]._pLevel; i++) {
hp += (random(57, 4) + 1) << 6;
}
for (int j = 0; j < GetSpellLevel(pnum, SPL_HEALOTHER); ++j) {
hp += (random(57, 6) + 1) << 6;
}
if (plr[pnum]._pClass == PC_WARRIOR) {
hp <<= 1;
}
if (plr[pnum]._pClass == PC_ROGUE) {
hp += hp >> 1;
}
plr[rid]._pHitPoints += hp;
if (plr[rid]._pHitPoints > plr[rid]._pMaxHP) {
plr[rid]._pHitPoints = plr[rid]._pMaxHP;
}
plr[rid]._pHPBase += hp;
if (plr[rid]._pHPBase > plr[rid]._pMaxHPBase) {
plr[rid]._pHPBase = plr[rid]._pMaxHPBase;
}
drawhpflag = TRUE;
}
}
| 38.275316 | 154 | 0.518561 | nomdenom |
666b7b7e6178d193ed53e9af879004db7faf907d | 3,228 | hpp | C++ | engine/src/utility/command.hpp | Sidharth-S-S/cloe | 974ef649e7dc6ec4e6869e4cf690c5b021e5091e | [
"Apache-2.0"
] | 20 | 2020-07-07T18:28:35.000Z | 2022-03-21T04:35:28.000Z | engine/src/utility/command.hpp | Sidharth-S-S/cloe | 974ef649e7dc6ec4e6869e4cf690c5b021e5091e | [
"Apache-2.0"
] | 46 | 2021-01-20T10:13:09.000Z | 2022-03-29T12:27:19.000Z | engine/src/utility/command.hpp | Sidharth-S-S/cloe | 974ef649e7dc6ec4e6869e4cf690c5b021e5091e | [
"Apache-2.0"
] | 12 | 2021-01-25T08:01:24.000Z | 2021-07-27T10:09:53.000Z | /*
* Copyright 2020 Robert Bosch GmbH
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* \file utility/command.hpp
* \see utility/command.cpp
*
* This file contains several types that make use of cloe::Command.
*/
#pragma once
#include <string> // for string
#include <system_error> // for system_error
#include <vector> // for vector<>
#include <boost/optional.hpp> // for optional<>
#include <boost/process/child.hpp> // for child
#include <cloe/core.hpp> // for Logger, Json, Conf, ...
#include <cloe/trigger.hpp> // for Action, ActionFactory, ...
#include <cloe/utility/command.hpp> // for Command
namespace engine {
struct CommandResult {
std::string name;
std::string command;
boost::optional<boost::process::child> child;
boost::optional<int> exit_code;
boost::optional<std::system_error> error;
std::vector<std::string> output;
};
class CommandExecuter {
public:
explicit CommandExecuter(cloe::Logger logger, bool enabled = true)
: logger_(logger), enabled_(enabled) {}
bool is_enabled() const { return enabled_; }
void set_enabled(bool v) { enabled_ = v; }
CommandResult run_and_release(const cloe::Command&) const;
void run(const cloe::Command&);
void run_all(const std::vector<cloe::Command>& cmds);
void wait(CommandResult&) const;
void wait_all();
std::vector<CommandResult> release_all();
cloe::Logger logger() const { return logger_; }
private:
std::vector<CommandResult> handles_;
cloe::Logger logger_{nullptr};
bool enabled_{false};
};
namespace actions {
class Command : public cloe::Action {
public:
Command(const std::string& name, const cloe::Command& cmd, CommandExecuter* exec)
: Action(name), command_(cmd), executer_(exec) {
assert(executer_ != nullptr);
}
cloe::ActionPtr clone() const override {
return std::make_unique<Command>(name(), command_, executer_);
}
void operator()(const cloe::Sync&, cloe::TriggerRegistrar&) override;
protected:
void to_json(cloe::Json& j) const override;
private:
cloe::Command command_;
CommandExecuter* executer_{nullptr};
};
class CommandFactory : public cloe::ActionFactory {
public:
using ActionType = Command;
explicit CommandFactory(CommandExecuter* exec)
: cloe::ActionFactory("command", "run a system command"), executer_(exec) {
assert(executer_ != nullptr);
}
cloe::TriggerSchema schema() const override;
cloe::ActionPtr make(const cloe::Conf& c) const override;
cloe::ActionPtr make(const std::string& s) const override;
private:
CommandExecuter* executer_{nullptr};
};
} // namespace actions
} // namespace engine
| 27.827586 | 83 | 0.701673 | Sidharth-S-S |
6678da66a2f24c7fc81b1bfb93c40b0ad6139e3f | 1,742 | cpp | C++ | Dialogs/blurdialog.cpp | kalpanki/ocvGUI | 9fc1f2278b414c316f091e1de5a4b1c4e3695ee9 | [
"BSD-2-Clause"
] | 2 | 2019-08-21T13:37:51.000Z | 2019-10-18T01:39:53.000Z | Dialogs/blurdialog.cpp | kalpanki/ocvGUI | 9fc1f2278b414c316f091e1de5a4b1c4e3695ee9 | [
"BSD-2-Clause"
] | null | null | null | Dialogs/blurdialog.cpp | kalpanki/ocvGUI | 9fc1f2278b414c316f091e1de5a4b1c4e3695ee9 | [
"BSD-2-Clause"
] | null | null | null | #include "blurdialog.h"
#include "ui_blurdialog.h"
#include <iostream>
using namespace std;
BlurDialog::BlurDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::BlurDialog)
{
ui->setupUi(this);
this->currentIndex = ui->BlurComboBox->currentIndex();
this->kernelH = ui->kernelHeightSpinBox->value();
this->kernelL = ui->KernelLenspinBox->value();
this->sigmaX = ui->sigmaXSpinBox->value();
this->sigmaY = ui->sigmaYSpinBox->value();
this->medianKernel = ui->medianKernelSpinBox->value();
}
BlurDialog::~BlurDialog()
{
delete ui;
}
void BlurDialog::on_BlurComboBox_currentIndexChanged(int index)
{
this->currentIndex = index;
emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel);
}
void BlurDialog::on_KernelLenspinBox_valueChanged(int val)
{
this->kernelL = val;
cout << "going to emit L" << endl;
emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel);
}
void BlurDialog::on_kernelHeightSpinBox_valueChanged(int val)
{
this->kernelH = val;
emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel);
}
void BlurDialog::on_sigmaXSpinBox_valueChanged(double val)
{
this->sigmaX = val;
emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel);
}
void BlurDialog::on_sigmaYSpinBox_valueChanged(double val)
{
this->sigmaY = val;
emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel);
}
void BlurDialog::on_medianKernelSpinBox_valueChanged(int val)
{
this->medianKernel = val;
emit sendBlurVals(currentIndex,kernelL, kernelH, sigmaX, sigmaY, medianKernel);
}
void BlurDialog::on_BlurCloseButton_clicked()
{
this->close();
}
| 26.393939 | 83 | 0.730195 | kalpanki |
667976e24f139ddb0d10d6c3f056d5374a2ccee1 | 5,484 | hpp | C++ | test/test-200-types/include/test-develop.hpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | null | null | null | test/test-200-types/include/test-develop.hpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | 49 | 2021-02-20T12:08:15.000Z | 2021-05-07T19:59:08.000Z | test/test-200-types/include/test-develop.hpp | Kartonagnick/tools-types | 4b3a697e579050eade081b82f9b96309fea8f5e7 | [
"MIT"
] | null | null | null | // [2021y-03m-10d][12:46:41] Idrisov Denis R.
#pragma once
#ifndef dTEST_DEVELOP_USED_
#define dTEST_DEVELOP_USED_ 1
#define CODE_GENERATION_ON
#define INCLUDE_AUTO_GENERATED
// #define INCLUDE_STRESS_TESTS
#define INCLUDE_LONG_LONG_TESTS
#define INCLUDE_LONG_TESTS
//==============================================================================
//===== tools/types/traits =================================||==================
#define TEST_IS_FLOATING // ready!
#define TEST_IS_SIGNED // ready!
#define TEST_IS_INTEGRAL // ready!
#define TEST_REMOVE_CV // ready!
#define TEST_CONDITIONAL // ready!
#define TEST_IS_SAME // ready!
#define TEST_ENABLE_IF // ready!
#define TEST_REMOVE_REFERENCE // ready!
#define TEST_DECAY // ready!
#define TEST_IS_CLASS // ready!
#define TEST_IS_CONST // ready!
#define TEST_IS_VOLATILE // ready!
#define TEST_IS_POINTER // ready!
#define TEST_IS_REFERENCE // ready!
#define TEST_REMOVE_POINTER // ready!
#define TEST_IS_FUNCTION // ready!
#define TEST_IS_ARRAY // ready!
#define TEST_IS_BASE_OF // ready!
#define TEST_IS_CONVERTIBLE // ready!
#define TEST_REMOVE_EXTENSION // ready!
#define TEST_REMOVE_ALL_EXTENSION // ready!
#define TEST_ADD_POINTER // ready!
#define TEST_IS_UNSIGNED // ready!
//==============================================================================
//===== tools/types/common =================================||==================
#define TEST_TOOLS_DEGRADATE // ready!
#define TEST_TOOLS_FOR_LVALUE // ready!
#define TEST_TOOLS_FOR_RVALUE // ready!
#define TEST_TOOLS_FIND_TYPE // ready!
#define TEST_TOOLS_IS_ZERO_ARRAY // ready!
#define TEST_TOOLS_SIZE_ARRAY // ready!
#define TEST_TOOLS_SMALL_ARRAY // ready!
#define TEST_TYPE_OF_ENUM // ready!
#define TEST_TOOLS_VARIADIC // ready!
#define TEST_TOOLS_IS_VOLATILE_DATA // ready!
#define TEST_TOOLS_IS_CONST_DATA // ready!
#define TEST_TOOLS_ADD_CONST_DATA // ready!
#define TEST_TOOLS_ENABLE_FOR // ready!
//==============================================================================
//===== tools/types/sfinae =================================||==================
#define TEST_TOOLS_SFINAE_DEREFERENCE // ready!
#define TEST_TOOLS_SFINAE_ACCESS // ready!
#define TEST_TOOLS_SFINAE_CALL // in progress...
#define TEST_TOOLS_SFINAE_BEGIN // ready!
#define TEST_TOOLS_SFINAE_END // ready!
//==============================================================================
//===== tools/types/sfinae =================================||==================
// #define TEST_TOOLS_DEREF_AVAILABLE // in progress...
#define TEST_TOOLS_SFINAE_CONCEPT // ready!
// #define TEST_TOOLS_IS_LAMBDA // in progress...
// #define TEST_TOOLS_IS_DEREFERENCABLE // in progress...
// #define TEST_TOOLS_HAS_OPERATOR_ACCESS // in progress...
// #define TEST_TOOLS_IS_INCREMENTABLE // in progress...
// #define TEST_TOOLS_IS_DECREMENTABLE // in progress...
// #define TEST_TOOLS_IS_ITERABLE // in progress...
// #define TEST_TOOLS_IS_ITERATOR // in progress...
// #define TEST_TOOLS_HAS_VALUE_TYPE // in progress...
// #define TEST_TOOLS_HAS_MAPPED_TYPE // in progress...
// #define TEST_TOOLS_HAS_BEGIN // in progress...
// #define TEST_TOOLS_HAS_END // in progress...
//==============================================================================
//===== tools/types ========================================||==================
#define TEST_TOOLS_FIXED // ready!
#define TEST_TOOLS_LIMIT // ready!
#define TEST_TOOLS_DEMANGLE // ready!
#define TEST_TOOLS_VOID_T // ready!
//==============================================================================
//==============================================================================
// in progress...
#endif // !dTEST_DEVELOP_USED_
| 58.340426 | 80 | 0.398432 | Kartonagnick |
6679f862eee8a9781371e0560ee2865749dd8c06 | 5,707 | cpp | C++ | Program Launcher/CCategory.cpp | barty32/program-launcher | f29277dda09f753e39258ff17af3b8c15d2504dc | [
"MIT"
] | null | null | null | Program Launcher/CCategory.cpp | barty32/program-launcher | f29277dda09f753e39258ff17af3b8c15d2504dc | [
"MIT"
] | null | null | null | Program Launcher/CCategory.cpp | barty32/program-launcher | f29277dda09f753e39258ff17af3b8c15d2504dc | [
"MIT"
] | null | null | null | //
// _
// ___ __ _| |_ ___ __ _ ___ _ __ _ _ ___ _ __ _ __
// / __/ _` | __/ _ \/ _` |/ _ \| '__| | | | / __| '_ \| '_ \
// | (_| (_| | || __/ (_| | (_) | | | |_| || (__| |_) | |_) |
// \___\__,_|\__\___|\__, |\___/|_| \__, (_)___| .__/| .__/
// |___/ |___/ |_| |_|
//
// This file contains functions related to Program Launcher's categories (in tab control)
//
// Functions included in this file:
//
// Copyright ©2021, barty12
// #include "LICENSE"
//
#include "pch.h"
#include "Program Launcher.h"
CCategory::CCategory(CProgramLauncher* ptrParent, const UINT parentIndex, const wstring& wsName)
:
ptrParent(ptrParent),
parentIndex(parentIndex),
wsCategoryName(wsName)
{
imSmall.Create(SMALL_ICON_SIZE, SMALL_ICON_SIZE, ILC_COLOR32, 0, 0);
imLarge.Create(Launcher->options.IconSize, Launcher->options.IconSize, ILC_COLOR32, 0, 0);
//CFile file(L"iconcache.db", CFile::modeRead);
//CArchive ar(&file, CArchive::load);
//imLarge.Read(&ar);
}
int CCategory::LoadElements(){
vItems.clear();
ElementProps props;
UINT j = 0;
for(; GetElementProperties(wsCategoryName, j, props); ++j){
vItems.push_back(make_shared<CLauncherItem>(this, j, props));
imLarge.Add(vItems[j]->LoadIcon(Launcher->options.IconSize));
imSmall.Add(vItems[j]->LoadIcon(SMALL_ICON_SIZE));
if(parentIndex == Launcher->GetCurrentCategoryIndex()){
vItems[j]->InsertIntoListView();
CMainWnd->m_statusBar.GetStatusBarCtrl().SetText(wstring(to_wstring(j) + L" items, loading...").c_str(), 255, 0);
//CMainWnd->m_statusBar.Invalidate();
}
}
CMainWnd->m_statusBar.GetStatusBarCtrl().SetText(wstring(to_wstring(j) + L" items").c_str(), 255, 0);
return j;
}
bool CCategory::Rename(){
CUserInputDlg dlg(wsCategoryName);
if(dlg.DoModal() == 1){
TCITEMW tie = {0};
tie.mask = TCIF_TEXT;
tie.pszText = wsCategoryName.data();
tie.cchTextMax = wsCategoryName.size();
CMainWnd->CTab.SetItem(parentIndex, &tie);
CMainWnd->Invalidate(false);
return true;
}
return false;
}
bool CCategory::Remove(bool bAsk, bool bKeepItems){
if(!bAsk || CMainWnd->MessageBoxW(std::format(GetString(IDS_REMOVE_CATEGORY_PROMPT), wsCategoryName).c_str(), GetString(IDS_REMOVE_CATEGORY).c_str(), MB_YESNO | MB_ICONEXCLAMATION) == IDYES){
UINT index = parentIndex;
Launcher->vCategories.erase(Launcher->vCategories.begin() + index);
Launcher->ReindexCategories(index);
CMainWnd->CTab.DeleteItem(index);
if(Launcher->vCategories.size() == 0){
CMainWnd->UpdateListView();
return true;
}
CMainWnd->CTab.SetCurSel(CMainWnd->CTab.GetItemCount() - 1);
CMainWnd->UpdateListView();
Launcher->bRebuildIconCache = true;
return true;
}
return false;
}
bool CCategory::Move(UINT newPos, bool bRelative){
if(bRelative){
newPos += parentIndex;
}
shared_ptr<CCategory> temp = ptrParent->vCategories[parentIndex];
if(parentIndex == newPos){
return true;
}
else if(newPos >= ptrParent->vCategories.size()){
return false;
}
else if(parentIndex < newPos){
for(UINT i = parentIndex; i < newPos; ++i){
ptrParent->vCategories[i] = ptrParent->vCategories[i + 1];
}
}
else{
for(UINT i = parentIndex; i > newPos; --i){
ptrParent->vCategories[i] = ptrParent->vCategories[i - 1];
}
}
ptrParent->vCategories[newPos] = temp;
ptrParent->ReindexCategories();
CMainWnd->UpdateListView(true);
Launcher->bRebuildIconCache = true;
return true;
}
bool CCategory::MoveTab(UINT newPos, bool bRelative){
if(bRelative){
newPos += parentIndex;
}
CMainWnd->CTab.ReorderTab(parentIndex, newPos);
return true;
}
void CCategory::ReindexItems(UINT iStart){
for(size_t i = iStart; i < vItems.size(); ++i){
vItems[i]->parentIndex = i;
}
}
CLauncherItem* CCategory::GetItem(UINT index){
return vItems.at(index).get();
}
CLauncherItem* CCategory::GetSelectedItem(){
return vItems.at(Launcher->GetSelectedItemIndex()).get();
}
// CUserInputDlg dialog
IMPLEMENT_DYNAMIC(CUserInputDlg, CDialog)
CUserInputDlg::CUserInputDlg(wstring& pName, CWnd* pParent /*=nullptr*/)
: CDialog(IDD_USERINPUTDLG, pParent),
m_wsName(pName){
}
CUserInputDlg::~CUserInputDlg(){}
void CUserInputDlg::DoDataExchange(CDataExchange* pDX){
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CUserInputDlg, CDialog)
ON_COMMAND(IDC_USERINPUTDLGEDIT, &CUserInputDlg::OnUserInput)
END_MESSAGE_MAP()
// CUserInputDlg message handlers
BOOL CUserInputDlg::OnInitDialog(){
CDialog::OnInitDialog();
//center the dialog
this->CenterWindow();
//set maximum number of characters to CATEGORY_NAME_LEN
this->SendDlgItemMessageW(IDC_USERINPUTDLGEDIT, EM_SETLIMITTEXT, CATEGORY_NAME_LEN);
if(!m_wsName.empty()){
this->SetWindowTextW(GetString(IDS_RENAME_CATEGORY).c_str());
this->GetDlgItem(IDC_USERINPUTDLGEDIT)->SetWindowTextW(m_wsName.c_str());
}
return true;
}
void CUserInputDlg::OnUserInput(){
// Set the default push button to "OK" when the user enters text.
//if(HIWORD(wParam) == EN_CHANGE){
this->SendMessageW(DM_SETDEFID, IDOK);
//}
}
void CUserInputDlg::OnOK(){
//CDialog::OnOK();
try{
CString name;
this->GetDlgItem(IDC_USERINPUTDLGEDIT)->GetWindowTextW(name);
if(name.GetLength() >= CATEGORY_NAME_LEN){
throw IDS_NAME_TOO_LONG;
}
if(name.GetLength() <= 0){
throw IDS_ENTER_VALID_NAME;
}
if(name.Find(CATEGORY_NAME_DELIM) != -1 || name == L"general" || name == L"appereance" || name == L"categories"){
throw IDS_NAME_INVALID_CHARACTERS;
}
m_wsName = name;
this->EndDialog(true);
return;
} catch(int code){
ErrorMsg(code);
return;
} catch(...){
ErrorMsg(IDS_ERROR);
ErrorHandlerDebug();
return;
}
}
| 25.823529 | 192 | 0.686175 | barty32 |
6682ad244c2bee9a0251cff2761fa395fef5ab07 | 1,529 | hpp | C++ | Parallel/OMPFor.hpp | DLancer999/SPHSimulator | 4f2f3a29d9769e62a9cae3d036b3e09dac99e305 | [
"MIT"
] | null | null | null | Parallel/OMPFor.hpp | DLancer999/SPHSimulator | 4f2f3a29d9769e62a9cae3d036b3e09dac99e305 | [
"MIT"
] | null | null | null | Parallel/OMPFor.hpp | DLancer999/SPHSimulator | 4f2f3a29d9769e62a9cae3d036b3e09dac99e305 | [
"MIT"
] | 1 | 2022-02-03T08:21:46.000Z | 2022-02-03T08:21:46.000Z |
/*************************************************************************\
License
Copyright (c) 2018 Kavvadias Ioannis.
This file is part of SPHSimulator.
Licensed under the MIT License. See LICENSE file in the project root for
full license information.
Description
Utility functions for ranges
SourceFiles
-
\************************************************************************/
#ifndef ParallelOMPFor_H
#define ParallelOMPFor_H
#include <cstdio>
#include <fstream>
#include <thread>
#include <iostream>
#include <string>
#include <omp.h>
#include "ParallelImpl.hpp"
#include <boost/program_options.hpp>
struct OMPFor : private ParallelImpl<OMPFor>
{
template <typename Functor>
static void For(size_t rangeSize, Functor f) {
#pragma omp parallel for
for (size_t i=0; i<rangeSize; ++i) {
f(i);
}
}
static void readSettings() {
int nThreads = 0;
std::ifstream Config_File("ParallelConfig.ini");
using namespace boost::program_options;
options_description SimSet("Settings");
SimSet.add_options()
("ParallelSettings.nThreads", value<int>(&nThreads));
variables_map vm;
store(parse_config_file(Config_File, SimSet), vm);
notify(vm);
if (!nThreads) {
nThreads = static_cast<int>(std::thread::hardware_concurrency());
if (!nThreads) {
std::cerr<<"Hardware_concurrency method failed!!"<<std::endl;
nThreads = 1;
}
}
omp_set_num_threads(nThreads);
}
};
#endif
| 22.485294 | 77 | 0.606279 | DLancer999 |
66965d15808e8f0b412b06866e9adb3e76a5d424 | 1,352 | hpp | C++ | include/cmn/rect.hpp | InsaneHamster/ihamster | 0f09e7eec3dff68ba7c2e899b03fd75940d3e242 | [
"MIT"
] | 1 | 2018-01-28T14:10:26.000Z | 2018-01-28T14:10:26.000Z | include/cmn/rect.hpp | InsaneHamster/ihamster | 0f09e7eec3dff68ba7c2e899b03fd75940d3e242 | [
"MIT"
] | null | null | null | include/cmn/rect.hpp | InsaneHamster/ihamster | 0f09e7eec3dff68ba7c2e899b03fd75940d3e242 | [
"MIT"
] | null | null | null | #pragma once
#include "point.hpp"
namespace cmn
{
template< typename T, int D >
struct rect_tt
{
typedef T value_type;
static int const dimension = D;
typedef point_tt<T,D> point_t;
point_t origin;
point_t size;
};
template<typename T>
struct rect_tt<T, 2>
{
typedef T value_type;
static int const dimension = 2;
typedef point_tt<T,dimension> point_t;
point_t origin;
point_t size;
rect_tt(){}
rect_tt( point_t const & _origin, point_t const & _size ) : origin(_origin), size(_size){}
rect_tt( T const & x, T const & y, T const & width, T const & height ) : origin(x,y), size(width, height){}
bool operator == (rect_tt const & other) const { return origin == other.origin && size == other.size; }
bool operator != (rect_tt const & other) const { return origin != other.origin || size != other.size; }
//will fail on unsigned
bool is_inside( point_t const & pt ) const { point_t s = pt - origin; if( s.x < 0 || s.y < 0 || s.x >= size.x || s.y >= size.y ) return false; else return true; };
};
typedef rect_tt< int, 2 > rect2i_t;
typedef rect_tt< float, 2 > rect2f_t;
}; | 30.727273 | 171 | 0.545118 | InsaneHamster |
669cbac0cbdd5507c183a99e9fda1953d9dae3ef | 776 | cpp | C++ | src/algorithms/warmup/plus_minus/plus_minus.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | src/algorithms/warmup/plus_minus/plus_minus.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | src/algorithms/warmup/plus_minus/plus_minus.cpp | bmgandre/hackerrank-cpp | f4af5777afba233c284790e02c0be7b82108c677 | [
"MIT"
] | null | null | null | #include "plus_minus.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace hackerrank::bmgandre::algorithms::warmup;
/// Practice>Algorithms>Warmup>Plus Minus
///
/// https://www.hackerrank.com/challenges/plus-minus
void plus_minus::solve()
{
auto count = 0;
std::cin >> count;
auto negatives = .0, positives = .0, zeros = .0, current = .0;
for (auto i = 0; i < count; i++) {
std::cin >> current;
if (current < 0) {
++negatives;
} else if (current > 0) {
++positives;
} else {
++zeros;
}
}
std::cout << std::setprecision(6) << std::fixed << positives / count << std::endl
<< std::setprecision(6) << std::fixed << negatives / count << std::endl
<< std::setprecision(6) << std::fixed << zeros / count << std::endl;
}
| 24.25 | 82 | 0.614691 | bmgandre |
66a043db9a0fe52d8c8ab13abe86d1b9e0e5c8ad | 3,648 | cpp | C++ | src/GUI/FileIO.cpp | davidgreisler/four-in-a-line | a21014e926df30359365d76510c64665e49096e3 | [
"MIT"
] | 4 | 2015-01-18T09:33:30.000Z | 2019-02-28T12:00:09.000Z | src/GUI/FileIO.cpp | davidgreisler/four-in-a-line | a21014e926df30359365d76510c64665e49096e3 | [
"MIT"
] | null | null | null | src/GUI/FileIO.cpp | davidgreisler/four-in-a-line | a21014e926df30359365d76510c64665e49096e3 | [
"MIT"
] | null | null | null | #include "FileIO.hpp"
#include <QFile>
#include <QTextStream>
#include <QFileDialog>
#include <QMessageBox>
namespace GUI
{
/**
* Opens the file with the given filename, reads the whole file and stores it in content.
*
* @param parentWidget Parent widget.
* @param fileName File name/path of the file.
* @param content Reference to a string where the file's content is stored.
* @return When the file has been read successfully true, otherwise false.
*/
bool FileIO::GetFileContent(QWidget* parentWidget, QString fileName, QByteArray& content)
{
QFile file(fileName);
if (file.open(QIODevice::ReadOnly))
{
QTextStream stream(&file);
content.append(stream.readAll());
return true;
}
else
{
QString errorMessage = QObject::tr("Failed to open the file '%1' for reading.");
QMessageBox::critical(parentWidget, QObject::tr("Failed to open file"),
errorMessage.arg(fileName),
QMessageBox::Abort);
}
return false;
}
/**
* Opens the file with the given filename for writing, truncates it and then writes content into the
* file.
*
* @param parentWidget Parent widget.
* @param fileName File name/path of the file.
* @param content Content to write into the file.
* @return When the content was written into the file successfully true, otherwise false.
*/
bool FileIO::SetFileContent(QWidget* parentWidget, QString fileName, const QByteArray& content)
{
QFile file(fileName);
if (file.open(QIODevice::WriteOnly | QIODevice::Truncate))
{
QTextStream stream(&file);
stream << content;
stream.flush();
return true;
}
else
{
QString errorMessage = QObject::tr("Failed to open the file '%1' for writing.");
QMessageBox::critical(parentWidget, QObject::tr("Failed to open file"),
errorMessage.arg(fileName),
QMessageBox::Abort);
}
return false;
}
/**
* Shows an open file dialog asking the user for one existing file and returns the specified
* filename.
*
* @param parentWidget Parent widget.
* @param fileName Reference to a string where the filename is stored.
* @param nameFilter Name filter for the open file dialog.
* @return When the user specified an existing file name true, otherwise false.
*/
bool FileIO::GetExistingFileName(QWidget* parentWidget, QString& fileName, QString nameFilter)
{
QFileDialog fileDialog(parentWidget);
fileDialog.setFileMode(QFileDialog::ExistingFile);
fileDialog.setNameFilter(nameFilter);
if (fileDialog.exec())
{
QStringList selectedFiles = fileDialog.selectedFiles();
if (!selectedFiles.empty())
{
fileName = selectedFiles.at(0);
return true;
}
}
return false;
}
/**
* Shows a save file dialog asking the user for one filename and returns the specified filename.
*
* @param parentWidget Parent widget.
* @param fileName Reference to a string where the filename is stored.
* @param defaultSuffix The default suffix to use.
* @param nameFilter Name filter for the save file dialog.
* @return When the user specified a file name true, otherwise false.
*/
bool FileIO::GetSaveFileName(QWidget* parentWidget,
QString& fileName, QString defaultSuffix, QString nameFilter)
{
QFileDialog fileDialog(parentWidget);
fileDialog.setFileMode(QFileDialog::AnyFile);
fileDialog.setAcceptMode(QFileDialog::AcceptSave);
fileDialog.setDefaultSuffix(defaultSuffix);
fileDialog.setNameFilter(nameFilter);
if (fileDialog.exec())
{
QStringList selectedFiles = fileDialog.selectedFiles();
if (!selectedFiles.empty())
{
fileName = selectedFiles.at(0);
return true;
}
}
return false;
}
}
| 26.627737 | 100 | 0.714638 | davidgreisler |
66a3907f117317eee1f35f0f5fb23e9a043976ce | 12,026 | cpp | C++ | graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_util.d3d12.cpp | nagakagachi/sample_projct | 300fcdaf65a009874ce1964a64682aeb6a6ef82e | [
"MIT"
] | null | null | null | graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_util.d3d12.cpp | nagakagachi/sample_projct | 300fcdaf65a009874ce1964a64682aeb6a6ef82e | [
"MIT"
] | null | null | null | graphics_test/graphics_test/src/ngl/rhi/d3d12/rhi_util.d3d12.cpp | nagakagachi/sample_projct | 300fcdaf65a009874ce1964a64682aeb6a6ef82e | [
"MIT"
] | null | null | null |
#include "rhi_util.d3d12.h"
namespace ngl
{
namespace rhi
{
DXGI_FORMAT ConvertResourceFormat(ResourceFormat v)
{
static DXGI_FORMAT table[] =
{
DXGI_FORMAT_UNKNOWN,
DXGI_FORMAT_R32G32B32A32_TYPELESS,
DXGI_FORMAT_R32G32B32A32_FLOAT,
DXGI_FORMAT_R32G32B32A32_UINT,
DXGI_FORMAT_R32G32B32A32_SINT,
DXGI_FORMAT_R32G32B32_TYPELESS,
DXGI_FORMAT_R32G32B32_FLOAT,
DXGI_FORMAT_R32G32B32_UINT,
DXGI_FORMAT_R32G32B32_SINT,
DXGI_FORMAT_R16G16B16A16_TYPELESS,
DXGI_FORMAT_R16G16B16A16_FLOAT,
DXGI_FORMAT_R16G16B16A16_UNORM,
DXGI_FORMAT_R16G16B16A16_UINT,
DXGI_FORMAT_R16G16B16A16_SNORM,
DXGI_FORMAT_R16G16B16A16_SINT,
DXGI_FORMAT_R32G32_TYPELESS,
DXGI_FORMAT_R32G32_FLOAT,
DXGI_FORMAT_R32G32_UINT,
DXGI_FORMAT_R32G32_SINT,
DXGI_FORMAT_R32G8X24_TYPELESS,
DXGI_FORMAT_D32_FLOAT_S8X24_UINT,
DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS,
DXGI_FORMAT_X32_TYPELESS_G8X24_UINT,
DXGI_FORMAT_R10G10B10A2_TYPELESS,
DXGI_FORMAT_R10G10B10A2_UNORM,
DXGI_FORMAT_R10G10B10A2_UINT,
DXGI_FORMAT_R11G11B10_FLOAT,
DXGI_FORMAT_R8G8B8A8_TYPELESS,
DXGI_FORMAT_R8G8B8A8_UNORM,
DXGI_FORMAT_R8G8B8A8_UNORM_SRGB,
DXGI_FORMAT_R8G8B8A8_UINT,
DXGI_FORMAT_R8G8B8A8_SNORM,
DXGI_FORMAT_R8G8B8A8_SINT,
DXGI_FORMAT_R16G16_TYPELESS,
DXGI_FORMAT_R16G16_FLOAT,
DXGI_FORMAT_R16G16_UNORM,
DXGI_FORMAT_R16G16_UINT,
DXGI_FORMAT_R16G16_SNORM,
DXGI_FORMAT_R16G16_SINT,
DXGI_FORMAT_R32_TYPELESS,
DXGI_FORMAT_D32_FLOAT,
DXGI_FORMAT_R32_FLOAT,
DXGI_FORMAT_R32_UINT,
DXGI_FORMAT_R32_SINT,
DXGI_FORMAT_R24G8_TYPELESS,
DXGI_FORMAT_D24_UNORM_S8_UINT,
DXGI_FORMAT_R24_UNORM_X8_TYPELESS,
DXGI_FORMAT_X24_TYPELESS_G8_UINT,
DXGI_FORMAT_R8G8_TYPELESS,
DXGI_FORMAT_R8G8_UNORM,
DXGI_FORMAT_R8G8_UINT,
DXGI_FORMAT_R8G8_SNORM,
DXGI_FORMAT_R8G8_SINT,
DXGI_FORMAT_R16_TYPELESS,
DXGI_FORMAT_R16_FLOAT,
DXGI_FORMAT_D16_UNORM,
DXGI_FORMAT_R16_UNORM,
DXGI_FORMAT_R16_UINT,
DXGI_FORMAT_R16_SNORM,
DXGI_FORMAT_R16_SINT,
DXGI_FORMAT_R8_TYPELESS,
DXGI_FORMAT_R8_UNORM,
DXGI_FORMAT_R8_UINT,
DXGI_FORMAT_R8_SNORM,
DXGI_FORMAT_R8_SINT,
DXGI_FORMAT_A8_UNORM,
DXGI_FORMAT_R1_UNORM,
DXGI_FORMAT_R9G9B9E5_SHAREDEXP,
DXGI_FORMAT_R8G8_B8G8_UNORM,
DXGI_FORMAT_G8R8_G8B8_UNORM,
DXGI_FORMAT_BC1_TYPELESS,
DXGI_FORMAT_BC1_UNORM,
DXGI_FORMAT_BC1_UNORM_SRGB,
DXGI_FORMAT_BC2_TYPELESS,
DXGI_FORMAT_BC2_UNORM,
DXGI_FORMAT_BC2_UNORM_SRGB,
DXGI_FORMAT_BC3_TYPELESS,
DXGI_FORMAT_BC3_UNORM,
DXGI_FORMAT_BC3_UNORM_SRGB,
DXGI_FORMAT_BC4_TYPELESS,
DXGI_FORMAT_BC4_UNORM,
DXGI_FORMAT_BC4_SNORM,
DXGI_FORMAT_BC5_TYPELESS,
DXGI_FORMAT_BC5_UNORM,
DXGI_FORMAT_BC5_SNORM,
DXGI_FORMAT_B5G6R5_UNORM,
DXGI_FORMAT_B5G5R5A1_UNORM,
DXGI_FORMAT_B8G8R8A8_UNORM,
DXGI_FORMAT_B8G8R8X8_UNORM,
DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM,
DXGI_FORMAT_B8G8R8A8_TYPELESS,
DXGI_FORMAT_B8G8R8A8_UNORM_SRGB,
DXGI_FORMAT_B8G8R8X8_TYPELESS,
DXGI_FORMAT_B8G8R8X8_UNORM_SRGB,
DXGI_FORMAT_BC6H_TYPELESS,
DXGI_FORMAT_BC6H_UF16,
DXGI_FORMAT_BC6H_SF16,
DXGI_FORMAT_BC7_TYPELESS,
DXGI_FORMAT_BC7_UNORM,
DXGI_FORMAT_BC7_UNORM_SRGB,
DXGI_FORMAT_AYUV,
DXGI_FORMAT_Y410,
DXGI_FORMAT_Y416,
DXGI_FORMAT_NV12,
DXGI_FORMAT_P010,
DXGI_FORMAT_P016,
DXGI_FORMAT_420_OPAQUE,
DXGI_FORMAT_YUY2,
DXGI_FORMAT_Y210,
DXGI_FORMAT_Y216,
DXGI_FORMAT_NV11,
DXGI_FORMAT_AI44,
DXGI_FORMAT_IA44,
DXGI_FORMAT_P8,
DXGI_FORMAT_A8P8,
DXGI_FORMAT_B4G4R4A4_UNORM
};
static_assert(std::size(table) == static_cast<size_t>(ResourceFormat::_MAX), "");
// 現状はDXGIと一対一の対応
return table[static_cast<u32>(v)];
}
D3D12_RESOURCE_STATES ConvertResourceState(ResourceState v)
{
D3D12_RESOURCE_STATES ret = {};
switch (v)
{
case ResourceState::Common:
{
ret = D3D12_RESOURCE_STATE_COMMON;
break;
}
case ResourceState::General:
{
ret = D3D12_RESOURCE_STATE_GENERIC_READ;
break;
}
case ResourceState::ConstatnBuffer:
{
ret = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
break;
}
case ResourceState::VertexBuffer:
{
ret = D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER;
break;
}
case ResourceState::IndexBuffer:
{
ret = D3D12_RESOURCE_STATE_INDEX_BUFFER;
break;
}
case ResourceState::RenderTarget:
{
ret = D3D12_RESOURCE_STATE_RENDER_TARGET;
break;
}
case ResourceState::ShaderRead:
{
ret = D3D12_RESOURCE_STATE_PIXEL_SHADER_RESOURCE;
break;
}
case ResourceState::UnorderedAccess:
{
ret = D3D12_RESOURCE_STATE_UNORDERED_ACCESS;
break;
}
case ResourceState::DepthWrite:
{
ret = D3D12_RESOURCE_STATE_DEPTH_WRITE;
break;
}
case ResourceState::DepthRead:
{
ret = D3D12_RESOURCE_STATE_DEPTH_READ;
break;
}
case ResourceState::IndirectArgument:
{
ret = D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT;
break;
}
case ResourceState::CopyDst:
{
ret = D3D12_RESOURCE_STATE_COPY_DEST;
break;
}
case ResourceState::CopySrc:
{
ret = D3D12_RESOURCE_STATE_COPY_SOURCE;
break;
}
case ResourceState::Present:
{
ret = D3D12_RESOURCE_STATE_PRESENT;
break;
}
default:
{
std::cout << "ERROR : Invalid Resource State" << std::endl;
}
}
return ret;
}
D3D12_BLEND_OP ConvertBlendOp(BlendOp v)
{
switch (v)
{
case BlendOp::Add:
{
return D3D12_BLEND_OP_ADD;
}
case BlendOp::Subtract:
{
return D3D12_BLEND_OP_SUBTRACT;
}
case BlendOp::RevSubtract:
{
return D3D12_BLEND_OP_REV_SUBTRACT;
}
case BlendOp::Min:
{
return D3D12_BLEND_OP_MIN;
}
case BlendOp::Max:
{
return D3D12_BLEND_OP_MAX;
}
default:
{
return D3D12_BLEND_OP_ADD;
}
}
}
D3D12_BLEND ConvertBlendFactor(BlendFactor v)
{
switch (v)
{
case BlendFactor::Zero:
{
return D3D12_BLEND_ZERO;
}
case BlendFactor::One:
{
return D3D12_BLEND_ONE;
}
case BlendFactor::SrcColor:
{
return D3D12_BLEND_SRC_COLOR;
}
case BlendFactor::InvSrcColor:
{
return D3D12_BLEND_INV_SRC_COLOR;
}
case BlendFactor::SrcAlpha:
{
return D3D12_BLEND_SRC_ALPHA;
}
case BlendFactor::InvSrcAlpha:
{
return D3D12_BLEND_INV_SRC_ALPHA;
}
case BlendFactor::DestAlpha:
{
return D3D12_BLEND_DEST_ALPHA;
}
case BlendFactor::InvDestAlpha:
{
return D3D12_BLEND_INV_DEST_ALPHA;
}
case BlendFactor::DestColor:
{
return D3D12_BLEND_DEST_COLOR;
}
case BlendFactor::InvDestColor:
{
return D3D12_BLEND_INV_DEST_COLOR;
}
case BlendFactor::SrcAlphaSat:
{
return D3D12_BLEND_SRC_ALPHA_SAT;
}
case BlendFactor::BlendFactor:
{
return D3D12_BLEND_BLEND_FACTOR;
}
case BlendFactor::InvBlendFactor:
{
return D3D12_BLEND_INV_BLEND_FACTOR;
}
case BlendFactor::Src1Color:
{
return D3D12_BLEND_SRC1_COLOR;
}
case BlendFactor::InvSrc1Color:
{
return D3D12_BLEND_INV_SRC1_COLOR;
}
case BlendFactor::Src1Alpha:
{
return D3D12_BLEND_SRC1_ALPHA;
}
case BlendFactor::InvSrc1Alpha:
{
return D3D12_BLEND_INV_SRC1_ALPHA;
}
default:
{
return D3D12_BLEND_ONE;
}
}
}
D3D12_CULL_MODE ConvertCullMode(CullingMode v)
{
switch (v)
{
case CullingMode::Front:
return D3D12_CULL_MODE_FRONT;
case CullingMode::Back:
return D3D12_CULL_MODE_BACK;
default:
return D3D12_CULL_MODE_NONE;
}
}
D3D12_FILL_MODE ConvertFillMode(FillMode v)
{
switch (v)
{
case FillMode::Wireframe:
return D3D12_FILL_MODE_WIREFRAME;
case FillMode::Solid:
return D3D12_FILL_MODE_SOLID;
default:
return D3D12_FILL_MODE_SOLID;
}
}
D3D12_STENCIL_OP ConvertStencilOp(StencilOp v)
{
switch (v)
{
case StencilOp::Keep:
return D3D12_STENCIL_OP_KEEP;
case StencilOp::Zero:
return D3D12_STENCIL_OP_ZERO;
case StencilOp::Replace:
return D3D12_STENCIL_OP_REPLACE;
case StencilOp::IncrSat:
return D3D12_STENCIL_OP_INCR_SAT;
case StencilOp::DecrSat:
return D3D12_STENCIL_OP_DECR_SAT;
case StencilOp::Invert:
return D3D12_STENCIL_OP_INVERT;
case StencilOp::Incr:
return D3D12_STENCIL_OP_INCR;
case StencilOp::Decr:
return D3D12_STENCIL_OP_DECR;
default:
return D3D12_STENCIL_OP_KEEP;
}
}
D3D12_COMPARISON_FUNC ConvertComparisonFunc(CompFunc v)
{
switch (v)
{
case CompFunc::Never:
return D3D12_COMPARISON_FUNC_NEVER;
case CompFunc::Less:
return D3D12_COMPARISON_FUNC_LESS;
case CompFunc::Equal:
return D3D12_COMPARISON_FUNC_EQUAL;
case CompFunc::LessEqual:
return D3D12_COMPARISON_FUNC_LESS_EQUAL;
case CompFunc::Greater:
return D3D12_COMPARISON_FUNC_GREATER;
case CompFunc::NotEqual:
return D3D12_COMPARISON_FUNC_NOT_EQUAL;
case CompFunc::GreaterEqual:
return D3D12_COMPARISON_FUNC_GREATER_EQUAL;
case CompFunc::Always:
return D3D12_COMPARISON_FUNC_ALWAYS;
default:
return D3D12_COMPARISON_FUNC_ALWAYS;
}
}
D3D12_PRIMITIVE_TOPOLOGY_TYPE ConvertPrimitiveTopologyType(PrimitiveTopologyType v)
{
switch (v)
{
case PrimitiveTopologyType::Point:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT;
case PrimitiveTopologyType::Line:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE;
case PrimitiveTopologyType::Triangle:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
case PrimitiveTopologyType::Patch:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_PATCH;
default:
return D3D12_PRIMITIVE_TOPOLOGY_TYPE_UNDEFINED;
}
}
D3D_PRIMITIVE_TOPOLOGY ConvertPrimitiveTopology(ngl::rhi::PrimitiveTopology v)
{
switch (v)
{
case PrimitiveTopology::PointList:
return D3D_PRIMITIVE_TOPOLOGY_POINTLIST;
case PrimitiveTopology::LineList:
return D3D_PRIMITIVE_TOPOLOGY_LINELIST;
case PrimitiveTopology::LineStrip:
return D3D_PRIMITIVE_TOPOLOGY_LINESTRIP;
case PrimitiveTopology::TriangleList:
return D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
case PrimitiveTopology::TriangleStrip:
return D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
default:
assert(false);
return D3D_PRIMITIVE_TOPOLOGY_UNDEFINED;
}
}
D3D12_FILTER ConvertTextureFilter(TextureFilterMode v)
{
static constexpr D3D12_FILTER table[] =
{
D3D12_FILTER_MIN_MAG_MIP_POINT,
D3D12_FILTER_MIN_MAG_POINT_MIP_LINEAR,
D3D12_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT,
D3D12_FILTER_MIN_POINT_MAG_MIP_LINEAR,
D3D12_FILTER_MIN_LINEAR_MAG_MIP_POINT,
D3D12_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR,
D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT,
D3D12_FILTER_MIN_MAG_MIP_LINEAR,
D3D12_FILTER_ANISOTROPIC,
D3D12_FILTER_COMPARISON_MIN_MAG_MIP_POINT,
D3D12_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR,
D3D12_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT,
D3D12_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR,
D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT,
D3D12_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR,
D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT,
D3D12_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR,
D3D12_FILTER_COMPARISON_ANISOTROPIC
};
assert(std::size(table) > static_cast<size_t>(v));
return table[static_cast<size_t>(v)];
}
D3D12_TEXTURE_ADDRESS_MODE ConvertTextureAddressMode(TextureAddressMode v)
{
static constexpr D3D12_TEXTURE_ADDRESS_MODE table[] =
{
D3D12_TEXTURE_ADDRESS_MODE_WRAP,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR,
D3D12_TEXTURE_ADDRESS_MODE_CLAMP,
D3D12_TEXTURE_ADDRESS_MODE_BORDER,
D3D12_TEXTURE_ADDRESS_MODE_MIRROR_ONCE
};
assert(std::size(table) > static_cast<size_t>(v));
return table[static_cast<size_t>(v)];
}
}
} | 23.580392 | 85 | 0.741144 | nagakagachi |
66b67c2affc8a6f7db4583a13eaf253b5d9edb44 | 943 | cpp | C++ | BMCP/Coloring.cpp | TomaszRewak/BMCP | 99e94b11f70658d9b8de792b36af7ecbb215d665 | [
"MIT"
] | 2 | 2019-11-04T15:09:52.000Z | 2022-01-12T05:41:16.000Z | BMCP/Coloring.cpp | TomaszRewak/BMCP | 99e94b11f70658d9b8de792b36af7ecbb215d665 | [
"MIT"
] | null | null | null | BMCP/Coloring.cpp | TomaszRewak/BMCP | 99e94b11f70658d9b8de792b36af7ecbb215d665 | [
"MIT"
] | 1 | 2020-09-09T12:24:35.000Z | 2020-09-09T12:24:35.000Z | // ========================================
// ======= Created by Tomasz Rewak ========
// ========================================
// ==== https://github.com/TomaszRewak ====
// ========================================
#include "Coloring.h"
namespace BMCP
{
size_t Coloring::size()
{
return genotype.size();
}
Coloring::Coloring(Graph& graph)
{
genotype.resize(graph.nodes.size());
for (size_t i = 0; i < graph.nodes.size(); i++)
genotype[i] = std::vector<int>(graph.nodes[i].weight, 0);
}
void Coloring::sortNode(int i)
{
std::sort(genotype[i].begin(), genotype[i].end());
}
void Coloring::sort()
{
for (int i = 0; i < genotype.size(); i++)
sortNode(i);
}
std::ostream& operator<<(std::ostream& stream, Coloring& specimen) {
for (int i = 0; i < specimen.size(); i++) {
stream << (i + 1);
for (int g : specimen.genotype[i])
stream << " " << g;
stream << std::endl;
}
return stream;
}
} | 20.955556 | 69 | 0.498409 | TomaszRewak |
66b6c0c945523ad16100001e06698e0eeed87762 | 3,496 | hpp | C++ | src/includes/utils.hpp | WillBlack403/ZKP-onehot | 42119353c6dfe3970267de1cb53d537854671f14 | [
"MIT"
] | null | null | null | src/includes/utils.hpp | WillBlack403/ZKP-onehot | 42119353c6dfe3970267de1cb53d537854671f14 | [
"MIT"
] | null | null | null | src/includes/utils.hpp | WillBlack403/ZKP-onehot | 42119353c6dfe3970267de1cb53d537854671f14 | [
"MIT"
] | null | null | null | /*Author: William Black,
* Ryan Henry
*Email: [email protected],
* [email protected]
*Date: 2019/06/28
*Project: Proof Of Concept for: There are 10 Types of Vectors (and Polynomials)
*File:utils.hpp
* Contains function declations of utility functions used in this project.
*/
#ifndef __horners_hpp__
#define __horners_hpp__
#include<gmpxx.h>
#include<NTL/ZZ_p.h>
#include<NTL/ZZ_pX.h>
extern"C"{
#include<relic/relic_core.h>
}
#include"pedersen.hpp"
#include<vector>
using namespace NTL;
using namespace std;
/* Function: horners_method
*
* Computes the evaluation of a polynomial with coefficients as commitments, done using horners method for evaluation of polynomials.
*
* vector<Pedersen_Commitments>: coefficients of the polynomial
* size_t: number of coefficients
* bn_t: value to evaluate the polynomail at.
*
* Returns: Pedersen_Commitment to the evaluation.
*/
Pedersen_Commitment horners_method(vector<Pedersen_Commitment>,size_t,bn_t);
/* Function: horners_method
*
* Computes the evaluation of a polynomial with coefficients in Zp, done using NTL's polynomial evaluation.
*
* vector<ZZ_p>: coefficients of the polynomial
* ZZ_p: Value ot evaluate the polynomial at.
*
* Return: ZZ_p, the evaluation of the polynomail at set value.
*/
ZZ_p horners_method(vector<ZZ_p>,ZZ_p);
/*Function: multi_exp
*
* Computes the value defined by commitments[1]^exponents[1]*...*commitment[n]^exponents[n].
*
* Pedersen P: Used to create Pedersen_Commitments.
* vector<Pederesen_Commitment> commitments: The vector of commitments to be raised to exponents,
* vector<ZZ_p> exponents: The vector of ZZ_p used to raise the commitment to.
* const uint window_size: The the size of the preoccupation step reasonable values are between [1-8]
*
* Returns: Result of the computation.
*/
Pedersen_Commitment multi_exp(Pedersen& P,vector<Pedersen_Commitment> commitments,vector<ZZ_p> exponents, const uint window_size);
/*Function: multi_exp_sub -- multi-exponentiation-subcomputation
*
* Call multi_exp on subsets of the larges computation; this should be used if ram is exceeded.
*
* const int chunks: number of descrete disjoint subsets to call multiexp on.
*
* Returns: result
*/
Pedersen_Commitment multi_exp_sub(Pedersen& P, vector<Pedersen_Commitment> commitments, vector<ZZ_p> exponents,const int window_size, const int chucks);
/*Function: conv
*
* Converts between NTL and RELIC-Toolkit
*
* bn_t out: Relic big integer
* ZZ_p in: NTL big integer subject to prime p
*/
void conv(bn_t out, ZZ_p in);
/*Function: conv
*
* Converts between NTL and RELIC-Toolkit
*
* bn_t in: Relic big integer
* ZZ_p out: NTL big integer subject to prime p
*/
void conv(ZZ_p& out, bn_t in);
/*Function: conv
*
* Converts between NTL and RELIC-Toolkit
*
* bn_t in: Relic big integer
* ZZ out: NTL big integer
*/
void conv(ZZ& out,bn_t in);
/* Function: genRandomT
*
* Creates a random value subject to the defined security parameters.
*
* uint lambda: desired security such that soundness is 2^{-lambda}
* uint bitlength: bitlength=lg(N) such that N is the length of the vector in the ZKP
*
* Returns: random value.
*/
ZZ_p genRandomT(uint lambda, uint bitlength);
/* Function: genRandom
*
* Creates random value subject ot defined security parameter
*
* unint lambda: desired security such that soundness is 2^{-lambda}
*
* Returns: random value.
*/
ZZ_p genRandom(uint lambda);
#endif | 29.880342 | 152 | 0.741419 | WillBlack403 |
66ba586ba3c57343ffa3c0dd543a2a312e372c85 | 2,362 | cpp | C++ | Sources/Sound/AudioWorld/audio_world.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 248 | 2015-01-08T05:21:40.000Z | 2022-03-20T02:59:16.000Z | Sources/Sound/AudioWorld/audio_world.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 39 | 2015-01-14T17:37:07.000Z | 2022-03-17T12:59:26.000Z | Sources/Sound/AudioWorld/audio_world.cpp | xctan/ClanLib | 1a8d6eb6cab3e93fd5c6be618fb6f7bd1146fc2d | [
"Linux-OpenIB"
] | 82 | 2015-01-11T13:23:49.000Z | 2022-02-19T03:17:24.000Z |
#include "Sound/precomp.h"
#include "API/Sound/AudioWorld/audio_world.h"
#include "API/Sound/AudioWorld/audio_object.h"
#include "API/Sound/soundbuffer.h"
#include "API/Core/Math/cl_math.h"
#include "audio_world_impl.h"
#include "audio_object_impl.h"
namespace clan
{
AudioWorld::AudioWorld(const ResourceManager &resources)
: impl(std::make_shared<AudioWorld_Impl>(resources))
{
}
void AudioWorld::set_listener(const Vec3f &position, const Quaternionf &orientation)
{
impl->listener_position = position;
impl->listener_orientation = orientation;
}
bool AudioWorld::is_ambience_enabled() const
{
return impl->play_ambience;
}
void AudioWorld::enable_reverse_stereo(bool enable)
{
impl->reverse_stereo = enable;
}
bool AudioWorld::is_reverse_stereo_enabled() const
{
return impl->reverse_stereo;
}
void AudioWorld::update()
{
for (auto it = impl->objects.begin(); it != impl->objects.end(); ++it)
{
impl->update_session(*it);
}
for (auto it = impl->active_objects.begin(); it != impl->active_objects.end();)
{
if (it->impl->session.is_playing())
{
++it;
}
else
{
it = impl->active_objects.erase(it);
}
}
}
/////////////////////////////////////////////////////////////////////////////
AudioWorld_Impl::AudioWorld_Impl(const ResourceManager &resources)
: play_ambience(true), reverse_stereo(false), resources(resources)
{
}
AudioWorld_Impl::~AudioWorld_Impl()
{
}
void AudioWorld_Impl::update_session(AudioObject_Impl *obj)
{
if (obj->attenuation_begin != obj->attenuation_end)
{
// Calculate volume from distance
float distance = obj->position.distance(listener_position);
float t = 1.0f - smoothstep(obj->attenuation_begin, obj->attenuation_end, distance);
// Calculate pan from ear angle
Vec3f sound_direction = Vec3f::normalize(obj->position - listener_position);
Vec3f ear_vector = listener_orientation.rotate_vector(Vec3f(1.0f, 0.0f, 0.0f));
float pan = Vec3f::dot(ear_vector, sound_direction);
if (reverse_stereo)
pan = -pan;
// Final volume needs to stay the same no matter the panning direction
float volume = (0.5f + std::abs(pan) * 0.5f) * t * obj->volume;
obj->session.set_volume(volume);
obj->session.set_pan(pan);
}
else
{
obj->session.set_volume(obj->volume);
obj->session.set_pan(0.0f);
}
}
}
| 24.350515 | 87 | 0.680779 | xctan |
66bf1efd3a0bed608491a19bc7320a774df752dd | 2,732 | cpp | C++ | RUNETag/WinNTL/tests/LLLTest.cpp | vshesh/RUNEtag | 800e93fb7c0560ea5a6261ffc60c02638a8cc8c9 | [
"MIT"
] | null | null | null | RUNETag/WinNTL/tests/LLLTest.cpp | vshesh/RUNEtag | 800e93fb7c0560ea5a6261ffc60c02638a8cc8c9 | [
"MIT"
] | null | null | null | RUNETag/WinNTL/tests/LLLTest.cpp | vshesh/RUNEtag | 800e93fb7c0560ea5a6261ffc60c02638a8cc8c9 | [
"MIT"
] | null | null | null |
#include <NTL/LLL.h>
NTL_CLIENT
int main()
{
mat_ZZ B;
long s;
#if 1
cin >> B;
#else
long i, j;
long n;
cerr << "n: ";
cin >> n;
long m;
cerr << "m: ";
cin >> m;
long k;
cerr << "k: ";
cin >> k;
B.SetDims(n, m);
for (i = 1; i <= n; i++)
for (j = 1; j <= m; j++) {
RandomLen(B(i,j), k);
if (RandomBnd(2)) negate(B(i,j), B(i,j));
}
#endif
mat_ZZ U, B0, B1, B2;
B0 = B;
double t;
ZZ d;
B = B0;
cerr << "LLL_FP...";
t = GetTime();
s = LLL_FP(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "LLL_QP...";
t = GetTime();
s = LLL_QP(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "LLL_XD...";
t = GetTime();
s = LLL_XD(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "LLL_RR...";
t = GetTime();
s = LLL_RR(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "G_LLL_FP...";
t = GetTime();
s = G_LLL_FP(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "G_LLL_QP...";
t = GetTime();
s = G_LLL_QP(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "G_LLL_XD...";
t = GetTime();
s = G_LLL_XD(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "G_LLL_RR...";
t = GetTime();
s = G_LLL_RR(B, U, 0.99);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
LLL(d, B, 90, 100);
if (B1 != B) Error("bad LLLTest (2)");
B = B0;
cerr << "LLL...";
t = GetTime();
s = LLL(d, B, U);
cerr << (GetTime()-t) << "\n";
mul(B1, U, B0);
if (B1 != B) Error("bad LLLTest (1)");
cout << "rank = " << s << "\n";
cout << "det = " << d << "\n";
cout << "B = " << B << "\n";
cout << "U = " << U << "\n";
}
| 19.514286 | 50 | 0.424597 | vshesh |
66c21c06dc026017e81dd6afcfd53b9af551b1f6 | 1,147 | cpp | C++ | lib/io/src/swap.cpp | solosTec/cyng | 3862a6b7a2b536d1f00fef20700e64170772dcff | [
"MIT"
] | null | null | null | lib/io/src/swap.cpp | solosTec/cyng | 3862a6b7a2b536d1f00fef20700e64170772dcff | [
"MIT"
] | null | null | null | lib/io/src/swap.cpp | solosTec/cyng | 3862a6b7a2b536d1f00fef20700e64170772dcff | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2018 Sylko Olzscher
*
*/
#include <cyng/io/swap.h>
namespace cyng
{
std::uint16_t swap_num(std::uint16_t val)
{
return (val << 8) | (val >> 8);
}
std::int16_t swap_num(std::int16_t val)
{
return (val << 8) | ((val >> 8) & 0xFF);
}
std::uint32_t swap_num(std::uint32_t val)
{
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | (val >> 16);
}
std::int32_t swap_num(std::int32_t val)
{
val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF);
return (val << 16) | ((val >> 16) & 0xFFFF);
}
std::int64_t swap_num(std::int64_t val)
{
val = ((val << 8) & 0xFF00FF00FF00FF00ULL) | ((val >> 8) & 0x00FF00FF00FF00FFULL);
val = ((val << 16) & 0xFFFF0000FFFF0000ULL) | ((val >> 16) & 0x0000FFFF0000FFFFULL);
return (val << 32) | ((val >> 32) & 0xFFFFFFFFULL);
}
std::uint64_t swap_num(std::uint64_t val)
{
val = ((val << 8) & 0xFF00FF00FF00FF00ULL) | ((val >> 8) & 0x00FF00FF00FF00FFULL);
val = ((val << 16) & 0xFFFF0000FFFF0000ULL) | ((val >> 16) & 0x0000FFFF0000FFFFULL);
return (val << 32) | (val >> 32);
}
}
| 22.94 | 86 | 0.571055 | solosTec |
66c338b089efe6c614fb526cd5fa0e7984738317 | 51 | cpp | C++ | src/RefCore/Var.cpp | sppp/TheoremProver | efd583bc78e8fa93f6946def5f6af77001d01763 | [
"BSD-3-Clause"
] | null | null | null | src/RefCore/Var.cpp | sppp/TheoremProver | efd583bc78e8fa93f6946def5f6af77001d01763 | [
"BSD-3-Clause"
] | null | null | null | src/RefCore/Var.cpp | sppp/TheoremProver | efd583bc78e8fa93f6946def5f6af77001d01763 | [
"BSD-3-Clause"
] | null | null | null | #include "RefCore.h"
namespace RefCore {
}
| 8.5 | 21 | 0.607843 | sppp |
66c889f150ecfffe511b6cd69f485e795db892a1 | 1,342 | cpp | C++ | server/homeserver/network/json/JsonApi.Core.cpp | williamkoehler/home-server | ce99af73ea2e53fea3939fe0c4442433e65ac670 | [
"MIT"
] | 1 | 2021-07-05T21:11:59.000Z | 2021-07-05T21:11:59.000Z | server/homeserver/network/json/JsonApi.Core.cpp | williamkoehler/home-server | ce99af73ea2e53fea3939fe0c4442433e65ac670 | [
"MIT"
] | null | null | null | server/homeserver/network/json/JsonApi.Core.cpp | williamkoehler/home-server | ce99af73ea2e53fea3939fe0c4442433e65ac670 | [
"MIT"
] | null | null | null | #include "JsonApi.hpp"
#include "../../Core.hpp"
#include "../../tools/EMail.hpp"
namespace server
{
// Core
void JsonApi::BuildJsonSettings(const Ref<User>& user, rapidjson::Value& output, rapidjson::Document::AllocatorType& allocator)
{
assert(output.IsObject());
// Core settings
{
rapidjson::Value coreJson = rapidjson::Value(rapidjson::kObjectType);
Ref<Core> core = Core::GetInstance();
assert(core != nullptr);
boost::lock_guard lock(core->mutex);
coreJson.AddMember("name", rapidjson::Value(core->name.c_str(), core->name.size(), allocator), allocator);
output.AddMember("core", coreJson, allocator);
}
// EMail settings
{
rapidjson::Value emailJson = rapidjson::Value(rapidjson::kObjectType);
Ref<EMail> email = EMail::GetInstance();
assert(email != nullptr);
boost::lock_guard lock(email->mutex);
rapidjson::Value recipientListJson = rapidjson::Value(rapidjson::kArrayType);
for (std::string& recipient : email->recipients)
recipientListJson.PushBack(rapidjson::Value(recipient.c_str(), recipient.size(), allocator), allocator);
emailJson.AddMember("recipients", recipientListJson, allocator);
output.AddMember("email", emailJson, allocator);
}
// User settings
{
//rapidjson::Value userJson = rapidjson::Value(rapidjson::kObjectType);
}
}
} | 24.851852 | 128 | 0.697466 | williamkoehler |
66c9e7bb67a6e27cfea4b72d827ad9fc7ce1b116 | 6,210 | cpp | C++ | src/base/ossimCsvFile.cpp | vladislav-horbatiuk/ossim | 82417ad868fac022672335e1684bdd91d662c18c | [
"MIT"
] | 251 | 2015-10-20T09:08:11.000Z | 2022-03-22T18:16:38.000Z | src/base/ossimCsvFile.cpp | IvanLJF/ossim | 2e0143f682b9884a09ff2598ef8737f29e44fbdf | [
"MIT"
] | 73 | 2015-11-02T17:12:36.000Z | 2021-11-15T17:41:47.000Z | src/base/ossimCsvFile.cpp | IvanLJF/ossim | 2e0143f682b9884a09ff2598ef8737f29e44fbdf | [
"MIT"
] | 146 | 2015-10-15T16:00:15.000Z | 2022-03-22T12:37:14.000Z | #include <ossim/base/ossimCsvFile.h>
#include <iostream>
#include <iterator>
static const ossim_uint32 DEFAULT_BUFFER_SIZE = 1024;
ossim_int32 ossimCsvFile::INVALID_INDEX = -1;
static std::istream& csvSkipWhiteSpace(std::istream& in)
{
int c = in.peek();
while(!in.fail()&& ( (c == ' ')||(c == '\t')||(c == '\n')||(c == '\r') ) )
{
in.ignore(1);
c = in.peek();
}
return in;
}
ossimCsvFile::Record::Record(ossimCsvFile* csvFile)
:theCsvFile(csvFile)
{
}
bool ossimCsvFile::Record::valueAt(const ossimString& fieldName,
ossimString& value)const
{
bool result = false;
if(theCsvFile)
{
ossim_int32 idx = theCsvFile->indexOfField(fieldName);
if((idx > 0)&&(idx < (ossim_int32)theValues.size()))
{
value = theValues[idx];
result = true;
}
}
return result;
}
bool ossimCsvFile::Record::valueAt(ossim_uint32 idx,
ossimString& value)const
{
bool result = false;
if(idx < theValues.size())
{
value = theValues[idx];
result = true;
}
return result;
}
ossimString& ossimCsvFile::Record::operator [](const ossimString& fieldName)
{
if(theCsvFile)
{
ossim_int32 idx = theCsvFile->indexOfField(fieldName);
if((idx >= 0)&&(idx < (ossim_int32)theValues.size()))
{
return theValues[idx];
}
}
return theDummyValue;
}
const ossimString& ossimCsvFile::Record::operator [](const ossimString& fieldName)const
{
if(theCsvFile)
{
ossim_int32 idx = theCsvFile->indexOfField(fieldName);
if((idx >= 0)&&(idx < (ossim_int32)theValues.size()))
{
return theValues[idx];
}
}
return theDummyValue;
}
ossimString& ossimCsvFile::Record::operator [](ossim_uint32 idx)
{
if(idx < theValues.size())
{
return theValues[idx];
}
return theDummyValue;
}
const ossimString& ossimCsvFile::Record::operator [](ossim_uint32 idx)const
{
if(idx < theValues.size())
{
return theValues[idx];
}
return theDummyValue;
}
ossimCsvFile::ossimCsvFile(const ossimString& separatorList)
:theInputStream(0),
theSeparatorList(separatorList),
theOpenFlag(false)
{
}
ossimCsvFile::~ossimCsvFile()
{
close();
}
bool ossimCsvFile::readCsvLine(std::istream& inStream,
ossimCsvFile::StringListType& tokens)const
{
tokens.clear();
bool done = false;
char c;
const char quote = '\"';
bool inQuotedString = false;
bool inDoubleQuote = false;
ossimString currentToken;
inStream >> csvSkipWhiteSpace;
while(!done&&inStream.get(c)&&inStream.good())
{
if(c > 0x7e )
{
return false;
}
if((c!='\n')&&
(c!='\r'))
{
// check to see if we are quoted and check to see if double quoted
if(c == quote)
{
// check if at a double quote
if(inStream.peek() == quote)
{
currentToken += quote;
inStream.ignore(1);
if(!inDoubleQuote)
{
inDoubleQuote = true;
}
else
{
inDoubleQuote = false;
}
}
else
{
if(!inQuotedString)
{
inQuotedString = true;
}
else
{
inQuotedString = false;
}
}
}
// if we are at a separator then check to see if we are inside a quoted string
else if(theSeparatorList.contains(c))
{
// ignore token separator if quoted
if(inQuotedString||inDoubleQuote)
{
currentToken += c;
}
else
{
// push the current token.
currentToken = currentToken.trim();
tokens.push_back(currentToken);
currentToken = "";
inStream >> csvSkipWhiteSpace;
}
}
else
{
currentToken += c;
}
}
else if(!inQuotedString||inDoubleQuote)
{
currentToken = currentToken.trim();
tokens.push_back(currentToken);
done = true;
}
else
{
currentToken += c;
}
}
return (inStream.good()&&(tokens.size()>0));
}
bool ossimCsvFile::open(const ossimFilename& file, const ossimString& flags)
{
close();
if((*flags.begin()) == 'r')
{
theInputStream = new std::ifstream(file.c_str(), std::ios::in|std::ios::binary);
theOpenFlag = true;
theRecordBuffer = new ossimCsvFile::Record(this);
}
else
{
return theOpenFlag;
}
return theOpenFlag;
}
bool ossimCsvFile::readHeader()
{
if(theOpenFlag)
{
theFieldHeaderList.clear();
return readCsvLine(*theInputStream, theFieldHeaderList);
}
return false;
}
void ossimCsvFile::close()
{
if(theOpenFlag)
{
theFieldHeaderList.clear();
if(theInputStream)
{
delete theInputStream;
theInputStream = 0;
}
theOpenFlag = false;
theRecordBuffer = 0;
}
}
ossimRefPtr<ossimCsvFile::Record> ossimCsvFile::nextRecord()
{
if(!theOpenFlag) return ossimRefPtr<ossimCsvFile::Record>(0);
if(theFieldHeaderList.empty())
{
if(!readHeader())
{
return ossimRefPtr<ossimCsvFile::Record>();
}
}
if(!readCsvLine(*theInputStream, theRecordBuffer->values()))
{
return ossimRefPtr<ossimCsvFile::Record>();
}
return theRecordBuffer;
}
const ossimCsvFile::StringListType& ossimCsvFile::fieldHeaderList()const
{
return theFieldHeaderList;
}
ossim_int32 ossimCsvFile::indexOfField(const ossimString& fieldName)const
{
ossim_int32 result = ossimCsvFile::INVALID_INDEX;
ossim_uint32 idx = 0;
for(;idx < theFieldHeaderList.size(); ++idx)
{
if(theFieldHeaderList[idx] == fieldName)
{
result = (ossim_int32)idx;
break;
}
}
return result;
}
| 22.099644 | 87 | 0.554267 | vladislav-horbatiuk |
66cb1a9278851d2d9dc166e3c1f28165679a8dbc | 309 | hpp | C++ | r0 - hardware testing code/src/aqua_inputs.hpp | Tassany/projeto_aquaponia_fablab | 1973b9a74fd929ac445f95d1dda4cf0381c0c1cf | [
"MIT"
] | null | null | null | r0 - hardware testing code/src/aqua_inputs.hpp | Tassany/projeto_aquaponia_fablab | 1973b9a74fd929ac445f95d1dda4cf0381c0c1cf | [
"MIT"
] | null | null | null | r0 - hardware testing code/src/aqua_inputs.hpp | Tassany/projeto_aquaponia_fablab | 1973b9a74fd929ac445f95d1dda4cf0381c0c1cf | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <SPI.h>
#include <aqua_pins.hpp>
uint8_t aqua_inputs() {
digitalWrite(AQ_PIN_PL, true);
SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE2));
uint8_t data = SPI.transfer(0);
SPI.endTransaction();
digitalWrite(AQ_PIN_PL, false);
return data;
}
| 23.769231 | 68 | 0.705502 | Tassany |
66cbb6525540e5091d6eb0ed00a16e7753948acc | 10,463 | cc | C++ | src/vt/vrt/collection/balance/stats_restart_reader.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 26 | 2019-11-26T08:36:15.000Z | 2022-02-15T17:13:21.000Z | src/vt/vrt/collection/balance/stats_restart_reader.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 1,215 | 2019-09-09T14:31:33.000Z | 2022-03-30T20:20:14.000Z | src/vt/vrt/collection/balance/stats_restart_reader.cc | rbuch/vt | 74c2e0cae3201dfbcbfda7644c354703ddaed6bb | [
"BSD-3-Clause"
] | 12 | 2019-09-08T00:03:05.000Z | 2022-02-23T21:28:35.000Z | /*
//@HEADER
// *****************************************************************************
//
// stats_restart_reader.cc
// DARMA/vt => Virtual Transport
//
// Copyright 2019-2021 National Technology & Engineering Solutions of Sandia, LLC
// (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S.
// Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact [email protected]
//
// *****************************************************************************
//@HEADER
*/
#if !defined INCLUDED_VT_VRT_COLLECTION_BALANCE_STATS_RESTART_READER_CC
#define INCLUDED_VT_VRT_COLLECTION_BALANCE_STATS_RESTART_READER_CC
#include "vt/config.h"
#include "vt/vrt/collection/balance/stats_restart_reader.h"
#include "vt/objgroup/manager.h"
#include "vt/vrt/collection/balance/stats_data.h"
#include "vt/utils/json/json_reader.h"
#include "vt/utils/json/decompression_input_container.h"
#include "vt/utils/json/input_iterator.h"
#include <cinttypes>
#include <nlohmann/json.hpp>
namespace vt { namespace vrt { namespace collection { namespace balance {
void StatsRestartReader::setProxy(
objgroup::proxy::Proxy<StatsRestartReader> in_proxy
) {
proxy_ = in_proxy;
}
/*static*/ std::unique_ptr<StatsRestartReader> StatsRestartReader::construct() {
auto ptr = std::make_unique<StatsRestartReader>();
auto proxy = theObjGroup()->makeCollective<StatsRestartReader>(ptr.get());
proxy.get()->setProxy(proxy);
return ptr;
}
void StatsRestartReader::startup() {
auto const file_name = theConfig()->getLBStatsFileIn();
readStats(file_name);
}
std::vector<ElementIDType> const&
StatsRestartReader::getMoveList(PhaseType phase) const {
vtAssert(proc_move_list_.size() > phase, "Phase must exist");
return proc_move_list_.at(phase);
}
void StatsRestartReader::clearMoveList(PhaseType phase) {
if (proc_move_list_.size() > phase) {
proc_move_list_.at(phase).clear();
}
}
bool StatsRestartReader::needsLB(PhaseType phase) const {
if (proc_phase_runs_LB_.size() > phase) {
return proc_phase_runs_LB_.at(phase);
} else {
return false;
}
}
std::deque<std::vector<ElementIDType>> const&
StatsRestartReader::getMigrationList() const {
return proc_move_list_;
}
std::deque<std::set<ElementIDType>> StatsRestartReader::readIntoElementHistory(
StatsData const& sd
) {
std::deque<std::set<ElementIDType>> element_history;
for (PhaseType phase = 0; phase < sd.node_data_.size(); phase++) {
std::set<ElementIDType> buffer;
for (auto const& obj : sd.node_data_.at(phase)) {
if (obj.first.isMigratable()) {
buffer.insert(obj.first.id);
}
}
element_history.emplace_back(std::move(buffer));
}
return element_history;
}
void StatsRestartReader::readStatsFromStream(std::stringstream stream) {
using vt::util::json::DecompressionInputContainer;
using vt::vrt::collection::balance::StatsData;
using json = nlohmann::json;
auto c = DecompressionInputContainer(
DecompressionInputContainer::AnyStreamTag{}, std::move(stream)
);
json j = json::parse(c);
auto sd = StatsData(j);
auto element_history = readIntoElementHistory(sd);
constructMoveList(std::move(element_history));
}
void StatsRestartReader::readStats(std::string const& fileName) {
// Read the input files
auto elements_history = inputStatsFile(fileName);
constructMoveList(std::move(elements_history));
}
void StatsRestartReader::constructMoveList(
std::deque<std::set<ElementIDType>> element_history
) {
if (element_history.empty()) {
vtWarn("No element history provided");
return;
}
auto const num_iters = element_history.size() - 1;
proc_move_list_.resize(num_iters);
proc_phase_runs_LB_.resize(num_iters, true);
if (theContext()->getNode() == 0) {
msgsReceived.resize(num_iters, 0);
totalMove.resize(num_iters);
}
// Communicate the migration information
createMigrationInfo(element_history);
}
std::deque<std::set<ElementIDType>>
StatsRestartReader::inputStatsFile(std::string const& fileName) {
using vt::util::json::Reader;
using vt::vrt::collection::balance::StatsData;
Reader r{fileName};
auto json = r.readFile();
auto sd = StatsData(*json);
return readIntoElementHistory(sd);
}
void StatsRestartReader::createMigrationInfo(
std::deque<std::set<ElementIDType>>& element_history
) {
const auto num_iters = element_history.size() - 1;
const auto myNodeID = static_cast<ElementIDType>(theContext()->getNode());
for (size_t ii = 0; ii < num_iters; ++ii) {
auto& elms = element_history[ii];
auto& elmsNext = element_history[ii + 1];
std::set<ElementIDType> diff;
std::set_difference(elmsNext.begin(), elmsNext.end(), elms.begin(),
elms.end(), std::inserter(diff, diff.begin()));
const size_t qi = diff.size();
const size_t pi = elms.size() - (elmsNext.size() - qi);
auto& myList = proc_move_list_[ii];
myList.reserve(3 * (pi + qi) + 1);
//--- Store the iteration number
myList.push_back(static_cast<ElementIDType>(ii));
//--- Store partial migration information (i.e. nodes moving in)
for (auto iEle : diff) {
myList.push_back(iEle); //--- permID to receive
myList.push_back(no_element_id); // node moving from
myList.push_back(myNodeID); // node moving to
}
diff.clear();
//--- Store partial migration information (i.e. nodes moving out)
std::set_difference(elms.begin(), elms.end(), elmsNext.begin(),
elmsNext.end(), std::inserter(diff, diff.begin()));
for (auto iEle : diff) {
myList.push_back(iEle); //--- permID to send
myList.push_back(myNodeID); // node migrating from
myList.push_back(no_element_id); // node migrating to
}
//
// Create a message storing the vector
//
proxy_[0].send<VecMsg, &StatsRestartReader::gatherMsgs>(myList);
//
// Clear old distribution of elements
//
elms.clear();
}
}
void StatsRestartReader::gatherMsgs(VecMsg *msg) {
auto sentVec = msg->getTransfer();
vtAssert(sentVec.size() % 3 == 1, "Expecting vector of length 3n+1");
ElementIDType const phaseID = sentVec[0];
//
// --- Combine the different pieces of information
//
msgsReceived[phaseID] += 1;
auto& migrate = totalMove[phaseID];
for (size_t ii = 1; ii < sentVec.size(); ii += 3) {
auto const permID = sentVec[ii];
auto const nodeFrom = static_cast<NodeType>(sentVec[ii + 1]);
auto const nodeTo = static_cast<NodeType>(sentVec[ii + 2]);
auto iptr = migrate.find(permID);
if (iptr == migrate.end()) {
migrate.insert(std::make_pair(permID, std::make_pair(nodeFrom, nodeTo)));
}
else {
auto &nodePair = iptr->second;
nodePair.first = std::max(nodePair.first, nodeFrom);
nodePair.second = std::max(nodePair.second, nodeTo);
}
}
//
// --- Check whether all the messages have been received
//
const NodeType numNodes = theContext()->getNumNodes();
if (msgsReceived[phaseID] < static_cast<std::size_t>(numNodes))
return;
//
//--- Distribute the information when everything has been received
//
size_t const header = 2;
for (NodeType in = 0; in < numNodes; ++in) {
size_t iCount = 0;
for (auto iNode : migrate) {
if (iNode.second.first == in)
iCount += 1;
}
std::vector<ElementIDType> toMove(2 * iCount + header);
iCount = 0;
toMove[iCount++] = phaseID;
toMove[iCount++] = static_cast<ElementIDType>(migrate.size());
for (auto iNode : migrate) {
if (iNode.second.first == in) {
toMove[iCount++] = iNode.first;
toMove[iCount++] = static_cast<ElementIDType>(iNode.second.second);
}
}
if (in > 0) {
proxy_[in].send<VecMsg, &StatsRestartReader::scatterMsgs>(toMove);
} else {
proc_phase_runs_LB_[phaseID] = (!migrate.empty());
auto& myList = proc_move_list_[phaseID];
myList.resize(toMove.size() - header);
std::copy(&toMove[header], toMove.data() + toMove.size(),
myList.begin());
}
}
migrate.clear();
}
void StatsRestartReader::scatterMsgs(VecMsg *msg) {
const size_t header = 2;
auto recvVec = msg->getTransfer();
vtAssert((recvVec.size() -header) % 2 == 0,
"Expecting vector of length 2n+2");
//--- Get the iteration number associated with the message
const ElementIDType phaseID = recvVec[0];
//--- Check whether some migration will be done
proc_phase_runs_LB_[phaseID] = static_cast<bool>(recvVec[1] > 0);
auto &myList = proc_move_list_[phaseID];
if (!proc_phase_runs_LB_[phaseID]) {
myList.clear();
return;
}
//--- Copy the migration information
myList.resize(recvVec.size() - header);
std::copy(&recvVec[header], recvVec.data()+recvVec.size(), myList.begin());
}
}}}} /* end namespace vt::vrt::collection::balance */
#endif /*INCLUDED_VT_VRT_COLLECTION_BALANCE_STATS_RESTART_READER_CC*/
| 34.531353 | 81 | 0.684985 | rbuch |
66cc0f3b846b4a8720da090292c610a1779841ca | 6,876 | cc | C++ | lite/kernels/arm/box_coder_compute.cc | shentanyue/Paddle-Lite | c6baab724c9047c3e9809db3fc24b7a2b5ca26a2 | [
"Apache-2.0"
] | 1 | 2022-01-27T07:34:50.000Z | 2022-01-27T07:34:50.000Z | lite/kernels/arm/box_coder_compute.cc | shentanyue/Paddle-Lite | c6baab724c9047c3e9809db3fc24b7a2b5ca26a2 | [
"Apache-2.0"
] | 1 | 2021-05-26T05:19:38.000Z | 2021-05-26T05:19:38.000Z | lite/kernels/arm/box_coder_compute.cc | shentanyue/Paddle-Lite | c6baab724c9047c3e9809db3fc24b7a2b5ca26a2 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lite/kernels/arm/box_coder_compute.h"
#include <algorithm>
#include <string>
#include <vector>
#include "lite/backends/arm/math/funcs.h"
#ifdef ENABLE_ARM_FP16
#include "lite/backends/arm/math/fp16/box_coder_fp16.h"
#endif
namespace paddle {
namespace lite {
namespace kernels {
namespace arm {
void BoxCoderCompute::Run() {
auto& param = Param<operators::BoxCoderParam>();
auto* prior_box = param.prior_box;
auto* prior_box_var = param.prior_box_var;
auto* target_box = param.target_box;
auto* output_box = param.proposals;
std::vector<float> variance = param.variance;
std::string code_type = param.code_type;
bool normalized = param.box_normalized;
auto row = target_box->dims()[0];
auto col = prior_box->dims()[0];
if (code_type == "decode_center_size") {
col = target_box->dims()[1];
}
auto len = prior_box->dims()[1]; // 4
output_box->Resize({row, col, len}); // N x M x 4
auto* output = output_box->mutable_data<float>();
auto axis = param.axis;
const float* target_box_data = target_box->data<float>();
const float* prior_box_data = prior_box->data<float>();
bool var_len4 = false;
int var_size = 0;
const float* variance_data;
if (prior_box_var != nullptr) {
var_size = 2;
variance_data = prior_box_var->data<float>();
var_len4 = false;
} else {
var_size = 1;
variance_data = param.variance.data();
var_len4 = true;
}
if (code_type == "encode_center_size") {
lite::arm::math::encode_bbox_center_kernel(row,
target_box_data,
prior_box_data,
variance_data,
var_len4,
col,
output);
} else if (code_type == "decode_center_size") {
if (axis == 0) {
lite::arm::math::decode_bbox_center_kernel(row,
target_box_data,
prior_box_data,
variance_data,
var_len4,
col,
normalized,
output);
} else {
auto prior_box_var_data =
prior_box_var ? prior_box_var->data<float>() : nullptr;
lite::arm::math::decode_center_size_axis_1(var_size,
row,
col,
len,
target_box_data,
prior_box_data,
prior_box_var_data,
normalized,
variance,
output);
}
} else {
LOG(FATAL) << "box_coder don't support this code_type: " << code_type;
}
}
#ifdef ENABLE_ARM_FP16
void BoxCoderFp16Compute::Run() {
auto& param = Param<operators::BoxCoderParam>();
auto* prior_box = param.prior_box;
auto* prior_box_var = param.prior_box_var;
auto* target_box = param.target_box;
auto* output_box = param.proposals;
std::vector<float16_t> variance(param.variance.size());
std::transform(param.variance.begin(),
param.variance.end(),
variance.begin(),
[](float x) { return static_cast<float16_t>(x); });
std::string code_type = param.code_type;
bool normalized = param.box_normalized;
auto row = target_box->dims()[0];
auto col = prior_box->dims()[0];
if (code_type == "decode_center_size") {
col = target_box->dims()[1];
}
auto len = prior_box->dims()[1];
output_box->Resize({row, col, len});
auto* output = output_box->mutable_data<float16_t>();
const float16_t* loc_data = target_box->data<float16_t>();
const float16_t* prior_data = prior_box->data<float16_t>();
const float16_t* variance_data;
bool var_len4 = false;
if (param.prior_box_var != nullptr) {
variance_data = prior_box_var->data<float16_t>();
var_len4 = false;
} else {
variance_data = variance.data();
var_len4 = true;
}
lite::arm::math::fp16::decode_bboxes(row,
param.axis,
loc_data,
prior_data,
variance_data,
var_len4,
code_type,
normalized,
col,
output);
}
#endif
} // namespace arm
} // namespace kernels
} // namespace lite
} // namespace paddle
#ifdef ENABLE_ARM_FP16
REGISTER_LITE_KERNEL(box_coder,
kARM,
kFP16,
kNCHW,
paddle::lite::kernels::arm::BoxCoderFp16Compute,
def)
.BindInput("PriorBox",
{LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))})
.BindInput("PriorBoxVar",
{LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))})
.BindInput("TargetBox",
{LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))})
.BindOutput("OutputBox",
{LiteType::GetTensorTy(TARGET(kARM), PRECISION(kFP16))})
.Finalize();
#endif // ENABLE_ARM_FP16
REGISTER_LITE_KERNEL(box_coder,
kARM,
kFloat,
kNCHW,
paddle::lite::kernels::arm::BoxCoderCompute,
def)
.BindInput("PriorBox", {LiteType::GetTensorTy(TARGET(kARM))})
.BindInput("PriorBoxVar", {LiteType::GetTensorTy(TARGET(kARM))})
.BindInput("TargetBox", {LiteType::GetTensorTy(TARGET(kARM))})
.BindOutput("OutputBox", {LiteType::GetTensorTy(TARGET(kARM))})
.Finalize();
| 36.967742 | 75 | 0.528069 | shentanyue |
66cdc42eaeffa61eb5f56d5a8dcdc6272bf062c7 | 3,438 | hpp | C++ | Kernel/include/generic_symbolicator_factory.hpp | foxostro/FlapjackOS | 34bd2cc9b0983b917a089efe2055ca8f78d56d9a | [
"BSD-2-Clause"
] | null | null | null | Kernel/include/generic_symbolicator_factory.hpp | foxostro/FlapjackOS | 34bd2cc9b0983b917a089efe2055ca8f78d56d9a | [
"BSD-2-Clause"
] | null | null | null | Kernel/include/generic_symbolicator_factory.hpp | foxostro/FlapjackOS | 34bd2cc9b0983b917a089efe2055ca8f78d56d9a | [
"BSD-2-Clause"
] | null | null | null | #ifndef FLAPJACKOS_COMMON_INCLUDE_GENERIC_SYMBOLICATOR_FACTORY_HPP
#define FLAPJACKOS_COMMON_INCLUDE_GENERIC_SYMBOLICATOR_FACTORY_HPP
#include <symbolicator.hpp>
#include <hardware_memory_management_unit.hpp>
#include <multiboot.h>
#include <common/elf.hpp>
#include <common/vector.hpp>
#include <common/logger.hpp>
template<typename ElfSectionHeader, typename ElfSymbol>
class GenericSymbolicatorFactory {
public:
GenericSymbolicatorFactory(HardwareMemoryManagementUnit& mmu,
multiboot_info_t* mb_info)
: mmu_(mmu), mb_info_(mb_info), shdr_table_count_(0), shdr_table_(nullptr)
{
assert(mb_info);
}
Symbolicator make_symbolicator()
{
multiboot_elf_section_header_table_t& elf_sec = mb_info_->u.elf_sec;
assert(sizeof(ElfSectionHeader) == elf_sec.size);
shdr_table_count_ = elf_sec.num;
shdr_table_ = new ElfSectionHeader[shdr_table_count_];
ElfSectionHeader* shdr_table = get_shdr_pointer(elf_sec.addr);
memmove(shdr_table_, shdr_table, elf_sec.num * elf_sec.size);
register_all_symbols();
return std::move(symbolicator_);
}
protected:
virtual bool is_elf_symbol_a_function(const ElfSymbol& elf_symbol) = 0;
private:
HardwareMemoryManagementUnit& mmu_;
multiboot_info_t* mb_info_;
size_t shdr_table_count_;
ElfSectionHeader* shdr_table_;
Symbolicator symbolicator_;
ElfSectionHeader* get_shdr_pointer(uintptr_t physical_address)
{
return reinterpret_cast<ElfSectionHeader*>(mmu_.convert_physical_to_logical_address(physical_address));
}
void register_all_symbols()
{
auto& shdr = get_symbol_table_shdr();
const ElfSymbol* elf_symbols = reinterpret_cast<const ElfSymbol*>(mmu_.convert_physical_to_logical_address(shdr.sh_addr));
for (size_t i = 0, n = (shdr.sh_size / sizeof(ElfSymbol)); i < n; ++i){
const ElfSymbol& elf_symbol = elf_symbols[i];
if (is_elf_symbol_a_function(elf_symbol)) {
register_elf_symbol(elf_symbol);
}
}
}
const ElfSectionHeader& get_symbol_table_shdr()
{
return get_shdr_of_type(Elf::SHT_SYMTAB);
}
const ElfSectionHeader& get_shdr_of_type(unsigned type)
{
const ElfSectionHeader* shdr = &shdr_table_[0];
for (size_t i = 0; i < shdr_table_count_; ++i) {
if (shdr_table_[i].sh_type == type) {
shdr = &shdr_table_[i];
break;
}
}
return *shdr;
}
void register_elf_symbol(const ElfSymbol& elf_symbol)
{
assert(is_elf_symbol_a_function(elf_symbol));
Symbolicator::Symbol symbol_to_register;
symbol_to_register.address = elf_symbol.st_value;
symbol_to_register.name = SharedPointer(strdup(get_string(elf_symbol.st_name)));
symbolicator_.register_symbol(symbol_to_register);
}
const char* get_string(size_t index)
{
return get_string_table() + index;
}
const char* get_string_table()
{
auto& shdr = get_string_table_shdr();
return reinterpret_cast<const char*>(mmu_.convert_physical_to_logical_address(shdr.sh_addr));
}
const ElfSectionHeader& get_string_table_shdr()
{
return get_shdr_of_type(Elf::SHT_STRTAB);
}
};
#endif // FLAPJACKOS_COMMON_INCLUDE_GENERIC_SYMBOLICATOR_FACTORY_HPP
| 32.742857 | 130 | 0.690809 | foxostro |
66cf9089ab7fe6895fd8c6c6cf77830b0ef44b51 | 2,298 | cpp | C++ | EpicForceTools/bin2c/main.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | 1 | 2021-03-30T06:28:32.000Z | 2021-03-30T06:28:32.000Z | EpicForceTools/bin2c/main.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | EpicForceTools/bin2c/main.cpp | MacgyverLin/MagnumEngine | 975bd4504a1e84cb9698c36e06bd80c7b8ced0ff | [
"MIT"
] | null | null | null | // bin2c.c
//
// convert a binary file into a C source vector
//
// THE "BEER-WARE LICENSE" (Revision 3.1415):
// sandro AT sigala DOT it wrote this file. As long as you retain this notice you can do
// whatever you want with this stuff. If we meet some day, and you think this stuff is
// worth it, you can buy me a beer in return. Sandro Sigala
//
// syntax: bin2c [-c] [-z] <input_file> <output_file>
//
// -c add the "const" keyword to definition
// -z terminate the array with a zero (useful for embedded C strings)
//
// examples:
// bin2c -c myimage.png myimage_png.cpp
// bin2c -z sometext.txt sometext_txt.cpp
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
int useconst = 0;
int zeroterminated = 0;
int myfgetc(FILE *f)
{
int c = fgetc(f);
if (c == EOF && zeroterminated)
{
zeroterminated = 0;
return 0;
}
return c;
}
void process(const char *ifname, const char *ofname)
{
FILE *ifile, *ofile;
ifile = fopen(ifname, "rb");
if (ifile == NULL)
{
fprintf(stderr, "cannot open %s for reading\n", ifname);
exit(1);
}
ofile = fopen(ofname, "wb");
if (ofile == NULL)
{
fprintf(stderr, "cannot open %s for writing\n", ofname);
exit(1);
}
char buf[PATH_MAX], *p;
const char *cp;
if ((cp = strrchr(ifname, '/')) != NULL)
{
++cp;
} else {
if ((cp = strrchr(ifname, '\\')) != NULL)
++cp;
else
cp = ifname;
}
strcpy(buf, cp);
for (p = buf; *p != '\0'; ++p)
{
if (!isalnum(*p))
*p = '_';
}
fprintf(ofile, "static %sunsigned char %s[] = {\n", useconst ? "const " : "", buf);
int c, col = 1;
while ((c = myfgetc(ifile)) != EOF)
{
if (col >= 78 - 6)
{
fputc('\n', ofile);
col = 1;
}
fprintf(ofile, "0x%.2x, ", c);
col += 6;
}
fprintf(ofile, "\n};\n");
fclose(ifile);
fclose(ofile);
}
void usage(void)
{
fprintf(stderr, "usage: bin2c [-cz] <input_file> <output_file>\n");
exit(1);
}
int main(int argc, char **argv)
{
while (argc > 3)
{
if (!strcmp(argv[1], "-c"))
{
useconst = 1;
--argc;
++argv;
} else if (!strcmp(argv[1], "-z"))
{
zeroterminated = 1;
--argc;
++argv;
} else {
usage();
}
}
if (argc != 3)
{
usage();
}
process(argv[1], argv[2]);
return 0;
} | 18.836066 | 88 | 0.578329 | MacgyverLin |
66d159a07d7c1db5a2034ce136cf06dddcbb6e11 | 5,967 | cpp | C++ | test/collision/vector.cpp | neboat/cilktools | 7065c4f3281f133f2fd1a2e94b83c7326396ef7e | [
"MIT"
] | 3 | 2017-01-30T22:44:33.000Z | 2021-03-06T16:37:18.000Z | test/collision/vector.cpp | neboat/cilktools | 7065c4f3281f133f2fd1a2e94b83c7326396ef7e | [
"MIT"
] | null | null | null | test/collision/vector.cpp | neboat/cilktools | 7065c4f3281f133f2fd1a2e94b83c7326396ef7e | [
"MIT"
] | 5 | 2015-06-17T14:12:11.000Z | 2017-10-19T12:17:19.000Z | //========================================================================//
// Copyright 1994 (Unpublished Material) //
// SolidWorks Inc. //
//========================================================================//
//
// File Name: vector.cpp
//
// Application: Math/Geometry utilities
//
// Contents: methods for classes for simple 3d geometry elements
//
//========================================================================//
// Include this set first to get PCH efficiency
#define MATHGEOM_FILE
#include "stdafx.h"
// end pch efficiency set
static const mgVector_c NullVec( 0, 0, 0 );
mgVector_c::mgVector_c( double x, double y, double z )
{
iComp[0] = x;
iComp[1] = y;
iComp[2] = z;
}
mgVector_c::mgVector_c( const double v[ 3 ] )
{
iComp[0] = v[0];
iComp[1] = v[1];
iComp[2] = v[2];
}
mgVector_c::mgVector_c( )
{
iComp[0] = 0.0;
iComp[1] = 0.0;
iComp[2] = 0.0;
}
mgVector_c::mgVector_c( const mgVector_c& v )
{
iComp[0] = (v.iComp)[0];
iComp[1] = (v.iComp)[1];
iComp[2] = (v.iComp)[2];
}
mgVector_c const& mgVector_c::operator=(const mgVector_c& v)
{
iComp[0] = (v.iComp)[0];
iComp[1] = (v.iComp)[1];
iComp[2] = (v.iComp)[2];
return *this;
}
mgVector_c::~mgVector_c()
{
}
void mgVector_c::set_x( double new_x )
{
iComp[0] = new_x;
}
void mgVector_c::set_y( double new_y )
{
iComp[1] = new_y;
}
void mgVector_c::set_z( double new_z )
{
iComp[2] = new_z;
}
void mgVector_c::set( double compIn[3] )
{
memcpy( iComp, compIn, 3 * sizeof( double ) );
}
void mgVector_c::set( double new_x, double new_y, double new_z)
{
iComp[0] = new_x;
iComp[1] = new_y;
iComp[2] = new_z;
}
mgVector_c operator-( mgVector_c const &v )
{
return mgVector_c ( -(v.iComp[0]), -(v.iComp[1]), -(v.iComp[2]) );
}
mgVector_c operator+( mgVector_c const &v1, mgVector_c const &v2 )
{
return mgVector_c ( ( v1.iComp[0] + v2.iComp[0] ),
( v1.iComp[1] + v2.iComp[1] ),
( v1.iComp[2] + v2.iComp[2] )
);
}
mgVector_c const &mgVector_c::operator+=( mgVector_c const &v )
{
iComp[0] += (v.iComp)[0];
iComp[1] += (v.iComp)[1];
iComp[2] += (v.iComp)[2];
return *this;
}
mgVector_c operator-( mgVector_c const &v1, mgVector_c const &v2 )
{
return mgVector_c ( ( v1.iComp[0] - v2.iComp[0] ),
( v1.iComp[1] - v2.iComp[1] ),
( v1.iComp[2] - v2.iComp[2] )
);
}
mgVector_c operator*( double s, mgVector_c const &v )
{
return mgVector_c ( s * ( v.iComp[0] ), s * ( v.iComp[1] ), s * ( v.iComp[2] ) );
}
mgVector_c operator*( mgVector_c const &v, double s )
{
return mgVector_c ( s * ( v.iComp[0] ), s * ( v.iComp[1] ), s * ( v.iComp[2] ) );
}
mgVector_c const &mgVector_c::operator*=( double s )
{
iComp[0] *= s;
iComp[1] *= s;
iComp[2] *= s;
return *this;
}
double operator%( mgVector_c const &v1, mgVector_c const &v2 )
{
// Dot product
return (
( v1.iComp[0] * v2.iComp[0] ) +
( v1.iComp[1] * v2.iComp[1] ) +
( v1.iComp[2] * v2.iComp[2] )
);
}
mgVector_c operator*( mgVector_c const &v1, mgVector_c const &v2 )
{
// Cross product
double components[3];
components[0] = ( (v1.iComp )[1] * (v2.iComp )[2] ) -
( (v1.iComp )[2] * (v2.iComp )[1] );
components[1] = ( (v1.iComp )[2] * (v2.iComp )[0] ) -
( (v1.iComp )[0] * (v2.iComp )[2] );
components[2] = ( (v1.iComp )[0] * (v2.iComp )[1] ) -
( (v1.iComp )[1] * (v2.iComp )[0] );
return mgVector_c ( components );
}
mgVector_c operator/( mgVector_c const &v, double s)
{
if ( fabs(s) < gcLengthTolerance )
return mgVector_c( 0.0, 0.0, 0.0 );
else
return mgVector_c ( ( v.iComp[0] ) / s, ( v.iComp[1] ) / s, ( v.iComp[2] ) / s );
}
BOOL mgVector_c::isNotNull() const
{
if ( fabs ( iComp[0] ) <gcLengthTolerance && fabs ( iComp[1] ) <gcLengthTolerance && fabs ( iComp[2] ) < gcLengthTolerance )
{
return FALSE;
}
return TRUE;
}
BOOL mgVector_c::isNull() const
{
if ( fabs ( iComp[0] ) <gcLengthTolerance && fabs ( iComp[1] ) <gcLengthTolerance && fabs ( iComp[2] ) < gcLengthTolerance )
{
return TRUE;
}
return FALSE;
}
BOOL operator==(mgVector_c const &v1, mgVector_c const &v2)
{
return (
( fabs ( (v1.iComp[0] ) - ( v2.iComp[0] ) ) < gcLengthTolerance ) &&
( fabs ( (v1.iComp[1] ) - ( v2.iComp[1] ) ) < gcLengthTolerance ) &&
( fabs ( (v1.iComp[2] ) - ( v2.iComp[2] ) ) < gcLengthTolerance )
);
}
BOOL operator!=(mgVector_c const &v1, mgVector_c const &v2)
{
return (
( fabs ( (v1.iComp[0] ) - ( v2.iComp[0] ) ) > gcLengthTolerance ) ||
( fabs ( (v1.iComp[1] ) - ( v2.iComp[1] ) ) > gcLengthTolerance ) ||
( fabs ( (v1.iComp[2] ) - ( v2.iComp[2] ) ) > gcLengthTolerance )
);
}
mgVector_c mg_Normalise( mgVector_c const &v )
{
double denominator = v.x()*v.x() + v.y()*v.y() + v.z()*v.z();
if (denominator < gcDoubleTolerance)
return mgVector_c( 0.0, 0.0, 0.0 );
return mgVector_c( v.x()/denominator, v.y()/denominator, v.z()/denominator );
}
double vol(mgVector_c const &v1,
mgVector_c const &v2, mgVector_c const &v3)
{
mgVector_c vect = v1*v2;
return(vect % v3);
}
BOOL mgVector_c::isOrthogonal ()
{
if ( fabs( x() ) < gcLengthTolerance &&
fabs( y() ) < gcLengthTolerance &&
fabs( z() ) < gcLengthTolerance )
return FALSE; // everything zero
if ( fabs( x() ) < gcLengthTolerance &&
fabs( y() ) < gcLengthTolerance )
return TRUE; // has a Z only
if ( fabs( x() ) < gcLengthTolerance &&
fabs( z() ) < gcLengthTolerance )
return TRUE; // has a Y only
if ( fabs( y() ) < gcLengthTolerance &&
fabs( z() ) < gcLengthTolerance )
return TRUE; // has a X only
return FALSE;
}
// cast operator to conveniently pass the list to parasolid
mgVector_c::operator double* ()
{
return iComp;
}
BOOL mgVector_c::normalise()
{
if (isNull())
return FALSE;
*this = mg_Normalise(*this);
return TRUE;
}
| 22.516981 | 127 | 0.558405 | neboat |
202d45e38a36b90376523fe8e8129b6bf0cd7b7e | 10,782 | cpp | C++ | src/math/matrix/matrix3x3.cpp | Gotatang/DadEngine_2.0 | 1e97e86996571c8ba1efec72b0f0e914d86533d3 | [
"MIT"
] | 2 | 2018-03-12T13:59:13.000Z | 2018-11-27T20:13:57.000Z | src/math/matrix/matrix3x3.cpp | Gotatang/DadEngine_2.0 | 1e97e86996571c8ba1efec72b0f0e914d86533d3 | [
"MIT"
] | 5 | 2018-12-22T10:43:28.000Z | 2019-01-17T22:02:16.000Z | src/math/matrix/matrix3x3.cpp | ladevieq/dadengine | 1e97e86996571c8ba1efec72b0f0e914d86533d3 | [
"MIT"
] | null | null | null | #include "matrix/matrix3x3.hpp"
#include "constants.hpp"
#include "vector/vector2.hpp"
#include "vector/vector3.hpp"
#include <limits>
namespace DadEngine
{
Matrix3x3::Matrix3x3(std::array<Vector3, 3> _vectors)
{
m_11 = _vectors[0U].x, m_12 = _vectors[1U].x, m_13 = _vectors[2U].x;
m_21 = _vectors[0U].y, m_22 = _vectors[1U].y, m_23 = _vectors[2U].y;
m_31 = _vectors[0U].z, m_32 = _vectors[1U].z, m_33 = _vectors[2U].z;
}
Matrix3x3::Matrix3x3(
float _11, float _12, float _13, float _21, float _22, float _23, float _31, float _32, float _33)
{
m_11 = _11, m_12 = _12, m_13 = _13;
m_21 = _21, m_22 = _22, m_23 = _23;
m_31 = _31, m_32 = _32, m_33 = _33;
}
Matrix3x3::Matrix3x3(std::array<float, 9> _data)
{
m_11 = _data[0U], m_12 = _data[1U], m_13 = _data[2U];
m_21 = _data[3U], m_22 = _data[4U], m_23 = _data[5U];
m_31 = _data[6U], m_32 = _data[7U], m_33 = _data[8U];
}
// Standard matrix functions
void Matrix3x3::SetIdentity()
{
m_11 = 1.f, m_12 = 0.f, m_13 = 0.f;
m_21 = 0.f, m_22 = 1.f, m_23 = 0.f;
m_31 = 0.f, m_32 = 0.f, m_33 = 1.f;
}
void Matrix3x3::Transpose()
{
Matrix3x3 temp = *this;
m_12 = m_21;
m_13 = m_31;
m_23 = m_32;
m_21 = temp.m_12;
m_31 = temp.m_13;
m_32 = temp.m_23;
}
void Matrix3x3::Inverse()
{
float cof11 = (m_22 * m_33 - m_23 * m_32);
float cof12 = -(m_21 * m_33 - m_23 * m_31);
float cof13 = (m_21 * m_32 - m_22 * m_31);
float determinant = m_11 * cof11 + m_12 * cof12 + m_13 * cof13;
if (determinant > std::numeric_limits<decltype(determinant)>::epsilon()
|| determinant < std::numeric_limits<decltype(determinant)>::epsilon()) {
determinant = 1.f / determinant;
float cof21 = -(m_12 * m_33 - m_13 * m_32);
float cof22 = (m_11 * m_33 - m_13 * m_31);
float cof23 = -(m_11 * m_32 - m_12 * m_31);
float cof31 = (m_12 * m_23 - m_13 * m_22);
float cof32 = -(m_11 * m_23 - m_13 * m_21);
float cof33 = (m_11 * m_22 - m_12 * m_21);
m_11 = cof11 * determinant, m_12 = cof12 * determinant, m_13 = cof13 * determinant;
m_21 = cof21 * determinant, m_22 = cof22 * determinant, m_23 = cof23 * determinant;
m_31 = cof31 * determinant, m_32 = cof32 * determinant, m_33 = cof33 * determinant;
// Transpose();
}
}
float Matrix3x3::Determinant() const
{
float cof11 = (m_22 * m_33 - m_23 * m_32);
float cof12 = -(m_21 * m_33 - m_23 * m_31);
float cof13 = (m_21 * m_32 - m_22 * m_31);
return m_11 * cof11 + m_12 * cof12 + m_13 * cof13;
}
void Matrix3x3::RotationX(float _angle)
{
float cos = std::cos(_angle);
float sin = std::sin(_angle);
m_11 = 1.f, m_12 = 0.f, m_13 = 0.f;
m_21 = 0.f, m_22 = cos, m_23 = -sin;
m_31 = 0.f, m_32 = sin, m_33 = cos;
}
void Matrix3x3::RotationY(float _angle)
{
float cos = std::cos(_angle);
float sin = std::sin(_angle);
m_11 = cos, m_12 = 0.f, m_13 = sin;
m_21 = 0.f, m_22 = 1.f, m_23 = 0.f;
m_31 = -sin, m_32 = 0.f, m_33 = cos;
}
void Matrix3x3::RotationZ(float _angle)
{
float cos = std::cos(_angle);
float sin = std::sin(_angle);
m_11 = cos, m_12 = -sin, m_13 = 0.f;
m_21 = sin, m_22 = cos, m_23 = 0.f;
m_31 = 0.f, m_32 = 0.f, m_33 = 1.f;
}
void Matrix3x3::Rotation(float _angle, Vector3 _axis)
{
float cos = std::cos(_angle);
float sin = std::sin(_angle);
float cosLessOne = 1 - cos;
m_11 = cos + (cosLessOne * _axis.x * _axis.x),
m_12 = (cosLessOne * _axis.x * _axis.y) - (sin * _axis.z),
m_13 = (cosLessOne * _axis.x * _axis.z) + (sin * _axis.y);
m_21 = (cosLessOne * _axis.x * _axis.y) + (sin * _axis.z),
m_22 = cos + (cosLessOne * _axis.y * _axis.y),
m_23 = (cosLessOne * _axis.y * _axis.z) - (sin * _axis.x);
m_31 = (cosLessOne * _axis.x * _axis.z) - (sin * _axis.y),
m_32 = (cosLessOne * _axis.y * _axis.z) + (sin * _axis.x),
m_33 = cos + (cosLessOne * _axis.z * _axis.z);
}
void Matrix3x3::Scale(float _scaleX, float _scaleY, float _scaleZ)
{
m_11 = _scaleX, m_12 = 0.f, m_13 = 0.f;
m_21 = 0.f, m_22 = _scaleY, m_23 = 0.f;
m_31 = 0.f, m_32 = 0.f, m_33 = _scaleZ;
}
void Matrix3x3::Translation(Vector2 _translation)
{
m_11 = 0.f, m_12 = 0.f, m_13 = _translation.x;
m_21 = 0.f, m_22 = 0.f, m_23 = _translation.y;
m_31 = 0.f, m_32 = 0.f, m_33 = 1.f;
}
// Binary math operators
Matrix3x3 Matrix3x3::operator+(Matrix3x3 &_matrix) const
{
Matrix3x3 result;
result.m_11 = m_11 + _matrix.m_11, result.m_12 = m_12 + _matrix.m_12,
result.m_13 = m_13 + _matrix.m_13;
result.m_21 = m_21 + _matrix.m_21, result.m_22 = m_22 + _matrix.m_22,
result.m_23 = m_23 + _matrix.m_23;
result.m_31 = m_31 + _matrix.m_31, result.m_32 = m_32 + _matrix.m_32,
result.m_33 = m_33 + _matrix.m_33;
return result;
}
Matrix3x3 Matrix3x3::operator-(Matrix3x3 &_matrix) const
{
Matrix3x3 result;
result.m_11 = m_11 - _matrix.m_11, result.m_12 = m_12 - _matrix.m_12,
result.m_13 = m_13 - _matrix.m_13;
result.m_21 = m_21 - _matrix.m_21, result.m_22 = m_22 - _matrix.m_22,
result.m_23 = m_23 - _matrix.m_23;
result.m_31 = m_31 - _matrix.m_31, result.m_32 = m_32 - _matrix.m_32,
result.m_33 = m_33 - _matrix.m_33;
return result;
}
Matrix3x3 Matrix3x3::operator*(float &_factor) const
{
Matrix3x3 result;
result.m_11 = m_11 * _factor, result.m_12 = m_12 * _factor,
result.m_13 = m_13 * _factor;
result.m_21 = m_21 * _factor, result.m_22 = m_22 * _factor,
result.m_23 = m_23 * _factor;
result.m_31 = m_31 * _factor, result.m_32 = m_32 * _factor,
result.m_33 = m_33 * _factor;
return result;
}
Vector3 Matrix3x3::operator*(Vector3 &_vector) const
{
return Vector3(m_11 * _vector.x + m_12 * _vector.y + m_13 * _vector.z,
m_21 * _vector.x + m_22 * _vector.y + m_23 * _vector.z,
m_31 * _vector.x + m_32 * _vector.y + m_33 * _vector.z);
}
Matrix3x3 Matrix3x3::operator*(Matrix3x3 &_matrix) const
{
Matrix3x3 result;
result.m_11 = m_11 * _matrix.m_11 + m_12 * _matrix.m_21 + m_13 * _matrix.m_31;
result.m_12 = m_11 * _matrix.m_12 + m_12 * _matrix.m_22 + m_13 * _matrix.m_32;
result.m_13 = m_11 * _matrix.m_13 + m_12 * _matrix.m_23 + m_13 * _matrix.m_33;
result.m_21 = m_21 * _matrix.m_11 + m_22 * _matrix.m_21 + m_23 * _matrix.m_31;
result.m_22 = m_21 * _matrix.m_12 + m_22 * _matrix.m_22 + m_23 * _matrix.m_32;
result.m_23 = m_21 * _matrix.m_13 + m_22 * _matrix.m_23 + m_23 * _matrix.m_33;
result.m_31 = m_31 * _matrix.m_11 + m_32 * _matrix.m_21 + m_33 * _matrix.m_31;
result.m_32 = m_31 * _matrix.m_12 + m_32 * _matrix.m_22 + m_33 * _matrix.m_32;
result.m_33 = m_31 * _matrix.m_13 + m_32 * _matrix.m_23 + m_33 * _matrix.m_33;
return result;
}
Matrix3x3 Matrix3x3::operator/(float &_factor) const
{
Matrix3x3 result;
result.m_11 = m_11 / _factor, result.m_12 = m_12 / _factor,
result.m_13 = m_13 / _factor;
result.m_21 = m_21 / _factor, result.m_22 = m_22 / _factor,
result.m_23 = m_23 / _factor;
result.m_31 = m_31 / _factor, result.m_32 = m_32 / _factor,
result.m_33 = m_33 / _factor;
return result;
}
Matrix3x3 Matrix3x3::operator/(Matrix3x3 &_matrix) const
{
Matrix3x3 result;
_matrix.Inverse();
result = *this * _matrix;
return result;
}
// Binary assignement math operators
void Matrix3x3::operator+=(Matrix3x3 &_matrix)
{
m_11 += _matrix.m_11, m_12 += _matrix.m_12, m_13 += _matrix.m_13;
m_21 += _matrix.m_21, m_22 += _matrix.m_22, m_23 += _matrix.m_23;
m_31 += _matrix.m_31, m_32 += _matrix.m_32, m_33 += _matrix.m_33;
}
void Matrix3x3::operator-=(Matrix3x3 &_matrix)
{
m_11 -= _matrix.m_11, m_12 -= _matrix.m_12, m_13 -= _matrix.m_13;
m_21 -= _matrix.m_21, m_22 -= _matrix.m_22, m_23 -= _matrix.m_23;
m_31 -= _matrix.m_31, m_32 -= _matrix.m_32, m_33 -= _matrix.m_33;
}
void Matrix3x3::operator*=(float &_factor)
{
m_11 *= _factor, m_12 *= _factor, m_13 *= _factor;
m_21 *= _factor, m_22 *= _factor, m_23 *= _factor;
m_31 *= _factor, m_32 *= _factor, m_33 *= _factor;
}
Vector3 Matrix3x3::operator*=(Vector3 &_vector) const
{
return Vector3(m_11 * _vector.x + m_12 * _vector.y + m_13 * _vector.z,
m_21 * _vector.x + m_22 * _vector.y + m_23 * _vector.z,
m_31 * _vector.x + m_32 * _vector.y + m_33 * _vector.z);
}
void Matrix3x3::operator*=(Matrix3x3 &_matrix)
{
Matrix3x3 temp = *this;
m_11 = temp.m_11 * _matrix.m_11 + temp.m_12 * _matrix.m_21
+ temp.m_13 * _matrix.m_31;
m_12 = temp.m_11 * _matrix.m_12 + temp.m_12 * _matrix.m_22
+ temp.m_13 * _matrix.m_32;
m_13 = temp.m_11 * _matrix.m_13 + temp.m_12 * _matrix.m_23
+ temp.m_13 * _matrix.m_33;
m_21 = temp.m_21 * _matrix.m_11 + temp.m_22 * _matrix.m_21
+ temp.m_23 * _matrix.m_31;
m_22 = temp.m_21 * _matrix.m_12 + temp.m_22 * _matrix.m_22
+ temp.m_23 * _matrix.m_32;
m_23 = temp.m_21 * _matrix.m_13 + temp.m_22 * _matrix.m_23
+ temp.m_23 * _matrix.m_33;
m_31 = temp.m_31 * _matrix.m_11 + temp.m_32 * _matrix.m_21
+ temp.m_33 * _matrix.m_31;
m_32 = temp.m_31 * _matrix.m_12 + temp.m_32 * _matrix.m_22
+ temp.m_33 * _matrix.m_32;
m_33 = temp.m_31 * _matrix.m_13 + temp.m_32 * _matrix.m_23
+ temp.m_33 * _matrix.m_33;
}
void Matrix3x3::operator/=(float &_factor)
{
m_11 /= _factor, m_12 /= _factor, m_13 /= _factor;
m_21 /= _factor, m_22 /= _factor, m_23 /= _factor;
m_31 /= _factor, m_32 /= _factor, m_33 /= _factor;
}
void Matrix3x3::operator/=(Matrix3x3 &_matrix)
{
_matrix.Inverse();
*this *= _matrix;
}
} // namespace DadEngine
| 34.557692 | 106 | 0.560286 | Gotatang |
2032531a2a5b2ff52b3ce301a1007240bd5e3ba0 | 781 | cc | C++ | leet_code/Check_If_Word_Is_Valid_After_Substitutions/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | 1 | 2020-04-11T22:04:23.000Z | 2020-04-11T22:04:23.000Z | leet_code/Check_If_Word_Is_Valid_After_Substitutions/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | leet_code/Check_If_Word_Is_Valid_After_Substitutions/solve.cc | ldy121/algorithm | 7939cb4c15e2bc655219c934f00c2bb74ddb4eec | [
"Apache-2.0"
] | null | null | null | class Solution {
private :
const int windowSize = 3;
const char invalid = -1;
public:
bool isValid(string S) {
string& in = S;
for (bool isChange = true; isChange;) {
string data;
for (int i = 0; i < in.length(); ++i) {
if (in[i] != invalid) {
data += in[i];
}
}
isChange = false;
for (string::size_type idx = data.find("abc", 0);
idx != string::npos;
idx = data.find("abc", idx)) {
data[idx] = data[idx + 1] = data[idx + 2] = invalid;
isChange = true;
}
in = data;
}
return (in.length() == 0);
}
};
| 26.033333 | 68 | 0.386684 | ldy121 |
20336bb91326e6df27c8ebf0790a01ef49d9b053 | 729 | cpp | C++ | cpp_alkeet/2_Harjoitukset_190912/fourth.cpp | Diapolo10/TAMK-Exercises | 904958cc41b253201eef182f17e43d95cf4f7c89 | [
"MIT"
] | null | null | null | cpp_alkeet/2_Harjoitukset_190912/fourth.cpp | Diapolo10/TAMK-Exercises | 904958cc41b253201eef182f17e43d95cf4f7c89 | [
"MIT"
] | null | null | null | cpp_alkeet/2_Harjoitukset_190912/fourth.cpp | Diapolo10/TAMK-Exercises | 904958cc41b253201eef182f17e43d95cf4f7c89 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using std::vector;
double mass_sum(vector<double> nums) {
double result = .0;
for (auto num : nums) {
result += num;
}
return result;
}
vector<double>& get_passenger_masses(int n=4) {
vector<double> masses;
for (int i = 1; i <= n; ++i) {
double mass;
std::cout << "Passenger #" << i << ": ";
std::cin >> mass;
masses.push_back(mass);
}
return masses;
}
int main(void) {
double max_mass;
vector<double> people;
std::cout << "Elevator's maximum supported mass: ";
std::cin >> max_mass;
people = get_passenger_masses();
std::cout << ((mass_sum(people) > max_mass) ? "Overweight, elevator not usable!" : "Elevator at your service!") << "\n";
return 0;
} | 16.2 | 121 | 0.628258 | Diapolo10 |
2035f9c617a2c5660a1e1a416b52124a7f622c40 | 3,188 | cpp | C++ | test/test_optimizers.cpp | AvocadoML/CudaBackend | 314413c12efa7cb12a1ff0c2572c8aad9190d419 | [
"Apache-2.0"
] | 2 | 2022-03-14T07:13:37.000Z | 2022-03-16T00:16:33.000Z | test/test_optimizers.cpp | AvocadoML/CudaBackend | 314413c12efa7cb12a1ff0c2572c8aad9190d419 | [
"Apache-2.0"
] | null | null | null | test/test_optimizers.cpp | AvocadoML/CudaBackend | 314413c12efa7cb12a1ff0c2572c8aad9190d419 | [
"Apache-2.0"
] | 1 | 2022-03-14T07:13:44.000Z | 2022-03-14T07:13:44.000Z | /*
* test_optimizers.cpp
*
* Created on: Jan 27, 2022
* Author: Maciej Kozarzewski
*/
#include <testing/testing_helpers.hpp>
#include <gtest/gtest.h>
namespace avocado
{
namespace backend
{
TEST(TestOptimizer, float32_sgd)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT32))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32);
data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.0, 0., 0.0, 0.0 }, { false, false, false, false });
float alpha = 1.1f, beta = 0.1f;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float32_sgd_momentum)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT32))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32);
data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, false, false, false });
float alpha = 1.1f, beta = 0.1f;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float32_sgd_nesterov)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT32))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32);
data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, true, false, false });
float alpha = 1.1f, beta = 0.1f;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float32_adam)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT32))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT32);
data.set(AVOCADO_OPTIMIZER_ADAM, 0.01, { 0.01, 0.001, 0.0, 0.0 }, { false, false, false, false });
float alpha = 1.1f, beta = 0.1f;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float64_sgd)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT64))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64);
data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.0, 0., 0.0, 0.0 }, { false, false, false, false });
double alpha = 1.1, beta = 0.1;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float64_sgd_momentum)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT64))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64);
data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, false, false, false });
double alpha = 1.1, beta = 0.1;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float64_sgd_nesterov)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT64))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64);
data.set(AVOCADO_OPTIMIZER_SGD, 0.01, { 0.01, 0.0, 0.0, 0.0 }, { true, true, false, false });
double alpha = 1.1, beta = 0.1;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
TEST(TestOptimizer, float64_adam)
{
if (not supportsType(AVOCADO_DTYPE_FLOAT64))
GTEST_SKIP();
OptimizerTester data( { 23, 45 }, AVOCADO_DTYPE_FLOAT64);
data.set(AVOCADO_OPTIMIZER_ADAM, 0.01, { 0.01, 0.001, 0.0, 0.0 }, { false, false, false, false });
double alpha = 1.1, beta = 0.1;
EXPECT_LT(data.getDifference(&alpha, &beta), 1.0e-4);
}
} /* namespace backend */
} /* namespace avocado */
| 34.27957 | 101 | 0.663425 | AvocadoML |
2039ba4370d7625f068debb573eb3548460aabea | 744 | cpp | C++ | Arrays/miscellaneous/k_divisible_elements_subarray.cpp | khushisinha20/Data-Structures-and-Algorithms | 114d365d03f7ba7175eefeace281972820a7fc76 | [
"Apache-2.0"
] | null | null | null | Arrays/miscellaneous/k_divisible_elements_subarray.cpp | khushisinha20/Data-Structures-and-Algorithms | 114d365d03f7ba7175eefeace281972820a7fc76 | [
"Apache-2.0"
] | null | null | null | Arrays/miscellaneous/k_divisible_elements_subarray.cpp | khushisinha20/Data-Structures-and-Algorithms | 114d365d03f7ba7175eefeace281972820a7fc76 | [
"Apache-2.0"
] | null | null | null | //leetcode.com/problems/k-divisible-elements-subarrays/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int countDistinct(vector<int>& nums, int k, int p) {
set<vector<int>> distinct_subarrays;
int multiples_of_p = 0;
for (int i = 0; i < nums.size(); ++i) {
multiples_of_p = 0;
vector<int> subarray;
for (int j = i; j < nums.size(); ++j) {
subarray.push_back(nums[j]);
if (nums[j] % p == 0)
++multiples_of_p;
if (multiples_of_p > k)
break;
distinct_subarrays.insert(subarray);
}
}
return distinct_subarrays.size();
}
}; | 29.76 | 56 | 0.508065 | khushisinha20 |
203a102f86509c20df7e82f0cec3a908a06547bf | 2,459 | hpp | C++ | INCLUDE/json.hpp | n-mam/cpp-osl | 44f32d9e0670b30ff08f08f540e0f161f7d62965 | [
"MIT"
] | null | null | null | INCLUDE/json.hpp | n-mam/cpp-osl | 44f32d9e0670b30ff08f08f540e0f161f7d62965 | [
"MIT"
] | null | null | null | INCLUDE/json.hpp | n-mam/cpp-osl | 44f32d9e0670b30ff08f08f540e0f161f7d62965 | [
"MIT"
] | null | null | null | #ifndef JSON_HPP
#define JSON_HPP
#include <map>
#include <regex>
#include <string>
#include <vector>
#include <sstream>
#include <string.hpp>
class Json
{
public:
Json()
{
}
Json(const std::string& s)
{
iJsonString = s;
Parse();
}
~Json()
{
}
bool IsOk()
{
return false;
}
std::string GetKey(const std::string& key)
{
return iMap[key];
}
void SetKey(const std::string& key, const std::string& value)
{
iMap[key] = std::regex_replace(value, std::regex(R"(\\)"), R"(\\)");
}
bool HasKey(const std::string& key)
{
auto fRet = iMap.find(key);
if (fRet != iMap.end())
{
return true;
}
else
{
return false;
}
}
std::string Stringify(void)
{
std::string js;
js += "{";
for (const auto &element : iMap)
{
if (js.length() > 1)
{
js += ", ";
}
js += "\"" + element.first + "\"" + ": ";
if ((element.second)[0] != '[')
{
js += "\"" + element.second + "\"";
}
else
{
js += element.second;
}
}
js += "}";
return js;
}
static std::string JsonListToArray(std::vector<Json>& list)
{
std::string value = "[";
for(auto& j : list)
{
value += j.Stringify();
value += ",";
}
value = trim(value, ",");
value += "]";
return value;
}
/*
* This assumes that the json has been stringifie'd and has only
* string kv pairs, otherwise this would fail miserably
* {"service":"ftp","request":"connect","list":"/","id":"0","host":"w","port":"w","user":"w","pass":"w"}
*/
void Parse(void)
{
ltrim(iJsonString, "{\"");
rtrim(iJsonString, "\"}");
auto pp = split(iJsonString, "\",\"");
for (auto& p : pp)
{
auto kv = split(p, "\":\"");
if (kv.size() == 2)
{
iMap.insert(
std::make_pair(kv[0], kv[1])
);
}
}
}
void Dump(void)
{
}
private:
std::string iJsonString;
std::map<std::string, std::string> iMap;
};
#endif //JSON_HPP
| 16.727891 | 109 | 0.413176 | n-mam |
203a3fb00b88e7e7bac33472923c81858d9ec485 | 1,705 | cpp | C++ | Editor/Sources/o2Editor/Core/Properties/Basic/EnumProperty.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Editor/Sources/o2Editor/Core/Properties/Basic/EnumProperty.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Editor/Sources/o2Editor/Core/Properties/Basic/EnumProperty.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2Editor/stdafx.h"
#include "EnumProperty.h"
#include "o2/Scene/UI/Widgets/DropDown.h"
namespace Editor
{
EnumProperty::EnumProperty()
{}
EnumProperty::EnumProperty(const EnumProperty& other) :
TPropertyField<int>(other)
{
InitializeControls();
}
EnumProperty& EnumProperty::operator=(const EnumProperty& other)
{
TPropertyField<int>::operator=(other);
InitializeControls();
return *this;
}
void EnumProperty::InitializeControls()
{
mDropDown = FindChildByType<DropDown>();
if (mDropDown)
{
mDropDown->onSelectedText = THIS_FUNC(OnSelectedItem);
mDropDown->SetState("undefined", true);
}
}
const Type* EnumProperty::GetValueType() const
{
return mEnumType;
}
void EnumProperty::SpecializeType(const Type* type)
{
if (type->GetUsage() == Type::Usage::Property)
mEnumType = dynamic_cast<const EnumType*>(((const PropertyType*)type)->GetValueType());
else
mEnumType = dynamic_cast<const EnumType*>(type);
if (mEnumType)
{
mEntries = &mEnumType->GetEntries();
for (auto& kv : *mEntries)
mDropDown->AddItem(kv.second);
}
}
const Type* EnumProperty::GetValueTypeStatic()
{
return nullptr;
}
void EnumProperty::UpdateValueView()
{
mUpdatingValue = true;
if (mValuesDifferent)
{
mDropDown->value = (*mEntries).Get(mCommonValue);
mDropDown->SetState("undefined", true);
}
else
{
mDropDown->value = (*mEntries).Get(mCommonValue);
mDropDown->SetState("undefined", false);
}
mUpdatingValue = false;
}
void EnumProperty::OnSelectedItem(const WString& name)
{
if (mUpdatingValue)
return;
SetValueByUser(mEntries->FindValue(name).first);
}
}
DECLARE_CLASS(Editor::EnumProperty);
| 19.375 | 90 | 0.70088 | zenkovich |
203ae6d848b59e2bdcc89ce0d41f1f886bb6007b | 643 | cpp | C++ | Firmware/src/Buzzer/Buzzer.cpp | FERRERDEV/Mila | 80e9a0ba9e8d5e318a659f17523e3ab3a1d15dd4 | [
"MIT"
] | null | null | null | Firmware/src/Buzzer/Buzzer.cpp | FERRERDEV/Mila | 80e9a0ba9e8d5e318a659f17523e3ab3a1d15dd4 | [
"MIT"
] | null | null | null | Firmware/src/Buzzer/Buzzer.cpp | FERRERDEV/Mila | 80e9a0ba9e8d5e318a659f17523e3ab3a1d15dd4 | [
"MIT"
] | 1 | 2021-02-22T00:54:07.000Z | 2021-02-22T00:54:07.000Z | // Buzzer
#include "Buzzer.h"
// Arduino
#include "Arduino.h"
// Mila
#include "Mila.h"
Buzzer::Buzzer(int buzzerPin)
{
// Assign the buzzer pin.
this->buzzerPin = buzzerPin;
}
void Buzzer::playAlarm(alarm alarmToPlay, int loops)
{
bInfiniteAlarm = loops == -1;
while (bInfiniteAlarm)
{
for (int loop = loops; loop - loops >= 0; loop--)
{
if (bInfiniteAlarm)
loop++;
for (int i = 0; i < alarmToPlay.Lenght; i++)
{
tone(buzzerPin, alarmToPlay.Cue[i].Tone, alarmToPlay.Cue[i].Duration);
delay(alarmToPlay.Time);
}
delay(alarmToPlay.Time);
}
}
}
void Buzzer::stopAlarm()
{
bInfiniteAlarm = false;
}
| 15.682927 | 74 | 0.642302 | FERRERDEV |
203d7e2a78cc55216f2452d82f56b547523ba228 | 4,345 | hh | C++ | psdaq/psdaq/eb/EbLfLink.hh | slac-lcls/pdsdata2 | 6e2ad4f830cadfe29764dbd280fa57f8f9edc451 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/psdaq/eb/EbLfLink.hh | slac-lcls/pdsdata2 | 6e2ad4f830cadfe29764dbd280fa57f8f9edc451 | [
"BSD-3-Clause-LBNL"
] | null | null | null | psdaq/psdaq/eb/EbLfLink.hh | slac-lcls/pdsdata2 | 6e2ad4f830cadfe29764dbd280fa57f8f9edc451 | [
"BSD-3-Clause-LBNL"
] | null | null | null | #ifndef Pds_Eb_EbLfLink_hh
#define Pds_Eb_EbLfLink_hh
#include "Endpoint.hh"
#include <stdint.h>
#include <cstddef>
#include <vector>
namespace Pds {
namespace Eb {
int setupMr(Fabrics::Fabric* fabric,
void* region,
size_t size,
Fabrics::MemoryRegion** mr,
const unsigned& verbose);
class EbLfLink
{
public:
EbLfLink(Fabrics::Endpoint*, int depth, const unsigned& verbose);
public:
int recvU32(uint32_t* u32, const char* peer, const char* name);
int sendU32(uint32_t u32, const char* peer, const char* name);
int sendMr(Fabrics::MemoryRegion*, const char* peer);
int recvMr(Fabrics::RemoteAddress&, const char* peer);
public:
void* lclAdx(size_t offset) const;
size_t lclOfs(const void* buffer) const;
uintptr_t rmtAdx(size_t offset) const;
size_t rmtOfs(uintptr_t buffer) const;
public:
Fabrics::Endpoint* endpoint() const { return _ep; }
unsigned id() const { return _id; }
const uint64_t& tmoCnt() const { return _timedOut; }
public:
int post(const void* buf,
size_t len,
uint64_t immData);
int post(uint64_t immData);
int poll(uint64_t* data);
int poll(uint64_t* data, int msTmo);
public:
ssize_t postCompRecv();
ssize_t postCompRecv(unsigned count);
protected:
enum { _BegSync = 0x11111111,
_EndSync = 0x22222222,
_SvrSync = 0x33333333,
_CltSync = 0x44444444 };
protected: // Arranged in order of access frequency
unsigned _id; // ID of peer
Fabrics::Endpoint* _ep; // Endpoint
Fabrics::MemoryRegion* _mr; // Memory Region
Fabrics::RemoteAddress _ra; // Remote address descriptor
const unsigned& _verbose; // Print some stuff if set
uint64_t _timedOut;
public:
int _depth;
};
class EbLfSvrLink : public EbLfLink
{
public:
EbLfSvrLink(Fabrics::Endpoint*, int rxDepth, const unsigned& verbose);
public:
int prepare(unsigned id,
const char* peer);
int prepare(unsigned id,
size_t* size,
const char* peer);
int setupMr(void* region, size_t size, const char* peer);
private:
int _synchronizeBegin();
int _synchronizeEnd();
};
class EbLfCltLink : public EbLfLink
{
public:
EbLfCltLink(Fabrics::Endpoint*, int rxDepth, const unsigned& verbose, volatile uint64_t& pending);
public:
int prepare(unsigned id,
const char* peer);
int prepare(unsigned id,
void* region,
size_t lclSize,
size_t rmtSize,
const char* peer);
int prepare(unsigned id,
void* region,
size_t size,
const char* peer);
int setupMr(void* region, size_t size);
public:
int post(const void* buf,
size_t len,
uint64_t offset,
uint64_t immData,
void* ctx = nullptr);
private:
int _synchronizeBegin();
int _synchronizeEnd();
private: // Arranged in order of access frequency
volatile uint64_t& _pending; // Bit list of IDs currently posting
};
};
};
inline
void* Pds::Eb::EbLfLink::lclAdx(size_t offset) const
{
return static_cast<char*>(_mr->start()) + offset;
}
inline
size_t Pds::Eb::EbLfLink::lclOfs(const void* buffer) const
{
return static_cast<const char*>(buffer) -
static_cast<const char*>(_mr->start());
}
inline
uintptr_t Pds::Eb::EbLfLink::rmtAdx(size_t offset) const
{
return _ra.addr + offset;
}
inline
size_t Pds::Eb::EbLfLink::rmtOfs(uintptr_t buffer) const
{
return buffer - _ra.addr;
}
inline
ssize_t Pds::Eb::EbLfLink::postCompRecv(unsigned count)
{
ssize_t rc = 0;
for (unsigned i = 0; i < count; ++i)
{
rc = postCompRecv();
if (rc) break;
}
return rc;
}
#endif
| 28.585526 | 104 | 0.560184 | slac-lcls |
203e80f0620ee2e5c2eaa63de1aea61ab20e64ea | 2,597 | hpp | C++ | example/resnet/model.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | 93 | 2017-10-25T07:48:42.000Z | 2022-02-02T15:18:11.000Z | example/resnet/model.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | null | null | null | example/resnet/model.hpp | wzppengpeng/LittleConv | 12aab4cfbbe965fa8b4053bb464db1165cc4ec31 | [
"MIT"
] | 20 | 2018-02-06T10:01:36.000Z | 2019-07-07T09:26:40.000Z | /**
* the model define by resnet
*/
#include "licon/licon.hpp"
using namespace std;
using namespace licon;
nn::NodePtr BasicBlock(int in_channel, int out_channel, int stride=1) {
auto basic_block = nn::Squential::CreateSquential();
auto conv_block = nn::Squential::CreateSquential();
conv_block->Add(nn::Conv::CreateConv(in_channel, out_channel, 3, stride, 1));
conv_block->Add(nn::BatchNorm::CreateBatchNorm(out_channel));
conv_block->Add(nn::Relu::CreateRelu());
conv_block->Add(nn::Conv::CreateConv(out_channel, out_channel, 3, 1, 1));
conv_block->Add(nn::BatchNorm::CreateBatchNorm(out_channel));
if(stride == 1 && in_channel == out_channel) {
auto identity = nn::EltWiseSum::CreateEltWiseSum(true);
identity->Add(std::move(conv_block));
basic_block->Add(std::move(identity));
basic_block->Add(nn::Relu::CreateRelu());
} else {
auto identity = nn::EltWiseSum::CreateEltWiseSum(false);
auto short_cut = nn::Squential::CreateSquential();
short_cut->Add(nn::Conv::CreateConv(in_channel, out_channel, 1, stride));
short_cut->Add(nn::BatchNorm::CreateBatchNorm(out_channel));
identity->Add(std::move(conv_block));
identity->Add(std::move(short_cut));
basic_block->Add(std::move(identity));
basic_block->Add(nn::Relu::CreateRelu());
}
return basic_block;
}
nn::Model ResNet(const std::vector<int>& num_blocks, int num_classes=10) {
auto model = nn::Squential::CreateSquential();
int in_channel = 32;
auto _make_layer = [&in_channel](int out_channel, int num_blocks, int stride) {
vector<int> strides = {stride};
for(int i = 0; i < num_blocks - 1; ++i) strides.emplace_back(1);
auto layers = nn::Squential::CreateSquential();
for(auto s : strides) {
layers->Add(BasicBlock(in_channel, out_channel, s));
in_channel = out_channel * 1;
}
return layers;
};
model->Add(nn::Conv::CreateConv(3, 32, 3, 1, 1));
model->Add(nn::BatchNorm::CreateBatchNorm(32));
model->Add(nn::Relu::CreateRelu());
model->Add(_make_layer(32, num_blocks[0], 1));
model->Add(_make_layer(64, num_blocks[1], 2)); //16
model->Add(_make_layer(128, num_blocks[2], 2)); //8
model->Add(_make_layer(256, num_blocks[3], 2)); //4
model->Add(nn::AvePool::CreateAvePool(4)); //512 * 1 * 1
model->Add(nn::Linear::CreateLinear(256, num_classes));
model->Add(nn::Softmax::CreateSoftmax());
return model;
}
nn::Model ResNet18() {
return ResNet({2, 2, 2, 2});
} | 38.761194 | 83 | 0.644975 | wzppengpeng |
2040523da9fbf8fa9a4f9488a0b88c808831f963 | 655 | cpp | C++ | 383.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | 383.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | 383.cpp | pengzhezhe/LeetCode | 305ec0c5b4cb5ea7cd244b3308132dee778138bc | [
"Apache-2.0"
] | null | null | null | //
// Created by pzz on 2021/10/20.
//
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26] = {0};
for (char c: ransomNote)
record[c - 'a']++;
for (char c: magazine)
record[c - 'a']--;
for (int i: record) {
if (i > 0)
return false;
}
return true;
}
};
int main() {
string ransomNote = "a";
string magazine = "ab";
Solution solution;
cout << solution.canConstruct(ransomNote, magazine);
return 0;
} | 18.194444 | 59 | 0.538931 | pengzhezhe |
204162dacd7d6099609d23ddb4a3b6737485e432 | 5,423 | cpp | C++ | TouchGFXPortTo_ILI9341_XPT2046_basic_yt_tut2/TouchGFX/generated/images/src/BitmapDatabase.cpp | trteodor/TouchGFX_Test | cd1abdef7e5a6f161ad35754fd951ea5de076021 | [
"MIT"
] | 1 | 2022-02-25T07:20:23.000Z | 2022-02-25T07:20:23.000Z | TouchGFXPortTo_ILI9341_XPT2046_basic_yt_tut2/TouchGFX/generated/images/src/BitmapDatabase.cpp | trteodor/TouchGFX_Test | cd1abdef7e5a6f161ad35754fd951ea5de076021 | [
"MIT"
] | null | null | null | TouchGFXPortTo_ILI9341_XPT2046_basic_yt_tut2/TouchGFX/generated/images/src/BitmapDatabase.cpp | trteodor/TouchGFX_Test | cd1abdef7e5a6f161ad35754fd951ea5de076021 | [
"MIT"
] | 1 | 2021-12-26T22:11:21.000Z | 2021-12-26T22:11:21.000Z | // 4.16.1 0x3fe153e6
// Generated by imageconverter. Please, do not edit!
#include <BitmapDatabase.hpp>
#include <touchgfx/Bitmap.hpp>
extern const unsigned char image_blue_radio_buttons_radio_button_active[]; // BITMAP_BLUE_RADIO_BUTTONS_RADIO_BUTTON_ACTIVE_ID = 0, Size: 44x44 pixels
extern const unsigned char image_blue_radio_buttons_radio_button_inactive[]; // BITMAP_BLUE_RADIO_BUTTONS_RADIO_BUTTON_INACTIVE_ID = 1, Size: 44x44 pixels
extern const unsigned char image_butterflysmaller[]; // BITMAP_BUTTERFLYSMALLER_ID = 2, Size: 64x64 pixels
extern const unsigned char image_diodes[]; // BITMAP_DIODES_ID = 3, Size: 32x32 pixels
extern const unsigned char image_hor_therm_bg_scale[]; // BITMAP_HOR_THERM_BG_SCALE_ID = 4, Size: 280x77 pixels
extern const unsigned char image_hor_therm_progress[]; // BITMAP_HOR_THERM_PROGRESS_ID = 5, Size: 244x18 pixels
extern const unsigned char image_ledoff_scaled[]; // BITMAP_LEDOFF_SCALED_ID = 6, Size: 64x64 pixels
extern const unsigned char image_ledon_sclaed[]; // BITMAP_LEDON_SCLAED_ID = 7, Size: 64x64 pixels
extern const unsigned char image_menuscaled[]; // BITMAP_MENUSCALED_ID = 8, Size: 64x64 pixels
extern const unsigned char image_menuscaledwhite[]; // BITMAP_MENUSCALEDWHITE_ID = 9, Size: 64x64 pixels
extern const unsigned char image_mp3future[]; // BITMAP_MP3FUTURE_ID = 10, Size: 64x64 pixels
extern const unsigned char image_mp3futurepressed[]; // BITMAP_MP3FUTUREPRESSED_ID = 11, Size: 64x64 pixels
extern const unsigned char image_tempoff[]; // BITMAP_TEMPOFF_ID = 12, Size: 64x64 pixels
extern const unsigned char image_temponn[]; // BITMAP_TEMPONN_ID = 13, Size: 64x64 pixels
extern const unsigned char image_tictactoeoff[]; // BITMAP_TICTACTOEOFF_ID = 14, Size: 64x64 pixels
extern const unsigned char image_tictactoeon[]; // BITMAP_TICTACTOEON_ID = 15, Size: 64x64 pixels
extern const unsigned char image_trashszary[]; // BITMAP_TRASHSZARY_ID = 16, Size: 64x64 pixels
extern const unsigned char image_watchblack[]; // BITMAP_WATCHBLACK_ID = 17, Size: 64x64 pixels
extern const unsigned char image_watchwhite[]; // BITMAP_WATCHWHITE_ID = 18, Size: 64x64 pixels
extern const unsigned char image_whitetrash[]; // BITMAP_WHITETRASH_ID = 19, Size: 64x64 pixels
const touchgfx::Bitmap::BitmapData bitmap_database[] =
{
{ image_blue_radio_buttons_radio_button_active, 0, 44, 44, 3, 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_blue_radio_buttons_radio_button_inactive, 0, 44, 44, 3, 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 38, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_butterflysmaller, 0, 64, 64, 50, 34, 2, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 20, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_diodes, 0, 32, 32, 0, 0, 32, (uint8_t)(touchgfx::Bitmap::RGB565) >> 3, 32, (uint8_t)(touchgfx::Bitmap::RGB565) & 0x7 },
{ image_hor_therm_bg_scale, 0, 280, 77, 27, 25, 226, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 24, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_hor_therm_progress, 0, 244, 18, 9, 0, 226, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 18, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_ledoff_scaled, 0, 64, 64, 16, 11, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_ledon_sclaed, 0, 64, 64, 16, 11, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 32, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_menuscaled, 0, 64, 64, 20, 20, 24, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 4, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_menuscaledwhite, 0, 64, 64, 20, 20, 24, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 4, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_mp3future, 0, 64, 64, 10, 9, 44, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 46, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_mp3futurepressed, 0, 64, 64, 10, 9, 44, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 46, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_tempoff, 0, 64, 64, 21, 6, 13, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 56, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_temponn, 0, 64, 64, 21, 6, 13, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 56, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_tictactoeoff, 0, 64, 64, 11, 27, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 36, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_tictactoeon, 0, 64, 64, 11, 27, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 36, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_trashszary, 0, 64, 64, 8, 9, 48, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 10, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_watchblack, 0, 64, 64, 8, 11, 21, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_watchwhite, 0, 64, 64, 8, 11, 21, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 42, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 },
{ image_whitetrash, 0, 64, 64, 8, 9, 48, (uint8_t)(touchgfx::Bitmap::ARGB8888) >> 3, 10, (uint8_t)(touchgfx::Bitmap::ARGB8888) & 0x7 }
};
namespace BitmapDatabase
{
const touchgfx::Bitmap::BitmapData* getInstance()
{
return bitmap_database;
}
uint16_t getInstanceSize()
{
return (uint16_t)(sizeof(bitmap_database) / sizeof(touchgfx::Bitmap::BitmapData));
}
}
| 84.734375 | 169 | 0.717868 | trteodor |
20419ff541ea6aea735c6d5731d25609bde79291 | 2,752 | cpp | C++ | cpp_harness/HarnessUtils.cpp | 13ofClubs/parHarness | 1e82dfabc64af8bced353a5236d1888def8f5dab | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cpp_harness/HarnessUtils.cpp | 13ofClubs/parHarness | 1e82dfabc64af8bced353a5236d1888def8f5dab | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cpp_harness/HarnessUtils.cpp | 13ofClubs/parHarness | 1e82dfabc64af8bced353a5236d1888def8f5dab | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
Copyright 2015 University of Rochester
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 "HarnessUtils.hpp"
#include <list>
#include <iostream>
using namespace std;
void errexit (const char *err_str)
{
fprintf (stderr, "%s\n", err_str);
throw 1;
}
void faultHandler(int sig) {
void *buf[30];
size_t sz;
// scrape backtrace
sz = backtrace(buf, 30);
// print error msg
fprintf(stderr, "Error: signal %d:\n", sig);
backtrace_symbols_fd(buf, sz, STDERR_FILENO);
exit(1);
}
bool isInteger(const std::string &s){
// check for empty case, and easy fail at start of string
if(s.empty() || ( (s[0] != '-') && (s[0] != '+') && (!isdigit(s[0])) ) ){
return false;
}
// strol parses only if valid long.
char* buf;
strtol(s.c_str(), &buf, 60);
return (*buf == 0);
}
std::string machineName(){
char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
return std::string(hostname);
}
int numCores(){
return sysconf( _SC_NPROCESSORS_ONLN );
}
int archBits(){
if(sizeof(void*) == 8){
return 64;
}
else if(sizeof(void*) == 16){
return 128;
}
else if(sizeof(void*) == 4){
return 32;
}
else if(sizeof(void*) == 2){
return 8;
}
}
unsigned int nextRand(unsigned int last) {
unsigned int next = last;
next = next * 1103515245 + 12345;
return((unsigned)(next/65536) % 32768);
}
int warmMemory(unsigned int megabytes){
uint64_t preheat = megabytes*(2<<20);
int blockSize = sysconf(_SC_PAGESIZE);
int toAlloc = preheat / blockSize;
list<void*> allocd;
int ret = 0;
for(int i = 0; i<toAlloc; i++){
int32_t* ptr = (int32_t*)malloc(blockSize);
// ptr2,3 reserves space in case the list needs room
// this prevents seg faults, but we may be killed anyway
// if the system runs out of memory ("Killed" vs "Segmentation Fault")
int32_t* ptr2 = (int32_t*)malloc(blockSize);
int32_t* ptr3 = (int32_t*)malloc(blockSize);
if(ptr==NULL || ptr2==NULL || ptr3==NULL){
ret = -1;
break;
}
free(ptr2); free(ptr3);
ptr[0]=1;
allocd.push_back(ptr);
}
for(int i = 0; i<toAlloc; i++){
void* ptr = allocd.back();
allocd.pop_back();
free(ptr);
}
return ret;
}
| 22.193548 | 75 | 0.640625 | 13ofClubs |
20444e6d590c5db5d1d6fec05643d8a6815ecde1 | 1,360 | cpp | C++ | BOJ/boj13549_2.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | BOJ/boj13549_2.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | BOJ/boj13549_2.cpp | SukJinKim/Algo-Rhythm | db78de61643e9110ff0e721124a744e3b0ae27f0 | [
"MIT"
] | null | null | null | #include <array>
#include <deque>
#include <cstdio>
#include <limits>
#include <algorithm>
using namespace std;
const int MIN = 0;
const int MAX = (int)1e5;
const int INF = numeric_limits<int>::max();
array<int, MAX + 1> Time;
deque<int> dq;
bool inRange(int pos)
{
return (MIN <= pos && pos <= MAX);
}
int main()
{
int src, dest;
int currPos, teleportPos, forwardPos, backwardPos;
scanf("%d %d", &src, &dest);
fill(Time.begin(), Time.end(), INF);
Time[src] = 0;
dq.push_front(src);
while(!dq.empty())
{
currPos = dq.front();
dq.pop_front();
if(currPos == dest)
break;
backwardPos = currPos - 1;
forwardPos = currPos + 1;
teleportPos = currPos * 2;
if(inRange(backwardPos) && Time[currPos] + 1 < Time[backwardPos])
{
dq.push_back(backwardPos);
Time[backwardPos] = Time[currPos] + 1;
}
if(inRange(forwardPos) && Time[currPos] + 1 < Time[forwardPos])
{
dq.push_back(forwardPos);
Time[forwardPos] = Time[currPos] + 1;
}
if(inRange(teleportPos) && Time[currPos] < Time[teleportPos])
{
dq.push_front(teleportPos);
Time[teleportPos] = Time[currPos];
}
}
printf("%d\n", Time[dest]);
return 0;
}
| 21.25 | 73 | 0.544118 | SukJinKim |
20499339390607b74e0dd42cd5506c14ce40cde5 | 1,230 | cpp | C++ | examples/cpp/reflection/nested_set_member/src/main.cpp | teh-cmc/flecs | ef6c366bae1142fa501d505ccb28d3e23d27ebc2 | [
"MIT"
] | 18 | 2021-09-17T16:41:14.000Z | 2022-02-01T15:22:20.000Z | examples/cpp/reflection/nested_set_member/src/main.cpp | teh-cmc/flecs | ef6c366bae1142fa501d505ccb28d3e23d27ebc2 | [
"MIT"
] | 36 | 2021-09-21T10:22:16.000Z | 2022-01-22T10:25:11.000Z | examples/cpp/reflection/nested_set_member/src/main.cpp | teh-cmc/flecs | ef6c366bae1142fa501d505ccb28d3e23d27ebc2 | [
"MIT"
] | 6 | 2021-09-26T11:06:32.000Z | 2022-01-21T15:07:05.000Z | #include <nested_set_member.h>
#include <iostream>
struct Point {
float x;
float y;
};
struct Line {
Point start;
Point stop;
};
int main(int, char *[]) {
flecs::world ecs;
ecs.component<Point>()
.member<float>("x")
.member<float>("y");
ecs.component<Line>()
.member<Point>("start")
.member<Point>("stop");
// Create entity, set value of Line using reflection API
auto e = ecs.entity();
Line *ptr = e.get_mut<Line>();
auto cur = ecs.cursor<Line>(ptr);
cur.push(); // {
cur.member("start"); // start:
cur.push(); // {
cur.member("x"); // x:
cur.set_float(10); // 10
cur.member("y"); // y:
cur.set_float(20); // 20
cur.pop(); // }
cur.member("stop"); // stop:
cur.push(); // {
cur.member("x"); // x:
cur.set_float(30); // 30
cur.member("y"); // y:
cur.set_float(40); // 40
cur.pop(); // }
cur.pop(); // }
// Convert component to string
std::cout << ecs.to_expr(ptr).c_str() << "\n";
// {start: {x: 10.00, y: 20.00}, stop: {x: 30.00, y: 40.00}}
}
| 24.117647 | 64 | 0.462602 | teh-cmc |
204f6459fdb6c2bea4b77a8d5378c20ebf959e0c | 6,821 | cpp | C++ | pcim.cpp | cshelton/pcim-plain | e48fa9ce3130f38a6b8da95d3fe121070d66d27d | [
"MIT"
] | 2 | 2018-09-17T10:03:12.000Z | 2021-01-10T03:09:14.000Z | pcim.cpp | cshelton/pcim-plain | e48fa9ce3130f38a6b8da95d3fe121070d66d27d | [
"MIT"
] | null | null | null | pcim.cpp | cshelton/pcim-plain | e48fa9ce3130f38a6b8da95d3fe121070d66d27d | [
"MIT"
] | 2 | 2018-04-13T01:37:28.000Z | 2019-02-01T16:44:33.000Z | #include "pcim.h"
#include <algorithm>
#include <cmath>
#include <mutex>
#include <future>
#include <queue>
#include "serial.h"
using namespace std;
inline vector<vartrajrange> torange(const vector<traj> &data) {
vector<vartrajrange> ret;
if (data.empty()) return ret;
int nv = data[0].size();
for(auto &x : data) for(int v=0;v<nv;v++)
ret.emplace_back(&x,v);
return ret;
}
pcim::pcim(const vector<traj> &data,
const vector<shptr<pcimtest>> &tests,
const pcimparams ¶ms) {
const vector<vartrajrange> &d = torange(data);
ss s = suffstats(d);
build(d,s,tests,score(s,params),params);
}
inline vector<vartrajrange> torange(const vector<traj *> & data) {
vector<vartrajrange> ret;
if (data.empty()) return ret;
int nv = data[0]->size();
for(auto x : data) for(int v = 0; v < nv; v++) ret.emplace_back(x, v);
return ret;
}
pcim::pcim(const vector<traj *> & data,
const vector<shptr<pcimtest>> & tests,
const pcimparams & params) {
const vector<vartrajrange> & d = torange(data);
ss s = suffstats(d);
build(d , s, tests, score(s, params), params);
}
pcim::ss pcim::suffstats(const std::vector<vartrajrange> &data) {
ss ret;
ret.n=0.0;
ret.t=0.0;
for(const auto &x : data) {
ret.t += x.range.second-x.range.first;
const vartraj &vtr = (*(x.tr))[x.var];
auto i0 = vtr.upper_bound(x.range.first);
auto i1 = vtr.upper_bound(x.range.second);
ret.n += distance(i0,i1);
}
return ret;
}
double pcim::score(const ss &d, const pcimparams &p) {
double a_n = p.a+d.n;
double b_n = p.b+d.t;
double hn = d.n/2.0;
return p.lk
+ lgamma(a_n) - p.lga
+ p.alb - a_n*log(b_n);
}
void pcim::calcleaf(const ss &d, const pcimparams &p) {
rate = (p.a+d.n)/(p.b+d.t);
}
pcim::pcim(const vector<vartrajrange> &data, const pcim::ss &s,
const vector<shptr<pcimtest>> &tests,
double basescore, const pcimparams ¶ms) {
build(data,s,tests,basescore,params);
}
pcim::testpick pcim::picktest(const vector<vartrajrange> &data,
const vector<shptr<pcimtest>> &tests,
const pcimparams ¶ms,
int procnum, int nproc) const {
double sc = -numeric_limits<double>::infinity();
testpick ret;
ret.testnum = -1; ret.s1 = ret.s2 = sc;
for(int i=procnum;i<tests.size();i+=nproc) {
auto &t = tests[i];
vector<vartrajrange> td1,td2;
for(auto &x : data) t->chop(x,td1,td2);
if (td1.empty() || td2.empty()) continue;
ss tss1 = suffstats(td1), tss2 = suffstats(td2);
if (tss1.n<params.mne || tss2.n<params.mne) continue;
double rs1 = score(tss1,params);
double rs2 = score(tss2,params);
if (rs1+rs2>sc) {
ret.testnum = i;
ret.s1 = rs1; ret.s2=rs2; sc = rs1+rs2;
ret.ss1 = move(tss1); ret.ss2 = move(tss2);
ret.test = t;
ret.d1 = move(td1);
ret.d2 = move(td2);
}
}
return ret;
}
void pcim::build(const vector<vartrajrange> &data, const ss &s,
const vector<shptr<pcimtest>> &tests,
double basescore, const pcimparams ¶ms) {
assert(!data.empty());
vector<vartrajrange> d1,d2;
test.reset();
double sc = basescore;
testpick pick;
if (params.nproc<=1) {
pick = picktest(data,tests,params);
if (pick.s1+pick.s2>sc)
sc = pick.s1+pick.s2;
} else {
vector<future<testpick>> futs(params.nproc);
for(int i=0;i<params.nproc;i++)
futs[i] = async(launch::async,&pcim::picktest,
this,data,tests,params,i,params.nproc);
int picki = tests.size();
for(auto &f : futs) {
testpick p = f.get();
double newsc = p.s1+p.s2;
if (newsc>sc || (newsc==sc && p.testnum<picki)) {
pick = move(p);
picki = p.testnum;
sc = newsc;
}
}
}
if (sc > basescore) {
test = pick.test;
ttree = shptr<pcim>(new pcim(pick.d1,pick.ss1,
tests,pick.s1,params));
ftree = shptr<pcim>(new pcim(pick.d2,pick.ss2,
tests,pick.s2,params));
} else {
ttree.reset();
ftree.reset();
}
calcleaf(s,params);
stats = s;
}
double pcim::getevent(const traj &tr, double &t, double expsamp,
double unisamp, int &var, double maxt) const {
double until;
vector<const pcim *> leaves;
double r = getrate(tr,t,until,leaves);
while(expsamp>(until-t)*r) {
expsamp -= (until-t)*r;
if (until>maxt) return maxt;
t = until;
r = getrate(tr,t,until,leaves);
}
var = leaves.size()-1;
for(int i=0;i<leaves.size();i++) {
unisamp -= leaves[i]->rate/r;
if (unisamp<=0) { var = i; break; }
}
return t+expsamp/r;
}
double pcim::getrate(const traj &tr, double t, double &until,
vector<const pcim *> &ret) const {
until = numeric_limits<double>::infinity();
ret.resize(tr.size());
double r = 0.0;
for(int i=0;i<tr.size();i++)
r += getratevar(tr,i,t,until,ret[i]);
return r;
}
double pcim::getratevar(const traj &tr, int var, double t, double &until,
const pcim *&leaf) const {
if (!test) { leaf = this; return rate; }
double til;
bool dir = test->eval(tr,var,t,til);
if (til<until) until = til;
return (dir ? ttree : ftree)->getratevar(tr,var,t,until,leaf);
}
void pcim::print(ostream &os) const {
printhelp(os,0);
}
void pcim::print(ostream &os, const datainfo &info) const {
printhelp(os,0,&info);
}
void pcim::todot(ostream &os, const datainfo &info) const {
os << "digraph {" << endl;
int nn = 0;
todothelp(os,-1,false,nn,info);
os << "}" << endl;
}
void pcim::todothelp(ostream &os, int par, bool istrue, int &nn, const datainfo &info) const {
int mynode = nn++;
os << "\tNODE" << mynode << " [label=\"";
if (!ttree) os << "rate = " << rate;
else test->print(os,info);
os << "\"];" << endl;
if (par>=0) os << "\tNODE" << par << " -> NODE" << mynode << " [label=\"" <<
(istrue ? "Y: " : "N: ") << stats.n << ',' << stats.t << "\"];" << endl;
if (ttree) {
ttree->todothelp(os,mynode,true,nn,info);
ftree->todothelp(os,mynode,false,nn,info);
}
}
void pcim::printhelp(ostream &os, int lvl, const datainfo *info) const {
for(int i=0;i<lvl;i++) os << " ";
if (!ttree)
os << "rate = " << rate << " [" << stats.n << ',' << stats.t << "]" << endl;
else {
os << "if ";
if (info!=nullptr) test->print(os,*info);
else test->print(os);
os << " [" << stats.n << ',' << stats.t << "]" << endl;
ttree->printhelp(os,lvl+1,info);
for(int i=0;i<lvl;i++) os << " ";
os << "else" << endl;
ftree->printhelp(os,lvl+1,info);
}
}
double pcim::llh(const std::vector<vartrajrange> &tr) const {
if (!ttree) {
ss d = suffstats(tr);
return d.n*std::log(rate) - rate*d.t;
} else {
vector<vartrajrange> ttr,ftr;
for(auto &x : tr) test->chop(x,ttr,ftr);
return ttree->llh(ttr) + ftree->llh(ftr);
}
}
BOOST_CLASS_EXPORT_IMPLEMENT(pcimtest)
BOOST_CLASS_EXPORT_IMPLEMENT(timetest)
BOOST_CLASS_EXPORT_IMPLEMENT(counttest)
BOOST_CLASS_EXPORT_IMPLEMENT(varstattest<counttest>)
BOOST_CLASS_EXPORT_IMPLEMENT(vartest)
BOOST_CLASS_EXPORT_IMPLEMENT(staticgreqtest)
BOOST_CLASS_EXPORT_IMPLEMENT(staticeqtest)
BOOST_CLASS_EXPORT_IMPLEMENT(pcim)
| 27.393574 | 94 | 0.634218 | cshelton |
20556f7754c6f75e2f7ae5e881b60b422dae31dd | 7,378 | cpp | C++ | src/diffdrive_orientation.cpp | srmanikandasriram/ev3-ros | 8233c90934defd1db0616f8f83bc576e898c2a26 | [
"MIT"
] | 3 | 2016-11-30T19:23:16.000Z | 2020-07-13T12:16:08.000Z | src/diffdrive_orientation.cpp | srmanikandasriram/ev3-ros | 8233c90934defd1db0616f8f83bc576e898c2a26 | [
"MIT"
] | null | null | null | src/diffdrive_orientation.cpp | srmanikandasriram/ev3-ros | 8233c90934defd1db0616f8f83bc576e898c2a26 | [
"MIT"
] | 3 | 2016-11-30T19:23:19.000Z | 2019-06-19T14:46:18.000Z |
/*the srv file headers_ev3/go_to_goal.h should be of the form
float64 vecx
float64 vecy
---
float64 x
float64 y
float64 tf
This porgram enables the robot to orient itself along the vector (vecx,vecy) passed as request in rosservice call
*/
//Header files required to run ROS
#include <ros.h>
#include <nav_msgs/Odometry.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_broadcaster.h>
#include <tf/tf.h>
#include <headers/orientation.h>
//Header files required to run EV3dev
#include <iostream>
#include "ev3dev.h"
#include <thread>
#include <string.h>
#include <math.h>
#include <chrono>
//#include <errno.h>
using namespace std;
using namespace ev3dev;
using headers::orientation;
ros::NodeHandle nh;
//string ns = "/robot3/";
const float deg2rad = M_PI/180.0;//conversion from degrees to radians
float xc = 0, yc = 0 ,tc = 0; //current co-ordinates
float x = 0.0, y = 0.0, t = 0.0, t_offset = 0.0;//dynamic value of co-ordinates
float vx = 0, wt = 0, vl, vr,td = 0,t_error = 0,cerror = 0,L = 0.12,tIerror = 0,tDerror = 0, old_t_error = 0;//t_error = error in theta
float t_kp = 3 , t_ki = 0.05 , t_kd = 0.001;
char* srvrIP;
motor left_motor = OUTPUT_C, right_motor = OUTPUT_B;
sensor gsense = INPUT_4;
sensor us = INPUT_1;
float R=0.03, speed = R*deg2rad ;//conversion factor of linear speed to angular speed in rad/s;
int encoder[2]={0,0}, prev_encoder[2] = {0,0}, dl, dr,q,k ;
string left_motor_port, right_motor_port, sensor_port ;
float t_PID()
{
t_kp = 4 ; t_ki = 0; t_kd = 0;
float omega = 0 ;
tDerror = t_error - old_t_error;
tIerror = tIerror + t_error;
omega = t_kp * t_error + t_ki * tIerror + t_kd * tDerror;
old_t_error = t_error;
//cout << "omega = "<< omega << endl;
return omega ;
}
void svcCallback(const orientation::Request & req, orientation::Response & res)
{
int count = 0;
float xg, yg;
xg = req.vecx ; //obtaining goal's x-coordinate
yg = req.vecy ; //obtaining goal's y-coordinate
td = atan((yg - yc)/(xg - xc));//calculating theta desired
if((xg-xc>0)&&(yg-yc>0) || (xg-xc>0)&&(yg-yc<0))
td = td + 0;
if((xg-xc<0)&&(yg-yc>0))
td = M_PI - abs(td);
if((xg-xc<0)&&(yg-yc<0))
td = -M_PI + td;
cout<<"desired = "<<td/deg2rad <<endl;
cout<< "current ="<<tc/deg2rad <<endl;
t_error = td - tc ;
while(abs(t_error) >=0.01)
{
count++;
t_error = td - tc ;
wt = t_PID();
/* bang bang control
if(t_error > 0)
wt = 0.2;
else if(t_error < 0)
wt = -0.2;*/
vx = 0;
vr = (vx+L/2*wt)/(speed);
vl = (vx-L/2*wt)/(speed);
//cout<<"left , right = "<<vl <<" "<<vr <<endl;
left_motor.set_speed_regulation_enabled("on");
right_motor.set_speed_regulation_enabled("on");
if(vl!=0)
{
left_motor.set_speed_sp(vl);
left_motor.set_command("run-forever");
}
else
{
left_motor.set_speed_sp(0);
left_motor.set_command("run-forever");
}
if(vr!=0)
{
right_motor.set_speed_sp(vr);
right_motor.set_command("run-forever");
}
else
{
right_motor.set_speed_sp(0);
right_motor.set_command("run-forever");
}
}
res.x = xc ;
res.y = yc ;
res.tf = tc/deg2rad ;
td = 0;
tIerror = 0;
old_t_error = 0;
cout <<"error = "<<t_error<< endl;
cout<<"counts = "<< count <<endl;
cout<<"Service request message: ("<<req.vecx<<","<<req.vecy<<") received \n ";//responding with:("<< res.x<<","<<res.y<<","<<res.tf/deg2rad<<")\n";
cout<<"Current co-ordinates are \n (x,y,theta(degress)) == ("<<xc<<","<<yc<<","<<tc/deg2rad<<") \n";
vl = 0.0 , vr = 0.0 ;
left_motor.set_speed_sp(0);
left_motor.set_command("run-forever");
right_motor.set_speed_sp(0);
right_motor.set_command("run-forever");
}
ros::ServiceServer<orientation::Request, orientation::Response> server("ori_srv",&svcCallback);
void odometry() //function to calculate the odometry
{
int encoder[2]={0,0}, prev_encoder[2] = {0,0}, dl, dr;
while(1)
{
encoder[0] = left_motor.position();
encoder[1] = right_motor.position();
//obtaining angle rotated by left and right wheels in 100 ms
dl = encoder[0]-prev_encoder[0];
dr = encoder[1]-prev_encoder[1];
t = -gsense.value()*deg2rad - t_offset;//storing angle in radians after callibration
t = t/deg2rad;
if(t>0)
{
k = t/360;
t = t - k*360;
if(t>0&&t<90)
q =1;
if(t>90&&t<180)
q = 2;
if(t>180&&t<270)
q = 3;
if(t>270&&t<360)
q = 4;
if(q==1||q==2)
t = t + 0;
if(q==4||q==3)
t = -360 + t ;
}
if(t<0)
{
k = -t/360;
t = t + k*360;
if(t<0 && t>-90)
q =4;
if(t<-90&&t>-180)
q = 3;
if(t<-180&&t>-270)
q = 2;
if(t<-270&&t>-360)
q = 1;
if(q==4||q==3)
t = t + 0;
if(q==1||q==2)
t = 360 + t ;
}
t*=deg2rad;
tc = t;
//cout << "current value = "<<tc<<endl;
//converting angle rotated by wheels to linear displacement and printing it
x += cos(t)*speed*(dl+dr)/2.0; xc = x;
y += sin(t)*speed*(dl+dr)/2.0; yc = y;
cout<<"(x,y,theta) = "<<"("<<x<<","<<y<<","<<t/deg2rad<<")"<<endl ;
prev_encoder[0] = encoder[0];
prev_encoder[1] = encoder[1];
//motor.speed() returns speed in rad/s
vl = left_motor.speed();
vr = right_motor.speed();
//remmapping linear and angular velocity of centroid from vl, vr
vx = (vl+vr)/2*speed;
wt = (vl-vr)/L*speed;
this_thread::sleep_for(chrono::milliseconds(100));
}
}
int main(int argc, char* argv[])
{
if(argc<5)
{
cerr<<"Usage: "<<argv[0]<<" <IP address> <left motor port> <right motor port> <<gyro sensor port>\n";
cout<<"motor port options : outA outB outC outD \n";
cout<<"sensor port options : inA inB inC inD \n";
return 1;
}
else
{
srvrIP = (argv[1]);
left_motor_port = (argv[2]);
right_motor_port = (argv[3]);
sensor_port = (argv[4]);
gsense = sensor(sensor_port);
}
left_motor = motor(left_motor_port);
left_motor.reset();
left_motor.set_position(0);
left_motor.set_speed_regulation_enabled("on");
right_motor = motor(right_motor_port);
right_motor.reset();
right_motor.set_position(0);
right_motor.set_speed_regulation_enabled("on");
nh.initNode(srvrIP);
nh.advertiseService(server);
int milliseconds = 100;
// Set mode
//gsense = sensor(sensor_port);
string mode="GYRO-G&A";
gsense.set_mode(mode);
t_offset = -gsense.value()*deg2rad;//obtaining initial angle to callibrate
//cout<<"t_offset = "<< t_offset <<endl;
cout<<"gyroscope is callibrated"<<endl ;
thread odom (odometry);//'threading' odometry and the main functions
while(1)
{
nh.spinOnce();
sleep(1);
this_thread::sleep_for(std::chrono::milliseconds(milliseconds)); // sets frequency
}
odom.join();
return 0;
}
| 27.325926 | 149 | 0.561941 | srmanikandasriram |
2057181232b97d1b2157c851f24e60a42af468e8 | 197 | cpp | C++ | Content/Simulation/BodyInfo.cpp | jodavis42/NBody | 91a40ca60625494a27c517590d12df4a77f776b4 | [
"Unlicense"
] | null | null | null | Content/Simulation/BodyInfo.cpp | jodavis42/NBody | 91a40ca60625494a27c517590d12df4a77f776b4 | [
"Unlicense"
] | null | null | null | Content/Simulation/BodyInfo.cpp | jodavis42/NBody | 91a40ca60625494a27c517590d12df4a77f776b4 | [
"Unlicense"
] | 1 | 2018-12-07T22:19:06.000Z | 2018-12-07T22:19:06.000Z | #include "SimulationPrecompiled.hpp"
void BodyInfo::Load(Cog* cog)
{
mCog = cog;
mPosition = cog->has(Transform)->GetWorldTranslation();
mMass = cog->has(RigidBody)->GetMass();
}
| 19.7 | 58 | 0.659898 | jodavis42 |
20594cf85d943b944ec1da286269fbb073d497e5 | 1,544 | hpp | C++ | include/codegen/include/GlobalNamespace/ObstacleType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/ObstacleType.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/ObstacleType.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: System.Enum
#include "System/Enum.hpp"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: ObstacleType
struct ObstacleType : public System::Enum {
public:
// public System.Int32 value__
// Offset: 0x0
int value;
// static field const value: static public ObstacleType FullHeight
static constexpr const int FullHeight = 0;
// Get static field: static public ObstacleType FullHeight
static GlobalNamespace::ObstacleType _get_FullHeight();
// Set static field: static public ObstacleType FullHeight
static void _set_FullHeight(GlobalNamespace::ObstacleType value);
// static field const value: static public ObstacleType Top
static constexpr const int Top = 1;
// Get static field: static public ObstacleType Top
static GlobalNamespace::ObstacleType _get_Top();
// Set static field: static public ObstacleType Top
static void _set_Top(GlobalNamespace::ObstacleType value);
// Creating value type constructor for type: ObstacleType
ObstacleType(int value_ = {}) : value{value_} {}
}; // ObstacleType
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::ObstacleType, "", "ObstacleType");
#pragma pack(pop)
| 40.631579 | 76 | 0.709845 | Futuremappermydud |
205c73ec2df4c3f9c85c202af7aaad2b4ad2eddb | 196 | cpp | C++ | src/better_ChatEntry.cpp | ddarknut/better | 47d801c4fa8de6c32dff933de7d25b559421ce09 | [
"Apache-2.0"
] | 5 | 2020-11-21T03:44:17.000Z | 2021-07-10T22:51:28.000Z | src/better_ChatEntry.cpp | ddarknut/better | 47d801c4fa8de6c32dff933de7d25b559421ce09 | [
"Apache-2.0"
] | null | null | null | src/better_ChatEntry.cpp | ddarknut/better | 47d801c4fa8de6c32dff933de7d25b559421ce09 | [
"Apache-2.0"
] | 1 | 2021-03-24T20:33:57.000Z | 2021-03-24T20:33:57.000Z | #include <cstdlib>
#include "better_ChatEntry.h"
#include "better_alloc.h"
void ChatEntry_free(ChatEntry* ce)
{
if (ce->name) BETTER_FREE(ce->name);
if (ce->msg) BETTER_FREE(ce->msg);
}
| 19.6 | 40 | 0.688776 | ddarknut |
205d4591ca401d01d1c69f660ebf63b30638c5a4 | 1,203 | cpp | C++ | LeetCode/cpp/127.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 279 | 2019-02-19T16:00:32.000Z | 2022-03-23T12:16:30.000Z | LeetCode/cpp/127.cpp | ZintrulCre/LeetCode_Archiver | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 2 | 2019-03-31T08:03:06.000Z | 2021-03-07T04:54:32.000Z | LeetCode/cpp/127.cpp | ZintrulCre/LeetCode_Crawler | de23e16ead29336b5ee7aa1898a392a5d6463d27 | [
"MIT"
] | 12 | 2019-01-29T11:45:32.000Z | 2019-02-04T16:31:46.000Z | class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string> &wordList) {
int n = beginWord.size(), count = 0;
if (n != endWord.size())
return 0;
unordered_map<string, bool> words;
for (auto &l:wordList)
words[l] = true;
queue<string> que;
int size = 1;
que.push(beginWord);
string word = que.front();
while (!que.empty()) {
word = que.front();
if (word == endWord)
break;
que.pop();
for (int i = 0; i < word.size(); ++i) {
string temp = word;
for (int j = 0; j < 26; ++j) {
if ('a' + j == word[i])
continue;
temp[i] = 'a' + j;
if (words.find(temp) != words.end()) {
que.push(temp);
words.erase(temp);
}
}
}
--size;
if (size == 0) {
size = que.size();
++count;
}
}
return word == endWord ? count + 1 : 0;
}
}; | 30.846154 | 82 | 0.375727 | ZintrulCre |
206014f9e1269c5b0983deaea1dd932752f2a279 | 2,447 | cpp | C++ | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcReferentTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 426 | 2015-04-12T10:00:46.000Z | 2022-03-29T11:03:02.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcReferentTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 124 | 2015-05-15T05:51:00.000Z | 2022-02-09T15:25:12.000Z | IfcPlusPlus/src/ifcpp/IFC4/lib/IfcReferentTypeEnum.cpp | AlexVlk/ifcplusplus | 2f8cd5457312282b8d90b261dbf8fb66e1c84057 | [
"MIT"
] | 214 | 2015-05-06T07:30:37.000Z | 2022-03-26T16:14:04.000Z | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/BasicTypes.h"
#include "ifcpp/model/BuildingException.h"
#include "ifcpp/IFC4/include/IfcReferentTypeEnum.h"
// TYPE IfcReferentTypeEnum = ENUMERATION OF (KILOPOINT ,MILEPOINT ,STATION ,USERDEFINED ,NOTDEFINED);
shared_ptr<BuildingObject> IfcReferentTypeEnum::getDeepCopy( BuildingCopyOptions& options )
{
shared_ptr<IfcReferentTypeEnum> copy_self( new IfcReferentTypeEnum() );
copy_self->m_enum = m_enum;
return copy_self;
}
void IfcReferentTypeEnum::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCREFERENTTYPEENUM("; }
switch( m_enum )
{
case ENUM_KILOPOINT: stream << ".KILOPOINT."; break;
case ENUM_MILEPOINT: stream << ".MILEPOINT."; break;
case ENUM_STATION: stream << ".STATION."; break;
case ENUM_USERDEFINED: stream << ".USERDEFINED."; break;
case ENUM_NOTDEFINED: stream << ".NOTDEFINED."; break;
}
if( is_select_type ) { stream << ")"; }
}
const std::wstring IfcReferentTypeEnum::toString() const
{
switch( m_enum )
{
case ENUM_KILOPOINT: return L"KILOPOINT";
case ENUM_MILEPOINT: return L"MILEPOINT";
case ENUM_STATION: return L"STATION";
case ENUM_USERDEFINED: return L"USERDEFINED";
case ENUM_NOTDEFINED: return L"NOTDEFINED";
}
return L"";
}
shared_ptr<IfcReferentTypeEnum> IfcReferentTypeEnum::createObjectFromSTEP( const std::wstring& arg, const std::map<int,shared_ptr<BuildingEntity> >& map )
{
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcReferentTypeEnum>(); }
if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcReferentTypeEnum>(); }
shared_ptr<IfcReferentTypeEnum> type_object( new IfcReferentTypeEnum() );
if( std_iequal( arg, L".KILOPOINT." ) )
{
type_object->m_enum = IfcReferentTypeEnum::ENUM_KILOPOINT;
}
else if( std_iequal( arg, L".MILEPOINT." ) )
{
type_object->m_enum = IfcReferentTypeEnum::ENUM_MILEPOINT;
}
else if( std_iequal( arg, L".STATION." ) )
{
type_object->m_enum = IfcReferentTypeEnum::ENUM_STATION;
}
else if( std_iequal( arg, L".USERDEFINED." ) )
{
type_object->m_enum = IfcReferentTypeEnum::ENUM_USERDEFINED;
}
else if( std_iequal( arg, L".NOTDEFINED." ) )
{
type_object->m_enum = IfcReferentTypeEnum::ENUM_NOTDEFINED;
}
return type_object;
}
| 34.464789 | 154 | 0.734369 | AlexVlk |
20605f6282406f6912e3e3f5bd55441cfc49d0b0 | 617 | cpp | C++ | mine/46-permutations.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | mine/46-permutations.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | mine/46-permutations.cpp | Junlin-Yin/myLeetCode | 8a33605d3d0de9faa82b5092a8e9f56b342c463f | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> ans;
void recursiveBody(vector<int>& nums, int sz, vector<int>& perm){
if(sz == 0) { ans.push_back(perm); return; }
for(int i = 0; i < sz; ++i){
perm.push_back(nums[i]);
nums.erase(nums.begin()+i);
recursiveBody(nums, sz-1, perm);
nums.insert(nums.begin()+i, perm.back());
perm.pop_back();
}
}
vector<vector<int>> permute(vector<int>& nums) {
vector<int> perm;
recursiveBody(nums, nums.size(), perm);
return ans;
}
}; | 29.380952 | 70 | 0.504052 | Junlin-Yin |
206439cbbf0308036f2856125ffde097e5b80495 | 8,088 | hpp | C++ | keychain_lib/include/keychain_lib/secmod_protocol.hpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 29 | 2018-03-21T09:21:18.000Z | 2020-09-22T16:31:03.000Z | keychain_lib/include/keychain_lib/secmod_protocol.hpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 119 | 2018-03-16T14:02:04.000Z | 2019-04-16T21:16:32.000Z | keychain_lib/include/keychain_lib/secmod_protocol.hpp | jokefor300/array-io-keychain | 1c281b76332af339f0456de51caf65cae9950c91 | [
"MIT"
] | 3 | 2018-03-21T15:00:16.000Z | 2019-12-25T09:03:58.000Z | // Created by roman on 8/12/18.
//
#ifndef KEYCHAINAPP_KEYCHAIN_SEC_MOD_PROTOCOL_HPP
#define KEYCHAINAPP_KEYCHAIN_SEC_MOD_PROTOCOL_HPP
#include <string>
#include <fc_light/variant.hpp>
#include <fc_light/io/json.hpp>
#include <fc_light/reflect/reflect.hpp>
#include <fc_light/reflect/variant.hpp>
#include "bitcoin_transaction.hpp"
namespace keychain_app {
using byte_seq_t = std::vector<char>;
namespace secmod_commands {
enum struct blockchain_secmod_te {
unknown = 0,
ethereum,
bitcoin,
ethereum_swap, //HACK:
};
template<blockchain_secmod_te blockchain_type>
struct transaction_view
{
using type = std::string; // if transaction cannot be parsed
};
struct ethereum_trx_t {
ethereum_trx_t() : chainid(0) {}
std::string nonce, gasPrice, gas;
int chainid;
std::string to, value, data;
};
template<>
struct transaction_view<blockchain_secmod_te::ethereum> {
struct secmod_command_ethereum {
secmod_command_ethereum() {}
secmod_command_ethereum(std::string &&from_, ethereum_trx_t &&trx_)
: from(from_), trx_info(trx_) {}
std::string from;
ethereum_trx_t trx_info;
};
using type = secmod_command_ethereum;
};
template<>
struct transaction_view<blockchain_secmod_te::ethereum_swap> {
struct secmod_command_swap {
enum struct action_te {
create_swap = 0,
refund,
withdraw
};
struct swap_t {
action_te action;
std::string hash;
std::string address;
std::string secret;
};
secmod_command_swap() {}
secmod_command_swap(std::string &&from_, ethereum_trx_t &&trx_, swap_t &&swap_info_)
: from(from_), trx_info(trx_), swap_info(swap_info_) {}
std::string from;
ethereum_trx_t trx_info;
swap_t swap_info;
};
using type = secmod_command_swap;
};
template<>
struct transaction_view<blockchain_secmod_te::bitcoin> {
struct secmod_command_bitcoin {
secmod_command_bitcoin() {}
secmod_command_bitcoin(std::string &&from_, bitcoin_transaction_t &&trx_)
: from(from_), trx_info(trx_) {}
std::string from;
bitcoin_transaction_t trx_info;
};
using type = secmod_command_bitcoin;
};
enum struct events_te {
unknown = 0,
create_key,
sign_trx,
sign_hash,
unlock,
edit_key,
remove_key,
export_keys,
import_keys,
print_mnemonic,
last
};
template<events_te event>
struct secmod_event
{
using params_t = void;
};
template<>
struct secmod_event<events_te::create_key>
{
struct params {
params(): keyname(""){}
params(params&& a): keyname(a.keyname){}
std::string keyname;
};
using params_t = params;
};
template<>
struct secmod_event<events_te::sign_trx>
{
struct params {
params() : is_parsed(false), no_password(false), unlock_time(0) {}
params(params&& a ):is_parsed(a.is_parsed), no_password(a.no_password), keyname(a.keyname),
blockchain(a.blockchain), unlock_time(a.unlock_time), trx_view(a.trx_view) {}
bool is_parsed;
bool no_password;
std::string keyname;
blockchain_secmod_te blockchain;
int unlock_time;
fc_light::variant trx_view;
template <blockchain_secmod_te blockchain_type>
typename transaction_view<blockchain_type>::type get_trx_view() const
{
using return_t = typename transaction_view<blockchain_type>::type;
return trx_view.as<return_t>();
}
};
using params_t = params;
};
template<>
struct secmod_event<events_te::sign_hash>
{
struct params {
params(): no_password(false), keyname(""), from(""), hash(""){};
params(params&& a): no_password(a.no_password), keyname(a.keyname), from(a.from), hash(a.hash){}
bool no_password = false;
std::string keyname;
std::string from;
std::string hash;
};
using params_t = params;
};
template<>
struct secmod_event<events_te::unlock>
{
struct params
{
params(): no_password(false), unlock_time(0){}
params(params&& a): no_password(a.no_password), keyname(a.keyname), unlock_time(a.unlock_time){}
bool no_password;
std::string keyname;
int unlock_time;
};
using params_t = params;
};
template<>
struct secmod_event<events_te::edit_key>
{
struct params
{
params() : unlock_time(0) {}
params(params&& a): keyname(a.keyname), unlock_time(a.unlock_time){}
std::string keyname;
int unlock_time;
};
using params_t = params;
};
template<>
struct secmod_event<events_te::remove_key>
{
struct params {
params(params &&a): keyname(a.keyname){}
std::string keyname;
};
using params_t = params;
};
template<>
struct secmod_event<events_te::export_keys>
{
using params_t = void;
};
template<>
struct secmod_event<events_te::import_keys>
{
using params_t = void;
};
template<>
struct secmod_event<events_te::print_mnemonic>
{
using params_t = void; //TODO: will be implemented in future
};
struct secmod_command
{
secmod_command() : etype(secmod_commands::events_te::unknown) {}
events_te etype;
fc_light::variant params;
};
enum struct response_te
{
null = 0,
password,
boolean,
canceled
};
template <response_te response_type>
struct secmod_response
{
using params_t = void;
};
template <>
struct secmod_response<response_te::password>
{
using params_t = byte_seq_t;
};
template <>
struct secmod_response<response_te::boolean>
{
using params_t = bool;
};
struct secmod_response_common
{
secmod_response_common() : etype(secmod_commands::response_te::null) {}
response_te etype;
fc_light::variant params;
};
}
}
FC_LIGHT_REFLECT_ENUM(keychain_app::secmod_commands::blockchain_secmod_te, (unknown)(ethereum)(bitcoin)(ethereum_swap))
FC_LIGHT_REFLECT_ENUM(keychain_app::secmod_commands::events_te,
(unknown)(create_key)(sign_trx)(sign_hash)(unlock)(edit_key)(remove_key)(export_keys)(import_keys)(print_mnemonic))
FC_LIGHT_REFLECT_ENUM(keychain_app::secmod_commands::response_te, (null)(password)(boolean)(canceled))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::create_key>::params_t, (keyname))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::sign_trx>::params_t, (is_parsed)(no_password)(keyname)(blockchain)(unlock_time)(trx_view))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::sign_hash>::params_t, (no_password)(keyname)(from)(hash))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::unlock>::params_t, (no_password)(keyname)(unlock_time))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::edit_key>::params_t, (keyname)(unlock_time))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_event<keychain_app::secmod_commands::events_te::remove_key>::params_t, (keyname))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::ethereum_trx_t, (nonce)(gasPrice)(gas)(to)(value)(data)(chainid))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum>::type, (from)(trx_info))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::bitcoin>::type, (from)(trx_info))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap>::type, (from)(trx_info)(swap_info))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_command, (etype)(params))
FC_LIGHT_REFLECT(keychain_app::secmod_commands::secmod_response_common, (etype)(params))
FC_LIGHT_REFLECT_ENUM(
keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap>::type::action_te,
(create_swap)(refund)(withdraw))
FC_LIGHT_REFLECT(
keychain_app::secmod_commands::transaction_view<keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap>::type::swap_t,
(action)(hash)(address)(secret))
#endif //KEYCHAINAPP_KEYCHAIN_SEC_MOD_PROTOCOL_HPP
| 26.781457 | 193 | 0.740232 | jokefor300 |
206455e8ab5621e90739dc80f9a12d67d0628933 | 1,703 | hpp | C++ | include/problem/composition_8.hpp | tsakiridis/deplusplus | 383754182c929ab51d9af045bbf138d6d74c009c | [
"MIT"
] | null | null | null | include/problem/composition_8.hpp | tsakiridis/deplusplus | 383754182c929ab51d9af045bbf138d6d74c009c | [
"MIT"
] | null | null | null | include/problem/composition_8.hpp | tsakiridis/deplusplus | 383754182c929ab51d9af045bbf138d6d74c009c | [
"MIT"
] | null | null | null | #ifndef DE_OPTIMIZATION_PROBLEM_COMPOSITION_FUNCTION_8_HPP
#define DE_OPTIMIZATION_PROBLEM_COMPOSITION_FUNCTION_8_HPP
#include "problem/cec_composition_function.hpp"
#include "problem/ackley.hpp"
#include "problem/griewank.hpp"
#include "problem/discus.hpp"
#include "problem/rosenbrock.hpp"
#include "problem/happycat.hpp"
#include "problem/schaffer.hpp"
namespace DE {
namespace Problem {
/*!
* \class CompositionFunction8
* \brief Composition function 8 of CEC-2017
*/
class CompositionFunction8 : public CECComposition<double> {
public:
CompositionFunction8(const std::size_t D,
const char* shift_file = nullptr,
const char* rotation_file = nullptr)
: CECComposition<double>(D, "Composition Function 8") {
auto bias = std::vector<double>{0.0, 100.0, 200.0, 300.0, 400.0, 500.0};
functions_ = {BasicFunction(new AckleyFunction(D), 10, 10, bias[0]),
BasicFunction(new GriewankFunction(D), 20, 10, bias[1]),
BasicFunction(new DiscusFunction(D), 30, 1e-6, bias[2]),
BasicFunction(new RosenbrockFunction(D), 40, 1, bias[3]),
BasicFunction(new HappyCatFunction(D), 50, 1, bias[4]),
BasicFunction(new SchafferFunction(D), 60, 5e-4, bias[5])};
if (shift_file)
for (std::size_t i = 0; i < functions_.size(); ++i)
functions_[i].func->parse_shift_file(shift_file, i);
if (rotation_file)
for (std::size_t i = 0; i < functions_.size(); ++i)
functions_[i].func->parse_rotation_file(rotation_file, i * D);
}
};
} // namespace Problem
} // namespace DE
#endif // DE_OPTIMIZATION_PROBLEM_COMPOSITION_FUNCTION_8_HPP
| 38.704545 | 77 | 0.669407 | tsakiridis |
206561929d985c270fafe9ca79f362fc0f9868a9 | 374 | cpp | C++ | ComputerGraphics/src/Main.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | ComputerGraphics/src/Main.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | ComputerGraphics/src/Main.cpp | gerrygoo/graficas | 443832dc6820c0a93c8291831109e3248f57f9b0 | [
"MIT"
] | null | null | null | // #include <string>
// #include "scene_manager.h"
// #include <glad/glad.h>
// int main(int argc, char* argv[])
// {
// scene_manager::start(argc, argv, "Hello, World!", 800, 800);
// return 0;
// }
#include <iostream>
#include "scene_manager.h"
#include <vector>
int main(int argc, char* argv[]) {
scene_manager::start(argc, argv, "Hello World!", 1000, 1000);
}
| 19.684211 | 65 | 0.631016 | gerrygoo |
206a5c78743dfa16273ef830cac78f9fc98e52c3 | 225 | cc | C++ | build/ARM/python/m5/internal/param_ClockDomain.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | build/ARM/python/m5/internal/param_ClockDomain.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | build/ARM/python/m5/internal/param_ClockDomain.i_init.cc | Jakgn/gem5_test | 0ba7cc5213cf513cf205af7fc995cf679ebc1a3f | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
extern "C" {
void init_param_ClockDomain();
}
EmbeddedSwig embed_swig_param_ClockDomain(init_param_ClockDomain, "m5.internal._param_ClockDomain");
| 25 | 108 | 0.617778 | Jakgn |
206fce9b09872b55229c545460ca01e62d203ac9 | 3,152 | cpp | C++ | aws-cpp-sdk-ce/source/model/PlatformDifference.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-ce/source/model/PlatformDifference.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ce/source/model/PlatformDifference.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ce/model/PlatformDifference.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/core/Globals.h>
#include <aws/core/utils/EnumParseOverflowContainer.h>
using namespace Aws::Utils;
namespace Aws
{
namespace CostExplorer
{
namespace Model
{
namespace PlatformDifferenceMapper
{
static const int HYPERVISOR_HASH = HashingUtils::HashString("HYPERVISOR");
static const int NETWORK_INTERFACE_HASH = HashingUtils::HashString("NETWORK_INTERFACE");
static const int STORAGE_INTERFACE_HASH = HashingUtils::HashString("STORAGE_INTERFACE");
static const int INSTANCE_STORE_AVAILABILITY_HASH = HashingUtils::HashString("INSTANCE_STORE_AVAILABILITY");
static const int VIRTUALIZATION_TYPE_HASH = HashingUtils::HashString("VIRTUALIZATION_TYPE");
PlatformDifference GetPlatformDifferenceForName(const Aws::String& name)
{
int hashCode = HashingUtils::HashString(name.c_str());
if (hashCode == HYPERVISOR_HASH)
{
return PlatformDifference::HYPERVISOR;
}
else if (hashCode == NETWORK_INTERFACE_HASH)
{
return PlatformDifference::NETWORK_INTERFACE;
}
else if (hashCode == STORAGE_INTERFACE_HASH)
{
return PlatformDifference::STORAGE_INTERFACE;
}
else if (hashCode == INSTANCE_STORE_AVAILABILITY_HASH)
{
return PlatformDifference::INSTANCE_STORE_AVAILABILITY;
}
else if (hashCode == VIRTUALIZATION_TYPE_HASH)
{
return PlatformDifference::VIRTUALIZATION_TYPE;
}
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
overflowContainer->StoreOverflow(hashCode, name);
return static_cast<PlatformDifference>(hashCode);
}
return PlatformDifference::NOT_SET;
}
Aws::String GetNameForPlatformDifference(PlatformDifference enumValue)
{
switch(enumValue)
{
case PlatformDifference::HYPERVISOR:
return "HYPERVISOR";
case PlatformDifference::NETWORK_INTERFACE:
return "NETWORK_INTERFACE";
case PlatformDifference::STORAGE_INTERFACE:
return "STORAGE_INTERFACE";
case PlatformDifference::INSTANCE_STORE_AVAILABILITY:
return "INSTANCE_STORE_AVAILABILITY";
case PlatformDifference::VIRTUALIZATION_TYPE:
return "VIRTUALIZATION_TYPE";
default:
EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer();
if(overflowContainer)
{
return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue));
}
return {};
}
}
} // namespace PlatformDifferenceMapper
} // namespace Model
} // namespace CostExplorer
} // namespace Aws
| 34.26087 | 116 | 0.650381 | perfectrecall |
2071919f1d637958bc0d7a11ee95de66e045a410 | 3,176 | cpp | C++ | modules/filters/src/detection/detectedObject.cpp | voxel-dot-at/toffy | e9f14b186cf57225ad9eae99f227f894f0e5f940 | [
"Apache-2.0"
] | null | null | null | modules/filters/src/detection/detectedObject.cpp | voxel-dot-at/toffy | e9f14b186cf57225ad9eae99f227f894f0e5f940 | [
"Apache-2.0"
] | null | null | null | modules/filters/src/detection/detectedObject.cpp | voxel-dot-at/toffy | e9f14b186cf57225ad9eae99f227f894f0e5f940 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2018 Simon Vogl <[email protected]>
Angel Merino-Sastre <[email protected]>
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 <boost/log/trivial.hpp>
#include "toffy/detection/detectedObject.hpp"
using namespace toffy::detection;
using namespace cv;
int DetectedObject::COUNTER = 0;
DetectedObject::DetectedObject(): first_fc(-1)
{
id = COUNTER++;
RNG rng(id);
color = Scalar( rng.uniform(0,255),
rng.uniform(0,255),
rng.uniform(0,255) );
}
DetectedObject::DetectedObject(const DetectedObject& object): id(object.id),
color(object.color)
{
*this = object;
/*contour = object.contour;
contours = object.contours;
hierarchy = object.hierarchy;
mo = object.mo;
massCenter = object.massCenter;
idx = object.idx;
size = object.size;
first_fc = object.first_fc;
first_cts = object.first_cts;
first_ts = object.first_ts;
fc = object.fc;
cts = object.cts;
ts = object.ts;
size = object.size;*/
}
DetectedObject::~DetectedObject() {
while (record && !record->empty()) {
delete *record->begin();
record->pop_front();
}
}
DetectedObject* DetectedObject::clone(const DetectedObject& object) {
DetectedObject *newObject = new DetectedObject(object);
return newObject;
}
DetectedObject& DetectedObject::operator=( const DetectedObject& newDO ) {
contour = newDO.contour;
contours = newDO.contours;
hierarchy = newDO.hierarchy;
mo = newDO.mo;
massCenter = newDO.massCenter;
idx = newDO.idx;
size = newDO.size;
first_fc = newDO.first_fc;
first_cts = newDO.first_cts;
first_ts = newDO.first_ts;
fc = newDO.fc;
cts = newDO.cts;
ts = newDO.ts;
size = newDO.size;
massCenter3D = newDO.massCenter3D;
massCenterZ = newDO.massCenterZ;
return *this;
}
void DetectedObject::init() {
if (record) {
BOOST_LOG_TRIVIAL(warning) << "Detected object already initialized!";
}
first_fc = fc;
first_cts = cts;
first_ts = ts;
firstCenter = massCenter;
size = contourArea(contour);
record.reset(new boost::circular_buffer<detection::DetectedObject* >(10));
}
void DetectedObject::update(const DetectedObject& newDO)
{
if (record->full()) {
DetectedObject *last = record->back();
*last = *this;
record->push_front(last);
} else
record->push_front(new DetectedObject(*this));
*this = newDO;
//TODO Get new Stats here when object gets new state
//3d points ->
// pointTo3D(cv::Point point, float depthValue) or toffy::commons::pointTo3D(center, z, _cameraMatrix, depth->size());
}
| 25.821138 | 122 | 0.67034 | voxel-dot-at |
2077a119247db1b7412879ef7d764425b631c1cc | 840 | hpp | C++ | src/map.hpp | REPOmAN2v2/Mindstorm-rover | 1529a02f246eaa5132be2b34bba27df6dc776ead | [
"MIT",
"Unlicense"
] | null | null | null | src/map.hpp | REPOmAN2v2/Mindstorm-rover | 1529a02f246eaa5132be2b34bba27df6dc776ead | [
"MIT",
"Unlicense"
] | null | null | null | src/map.hpp | REPOmAN2v2/Mindstorm-rover | 1529a02f246eaa5132be2b34bba27df6dc776ead | [
"MIT",
"Unlicense"
] | null | null | null | #ifndef MAP_HPP_INCLUDED
#define MAP_HPP_INCLUDED
#include <vector>
#include <utility>
#include <queue>
#include "cell.hpp"
class Map {
public:
// The map is composed of a 2D vector of cells
std::vector< std::vector< Cell > > cells;
// Queue of map states (a new state is created everytime something changes
// on the map)
std::queue< std::vector< std::vector< Cell > > > history;
Map();
explicit Map(int);
explicit Map(int, int);
Cell getCell(size_t y, size_t x);
void updateRobotPos(std::pair<int,int> oldPos, std::pair<int,int> newPos);
bool validCoord(int y, int x) {return !(y < 0 || x < 0 || y >= vCells || x >= hCells);};
std::pair<int,int> getDest();
size_t height() {return vCells;};
size_t width() {return hCells;};
private:
// height and width of the map
size_t hCells, vCells;
void generateMaze();
};
#endif
| 26.25 | 89 | 0.680952 | REPOmAN2v2 |
207933cf4a9423cc0d3fde9eb79e0c3c1e95c057 | 213 | cpp | C++ | DSA/Bit Manipulation/5.Find position of the only set bit.cpp | mridul8920/winter-of-contributing | 9ee7c32cf6568c01f6a5263f4130e8edebb442fb | [
"MIT"
] | null | null | null | DSA/Bit Manipulation/5.Find position of the only set bit.cpp | mridul8920/winter-of-contributing | 9ee7c32cf6568c01f6a5263f4130e8edebb442fb | [
"MIT"
] | null | null | null | DSA/Bit Manipulation/5.Find position of the only set bit.cpp | mridul8920/winter-of-contributing | 9ee7c32cf6568c01f6a5263f4130e8edebb442fb | [
"MIT"
] | null | null | null | int findPosition(int N) {
int pos = 0, count = 0;
while (N != 0) {
if (N & 1 == 1) {
count++;
}
pos++;
N = N >> 1;
}
if (count == 0 || count > 1) {
return -1;
}
return pos;
}
| 14.2 | 32 | 0.399061 | mridul8920 |
207cf53ad626a85fd8461da773ae0dd74669854a | 10,573 | cpp | C++ | WTesterClient/widget_answer.cpp | RockRockWhite/WTester | 50a9de8ba7c48738eb054680d6eae0a2fc0c06e3 | [
"MIT"
] | null | null | null | WTesterClient/widget_answer.cpp | RockRockWhite/WTester | 50a9de8ba7c48738eb054680d6eae0a2fc0c06e3 | [
"MIT"
] | null | null | null | WTesterClient/widget_answer.cpp | RockRockWhite/WTester | 50a9de8ba7c48738eb054680d6eae0a2fc0c06e3 | [
"MIT"
] | null | null | null | #include "widget_answer.h"
#include "ui_widget_answer.h"
#include <QMessageBox>
#include <cmath>
#include <QTimer>
#include <QTextEdit>
#include <QCheckBox>
#include <QTcpSocket>
#pragma execution_character_set("utf-8")
extern QStringList question;
extern QString time;
QString errorNum;
QStringList answer,answer_u,empty,grade;
QLabel* imageLabel;
int m,h,question_left_count=0;
int size_y=5,totalGrade=0,totalGrade_u=0;
QTimer* timer=new QTimer();
widget_answer::widget_answer(QWidget *parent) :
QWidget(parent),
ui(new Ui::widget_answer)
{
ui->setupUi(this);
QObject::connect(timer,SIGNAL(timeout()),this,SLOT(timing()));
imageLabel = new QLabel(this);
ui->scrollArea->setWidgetResizable(1);
}
widget_answer::~widget_answer()
{
delete ui;
}
void widget_answer::init()
{
m=time.toInt()%60;
h=(time.toInt()-h)/60;
question_left_count=question.count()-1;
//设置时间
this->ui->timeEdit->setTime(QTime(h,m,0));
//启动倒计时
timer->start(1000);
size_y=0;
totalGrade=0;
totalGrade_u=0;
errorNum="";
//清理链表
answer.clear();
grade.clear();
empty.clear();
//释放内存
delete imageLabel;
//防止空指针
imageLabel=0;
imageLabel = new QLabel(this);
//重新设置按钮可用
ui->pushButton_ok->setEnabled(1);
this->fresh();
}
void widget_answer::timing()
{
if(ui->timeEdit->time().hour()==0&&ui->timeEdit->time().minute()==0&&ui->timeEdit->time().second()==0)
{
QMessageBox::information(this,"","时间结束");
for(int i=0;i<question_left_count;i++)
{
QCheckBox *checkBoxA=QObject::findChild<QCheckBox *>("QCheckBoxA"+QString::number(i));
QCheckBox *checkBoxB=QObject::findChild<QCheckBox *>("QCheckBoxB"+QString::number(i));
QCheckBox *checkBoxC=QObject::findChild<QCheckBox *>("QCheckBoxC"+QString::number(i));
QCheckBox *checkBoxD=QObject::findChild<QCheckBox *>("QCheckBoxD"+QString::number(i));
bool isEmpty=1;
QString a="";
//选择A
if(checkBoxA->isChecked())
{
a=a+"A";
isEmpty=0;
}
//选择B
if(checkBoxB->isChecked())
{
if(isEmpty)
{
a="B";
}
else
{
a=a+",B";
}
isEmpty=0;
}
//选择C
if(checkBoxC->isChecked())
{
if(isEmpty)
{
a="C";
}
else
{
a=a+",C";
}
isEmpty=0;
}
//选择D
if(checkBoxD->isChecked())
{
if(isEmpty)
{
a="D";
}
else
{
a=a+",D";
}
isEmpty=0;
}
//储存答案
if(isEmpty)
{
answer_u<<"EMPTY";
empty<<QString::number(i+1);
}
else
{
answer_u<<a;
}
}
if(empty.isEmpty())
{
QMessageBox::information(this,"恭喜","没有漏题!");
}
else
{
QString empty_num;
for(int n=0;n<empty.count();n++)
{
if(n==0)
{
empty_num=empty[n];
}
else
{
empty_num=empty_num+" "+empty[n];
}
}
QMessageBox::information(this,"提示",empty_num+"题还没有作答!");
}
ui->pushButton_ok->setEnabled(0);
this->check();
timer->stop();
}
else
{
ui->timeEdit->setTime(ui->timeEdit->time().addSecs(-1));
}
}
void widget_answer::fresh()
{
for(int i=0;i<question_left_count;i++)
{
size_y+=350;
//创建题目编辑框
QTextEdit *textEdit=new QTextEdit();
textEdit ->setObjectName("QLineEdit"+QString::number(i));
textEdit->setFont(QFont("Microsoft YaHei", 12, QFont::Normal));
textEdit->setGeometry(20,5+350*i,620,150);
textEdit->setParent( imageLabel);
textEdit->setEnabled(0);
//读取题目
int n=rand()%(question_left_count-i);
QStringList q_data=question[n].split("/");
question.removeAt(n);
if(q_data[5]=="0")
{
textEdit->setText(QString::number(i+1)+"."+q_data[0]+"(单选) "+q_data[7]+"分");
}
else
{
textEdit->setText(QString::number(i+1)+"."+q_data[0]+"(多选) "+q_data[7]+"分");
}
//创建答案选择框
//A
QCheckBox *checkBoxA=new QCheckBox("A."+q_data[1]+" ");
checkBoxA->setObjectName("QCheckBoxA"+QString::number(i));
checkBoxA->setFont(QFont("Microsoft YaHei", 12, QFont::Normal));
checkBoxA->setParent( imageLabel);
checkBoxA->setGeometry(30,5+350*i+150,620,50);
//B
QCheckBox *checkBoxB=new QCheckBox("B."+q_data[2]+" ");
checkBoxB->setObjectName("QCheckBoxB"+QString::number(i));
checkBoxB->setFont(QFont("Microsoft YaHei", 12, QFont::Normal));
checkBoxB->setParent(imageLabel);
checkBoxB->setGeometry(30,5+350*i+200,620,50);
//C
QCheckBox *checkBoxC=new QCheckBox("C."+q_data[3]+" ");
checkBoxC->setObjectName("QCheckBoxC"+QString::number(i));
checkBoxC->setFont(QFont("Microsoft YaHei", 12, QFont::Normal));
checkBoxC->setParent( imageLabel);
checkBoxC->setGeometry(30,5+350*i+250,620,50);
//D
QCheckBox *checkBoxD=new QCheckBox("D."+q_data[4]+" ");
checkBoxD->setObjectName("QCheckBoxD"+QString::number(i));
checkBoxD->setFont(QFont("Microsoft YaHei", 12, QFont::Normal));
checkBoxD->setParent( imageLabel);
checkBoxD->setGeometry(30,5+350*i+300,620,50);
//储存答案
answer<<q_data[6];
grade<<q_data[7];
}
//调整滚动框
QPixmap pixmap(":/ui/nothing");
pixmap = pixmap.scaled(620, size_y);
imageLabel->setPixmap(pixmap);
ui->scrollArea->setWidget(imageLabel);
}
void widget_answer::on_pushButton_ok_clicked()
{
QMessageBox msgBox;
empty.clear();
if(msgBox.question(this,"提交答案","确定提交您的答案,若提交将不可修改?")==QMessageBox::Yes)
{
for(int i=0;i<question_left_count;i++)
{
QCheckBox *checkBoxA=QObject::findChild<QCheckBox *>("QCheckBoxA"+QString::number(i));
QCheckBox *checkBoxB=QObject::findChild<QCheckBox *>("QCheckBoxB"+QString::number(i));
QCheckBox *checkBoxC=QObject::findChild<QCheckBox *>("QCheckBoxC"+QString::number(i));
QCheckBox *checkBoxD=QObject::findChild<QCheckBox *>("QCheckBoxD"+QString::number(i));
bool isEmpty=1;
QString a="";
//选择A
if(checkBoxA->isChecked())
{
a=a+"A";
isEmpty=0;
}
//选择B
if(checkBoxB->isChecked())
{
if(isEmpty)
{
a="B";
}
else
{
a=a+",B";
}
isEmpty=0;
}
//选择C
if(checkBoxC->isChecked())
{
if(isEmpty)
{
a="C";
}
else
{
a=a+",C";
}
isEmpty=0;
}
//选择D
if(checkBoxD->isChecked())
{
if(isEmpty)
{
a="D";
}
else
{
a=a+",D";
}
isEmpty=0;
}
//储存答案
if(isEmpty)
{
answer_u<<"EMPTY";
empty<<QString::number(i+1);
}
else
{
answer_u<<a;
QMessageBox::information(this,"",a);
}
}
if(empty.isEmpty())
{
QMessageBox::information(this,"恭喜","没有漏题!");
this->check();
ui->pushButton_ok->setEnabled(0);
}
else
{
QString empty_num;
for(int n=0;n<empty.count();n++)
{
if(n==0)
{
empty_num=empty[n];
}
else
{
empty_num=empty_num+" "+empty[n];
}
}
if(msgBox.question(this,"警告",empty_num+"题还没有作答,确认提交?")==QMessageBox::Yes)
{
this->check();
ui->pushButton_ok->setEnabled(0);
}
else
{
}
}
}
}
void widget_answer::check()
{
for(int i=0;i<question_left_count;i++)
{
if(answer_u[i]==answer[i])
{
QString g=grade[i];
totalGrade_u+=g.toFloat();
}
else
{
errorNum+=" "+QString::number(i+1);
}
}
extern QTcpSocket* tcpSocket;
extern QString loginedID;
extern QString qusetionName;
QDateTime current_date_time =QDateTime::currentDateTime();
QString date =current_date_time.toString("yyyy.MM.dd hh:mm:ss.zzz ddd");
tcpSocket->write("GRADE|"+loginedID.toUtf8()+"|"+qusetionName.toUtf8()+" 得分:"+QString::number(totalGrade_u).toUtf8()+" 完成时间:"+date.toUtf8());
if(tcpSocket->waitForReadyRead())
{
QString d=tcpSocket->readAll();
}
else
{
QMessageBox::information(this,"提交成绩失败","服务器连接超时,请检查您的网络配置.");
}
QMessageBox::information(this,"得分","您的得分为:"+QString::number(totalGrade_u)+"\n错误题号:"+errorNum);
}
| 27.823684 | 207 | 0.449352 | RockRockWhite |
207d572ba60eeb4b1900d9ccacff00a0cb24ca2e | 600 | cpp | C++ | plugins/single_plugins/autostart.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | 3 | 2019-01-16T14:43:24.000Z | 2019-10-09T10:07:33.000Z | plugins/single_plugins/autostart.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | null | null | null | plugins/single_plugins/autostart.cpp | SirCmpwn/wayfire | 007452f6ccc07ceca51879187bba142431832382 | [
"MIT"
] | 1 | 2019-05-07T09:46:58.000Z | 2019-05-07T09:46:58.000Z | #include <plugin.hpp>
#include "../../shared/config.hpp"
#include <core.hpp>
class wayfire_autostart : public wayfire_plugin_t
{
public:
void init(wayfire_config *config)
{
/* make sure we are run only when adding the first output */
if (core->get_next_output(output) != output)
return;
auto section = config->get_section("autostart");
for (const auto& command : section->options)
core->run(command.second.c_str());
}
};
extern "C"
{
wayfire_plugin_t *newInstance()
{
return new wayfire_autostart();
}
}
| 21.428571 | 68 | 0.613333 | SirCmpwn |
2083b0b313c271d325b3c26f93d5e7b738e8d634 | 657 | cpp | C++ | DxLibEngine/base/Input.cpp | darknesswind/LiteSTG | ec24641948369e6ee1a3bdcc0d6b78515f1a0374 | [
"MIT"
] | 2 | 2015-09-11T08:17:20.000Z | 2018-03-13T07:21:15.000Z | DxLibEngine/base/Input.cpp | darknesswind/LiteSTG | ec24641948369e6ee1a3bdcc0d6b78515f1a0374 | [
"MIT"
] | null | null | null | DxLibEngine/base/Input.cpp | darknesswind/LiteSTG | ec24641948369e6ee1a3bdcc0d6b78515f1a0374 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Input.h"
LInput::LInput(void)
: m_nJoyNum(0)
{
m_curKeyState.fill(0);
m_keyList.fill(KeyState::None);
m_logicKeyMap.fill(Keys::None);
m_nJoyNum = DxLib::GetJoypadNum();
}
LInput::~LInput(void)
{
}
bool LInput::update()
{
const bool bSucceed = (0 == DxLib::GetHitKeyStateAll(m_curKeyState.data()));
for (int i = 0; i < KeyCount; ++i)
{
// keyList[i] = (KeyState)(((keyList[i] | 2) == 2 ? 0 : 2) | curKeyState[i]);
m_keyList[i] = static_cast<KeyState>(((static_cast<uchar>(m_keyList[i]) << 1) & 0x2) | m_curKeyState[i]);
}
CheckRes(DxLib::GetMousePoint(&m_mousePos.rx(), &m_mousePos.ry()));
return bSucceed;
}
| 22.655172 | 107 | 0.656012 | darknesswind |
20891035a5804095b2634ce802a9eb9d4f7f906b | 2,244 | cpp | C++ | Source/Application.cpp | michal-z/PerfExperiments | 4431a74cb90407d7cd3645c4f218eaccd8516ea1 | [
"MIT"
] | 1 | 2021-11-07T07:22:47.000Z | 2021-11-07T07:22:47.000Z | Source/Application.cpp | michal-z/MyPerfExperiments | 4431a74cb90407d7cd3645c4f218eaccd8516ea1 | [
"MIT"
] | null | null | null | Source/Application.cpp | michal-z/MyPerfExperiments | 4431a74cb90407d7cd3645c4f218eaccd8516ea1 | [
"MIT"
] | null | null | null | #include "Pch.h"
#include "Application.h"
FApplication GApp;
void FApplication::Initialize()
{
QueryPerformanceCounter(&StartCounter);
QueryPerformanceFrequency(&Frequency);
SetProcessDPIAware();
MakeWindow(1280, 720);
}
void FApplication::Update()
{
UpdateFrameTime();
}
double FApplication::GetTime()
{
LARGE_INTEGER Counter;
QueryPerformanceCounter(&Counter);
return (Counter.QuadPart - StartCounter.QuadPart) / (double)Frequency.QuadPart;
}
void FApplication::UpdateFrameTime()
{
static double LastTime = -1.0;
static double LastFpsTime = 0.0;
static unsigned FpsFrame = 0;
if (LastTime < 0.0)
{
LastTime = GetTime();
LastFpsTime = LastTime;
}
FrameTime = GetTime();
FrameDeltaTime = (float)(FrameTime - LastTime);
LastTime = FrameTime;
if ((FrameTime - LastFpsTime) >= 1.0)
{
double Fps = FpsFrame / (FrameTime - LastFpsTime);
double AvgFrameTime = (1.0 / Fps) * 1000000.0;
char Text[256];
wsprintf(Text, "[%d fps %d us] %s", (int)Fps, (int)AvgFrameTime, ApplicationName);
SetWindowText(Window, Text);
LastFpsTime = FrameTime;
FpsFrame = 0;
}
FpsFrame++;
}
LRESULT CALLBACK FApplication::ProcessWindowMessage(HWND InWindow, UINT Message, WPARAM WParam, LPARAM LParam)
{
switch (Message)
{
case WM_KEYDOWN:
if (WParam == VK_ESCAPE)
{
PostQuitMessage(0);
return 0;
}
break;
case WM_DESTROY:
PostQuitMessage(0);
return 0;
}
return DefWindowProc(InWindow, Message, WParam, LParam);
}
void FApplication::MakeWindow(uint32_t ResolutionX, uint32_t ResolutionY)
{
WNDCLASS Winclass = {};
Winclass.lpfnWndProc = ProcessWindowMessage;
Winclass.hInstance = GetModuleHandle(nullptr);
Winclass.hCursor = LoadCursor(nullptr, IDC_ARROW);
Winclass.lpszClassName = ApplicationName;
if (!RegisterClass(&Winclass))
{
assert(0);
}
RECT Rect = { 0, 0, (int32_t)ResolutionX, (int32_t)ResolutionY };
if (!AdjustWindowRect(&Rect, WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX, 0))
{
assert(0);
}
Window = CreateWindowEx(
0, ApplicationName, ApplicationName,
WS_OVERLAPPED | WS_SYSMENU | WS_CAPTION | WS_MINIMIZEBOX | WS_VISIBLE,
CW_USEDEFAULT, CW_USEDEFAULT,
Rect.right - Rect.left, Rect.bottom - Rect.top,
NULL, NULL, NULL, 0);
assert(Window);
}
| 22.44 | 110 | 0.720588 | michal-z |
20899eef7027a43b056777e704f0326e9a4149b3 | 3,226 | hpp | C++ | src/ibeo_8l_sdk/src/ibeosdk/devices/IbeoEcu.hpp | tomcamp0228/ibeo_ros2 | ff56c88d6e82440ae3ce4de08f2745707c354604 | [
"MIT"
] | 1 | 2020-06-19T11:01:49.000Z | 2020-06-19T11:01:49.000Z | include/ibeosdk/devices/IbeoEcu.hpp | chouer19/enjoyDriving | e4a29e6cad7d3b0061d59f584cce7cdea2a55351 | [
"MIT"
] | null | null | null | include/ibeosdk/devices/IbeoEcu.hpp | chouer19/enjoyDriving | e4a29e6cad7d3b0061d59f584cce7cdea2a55351 | [
"MIT"
] | 2 | 2020-06-19T11:01:48.000Z | 2020-10-29T03:07:14.000Z | //======================================================================
/*! \file IbeoEcu.hpp
*
* \copydoc Copyright
* \author Mario Brumm (mb)
* \date Apr 24, 2012
*///-------------------------------------------------------------------
#ifndef IBEOSDK_IBEOECU_HPP_SEEN
#define IBEOSDK_IBEOECU_HPP_SEEN
//======================================================================
#include <ibeosdk/misc/WinCompatibility.hpp>
#include <ibeosdk/devices/IbeoDevice.hpp>
//======================================================================
namespace ibeosdk {
//======================================================================
class IbeoEcu : public IbeoDevice<IbeoEcu> {
public:
//========================================
/*!\brief Create an IbeoEcu (connection class).
*
* This constructor will create an IbeoEcu class object
* which will try to connect to an ECU,
* using the given IP address and port number.
*
* \param[in] ip IP address of the ECU
* to be connected with.
* \param[in] port Port number for the connection
* with the scanner.
*///-------------------------------------
IbeoEcu(const std::string& ip, const unsigned short port = 12002);
//========================================
/*!\brief Destructor.
*
* Will disconnect before destruction.
*///-------------------------------------
virtual ~IbeoEcu();
public:
//========================================
/*!\brief Establish the connection to the hardware.
*
* Reimplements IbeoDevice::getConnected. In
* addition it will send a setFilter command
* to the ECU to make all messages passes its
* output filter.
*///-------------------------------------
virtual void getConnected();
public:
//========================================
/*!\brief Send a command which expects no reply.
* \param[in] cmd Command to be sent.
* \return The result of the operation.
*///-------------------------------------
virtual statuscodes::Codes sendCommand(const EcuCommandBase& cmd);
//========================================
/*!\brief Send a command and wait for a reply.
*
* The command will be sent. The calling thread
* will sleep until a reply has been received
* but not longer than the number of milliseconds
* given in \a timeOut.
*
* \param[in] cmd Command to be sent.
* \param[in, out] reply The reply container for
* the reply to be stored into.
* \param[in] timeOut Number of milliseconds to
* wait for a reply.
* \return The result of the operation.
*///-------------------------------------
virtual statuscodes::Codes sendCommand(const EcuCommandBase& cmd,
EcuCommandReplyBase& reply,
const boost::posix_time::time_duration timeOut = boost::posix_time::milliseconds(500));
}; // IbeoEcu
//======================================================================
} // namespace ibeosdk
//======================================================================
#endif // IBEOSDK_IBEOECU_HPP_SEEN
//======================================================================
| 33.604167 | 127 | 0.450713 | tomcamp0228 |
208e31af872d140780be8836b8f8eb79ca09ca06 | 393 | hpp | C++ | inc/rook/ast/call.hpp | Vandise/Gambit-Archive | 6db1921d99d76cd10f8f1bd25c46776d435d85a7 | [
"MIT"
] | 1 | 2019-02-20T19:19:23.000Z | 2019-02-20T19:19:23.000Z | inc/rook/ast/call.hpp | Vandise/Gambit-Archive | 6db1921d99d76cd10f8f1bd25c46776d435d85a7 | [
"MIT"
] | null | null | null | inc/rook/ast/call.hpp | Vandise/Gambit-Archive | 6db1921d99d76cd10f8f1bd25c46776d435d85a7 | [
"MIT"
] | null | null | null | #ifndef __ROOK_CALLNODE
#define __ROOK_CALLNODE 1
#include "rook/ast/node.hpp"
#include <vector>
namespace RookAST
{
class CallNode : public RookAST::Node
{
protected:
std::string methodSignature;
int parameters;
public:
CallNode(std::string methodSignature, int parameters);
~CallNode();
void compile(RookVM::PawnExecutor* e);
};
}
#endif | 14.035714 | 60 | 0.669211 | Vandise |
209c4d620b6ba3e6717ab1b61a5efd30e62a2e99 | 1,036 | cpp | C++ | client/core/layers.cpp | syby119/icloth-web-application | 241d894b5f4805964ab7991b5ccb62e44a6aa7cb | [
"MIT"
] | 2 | 2021-11-12T05:53:48.000Z | 2021-11-12T05:53:59.000Z | client/core/layers.cpp | syby119/icloth-web-application | 241d894b5f4805964ab7991b5ccb62e44a6aa7cb | [
"MIT"
] | null | null | null | client/core/layers.cpp | syby119/icloth-web-application | 241d894b5f4805964ab7991b5ccb62e44a6aa7cb | [
"MIT"
] | null | null | null | #include <iostream>
#include "layers.h"
void Layers::set(int channel) noexcept {
_mask = 1 << channel;
}
void Layers::enable(int channel) noexcept {
_mask |= 1 << channel;
}
void Layers::enableAll() noexcept {
_mask = 0xFFFFFFFF;
}
void Layers::toggle(int channel) noexcept {
_mask ^= 1 << channel;
}
void Layers::disable(int channel) noexcept {
_mask &= ~(1 << channel);
}
void Layers::disableAll() noexcept {
_mask = 0;
}
bool Layers::isEnabled(int channel) const noexcept {
return _mask & (1 << channel);
}
bool Layers::test(Layers layers) const noexcept {
return _mask & layers._mask;
}
void Layers::printEnabledChannels() const {
bool first = true;
std::cout << "[";
for (int channel = 0; channel < getMaxChannels(); ++channel) {
if (isEnabled(channel)) {
if (first) {
std::cout << channel;
first = false;
} else {
std::cout << ", " << channel;
}
}
}
std::cout << "]";
} | 20.72 | 66 | 0.563707 | syby119 |
209cfe14153b98e74ba62878d208d95657a39e11 | 7,524 | cc | C++ | naos/src/kernel/arch/cpu.cc | kadds/NaOS | ea5eeed6f777b8f62acf3400b185c94131b6e1f0 | [
"BSD-3-Clause"
] | 14 | 2020-02-12T11:07:58.000Z | 2022-02-02T00:05:08.000Z | naos/src/kernel/arch/cpu.cc | kadds/NaOS | ea5eeed6f777b8f62acf3400b185c94131b6e1f0 | [
"BSD-3-Clause"
] | null | null | null | naos/src/kernel/arch/cpu.cc | kadds/NaOS | ea5eeed6f777b8f62acf3400b185c94131b6e1f0 | [
"BSD-3-Clause"
] | 4 | 2020-02-27T09:53:53.000Z | 2021-11-07T17:43:44.000Z | #include "kernel/arch/cpu.hpp"
#include "kernel/arch/klib.hpp"
#include "kernel/arch/task.hpp"
#include "kernel/arch/tss.hpp"
#include "kernel/arch/paging.hpp"
#include "kernel/mm/vm.hpp"
#include "kernel/mm/memory.hpp"
#include "kernel/mm/mm.hpp"
#include "kernel/task.hpp"
#include "kernel/trace.hpp"
#include "kernel/ucontext.hpp"
namespace arch::cpu
{
cpu_t per_cpu_data[max_cpu_support];
std::atomic_int last_cpuid = 0;
void *get_rsp()
{
void *stack;
__asm__ __volatile__("movq %%rsp,%0 \n\t" : "=r"(stack) : :);
return stack;
}
// switch task
void cpu_t::set_context(void *stack)
{
kernel_rsp = static_cast<byte *>(stack);
tss::set_rsp(cpu::current().get_id(), 0, stack);
}
bool cpu_t::is_in_exception_context() { return is_in_exception_context(get_rsp()); }
bool cpu_t::is_in_kernel_context() { return is_in_kernel_context(get_rsp()); }
bool cpu_t::is_in_interrupt_context() { return is_in_interrupt_context(get_rsp()); }
bool cpu_t::is_in_exception_context(void *rsp)
{
byte *t_rsp = get_exception_rsp();
byte *b_rsp = t_rsp - memory::exception_stack_size;
byte *s_rsp = static_cast<byte *>(rsp);
return s_rsp <= t_rsp && s_rsp >= b_rsp;
}
bool cpu_t::is_in_interrupt_context(void *rsp)
{
byte *t_rsp = get_interrupt_rsp();
byte *b_rsp = t_rsp - memory::interrupt_stack_size;
byte *s_rsp = static_cast<byte *>(rsp);
return s_rsp <= t_rsp && s_rsp >= b_rsp;
}
bool cpu_t::is_in_kernel_context(void *rsp)
{
byte *t_rsp = get_kernel_rsp();
byte *b_rsp = t_rsp - memory::kernel_stack_size;
byte *s_rsp = static_cast<byte *>(rsp);
return s_rsp <= t_rsp && s_rsp >= b_rsp;
}
cpuid_t init()
{
u64 cpuid = last_cpuid++;
auto &cur_data = per_cpu_data[cpuid];
cur_data.id = cpuid;
/// gs kernel base
_wrmsr(0xC0000102, (u64)&per_cpu_data[cpuid]);
kassert(_rdmsr(0xC0000102) == ((u64)&per_cpu_data[cpuid]), "Unable to write kernel gs_base");
/// gs user base
_wrmsr(0xC0000101, 0);
/// fs base
_wrmsr(0xC0000100, 0);
__asm__("swapgs \n\t" ::: "memory");
kassert(_rdmsr(0xC0000101) == ((u64)&per_cpu_data[cpuid]), "Unable to swap kernel gs register");
return cpuid;
}
bool has_init() { return last_cpuid >= 1; }
void init_data(cpuid_t cpuid)
{
_wrmsr(0xC0000101, (u64)&per_cpu_data[cpuid]);
auto &data = cpu::current();
data.interrupt_rsp = get_interrupt_stack_bottom(cpuid) + memory::interrupt_stack_size;
data.exception_rsp = get_exception_stack_bottom(cpuid) + memory::exception_stack_size;
data.exception_nmi_rsp = get_exception_nmi_stack_bottom(cpuid) + memory::exception_nmi_stack_size;
data.kernel_rsp = get_kernel_stack_bottom(cpuid) + memory::kernel_stack_size;
tss::set_rsp(cpuid, 0, data.kernel_rsp);
tss::set_ist(cpuid, 1, data.interrupt_rsp);
tss::set_ist(cpuid, 3, data.exception_rsp);
tss::set_ist(cpuid, 4, data.exception_nmi_rsp);
}
bool cpu_t::is_bsp() { return id == 0; }
cpu_t &get(cpuid_t cpuid) { return per_cpu_data[cpuid]; }
cpu_t ¤t()
{
u64 cpuid;
#ifdef _DEBUG
kassert(_rdmsr(0xC0000101) != 0, "Unreadable gs base");
kassert(_rdmsr(0xC0000102) == 0, "Unreadable kernel gs base");
#endif
__asm__("movq %%gs:0x0, %0\n\t" : "=r"(cpuid) : :);
return per_cpu_data[cpuid];
}
void *current_user_data()
{
u64 u;
__asm__("movq %%gs:0x10, %0\n\t" : "=r"(u) : :);
return (void *)u;
}
u64 count() { return last_cpuid; }
cpuid_t id() { return current().get_id(); }
void map(u64 &base, u64 pg, bool is_bsp = false) {
u64 size = pg * memory::page_size;
auto c = (arch::paging::base_paging_t *) memory::kernel_vm_info->mmu_paging.get_base_page();
base += memory::page_size;
phy_addr_t ks;
if (is_bsp) {
ks = phy_addr_t::from(0x90000 - size);
} else {
ks = memory::va2pa(memory::KernelBuddyAllocatorV->allocate(size, 0));
}
paging::map(c, reinterpret_cast<void*>(base), ks, paging::frame_size::size_4kb, pg, paging::flags::writable);
base += size;
}
void allocate_stack(int logic_num)
{
u64 base = memory::kernel_cpu_stack_bottom_address;
for (int i = 0; i < logic_num; i++)
{
if (i != 0) {
map(base, memory::kernel_stack_page_count);
} else {
map(base, memory::kernel_stack_page_count, true);
}
map(base, memory::exception_stack_page_count);
map(base, memory::interrupt_stack_page_count);
map(base, memory::exception_nmi_stack_page_count);
}
}
phy_addr_t get_kernel_stack_bottom_phy(cpuid_t id) {
void *vir = get_kernel_stack_bottom(id);
phy_addr_t phy = nullptr;
bool ret = paging::get_map_address(paging::current(), vir, &phy);
kassert(ret, "");
return phy;
}
phy_addr_t get_exception_stack_bottom_phy(cpuid_t id) {
void *vir = get_exception_stack_bottom(id);
phy_addr_t phy = nullptr;
bool ret = paging::get_map_address(paging::current(), vir, &phy);
kassert(ret, "");
return phy;
}
phy_addr_t get_interrupt_stack_bottom_phy(cpuid_t id) {
void *vir = get_interrupt_stack_bottom(id);
phy_addr_t phy = nullptr;
bool ret = paging::get_map_address(paging::current(), vir, &phy);
kassert(ret, "");
return phy;
}
phy_addr_t get_exception_nmi_stack_bottom_phy(cpuid_t id) {
void *vir = get_exception_nmi_stack_bottom(id);
phy_addr_t phy = nullptr;
bool ret = paging::get_map_address(paging::current(), vir, &phy);
kassert(ret, "");
return phy;
}
byte *get_kernel_stack_bottom(cpuid_t id)
{
u64 base = memory::kernel_cpu_stack_bottom_address;
u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size +
memory::exception_nmi_stack_size;
each_of_cpu_size += memory::page_size * 4; // guard pages
return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size);
}
byte *get_exception_stack_bottom(cpuid_t id)
{
u64 base = memory::kernel_cpu_stack_bottom_address;
u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size +
memory::exception_nmi_stack_size;
each_of_cpu_size += memory::page_size * 4; // guard pages
return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size * 2 + memory::kernel_stack_size);
}
byte *get_interrupt_stack_bottom(cpuid_t id)
{
u64 base = memory::kernel_cpu_stack_bottom_address;
u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size +
memory::exception_nmi_stack_size;
each_of_cpu_size += memory::page_size * 4; // guard pages
return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size * 3 + memory::kernel_stack_size +
memory::exception_stack_size);
}
byte *get_exception_nmi_stack_bottom(cpuid_t id)
{
u64 base = memory::kernel_cpu_stack_bottom_address;
u64 each_of_cpu_size = memory::kernel_stack_size + memory::exception_stack_size + memory::interrupt_stack_size +
memory::exception_nmi_stack_size;
each_of_cpu_size += memory::page_size * 4; // guard pages
return reinterpret_cast<byte *>(base + each_of_cpu_size * id + memory::page_size * 4 + memory::kernel_stack_size +
memory::exception_stack_size + memory::interrupt_stack_size);
}
} // namespace arch::cpu | 31.881356 | 118 | 0.68009 | kadds |
20a2ae88676f1ed59012289a780288c9fb47879c | 7,181 | hpp | C++ | QtDemoApp/auth/smbios.hpp | F474M0R64N4/license-system | 982f1297948353b58d736009a08c697c3e15a41b | [
"MIT"
] | 4 | 2020-10-13T19:57:16.000Z | 2021-09-08T11:57:12.000Z | client/client/src/auth/smbios.hpp | F474M0R64N4/license-system | 982f1297948353b58d736009a08c697c3e15a41b | [
"MIT"
] | null | null | null | client/client/src/auth/smbios.hpp | F474M0R64N4/license-system | 982f1297948353b58d736009a08c697c3e15a41b | [
"MIT"
] | null | null | null | #ifndef SMBIOS_H
#define SMBIOS_H
#pragma once
#include <cstdint>
#include <vector>
namespace smbios
{
namespace types
{
enum
{
bios_info = 0,
// Required
system_info = 1,
// Required
baseboard_info = 2,
module_info = 2,
system_enclosure = 3,
// Required
system_chassis = 3,
// Required
processor_info = 4,
// Required
memory_controller_info = 5,
// Obsolete
memory_module_info = 6,
// Obsolete
cache_info = 7,
// Required
port_connector_info = 8,
system_slots = 9,
// Required
onboard_device_info = 10,
// Obsolete
oem_strings = 11,
system_config_options = 12,
language_info = 13,
group_associations = 14,
system_event_log = 15,
memory_array = 16,
// Required
memory_device = 17,
// Required
memory_error_info_32_bit = 18,
memory_array_mapped_addr = 19,
// Required
memory_device_mapped_addr = 20,
builtin_pointing_device = 21,
portable_battery = 22,
system_reset = 23,
hardware_security = 24,
system_power_controls = 25,
voltage_probe = 26,
cooling_device = 27,
temperature_probe = 28,
electrical_current_probe = 29,
out_of_band_remote_access = 30,
bis_entry_point = 31,
// Required
system_boot_info = 32,
// Required
memory_error_info_64_bit = 33,
management_device = 34,
management_device_component = 35,
management_device_threshold = 36,
memory_channel = 37,
ipmi_device_info = 38,
system_power_supply = 39,
additional_info = 40,
onboard_device_extinfo = 41,
management_controller_host = 42,
inactive = 126,
end_of_table = 127,
// Always last structure
};
}
typedef uint8_t byte_t;
typedef uint16_t word_t;
typedef uint32_t dword_t;
#ifdef _MSC_VER
typedef __int64 qword_t;
#else
#ifdef INT64_C
typedef uint64_t qword_t;
#else
typedef (unsigned long long int) qwordt_t;
#endif
#endif
typedef byte_t str_id;
typedef byte_t enum_t;
typedef std::vector<char*> string_array_t;
struct header;
#pragma pack(push, 1)
struct raw_smbios_data
{
BYTE used20_calling_method;
BYTE smbios_major_version;
BYTE smbios_minor_version;
BYTE dmi_revision;
DWORD length;
BYTE smbios_table_data[1];
};
struct header
{
byte_t type;
byte_t length;
word_t handle;
};
struct string_list : header
{
byte_t count;
};
struct baseboard_info : header
{
byte_t manufacturer_name;
byte_t product_name;
byte_t version;
byte_t serial_number;
byte_t product;
byte_t version1;
byte_t serial_number1;
};
struct bios_info : header
{
// 2.0
str_id vendor;
str_id version;
word_t starting_segment;
str_id release_date;
byte_t rom_size;
qword_t characteristics;
// 2.4
byte_t ext_char1;
byte_t ext_char2;
byte_t sb_major;
byte_t sb_minor;
byte_t ec_major;
byte_t ec_minor;
};
struct system_info : header
{
// 2.0
str_id manufacturer;
str_id product_name;
str_id version;
str_id serial_number;
// 2.1
struct
{
dword_t time_low;
word_t time_mid;
word_t time_hi_and_version;
byte_t clock_seq_hi_and_reserved;
byte_t clock_seq_low;
byte_t node[6];
} uuid;
enum_t wakeup_type;
// 2.4
str_id sku;
str_id family;
};
struct system_chassis : header
{
// 2.0
str_id manufacturer;
byte_t type;
str_id version;
str_id serial_number;
str_id assert_tag;
// 2.1
enum_t bootup_state;
enum_t power_supply_state;
enum_t thermal_state;
enum_t security_status;
// 2.3
dword_t oem;
byte_t height;
byte_t cords;
};
struct proc_info : header
{
// 2.0
str_id socket_designation;
enum_t type;
enum_t family;
str_id manufacturer;
qword_t id;
str_id version;
byte_t voltage;
word_t clock;
word_t speed_max;
word_t speed_cur;
byte_t status;
enum_t upgrade;
// 2.1
word_t l1;
word_t l2;
word_t l3;
// 2.3
str_id serial_number;
str_id assert_tag;
str_id part_number;
// 2.5
byte_t cores;
byte_t cores_enabled;
byte_t threads;
word_t characteristics;
enum_t family2;
};
struct cache_info : header
{
// 2.0
str_id socket_designation;
word_t config;
word_t size_max;
word_t size_cur;
word_t sram_supported;
word_t sram_cur;
// 2.1
byte_t speed;
enum_t error_correction_type;
enum_t system_cache_type;
enum_t associativity;
};
struct slot : header
{
// 2.0
str_id slot_designation;
enum_t type;
enum_t data_bus_width;
enum_t current_usage;
enum_t length;
word_t id;
byte_t characteristics;
// 2.1
byte_t characteristics2;
// 2.6
word_t segment_group;
byte_t bus;
byte_t device;
};
typedef string_list oem_strings;
typedef string_list system_config_options;
struct lang_info : header
{
byte_t installed_langs;
byte_t flags;
byte_t reserved[15];
str_id current_lang;
};
struct mem_arr : header
{
// 2.1
enum_t location;
enum_t use;
enum_t error_correction;
dword_t capacity;
word_t error_info_handle;
word_t devices_number;
// 2.7
qword_t capacity_ext;
};
struct mem_device : header
{
// 2.1
word_t mem_arr_handle;
word_t mem_arr_error_info_handle;
word_t total_width;
word_t data_width;
word_t size;
enum_t form_factor;
byte_t device_set;
str_id device_locator;
str_id bank_locator;
enum_t type;
word_t type_detail;
// 2.3
word_t speed;
str_id manufacturer;
str_id serial_number;
str_id assert_tag;
str_id part_number;
// 2.6
byte_t attributes;
// 2.7
dword_t size_ext;
word_t clock_speed;
// 2.8
word_t voltage_min;
word_t voltage_max;
word_t voltage;
};
#pragma pack(pop)
class parser final
{
public:
parser() = default;
parser(const parser& x)
{
feed(x.raw_data_, x.raw_size_);
}
~parser()
{
clear();
}
std::vector<header*> headers;
static byte_t* skip(byte_t*);
static header* extract_strings(header*, string_array_t&);
void feed(const void* raw_smbios, size_t size);
void clear();
protected:
byte_t* raw_data_{};
size_t raw_size_{};
};
inline byte_t* parser::skip(byte_t* x)
{
auto* ptr = x + reinterpret_cast<header*>(x)->length;
size_t len;
if (*ptr == 0) ptr += 2;
else
do
{
len = strlen(reinterpret_cast<const char*>(ptr));
ptr += len + 1;
}
while (len > 0);
return ptr;
}
inline header* parser::extract_strings(header* x, string_array_t& a)
{
auto* ptr = reinterpret_cast<byte_t*>(x) + x->length;
a.clear();
a.push_back(nullptr);
if (*ptr == 0) ptr += 2;
else
for (;;)
{
auto* str = reinterpret_cast<char*>(ptr);
const auto len = strlen(str);
ptr += len + 1;
if (len == 0)
break;
a.push_back(str);
}
return reinterpret_cast<header*>(ptr);
}
inline void parser::feed(const void* raw_smbios, const size_t size)
{
clear();
raw_size_ = size;
raw_data_ = new byte_t[raw_size_];
memcpy(raw_data_, raw_smbios, size);
auto* x = raw_data_;
while (static_cast<size_t>(x - raw_data_) < raw_size_)
{
headers.push_back(reinterpret_cast<header*>(x));
x = skip(x);
}
}
inline void parser::clear()
{
headers.clear();
delete[] raw_data_;
raw_size_ = 0;
}
} // namespace smbios
#endif | 17.179426 | 69 | 0.682495 | F474M0R64N4 |
20a36919a2849dc05936f9aedecf1dcbee09ae40 | 2,536 | cc | C++ | test/integration/kinetic_energy_monitor_system.cc | jasmeet0915/ign-gazebo | fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2 | [
"ECL-2.0",
"Apache-2.0"
] | 198 | 2020-04-15T16:56:09.000Z | 2022-03-27T12:31:08.000Z | test/integration/kinetic_energy_monitor_system.cc | jasmeet0915/ign-gazebo | fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2 | [
"ECL-2.0",
"Apache-2.0"
] | 1,220 | 2020-04-15T18:10:29.000Z | 2022-03-31T22:37:06.000Z | test/integration/kinetic_energy_monitor_system.cc | jasmeet0915/ign-gazebo | fc2a98ec5e1b149d773eeb6cae4a407bd82a81a2 | [
"ECL-2.0",
"Apache-2.0"
] | 134 | 2020-04-15T16:59:57.000Z | 2022-03-26T08:51:31.000Z | /*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* 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 <gtest/gtest.h>
#include <ignition/msgs/double.pb.h>
#include <mutex>
#include <ignition/common/Console.hh>
#include <ignition/common/Util.hh>
#include <ignition/math/Pose3.hh>
#include <ignition/transport/Node.hh>
#include "ignition/gazebo/Server.hh"
#include "ignition/gazebo/SystemLoader.hh"
#include "ignition/gazebo/test_config.hh"
#include "../helpers/EnvTestFixture.hh"
using namespace ignition;
using namespace gazebo;
/// \brief Test Kinetic Energy Monitor system
class KineticEnergyMonitorTest : public InternalFixture<::testing::Test>
{
};
std::mutex mutex;
std::vector<msgs::Double> dblMsgs;
/////////////////////////////////////////////////
void cb(const msgs::Double &_msg)
{
mutex.lock();
dblMsgs.push_back(_msg);
mutex.unlock();
}
/////////////////////////////////////////////////
// The test checks the world pose and sensor readings of a falling altimeter
TEST_F(KineticEnergyMonitorTest, ModelFalling)
{
// Start server
ServerConfig serverConfig;
const auto sdfFile = std::string(PROJECT_SOURCE_PATH) +
"/test/worlds/altimeter.sdf";
serverConfig.SetSdfFile(sdfFile);
Server server(serverConfig);
EXPECT_FALSE(server.Running());
EXPECT_FALSE(*server.Running(0));
const std::string sensorName = "altimeter_sensor";
// subscribe to kinetic energy topic
std::string topic = "/model/altimeter_model/kinetic_energy";
transport::Node node;
node.Subscribe(topic, &cb);
// Run server
size_t iters = 1000u;
server.Run(true, iters, false);
// Wait for messages to be received
for (int sleep = 0; sleep < 30; ++sleep)
{
std::this_thread::sleep_for(std::chrono::milliseconds(100));
mutex.lock();
bool received = dblMsgs.size() > 0;
mutex.unlock();
if (received)
break;
}
mutex.lock();
EXPECT_EQ(1u, dblMsgs.size());
auto firstMsg = dblMsgs.front();
mutex.unlock();
EXPECT_GT(firstMsg.data(), 2);
}
| 26.416667 | 76 | 0.69164 | jasmeet0915 |
20a383dc150347f4a66ce92e9e3607015dc031dd | 10,264 | cpp | C++ | src/game/server/hl2/grenade_tripwire.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/server/hl2/grenade_tripwire.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/server/hl2/grenade_tripwire.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Implements the tripmine grenade.
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "util.h"
#include "shake.h"
#include "grenade_tripwire.h"
#include "grenade_homer.h"
#include "rope.h"
#include "rope_shared.h"
#include "engine/IEngineSound.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar sk_dmg_tripwire ( "sk_dmg_tripwire","0");
ConVar sk_tripwire_radius ( "sk_tripwire_radius","0");
#define GRENADETRIPWIRE_MISSILEMDL "models/Weapons/ar2_grenade.mdl"
#define TGRENADE_LAUNCH_VEL 1200
#define TGRENADE_SPIN_MAG 50
#define TGRENADE_SPIN_SPEED 100
#define TGRENADE_MISSILE_OFFSET 50
#define TGRENADE_MAX_ROPE_LEN 1500
LINK_ENTITY_TO_CLASS( npc_tripwire, CTripwireGrenade );
BEGIN_DATADESC( CTripwireGrenade )
DEFINE_FIELD( m_flPowerUp, FIELD_TIME ),
DEFINE_FIELD( m_nMissileCount, FIELD_INTEGER ),
DEFINE_FIELD( m_vecDir, FIELD_VECTOR ),
DEFINE_FIELD( m_vTargetPos, FIELD_POSITION_VECTOR ),
DEFINE_FIELD( m_vTargetOffset, FIELD_VECTOR ),
DEFINE_FIELD( m_pRope, FIELD_CLASSPTR ),
DEFINE_FIELD( m_pHook, FIELD_CLASSPTR ),
// Function Pointers
DEFINE_FUNCTION( WarningThink ),
DEFINE_FUNCTION( PowerupThink ),
DEFINE_FUNCTION( RopeBreakThink ),
DEFINE_FUNCTION( FireThink ),
END_DATADESC()
CTripwireGrenade::CTripwireGrenade()
{
m_vecDir.Init();
}
void CTripwireGrenade::Spawn( void )
{
Precache( );
SetMoveType( MOVETYPE_FLY );
SetSolid( SOLID_BBOX );
AddSolidFlags( FSOLID_NOT_SOLID );
SetModel( "models/Weapons/w_slam.mdl" );
m_nMissileCount = 0;
UTIL_SetSize(this, Vector( -4, -4, -2), Vector(4, 4, 2));
m_flPowerUp = gpGlobals->curtime + 1.2;//<<CHECK>>get rid of this
SetThink( WarningThink );
SetNextThink( gpGlobals->curtime + 1.0f );
m_takedamage = DAMAGE_YES;
m_iHealth = 1;
m_pRope = NULL;
m_pHook = NULL;
// Tripwire grenade sits at 90 on wall so rotate back to get m_vecDir
QAngle angles = GetLocalAngles();
angles.x -= 90;
AngleVectors( angles, &m_vecDir );
}
void CTripwireGrenade::Precache( void )
{
PrecacheModel("models/Weapons/w_slam.mdl");
PrecacheModel(GRENADETRIPWIRE_MISSILEMDL);
}
void CTripwireGrenade::WarningThink( void )
{
// play activate sound
EmitSound( "TripwireGrenade.Activate" );
// set to power up
SetThink( PowerupThink );
SetNextThink( gpGlobals->curtime + 1.0f );
}
void CTripwireGrenade::PowerupThink( void )
{
if (gpGlobals->curtime > m_flPowerUp)
{
MakeRope( );
RemoveSolidFlags( FSOLID_NOT_SOLID );
m_bIsLive = true;
}
SetNextThink( gpGlobals->curtime + 0.1f );
}
void CTripwireGrenade::BreakRope( void )
{
if (m_pRope)
{
m_pRope->m_RopeFlags |= ROPE_COLLIDE;
m_pRope->DetachPoint(0);
Vector vVelocity;
m_pHook->GetVelocity( &vVelocity, NULL );
if (vVelocity.Length() > 1)
{
m_pRope->DetachPoint(1);
}
}
}
void CTripwireGrenade::MakeRope( void )
{
SetThink( RopeBreakThink );
// Delay first think slightly so rope has time
// to appear if person right in front of it
SetNextThink( gpGlobals->curtime + 1.0f );
// Create hook for end of tripwire
m_pHook = (CTripwireHook*)CBaseEntity::Create( "tripwire_hook", GetLocalOrigin(), GetLocalAngles() );
if (m_pHook)
{
Vector vShootVel = 800*(m_vecDir + Vector(0,0,0.3)+RandomVector(-0.01,0.01));
m_pHook->SetVelocity( vShootVel, vec3_origin);
m_pHook->SetOwnerEntity( this );
m_pHook->m_hGrenade = this;
m_pRope = CRopeKeyframe::Create(this,m_pHook,0,0);
if (m_pRope)
{
m_pRope->m_Width = 1;
m_pRope->m_RopeLength = 3;
m_pRope->m_Slack = 100;
CPASAttenuationFilter filter( this,"TripwireGrenade.ShootRope" );
EmitSound( filter, entindex(),"TripwireGrenade.ShootRope" );
}
}
}
void CTripwireGrenade::Attach( void )
{
StopSound( "TripwireGrenade.ShootRope" );
}
void CTripwireGrenade::RopeBreakThink( void )
{
// See if I can go solid yet (has dropper moved out of way?)
if (IsSolidFlagSet(FSOLID_NOT_SOLID))
{
trace_t tr;
Vector vUpBit = GetAbsOrigin();
vUpBit.z += 5.0;
UTIL_TraceEntity( this, GetAbsOrigin(), vUpBit, MASK_SHOT, &tr );
if ( !tr.startsolid && (tr.fraction == 1.0) )
{
RemoveSolidFlags( FSOLID_NOT_SOLID );
}
}
// Check if rope had gotten beyond it's max length
float flRopeLength = (GetAbsOrigin()-m_pHook->GetAbsOrigin()).Length();
if (flRopeLength > TGRENADE_MAX_ROPE_LEN)
{
// Shoot missiles at hook
m_iHealth = 0;
BreakRope();
m_vTargetPos = m_pHook->GetAbsOrigin();
CrossProduct ( m_vecDir, Vector(0,0,1), m_vTargetOffset );
m_vTargetOffset *=TGRENADE_MISSILE_OFFSET;
SetThink(FireThink);
FireThink();
}
// Check to see if can see hook
// NOT MASK_SHOT because we want only simple hit boxes
trace_t tr;
UTIL_TraceLine( GetAbsOrigin(), m_pHook->GetAbsOrigin(), MASK_SOLID, this, COLLISION_GROUP_NONE, &tr );
// If can't see hook
CBaseEntity *pEntity = tr.m_pEnt;
if (tr.fraction != 1.0 && pEntity != m_pHook)
{
// Shoot missiles at place where rope was intersected
m_iHealth = 0;
BreakRope();
m_vTargetPos = tr.endpos;
CrossProduct ( m_vecDir, Vector(0,0,1), m_vTargetOffset );
m_vTargetOffset *=TGRENADE_MISSILE_OFFSET;
SetThink(FireThink);
FireThink();
return;
}
SetNextThink( gpGlobals->curtime + 0.1f );
}
//------------------------------------------------------------------------------
// Purpose : Die if I take any damage
// Input :
// Output :
//------------------------------------------------------------------------------
int CTripwireGrenade::OnTakeDamage_Alive( const CTakeDamageInfo &info )
{
// Killed upon any damage
Event_Killed( info );
return 0;
}
//-----------------------------------------------------------------------------
// Purpose: If someone damaged, me shoot of my missiles and die
// Input :
// Output :
//-----------------------------------------------------------------------------
void CTripwireGrenade::Event_Killed( const CTakeDamageInfo &info )
{
if (m_iHealth > 0)
{
// Fire missiles and blow up
for (int i=0;i<6;i++)
{
Vector vTargetPos = GetAbsOrigin() + RandomVector(-600,600);
FireMissile(vTargetPos);
}
BreakRope();
UTIL_Remove(this);
}
}
//------------------------------------------------------------------------------
// Purpose : Fire a missile at the target position
// Input :
// Output :
//------------------------------------------------------------------------------
void CTripwireGrenade::FireMissile(const Vector &vTargetPos)
{
Vector vTargetDir = (vTargetPos - GetAbsOrigin());
VectorNormalize(vTargetDir);
float flGravity = 0.0001; // No gravity on the missiles
bool bSmokeTrail = true;
float flHomingSpeed = 0;
Vector vLaunchVelocity = TGRENADE_LAUNCH_VEL*vTargetDir;
float flSpinMagnitude = TGRENADE_SPIN_MAG;
float flSpinSpeed = TGRENADE_SPIN_SPEED;
//<<CHECK>> hold in string_t
CGrenadeHomer *pGrenade = CGrenadeHomer::CreateGrenadeHomer( MAKE_STRING(GRENADETRIPWIRE_MISSILEMDL), MAKE_STRING("TripwireGrenade.FlySound"), GetAbsOrigin(), vec3_angle, edict() );
pGrenade->Spawn( );
pGrenade->SetSpin(flSpinMagnitude,flSpinSpeed);
pGrenade->SetHoming(0,0,0,0,0);
pGrenade->SetDamage(sk_dmg_tripwire.GetFloat());
pGrenade->SetDamageRadius(sk_tripwire_radius.GetFloat());
pGrenade->Launch(this,NULL,vLaunchVelocity,flHomingSpeed,flGravity,bSmokeTrail);
// Calculate travel time
float flTargetDist = (GetAbsOrigin() - vTargetPos).Length();
pGrenade->m_flDetonateTime = gpGlobals->curtime + flTargetDist/TGRENADE_LAUNCH_VEL;
}
//------------------------------------------------------------------------------
// Purpose : Shoot off a series of missiles over time, then go intert
// Input :
// Output :
//------------------------------------------------------------------------------
void CTripwireGrenade::FireThink()
{
SetNextThink( gpGlobals->curtime + 0.16f );
Vector vTargetPos = m_vTargetPos + (m_vTargetOffset * m_nMissileCount);
FireMissile(vTargetPos);
vTargetPos = m_vTargetPos - (m_vTargetOffset * m_nMissileCount);
FireMissile(vTargetPos);
m_nMissileCount++;
if (m_nMissileCount > 4)
{
m_iHealth = -1;
SetThink( NULL );
}
}
// ####################################################################
// CTripwireHook
//
// This is what the tripwire shoots out at the end of the rope
// ####################################################################
LINK_ENTITY_TO_CLASS( tripwire_hook, CTripwireHook );
//---------------------------------------------------------
// Save/Restore
//---------------------------------------------------------
BEGIN_DATADESC( CTripwireHook )
DEFINE_FIELD( m_hGrenade, FIELD_EHANDLE ),
DEFINE_FIELD( m_bAttached, FIELD_BOOLEAN ),
END_DATADESC()
void CTripwireHook::Spawn( void )
{
Precache( );
SetModel( "models/Weapons/w_grenade.mdl" );//<<CHECK>>
UTIL_SetSize(this, Vector( -1, -1, -1), Vector(1,1, 1));
m_takedamage = DAMAGE_NO;
m_bAttached = false;
CreateVPhysics();
}
bool CTripwireHook::CreateVPhysics()
{
// Create the object in the physics system
IPhysicsObject *pPhysicsObject = VPhysicsInitNormal( SOLID_BBOX, 0, false );
// Make sure I get touch called for static geometry
if ( pPhysicsObject )
{
int flags = pPhysicsObject->GetCallbackFlags();
flags |= CALLBACK_GLOBAL_TOUCH_STATIC;
pPhysicsObject->SetCallbackFlags(flags);
}
return true;
}
void CTripwireHook::Precache( void )
{
PrecacheModel("models/Weapons/w_grenade.mdl"); //<<CHECK>>
}
void CTripwireHook::EndTouch( CBaseEntity *pOther )
{
//<<CHECK>>do instead by clearing touch function
if (!m_bAttached)
{
m_bAttached = true;
SetVelocity(vec3_origin, vec3_origin);
SetMoveType( MOVETYPE_NONE );
EmitSound( "TripwireGrenade.Hook" );
// Let the tripwire grenade know that I've attached
CTripwireGrenade* pGrenade = dynamic_cast<CTripwireGrenade*>((CBaseEntity*)m_hGrenade);
if (pGrenade)
{
pGrenade->Attach();
}
}
}
void CTripwireHook::SetVelocity( const Vector &velocity, const AngularImpulse &angVelocity )
{
IPhysicsObject *pPhysicsObject = VPhysicsGetObject();
if ( pPhysicsObject )
{
pPhysicsObject->AddVelocity( &velocity, &angVelocity );
}
} | 25.853904 | 183 | 0.651598 | cstom4994 |
20a421a21adb494f67bfd0333cb69b1258419f2e | 210 | cpp | C++ | 2014/Communications/car-wire/slave_car_wire.cpp | WE-Bots/project-car-archive | 388fabc6e6c0cdde76a91d8277e29d29f01c5087 | [
"MIT"
] | null | null | null | 2014/Communications/car-wire/slave_car_wire.cpp | WE-Bots/project-car-archive | 388fabc6e6c0cdde76a91d8277e29d29f01c5087 | [
"MIT"
] | null | null | null | 2014/Communications/car-wire/slave_car_wire.cpp | WE-Bots/project-car-archive | 388fabc6e6c0cdde76a91d8277e29d29f01c5087 | [
"MIT"
] | 1 | 2018-08-15T14:30:54.000Z | 2018-08-15T14:30:54.000Z | #include "slave_car_wire.h"
void slave_car_wire::receiveEvent(){
if (Wire.available()){}
_cmd = Wire.readByte();
}
}
void slave_car_wire::requestEvent(){
//You kinda need to write this one yourself
} | 14 | 44 | 0.7 | WE-Bots |
20a626f8336273447e6fe5faa3a0fb2513d6251c | 55 | hpp | C++ | addons/admin/functions/script_component.hpp | ARCOMMADMIN/ARCORE | 5d8a632017abb646e6f01aa3eebf6c0747028213 | [
"MIT"
] | 1 | 2018-02-15T07:43:55.000Z | 2018-02-15T07:43:55.000Z | addons/admin/functions/script_component.hpp | ARCOMMADMIN/ARCORE | 5d8a632017abb646e6f01aa3eebf6c0747028213 | [
"MIT"
] | 36 | 2017-07-08T21:25:36.000Z | 2020-05-03T18:59:23.000Z | addons/admin/functions/script_component.hpp | ARCOMMADMIN/ARCORE | 5d8a632017abb646e6f01aa3eebf6c0747028213 | [
"MIT"
] | 4 | 2019-08-01T00:19:01.000Z | 2020-05-07T20:40:38.000Z | #include "\z\arcore\addons\admin\script_component.hpp"
| 27.5 | 54 | 0.8 | ARCOMMADMIN |
20a87caf8f6c132cf5237aa225734403bf7d678b | 286 | cpp | C++ | test_ext_core.cpp | tz-lom/thir | c85482f9fe6f7ecdfd9db6960f8e8277b3fe3979 | [
"MIT"
] | null | null | null | test_ext_core.cpp | tz-lom/thir | c85482f9fe6f7ecdfd9db6960f8e8277b3fe3979 | [
"MIT"
] | null | null | null | test_ext_core.cpp | tz-lom/thir | c85482f9fe6f7ecdfd9db6960f8e8277b3fe3979 | [
"MIT"
] | null | null | null | #include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/stringize.hpp>
#include BOOST_PP_STRINGIZE(BOOST_PP_CAT(BOOST_PP_CAT(test_ext_, THIR_TEST_EXTENSION), _.h))
int main(int argc, char *argv[])
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 26 | 92 | 0.751748 | tz-lom |
20a8d17dbb8eb529256e1e9c377f8c032ecc34bf | 280 | hpp | C++ | src/Elba/Graphics/GraphicsForwardDeclarations.hpp | nicholasammann/kotor-builder | ab0e042c09974a024a9884c6f9e34cf85ad63eeb | [
"MIT"
] | 1 | 2018-10-01T19:34:57.000Z | 2018-10-01T19:34:57.000Z | src/Elba/Graphics/GraphicsForwardDeclarations.hpp | nicholasammann/kotor-builder | ab0e042c09974a024a9884c6f9e34cf85ad63eeb | [
"MIT"
] | 9 | 2018-09-09T16:07:22.000Z | 2018-11-06T20:34:30.000Z | src/Elba/Graphics/GraphicsForwardDeclarations.hpp | nicholasammann/kotor-builder | ab0e042c09974a024a9884c6f9e34cf85ad63eeb | [
"MIT"
] | null | null | null | /**
* \file GraphicsForwardDeclarations.hpp
* \author Nicholas Ammann
* \date 2/24/2018
* \brief Forward declarations for all graphics classes.
*/
#pragma once
namespace Elba
{
class GraphicsModule;
class GraphicsFactory;
class Mesh;
class Submesh;
} // End of Elba namespace
| 14.736842 | 55 | 0.753571 | nicholasammann |
20a9fe709a650a0488eabb4e8d111ad85844a408 | 923 | cpp | C++ | codeforces/1480/A.cpp | gnomegeek/cp-submissions | c046be42876794d7cc6216db4e44a23c1174742d | [
"MIT"
] | null | null | null | codeforces/1480/A.cpp | gnomegeek/cp-submissions | c046be42876794d7cc6216db4e44a23c1174742d | [
"MIT"
] | null | null | null | codeforces/1480/A.cpp | gnomegeek/cp-submissions | c046be42876794d7cc6216db4e44a23c1174742d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define inf INT_MAX
#define int long long
#define ump unordered_map
#define endl "\n"
#define mod 1000000007
void OJ() {
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
void lego() {
string s;
cin >> s;
int n = s.length();
int turn = 1;
for (int i = 0; i < n; i++) {
if (turn) {
if (s[i] == 'a') {
cout << 'b';
} else {
cout << 'a';
}
} else {
if (s[i] == 'z') {
cout << 'y';
} else {
cout << 'z';
}
}
turn = !turn;
}
cout << endl;
}
signed main() {
OJ();
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int tt = 1;
if (true)
cin >> tt;
while (tt--) lego();
return 0;
} | 17.75 | 39 | 0.422535 | gnomegeek |
20b975eab6655b804b6e51d9954e802b1fe52f69 | 686 | cpp | C++ | All About C/Pointers/4. Arithmatic Operation 1.cpp | tausiq2003/C-with-DS | 3ec324b180456116b03aec58f2a85025180af9aa | [
"Apache-2.0"
] | 7 | 2020-10-01T13:31:02.000Z | 2021-11-06T16:22:31.000Z | All About C/Pointers/4. Arithmatic Operation 1.cpp | tausiq2003/C-with-DS | 3ec324b180456116b03aec58f2a85025180af9aa | [
"Apache-2.0"
] | 9 | 2020-10-01T10:35:59.000Z | 2021-10-03T15:00:18.000Z | All About C/Pointers/4. Arithmatic Operation 1.cpp | tausiq2003/C-with-DS | 3ec324b180456116b03aec58f2a85025180af9aa | [
"Apache-2.0"
] | 44 | 2020-10-01T08:49:30.000Z | 2021-10-31T18:19:48.000Z | #include<iostream>
using namespace std;
int main(){
int A[]{1,2,3,4,5,6};
int *p=A;
//base address of A is given to pointer P.
cout<<*p<<endl;
cout<<p<<endl;
// output will be 1 and address
p++; //writing *p++ is not necessory.
cout<<*p<<endl; // * is used for derefrencing, it will print address without *
cout<<p<<endl;
// output will be next digit with address, In pointer value shift either left or right., and value doesn't increment or decrement using ++ or --.
//output = 2
p--; //writing *p++ is not necessory.
cout<<*p<<endl;
cout<<p<<endl;
// output =1 with address
cout<<*p<<endl;
cout<<*(p+2)<<endl;
// *p = let say 1., then *(p+2)=3
return 0;
}
| 19.6 | 145 | 0.625364 | tausiq2003 |
20be09e4c096718daf43243eb9724aeaaed76ec1 | 1,508 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter3Exercise6.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter3Exercise6.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter3Exercise6.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE Comparison & Ordering Chapter3Exercise6.cpp
Bjarne Stroustrup "Programming: Principles and Practice Using C++"
COMMENT
Objective: Put in order three input numbers;
Next to each other if they are equal.
Input: Requests 3 numbers.
Output: Prints numbers in order.
Author: Chris B. Kirov
Date: 01.02.2014
*/
#include "../../std_lib_facilities.h"
int main()
{
cout << "Please enter three numbers." << endl;
cout << "The first number:\t" << endl;
int var1 = 0;
cin >> var1;
cout << "The second number:\t" << endl;
int var2 = 0;
cin >> var2;
cout << "The third number:\t" << endl;
int var3 = 0;
cin >> var3;
// Brute force (all possible permutations) = 3! => (number of comparisons) = 6
string res_msg = "The numbers in ascending order are: ";
if (var1 <= var2 && var2 <= var3)
{
cout << res_msg << var1 << ',' << var2 << ',' << var3 << endl;
}
else if (var1 >= var2 && var1 <= var3)
{
cout << res_msg << var2 << ',' << var1 << ',' << var3 << endl;
}
else if (var1 > var2 && var1 >= var3 && var2 <= var3)
{
cout << res_msg << var2 << ',' << var3 << ',' << var1 << endl;
}
else if (var1 >= var2 && var2 >= var3)
{
cout << res_msg << var3 << ',' << var2 << ',' << var1 << endl;
}
else if (var1 >= var3 && var1 >= var2)
{
cout << res_msg << var3 << ',' << var1 << ',' << var3 << endl;
}
else if (var1 <= var3 && var3 <= var2)
{
cout << res_msg << var1 << ',' << var3 << ',' << var2 << endl;
}
return 0;
} | 25.559322 | 80 | 0.547082 | Ziezi |
20be582a26d284e303c4f964404cc071d7226025 | 694 | cpp | C++ | problem_solving/SPOJ/OPCPIZZA/14158584_AC_180ms_16384kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | 2 | 2020-09-02T12:07:47.000Z | 2020-11-17T11:17:16.000Z | problem_solving/SPOJ/OPCPIZZA/14158584_AC_180ms_16384kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | null | null | null | problem_solving/SPOJ/OPCPIZZA/14158584_AC_180ms_16384kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | 4 | 2020-08-11T14:23:34.000Z | 2020-11-17T10:52:31.000Z | #include <bits/stdc++.h>
#define le 100005
using namespace std;
int n[le];
bool fnc(int a, int b, int key){
int lo = a + 1, hi = b - 1, mid;
while(lo <= hi){
mid = (lo + hi) >> 1;
if(n[mid] == key) return 1;
else if(n[mid] > key) hi = mid - 1;
else lo = mid + 1;
}
return 0;
}
int main(){
int t, len, m;
for(scanf("%d", &t); t--; ){
scanf("%d %d", &len, &m);
for(int i = 0; i < len; scanf("%d", &n[i]), i++);
sort(n, n + len);
int c = 0;
for(int i = 0; i < len - 1; i++){
int ve = m - n[i];
if(fnc(i, len, ve)) c++;
}
printf("%d\n", c);
}
return 0;
} | 23.931034 | 57 | 0.402017 | cosmicray001 |
20c083c60bc05f9a0c0cc3e8f1f6fdf391477339 | 2,743 | cpp | C++ | src/Network/NetworkDevice.cpp | Harsh14901/COP290-Pacman | e9f821f0351a0ead5ed89becab81a3c8c0a7c18e | [
"BSD-3-Clause"
] | null | null | null | src/Network/NetworkDevice.cpp | Harsh14901/COP290-Pacman | e9f821f0351a0ead5ed89becab81a3c8c0a7c18e | [
"BSD-3-Clause"
] | null | null | null | src/Network/NetworkDevice.cpp | Harsh14901/COP290-Pacman | e9f821f0351a0ead5ed89becab81a3c8c0a7c18e | [
"BSD-3-Clause"
] | null | null | null | #include "Network/NetworkDevice.hpp"
#include "Network/Packet.hpp"
const int NetworkDevice::MAX_BUFFER;
NetworkDevice::NetworkDevice() {
recv_socket = nullptr;
send_socket = nullptr;
ps_buffer = queue<PacketStore>();
}
NetworkDevice::NetworkDevice(TCPsocket* recv_socket, TCPsocket* send_socket)
: recv_socket(recv_socket), send_socket(send_socket) {}
bool NetworkDevice::packet_ready() { return !ps_buffer.empty(); }
void NetworkDevice::get_packets(PacketStore& ps) {
ps = ps_buffer.front();
ps_buffer.pop();
}
void NetworkDevice::recv() {
char buffer[MAX_BUFFER];
// cout << "NetworkDevice::recv() called" << endl;
if (SDLNet_TCP_Recv(*recv_socket, buffer, MAX_BUFFER) > 0) {
// printf("packet data recieved: %s\n", buffer);
auto ps = PacketStore();
ps.decode(buffer);
ps_buffer.push(ps);
}
// printf("buffer size: %ld\n", ps_buffer.size());
}
int NetworkDevice::send(PacketStore& ps) {
char buffer[MAX_BUFFER];
int n = ps.encode(buffer);
int size = strlen(buffer) + 1;
// printf("Sending buffer: %s\n", buffer);
if (SDLNet_TCP_Send(*send_socket, buffer, size) < size) {
fatalError("Error sending packet store: " + string(SDLNet_GetError()),
false);
network_error = true;
} else {
// cout << "packet store sent" << endl;
}
return n;
}
Server::Server(int port) : NetworkDevice(&csd, &csd), port(port) {}
Server::Server() : Server(PORT) {}
void Server::init() {
if (SDLNet_ResolveHost(&ip, NULL, port) < 0) {
fatalError("SDLNet_ResolveHost: " + string(SDLNet_GetError()), false);
network_error = true;
}
if (!(sd = SDLNet_TCP_Open(&ip))) {
fatalError("SDLNet_TCP_Open: " + string(SDLNet_GetError()), false);
network_error = true;
}
}
void Server::wait_for_connection() {
if ((csd = SDLNet_TCP_Accept(sd))) {
IPaddress* remote_ip_ptr;
if ((remote_ip_ptr = SDLNet_TCP_GetPeerAddress(csd))) {
remote_ip = *remote_ip_ptr;
printf("[+] Host connected: %x %d\n", SDLNet_Read32(&(remote_ip.host)),
SDLNet_Read16(&(remote_ip.port)));
connected = true;
} else {
fatalError("SDLNet_TCP_GetPeerAddress: " + string(SDLNet_GetError()),
false);
network_error = true;
}
}
}
bool Server::is_connected() { return connected; }
Client::Client(string server_host, int port)
: NetworkDevice(&sd, &sd), server_host(server_host), port(port) {}
Client::Client() : Client("", PORT) {}
void Client::init() {
if (SDLNet_ResolveHost(&server_ip, server_host.c_str(), port) < 0) {
fatalError("SDLNet_ResolveHost:" + string(SDLNet_GetError()), false);
network_error = true;
}
}
void Client::connect() {
while (!(sd = SDLNet_TCP_Open(&server_ip)))
;
} | 28.278351 | 77 | 0.65731 | Harsh14901 |
20c0cb79b7ebfbf47fa19688903bde1eec2ce3f1 | 4,775 | cpp | C++ | gui/renderers/VolumeRenderer.cpp | pavelsevecek/OpenSPH | d547c0af6270a739d772a4dcba8a70dc01775367 | [
"MIT"
] | 20 | 2021-04-02T04:30:08.000Z | 2022-03-01T09:52:01.000Z | gui/renderers/VolumeRenderer.cpp | pavelsevecek/OpenSPH | d547c0af6270a739d772a4dcba8a70dc01775367 | [
"MIT"
] | null | null | null | gui/renderers/VolumeRenderer.cpp | pavelsevecek/OpenSPH | d547c0af6270a739d772a4dcba8a70dc01775367 | [
"MIT"
] | 1 | 2022-01-22T11:44:52.000Z | 2022-01-22T11:44:52.000Z | #include "gui/renderers/VolumeRenderer.h"
#include "gui/Factory.h"
#include "gui/objects/Camera.h"
#include "gui/objects/Colorizer.h"
#include "gui/renderers/FrameBuffer.h"
#include "objects/finders/KdTree.h"
#include "objects/utility/OutputIterators.h"
NAMESPACE_SPH_BEGIN
VolumeRenderer::VolumeRenderer(SharedPtr<IScheduler> scheduler, const GuiSettings& settings)
: IRaytracer(scheduler, settings) {}
VolumeRenderer::~VolumeRenderer() = default;
const float MAX_DISTENTION = 50;
const float MIN_NEIGHS = 8;
void VolumeRenderer::initialize(const Storage& storage,
const IColorizer& colorizer,
const ICamera& UNUSED(camera)) {
cached.r = storage.getValue<Vector>(QuantityId::POSITION).clone();
this->setColorizer(colorizer);
cached.distention.resize(cached.r.size());
KdTree<KdNode> tree;
tree.build(*scheduler, cached.r, FinderFlag::SKIP_RANK);
Array<BvhSphere> spheres(cached.r.size());
spheres.reserve(cached.r.size());
ThreadLocal<Array<NeighborRecord>> neighs(*scheduler);
parallelFor(*scheduler, neighs, 0, cached.r.size(), [&](const Size i, Array<NeighborRecord>& local) {
const float initialRadius = cached.r[i][H];
float radius = initialRadius;
while (radius < MAX_DISTENTION * initialRadius) {
tree.findAll(cached.r[i], radius, local);
if (local.size() >= MIN_NEIGHS) {
break;
} else {
radius *= 1.5f;
}
}
BvhSphere s(cached.r[i], radius);
s.userData = i;
spheres[i] = s;
cached.distention[i] = min(radius / initialRadius, MAX_DISTENTION);
});
ArrayView<const Float> m = storage.getValue<Float>(QuantityId::MASS);
cached.referenceRadii.resize(cached.r.size());
if (storage.getMaterialCnt() > 0) {
for (Size matId = 0; matId < storage.getMaterialCnt(); ++matId) {
MaterialView mat = storage.getMaterial(matId);
const Float rho = mat->getParam<Float>(BodySettingsId::DENSITY);
for (Size i : mat.sequence()) {
const Float volume = m[i] / rho;
cached.referenceRadii[i] = root<3>(3._f * volume / (4._f * PI));
}
}
} else {
// guess the dentity
const Float rho = 1000._f;
for (Size i = 0; i < m.size(); ++i) {
const Float volume = m[i] / rho;
cached.referenceRadii[i] = root<3>(3._f * volume / (4._f * PI));
}
}
bvh.build(std::move(spheres));
for (ThreadData& data : threadData) {
data.data = RayData{};
}
shouldContinue = true;
}
bool VolumeRenderer::isInitialized() const {
return !cached.r.empty();
}
void VolumeRenderer::setColorizer(const IColorizer& colorizer) {
cached.colors.resize(cached.r.size());
for (Size i = 0; i < cached.r.size(); ++i) {
cached.colors[i] = colorizer.evalColor(i);
}
}
Rgba VolumeRenderer::shade(const RenderParams& params, const CameraRay& cameraRay, ThreadData& data) const {
const Vector dir = getNormalized(cameraRay.target - cameraRay.origin);
const Ray ray(cameraRay.origin, dir);
RayData& rayData(data.data);
Array<IntersectionInfo>& intersections = rayData.intersections;
intersections.clear();
bvh.getAllIntersections(ray, backInserter(intersections));
if (params.volume.absorption > 0.f) {
std::sort(intersections.begin(), intersections.end());
}
Rgba result = this->getEnviroColor(cameraRay);
for (const IntersectionInfo& is : reverse(intersections)) {
const BvhSphere* s = static_cast<const BvhSphere*>(is.object);
const Size i = s->userData;
const Vector hit = ray.origin() + ray.direction() * is.t;
const Vector center = cached.r[i];
const Vector toCenter = getNormalized(center - hit);
const float cosPhi = abs(dot(toCenter, ray.direction()));
const float distention = cached.distention[i];
// smoothing length should not have effect on the total emission
const float radiiFactor = cached.referenceRadii[i] / cached.r[i][H];
const float secant = 2._f * getLength(center - hit) * cosPhi * radiiFactor;
// make dilated particles absorb more
result = result * exp(-params.volume.absorption * secant * distention * pow<3>(cosPhi));
// 3th power of cosPhi to give more weight to the sphere center,
// divide by distention^3; distention should not affect the total emission
const float magnitude = params.volume.emission * pow<3>(cosPhi / distention) * secant;
result += cached.colors[i] * magnitude;
result.a() += magnitude;
}
result.a() = min(result.a(), 1.f);
return result;
}
NAMESPACE_SPH_END
| 37.015504 | 108 | 0.639372 | pavelsevecek |
20c12672fee4df28192a7f10dc5e6dc040f2090a | 606 | hh | C++ | click/elements/local/igmp/AddIPRouterAlertOption.hh | BasilRommens/IGMPv3-click | cb5d63192f0c0344d35dab35d928835c7c6f370f | [
"MIT"
] | null | null | null | click/elements/local/igmp/AddIPRouterAlertOption.hh | BasilRommens/IGMPv3-click | cb5d63192f0c0344d35dab35d928835c7c6f370f | [
"MIT"
] | null | null | null | click/elements/local/igmp/AddIPRouterAlertOption.hh | BasilRommens/IGMPv3-click | cb5d63192f0c0344d35dab35d928835c7c6f370f | [
"MIT"
] | null | null | null | #ifndef CLICK_AddIPRouterAlertOption_HH
#define CLICK_AddIPRouterAlertOption_HH
#include <click/element.hh>
#include <click/ipaddress.hh>
CLICK_DECLS
class AddIPRouterAlertOption : public Element {
public:
AddIPRouterAlertOption();
~AddIPRouterAlertOption();
const char *class_name() const { return "AddIPRouterAlertOption"; }
const char *port_count() const { return "1"; }
const char *processing() const { return PUSH; }
int configure(Vector <String> &conf, ErrorHandler *errh);
void push(int port, Packet *p);
};
CLICK_ENDDECLS
#endif //CLICK_AddIPRouterAlertOption_HH
| 24.24 | 71 | 0.745875 | BasilRommens |
20c1a34f72fe6a0be98b8dda94854aaee65158a7 | 14,843 | hpp | C++ | library/src/include/tensile_host.hpp | amcamd/rocBLAS | f0986a922269c2fe343c414ec13a055cf8574bc3 | [
"MIT"
] | null | null | null | library/src/include/tensile_host.hpp | amcamd/rocBLAS | f0986a922269c2fe343c414ec13a055cf8574bc3 | [
"MIT"
] | null | null | null | library/src/include/tensile_host.hpp | amcamd/rocBLAS | f0986a922269c2fe343c414ec13a055cf8574bc3 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright 2019-2021 Advanced Micro Devices, Inc.
* ************************************************************************/
/*********************************************************
* Declaration of the rocBLAS<->Tensile interface layer. *
*********************************************************/
#pragma once
#ifndef USE_TENSILE_HOST
#error "tensile_host.hpp #include'd when USE_TENSILE_HOST is undefined."
#endif
/*****************************************************************************
* WARNING: Tensile-specific data types, functions and macros should only be *
* referenced from tensile_host.cpp. This header file defines the interface *
* that the rest of rocBLAS uses to access Tensile. If another Tensile *
* feature needs to be accessed, the API for accessing it should be defined *
* in this file, without referencing any Tensile-specific identifiers here. *
*****************************************************************************/
#include "handle.hpp"
#include "tuple_helper.hpp"
#include <atomic>
/********************************************************************
* RocblasContractionProblem captures the arguments for a GEMM-like *
* contraction problem, to be passed to runContractionProblem. *
********************************************************************/
template <typename Ti, typename To = Ti, typename Tc = To>
struct RocblasContractionProblem
{
rocblas_handle handle;
rocblas_gemm_flags flags;
rocblas_operation trans_a;
rocblas_operation trans_b;
// The RocblasContractionProblem data members should exactly match
// Tensile's parameter types, even if rocBLAS uses differently
// sized or signed types. The constructors should convert rocBLAS
// types into the corresponding Tensile types stored in this class.
size_t m;
size_t n;
size_t k;
const Tc* alpha;
const Ti* A;
const Ti* const* batch_A;
size_t row_stride_a;
size_t col_stride_a;
size_t batch_stride_a;
size_t buffer_offset_a;
const Ti* B;
const Ti* const* batch_B;
size_t row_stride_b;
size_t col_stride_b;
size_t batch_stride_b;
size_t buffer_offset_b;
const Tc* beta;
const To* C;
const To* const* batch_C;
size_t row_stride_c;
size_t col_stride_c;
size_t batch_stride_c;
size_t buffer_offset_c;
To* D;
To* const* batch_D;
size_t row_stride_d;
size_t col_stride_d;
size_t batch_stride_d;
size_t buffer_offset_d;
size_t batch_count;
bool strided_batch;
// gemm
// gemm_strided_batched
RocblasContractionProblem(rocblas_handle handle,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const Tc* alpha,
const Ti* A,
const Ti* const* batch_A,
rocblas_int ld_a,
rocblas_stride batch_stride_a,
rocblas_int offset_a,
const Ti* B,
const Ti* const* batch_B,
rocblas_int ld_b,
rocblas_stride batch_stride_b,
rocblas_int offset_b,
const Tc* beta,
To* C,
To* const* batch_C,
rocblas_int ld_c,
rocblas_stride batch_stride_c,
rocblas_int offset_c,
rocblas_int batch_count,
bool strided_batch,
rocblas_gemm_flags flags)
: handle(handle)
, flags(flags)
, trans_a(trans_a)
, trans_b(trans_b)
, m(m)
, n(n)
, k(k)
, alpha(alpha)
, A(A)
, batch_A(batch_A)
, row_stride_a(1)
, col_stride_a(ld_a)
, batch_stride_a(batch_stride_a)
, buffer_offset_a(offset_a)
, B(B)
, batch_B(batch_B)
, row_stride_b(1)
, col_stride_b(ld_b)
, batch_stride_b(batch_stride_b)
, buffer_offset_b(offset_b)
, beta(beta)
, C(C)
, batch_C(batch_C)
, row_stride_c(1)
, col_stride_c(ld_c)
, batch_stride_c(batch_stride_c)
, buffer_offset_c(offset_c)
, D(C)
, batch_D(batch_C)
, row_stride_d(1)
, col_stride_d(ld_c)
, batch_stride_d(batch_stride_c)
, buffer_offset_d(offset_c)
, batch_count(batch_count)
, strided_batch(strided_batch)
{
}
// gemm_ex
// gemm_strided_batched_ex
RocblasContractionProblem(rocblas_handle handle,
rocblas_operation trans_a,
rocblas_operation trans_b,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const Tc* alpha,
const Ti* A,
const Ti* const* batch_A,
rocblas_int ld_a,
rocblas_stride batch_stride_a,
rocblas_int offset_a,
const Ti* B,
const Ti* const* batch_B,
rocblas_int ld_b,
rocblas_stride batch_stride_b,
rocblas_int offset_b,
const Tc* beta,
const To* C,
const To* const* batch_C,
rocblas_int ld_c,
rocblas_stride batch_stride_c,
rocblas_int offset_c,
To* D,
To* const* batch_D,
rocblas_int ld_d,
rocblas_stride batch_stride_d,
rocblas_int offset_d,
rocblas_int batch_count,
bool strided_batch,
rocblas_gemm_flags flags)
: handle(handle)
, flags(flags)
, trans_a(trans_a)
, trans_b(trans_b)
, m(m)
, n(n)
, k(k)
, alpha(alpha)
, A(A)
, batch_A(batch_A)
, row_stride_a(1)
, col_stride_a(ld_a)
, batch_stride_a(batch_stride_a)
, buffer_offset_a(offset_a)
, B(B)
, batch_B(batch_B)
, row_stride_b(1)
, col_stride_b(ld_b)
, batch_stride_b(batch_stride_b)
, buffer_offset_b(offset_b)
, beta(beta)
, C(C)
, batch_C(batch_C)
, row_stride_c(1)
, col_stride_c(ld_c)
, batch_stride_c(batch_stride_c)
, buffer_offset_c(offset_c)
, D(D)
, batch_D(batch_D)
, row_stride_d(1)
, col_stride_d(ld_d)
, batch_stride_d(batch_stride_d)
, buffer_offset_d(offset_d)
, batch_count(batch_count)
, strided_batch(strided_batch)
{
}
// gemm_ext2
// gemm_strided_batched_ext2
RocblasContractionProblem(rocblas_handle handle,
rocblas_int m,
rocblas_int n,
rocblas_int k,
const Tc* alpha,
const Ti* A,
const Ti* const* batch_A,
rocblas_stride row_stride_a,
rocblas_stride col_stride_a,
rocblas_stride batch_stride_a,
rocblas_int offset_a,
const Ti* B,
const Ti* const* batch_B,
rocblas_stride row_stride_b,
rocblas_stride col_stride_b,
rocblas_stride batch_stride_b,
rocblas_int offset_b,
const Tc* beta,
const To* C,
const To* const* batch_C,
rocblas_stride row_stride_c,
rocblas_stride col_stride_c,
rocblas_stride batch_stride_c,
rocblas_int offset_c,
To* D,
To* const* batch_D,
rocblas_stride row_stride_d,
rocblas_stride col_stride_d,
rocblas_stride batch_stride_d,
rocblas_int offset_d,
rocblas_int batch_count,
bool strided_batch)
: handle(handle)
, flags(rocblas_gemm_flags_none)
, trans_a(rocblas_operation_none)
, trans_b(rocblas_operation_none)
, m(m)
, n(n)
, k(k)
, alpha(alpha)
, A(A)
, batch_A(batch_A)
, row_stride_a(row_stride_a)
, col_stride_a(col_stride_a)
, batch_stride_a(batch_stride_a)
, buffer_offset_a(offset_a)
, B(B)
, batch_B(batch_B)
, row_stride_b(row_stride_b)
, col_stride_b(col_stride_b)
, batch_stride_b(batch_stride_b)
, buffer_offset_b(offset_b)
, beta(beta)
, C(C)
, batch_C(batch_C)
, row_stride_c(row_stride_c)
, col_stride_c(col_stride_c)
, batch_stride_c(batch_stride_c)
, buffer_offset_c(offset_c)
, D(D)
, batch_D(batch_D)
, row_stride_d(row_stride_d)
, col_stride_d(col_stride_d)
, batch_stride_d(batch_stride_d)
, buffer_offset_d(offset_d)
, batch_count(batch_count)
, strided_batch(strided_batch)
{
}
/***************************************************
* Print a RocblasContractionProblem for debugging *
***************************************************/
friend rocblas_ostream& operator<<(rocblas_ostream& os, const RocblasContractionProblem& prob)
{
return tuple_helper::print_tuple_pairs(
os,
std::make_tuple("a_type",
rocblas_precision_string<Ti>,
"b_type",
rocblas_precision_string<Ti>,
"c_type",
rocblas_precision_string<To>,
"d_type",
rocblas_precision_string<To>,
"compute_type",
rocblas_precision_string<Tc>,
"transA",
rocblas_transpose_letter(prob.trans_a),
"transB",
rocblas_transpose_letter(prob.trans_b),
"M",
prob.m,
"N",
prob.n,
"K",
prob.k,
"alpha",
*prob.alpha,
"row_stride_a",
prob.row_stride_a,
"col_stride_a",
prob.col_stride_a,
"row_stride_b",
prob.row_stride_b,
"col_stride_b",
prob.col_stride_b,
"row_stride_c",
prob.row_stride_c,
"col_stride_c",
prob.col_stride_c,
"row_stride_d",
prob.row_stride_d,
"col_stride_d",
prob.col_stride_d,
"beta",
*prob.beta,
"batch_count",
prob.batch_count,
"strided_batch",
prob.strided_batch,
"stride_a",
prob.batch_stride_a,
"stride_b",
prob.batch_stride_b,
"stride_c",
prob.batch_stride_c,
"stride_d",
prob.batch_stride_d,
"atomics_mode",
prob.handle->atomics_mode));
};
};
/*******************************************************************************
* runContractionProblem() solves a RocblasContractionProblem *
*******************************************************************************/
template <typename Ti, typename To, typename Tc>
rocblas_status runContractionProblem(RocblasContractionProblem<Ti, To, Tc> const& problem);
/***********************************************************************************
* Whether Tensile has been initialized for at least one device (used for testing) *
***********************************************************************************/
ROCBLAS_EXPORT std::atomic_bool& rocblas_tensile_is_initialized();
/**********************************************
* Whether to suppress Tensile error messages *
**********************************************/
inline bool& rocblas_suppress_tensile_error_messages()
{
thread_local bool t_suppress = false;
return t_suppress;
}
| 39.687166 | 98 | 0.418042 | amcamd |
20c3c75d9d3987d1ed165025b829f6e846b99d79 | 2,111 | cpp | C++ | src/bluecadet/tangibleengine/TangibleEngineSimulator.cpp | bluecadet/Cinder-BluecadetTangibleEngine | a96e08a8a4556d5699aea90cd04e687999e772a5 | [
"MIT"
] | null | null | null | src/bluecadet/tangibleengine/TangibleEngineSimulator.cpp | bluecadet/Cinder-BluecadetTangibleEngine | a96e08a8a4556d5699aea90cd04e687999e772a5 | [
"MIT"
] | null | null | null | src/bluecadet/tangibleengine/TangibleEngineSimulator.cpp | bluecadet/Cinder-BluecadetTangibleEngine | a96e08a8a4556d5699aea90cd04e687999e772a5 | [
"MIT"
] | null | null | null | #include "TangibleEngineSimulator.h"
#include "cinder/Log.h"
#include "cinder/Color.h"
#include "bluecadet/core/ScreenCamera.h"
#include "bluecadet/views/EllipseView.h"
using namespace ci;
using namespace ci::app;
using namespace std;
namespace bluecadet {
namespace tangibleengine {
//==================================================
// Public
//
TangibleEngineSimulator::TangibleEngineSimulator() :
mView(new views::BaseView())
{
//mParams = params::InterfaceGl::create("Tangible Engine Simulator", ivec2(200, 250));
}
TangibleEngineSimulator::~TangibleEngineSimulator() {
}
void TangibleEngineSimulator::setup(TangibleEnginePluginRef plugin, bluecadet::touch::TouchManagerRef touchManager) {
destroy();
mPlugin = plugin;
mTouchManager = touchManager;
setupTangibles();
mUpdateSignalConnection = App::get()->getSignalUpdate().connect(bind(&TangibleEngineSimulator::handleUpdate, this));
}
void TangibleEngineSimulator::destroy() {
mUpdateSignalConnection.disconnect();
//mParams->clear();
mPlugin = nullptr;
mTouchManager = nullptr;
}
//==================================================
// Protected
//
void TangibleEngineSimulator::setupTangibles() {
// TODO: move to heap/store permanently
const int maxNumPatterns = 128;
int numPatterns = maxNumPatterns;
TE_Pattern patterns[maxNumPatterns];
TE_GetPatterns(patterns, &numPatterns);
if (numPatterns <= 0) {
CI_LOG_W("No patterns configured with Tangible Engine. Make sure to call setup() after Tangible Engine has been configured.");
}
mView->removeAllChildren();
for (int i = 0; i < numPatterns; ++i) {
vec3 hsv = vec3((float)i / (float) numPatterns, 1.0f, 1.0f);
ColorA color = ColorA(hsvToRgb(hsv), 0.5f);
VirtualTangibleRef tangible(new VirtualTangible(patterns[i], color));
mTangibles.push_back(tangible);
mView->addChild(tangible);
}
}
void TangibleEngineSimulator::setupParams() {
}
void TangibleEngineSimulator::handleUpdate() {
for (auto tangible : mTangibles) {
tangible->updateTouches();
for (auto touch : tangible->getTouches()) {
mTouchManager->addTouch(touch);
}
}
}
}
}
| 23.455556 | 128 | 0.704879 | bluecadet |
20c737737bdc0360fd1d7e3b6522b18c4d90ae0e | 381 | cc | C++ | BOJ/2953.cc | Yaminyam/Algorithm | fe49b37b4b310f03273864bcd193fe88139f1c01 | [
"MIT"
] | 1 | 2019-05-18T00:02:12.000Z | 2019-05-18T00:02:12.000Z | BOJ/2953.cc | siontama/Algorithm | bb419e0d4dd09682bd4542f90038b492ee232bd2 | [
"MIT"
] | null | null | null | BOJ/2953.cc | siontama/Algorithm | bb419e0d4dd09682bd4542f90038b492ee232bd2 | [
"MIT"
] | null | null | null | #include<iostream>
#include<algorithm>
using namespace std;
int main()
{
int arr[5]={0,};
int ansn=0;
int ans=0;
for(int i=0;i<5;i++){
for(int j=0;j<4;j++){
int x;
cin >> x;
arr[i]+=x;
}
if(arr[i]>ans){
ansn = i+1;
ans = arr[i];
}
}
cout << ansn << " " << ans;
}
| 15.875 | 31 | 0.383202 | Yaminyam |
20c7f5364e5566b486f8fe607f38e4e9b2a5dcc1 | 231 | hpp | C++ | Miracle/src/Miracle/Graphics/Vertex.hpp | McFlyboy/Miracle | 03a41bb8e24ecf2dfc18b5e3aee964640ec9a593 | [
"MIT"
] | null | null | null | Miracle/src/Miracle/Graphics/Vertex.hpp | McFlyboy/Miracle | 03a41bb8e24ecf2dfc18b5e3aee964640ec9a593 | [
"MIT"
] | 3 | 2021-12-10T23:19:29.000Z | 2022-03-27T05:04:14.000Z | Miracle/src/Miracle/Graphics/Vertex.hpp | McFlyboy/Miracle | 03a41bb8e24ecf2dfc18b5e3aee964640ec9a593 | [
"MIT"
] | null | null | null | #pragma once
#include <Miracle/components/Miracle/Math/Vector2f.hpp>
#include <Miracle/components/Miracle/Math/Vector3f.hpp>
namespace Miracle::Graphics {
struct Vertex {
Math::Vector2f position;
Math::Vector3f color;
};
}
| 19.25 | 55 | 0.757576 | McFlyboy |
20c8ed7ee46a4d274d0249ce2a6cc66b953f6dd0 | 599 | cpp | C++ | Cplusplus/trik.cpp | Jayseff/OpenKattis | 921ef2b6b5138505663edf53885fa8b6e655887e | [
"AFL-3.0"
] | null | null | null | Cplusplus/trik.cpp | Jayseff/OpenKattis | 921ef2b6b5138505663edf53885fa8b6e655887e | [
"AFL-3.0"
] | null | null | null | Cplusplus/trik.cpp | Jayseff/OpenKattis | 921ef2b6b5138505663edf53885fa8b6e655887e | [
"AFL-3.0"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main()
{
string actions;
int arr[3] = {1,0,0};
int temp = 0;
cin >> actions;
for (int i = 0; i < actions.length(); i++)
{
if (actions[i] == 'A')
{
temp = arr[0];
arr[0] = arr[1];
arr[1] = temp;
}
if (actions[i] == 'B')
{
temp = arr[1];
arr[1] = arr[2];
arr[2] = temp;
}
if (actions[i] == 'C')
{
temp = arr[2];
arr[2] = arr[0];
arr[0] = temp;
}
}
for (int i = 0; i < 3; i++)
{
if (arr[i] == 1)
cout << i + 1;
}
return 0;
} | 14.609756 | 44 | 0.420701 | Jayseff |
20cba4e40438a256da188e5a8d2217fb7220e037 | 11,928 | cpp | C++ | src/screen_settings.cpp | puzrin/dispenser | e0283af232a65a840dedb15feaaccf1294a3a7cb | [
"MIT"
] | 28 | 2019-09-02T05:23:00.000Z | 2022-01-16T22:19:55.000Z | src/screen_settings.cpp | puzrin/dispenser | e0283af232a65a840dedb15feaaccf1294a3a7cb | [
"MIT"
] | null | null | null | src/screen_settings.cpp | puzrin/dispenser | e0283af232a65a840dedb15feaaccf1294a3a7cb | [
"MIT"
] | 10 | 2019-12-31T02:22:22.000Z | 2021-12-14T04:11:27.000Z | #include "app.h"
#include "screen_settings.h"
#include "etl/to_string.h"
#include "etl/cyclic_value.h"
enum setting_type {
TYPE_NEEDLE_DIA = 0,
TYPE_SYRINGE_DIA = 1,
TYPE_VISCOSITY = 2,
TYPE_FLUX_PERCENT = 3,
TYPE_MOVE_PUSHER = 4
};
typedef struct {
float step_scale = 0.0f;
float current_step = 0.0f;
uint16_t repeat_count = 0;
} setting_data_state_t;
typedef struct _setting_data {
enum setting_type const type;
const char * const title;
const char * (* const val_get_text_fn)(const struct _setting_data * data);
void (* const val_update_fn)(const struct _setting_data * data, lv_event_t e, int const key_code);
float * const val_ref;
const float min_value = 0.0f;
const float max_value = 0.0f;
const float min_step = 0.0f;
const float max_step = 0.0f;
const uint8_t precision = 1;
const char * const suffix = "";
setting_data_state_t * const s;
} setting_data_t;
void base_update_value_fn(const setting_data_t * data, lv_event_t e, int key_code)
{
// lazy init for first run
if (data->s->current_step < data->min_step) data->s->current_step = data->min_step;
if (data->s->step_scale <= 0.0f) data->s->step_scale = 10.0f;
if (e == LV_EVENT_RELEASED)
{
data->s->repeat_count = 0;
data->s->current_step = data->min_step;
return;
}
data->s->repeat_count++;
if (data->s->repeat_count >= 10)
{
data->s->repeat_count = 0;
data->s->current_step = fmin(data->s->current_step * data->s->step_scale, data->max_step);
}
float val = *data->val_ref;
if (key_code == LV_KEY_RIGHT) val = fmin(val + data->s->current_step, data->max_value);
else val = fmax(val - data->s->current_step, data->min_value);
*data->val_ref = val;
}
static const char * base_get_text_fn(const setting_data_t * data)
{
static etl::string<10> buf;
etl::to_string(*data->val_ref, buf, etl::format_spec().precision(data->precision));
buf += data->suffix;
return buf.c_str();
}
/*static setting_data_state_t s_data_needle_state = {};
static setting_data_t s_data_needle = {
.type = TYPE_NEEDLE_DIA,
.title = "Needle dia",
.val_redraw_fn = &base_redraw_fn,
.val_update_fn = &base_update_value_fn,
.val_ref = &app_data.needle_dia,
.min_value = 0.3f,
.max_value = 2.0f,
.min_step = 0.1f,
.max_step = 0.1f,
.precision = 1,
.suffix = " mm",
.s = &s_data_needle_state
};*/
static setting_data_state_t s_data_syringe_state = {};
static const setting_data_t s_data_syringe = {
.type = TYPE_SYRINGE_DIA,
.title = "Syringe dia",
.val_get_text_fn = &base_get_text_fn,
.val_update_fn = &base_update_value_fn,
.val_ref = &app_data.syringe_dia,
.min_value = 4.0f,
.max_value = 30.0f,
.min_step = 0.1f,
.max_step = 1.0f,
.precision = 1,
.suffix = " mm",
.s = &s_data_syringe_state
};
static setting_data_state_t s_data_viscosity_state = {};
static const setting_data_t s_data_viscosity = {
.type = TYPE_VISCOSITY,
.title = "Viscosity",
.val_get_text_fn = &base_get_text_fn,
.val_update_fn = &base_update_value_fn,
.val_ref = &app_data.viscosity,
.min_value = 1.0f,
.max_value = 1000.0f,
.min_step = 1.0f,
.max_step = 100.0f,
.precision = 1,
.suffix = " P",
.s = &s_data_viscosity_state
};
static setting_data_state_t s_data_flux_percent_state = {};
static const setting_data_t s_data_flux_percent = {
.type = TYPE_FLUX_PERCENT,
.title = "Flux part",
.val_get_text_fn = &base_get_text_fn,
.val_update_fn = &base_update_value_fn,
.val_ref = &app_data.flux_percent,
.min_value = 1.0f,
.max_value = 50.0f,
.min_step = 1.0f,
.max_step = 3.0f,
.precision = 0,
.suffix = "%",
.s = &s_data_flux_percent_state
};
static const char * move_pusher_get_text_fn(const setting_data_t * data)
{
(void)data;
return U_ICON_ARROWS;
}
static void pusher_update_value_fn(const setting_data_t * data, lv_event_t e, int key_code)
{
// TODO run motor in specified direction
(void)data; (void)e; (void) key_code;
}
static setting_data_state_t s_data_move_pusher_state = {};
static const setting_data_t s_data_move_pusher = {
.type = TYPE_MOVE_PUSHER,
.title = "Fast move",
.val_get_text_fn = &move_pusher_get_text_fn,
.val_update_fn = &pusher_update_value_fn,
.val_ref = NULL,
.min_value = 0.0f,
.max_value = 0.0f,
.min_step = 0.0f,
.max_step = 0.0f,
.precision = 0,
.suffix = "",
.s = &s_data_move_pusher_state
};
static lv_obj_t * page;
static bool destroyed = false;
static lv_design_cb_t orig_design_cb;
// Custom drawer to avoid labels create & save RAM.
static bool list_item_design_cb(lv_obj_t * obj, const lv_area_t * mask_p, lv_design_mode_t mode)
{
auto * s_data = reinterpret_cast<const setting_data_t *>(lv_obj_get_user_data(obj));
if(mode == LV_DESIGN_DRAW_MAIN)
{
orig_design_cb(obj, mask_p, mode);
lv_point_t title_pos = { .x = 4, .y = 4 };
lv_draw_label(
&obj->coords,
mask_p,
&app_data.styles.list_title,
lv_obj_get_opa_scale(obj),
s_data->title,
LV_TXT_FLAG_NONE,
&title_pos,
NULL,
NULL,
lv_obj_get_base_dir(obj)
);
lv_point_t desc_pos = { .x = 4, .y = 19 };
lv_draw_label(
&obj->coords,
mask_p,
&app_data.styles.list_desc,
lv_obj_get_opa_scale(obj),
s_data->val_get_text_fn(s_data),
LV_TXT_FLAG_NONE,
&desc_pos,
NULL,
NULL,
lv_obj_get_base_dir(obj)
);
return true;
}
return orig_design_cb(obj, mask_p, mode);
}
static void group_style_mod_cb(lv_group_t * group, lv_style_t * style)
{
if (destroyed) return;
style->body.main_color = COLOR_BG_HIGHLIGHT;
style->body.grad_color = COLOR_BG_HIGHLIGHT;
(void)group;
}
static void screen_settings_menu_item_cb(lv_obj_t * item, lv_event_t e)
{
if (destroyed) return;
// Next part is for keyboard only
if ((e != LV_EVENT_KEY) && (e != LV_EVENT_LONG_PRESSED) &&
(e != LV_EVENT_RELEASED) && (e != HACK_EVENT_RELEASED)) {
return;
}
int key_code = lv_indev_get_key(app_data.kbd);
static etl::cyclic_value<uint8_t, 0, 1> skip_cnt;
auto * s_data = reinterpret_cast<const setting_data_t *>(lv_obj_get_user_data(item));
switch (e)
{
// All keys except enter have `LV_EVENT_KEY` event for both
// click & repeat. And do not provide release & long press events.
case LV_EVENT_KEY:
switch (key_code)
{
// List navigation
case LV_KEY_UP:
skip_cnt++;
if (skip_cnt != 1) return;
lv_group_focus_prev(app_data.group);
// Scroll focused to visible area
lv_page_focus(page, lv_group_get_focused(app_data.group), true);
return;
case LV_KEY_DOWN:
skip_cnt++;
if (skip_cnt != 1) return;
lv_group_focus_next(app_data.group);
// Scroll focused to visible area
lv_page_focus(page, lv_group_get_focused(app_data.group), true);
return;
// Value change
case LV_KEY_LEFT:
case LV_KEY_RIGHT:
s_data->val_update_fn(s_data, e, key_code);
lv_obj_invalidate(item);
app_update_settings();
return;
}
return;
// for ENTER only
case LV_EVENT_LONG_PRESSED:
if (key_code == LV_KEY_ENTER)
{
app_data.skip_key_enter_release = true;
app_screen_create(false);
}
return;
// for ENTER only
case LV_EVENT_RELEASED:
if (key_code == LV_KEY_ENTER) {
if (app_data.skip_key_enter_release) {
app_data.skip_key_enter_release = false;
return;
}
app_screen_create(false);
return;
}
return;
// injected event from hacked driver
case HACK_EVENT_RELEASED:
skip_cnt = 0;
switch (key_code)
{
case LV_KEY_LEFT:
case LV_KEY_RIGHT:
s_data->val_update_fn(s_data, LV_EVENT_RELEASED, key_code);
return;
}
return;
}
}
void screen_settings_create()
{
lv_obj_t * screen = lv_scr_act();
lv_group_set_style_mod_cb(app_data.group, group_style_mod_cb);
lv_obj_t * mode_label = lv_label_create(screen, NULL);
lv_label_set_style(mode_label, LV_LABEL_STYLE_MAIN, &app_data.styles.header_icon);
lv_label_set_text(mode_label, U_ICON_SETTINGS);
lv_obj_set_pos(mode_label, 4, 4);
//
// Create list
//
page = lv_page_create(screen, NULL);
lv_page_set_anim_time(page, 150);
lv_page_set_style(page, LV_PAGE_STYLE_BG, &app_data.styles.list);
lv_page_set_style(page, LV_PAGE_STYLE_SCRL, &app_data.styles.list);
lv_page_set_sb_mode(page, LV_SB_MODE_OFF);
lv_page_set_scrl_layout(page, LV_LAYOUT_COL_L);
lv_obj_set_size(
page,
lv_obj_get_width(screen),
lv_obj_get_height(lv_scr_act()) - LIST_MARGIN_TOP
);
lv_obj_set_pos(page, 0, LIST_MARGIN_TOP);
lv_obj_t * selected_item = NULL;
uint8_t selected_id = (uint8_t)app_data.screen_settings_selected_id;
const setting_data_t * s_data_list[] = {
&s_data_syringe,
//&s_data_needle,
&s_data_viscosity,
&s_data_flux_percent,
&s_data_move_pusher,
NULL
};
for (uint8_t i = 0; s_data_list[i] != NULL; i++)
{
//
// Create list item & attach user data
//
auto * data = s_data_list[i];
lv_obj_t * item = lv_obj_create(page, NULL);
lv_obj_set_user_data(item, const_cast<setting_data_t *>(data));
lv_obj_set_style(item, &app_data.styles.main);
lv_obj_set_size(item, lv_obj_get_width(page), 37);
lv_obj_set_event_cb(item, screen_settings_menu_item_cb);
lv_group_add_obj(app_data.group, item);
// We use custom drawer to avoid labels use and reduce RAM comsumption
// significantly. Now it's ~ 170 bytes per entry.
// Since all callbacks are equal - use the same var to store old ones.
orig_design_cb = lv_obj_get_design_cb(item);
lv_obj_set_design_cb(item, list_item_design_cb);
if (data->type == selected_id) selected_item = item;
}
//
// Restore previous state
//
if (selected_item)
{
lv_group_focus_obj(selected_item);
if (app_data.screen_settings_scroll_pos != INT16_MAX)
{
lv_obj_set_y(lv_page_get_scrl(page), app_data.screen_settings_scroll_pos);
}
else lv_page_focus(page, lv_group_get_focused(app_data.group), LV_ANIM_OFF);
}
destroyed = false;
}
void screen_settings_destroy()
{
if (destroyed) return;
destroyed = true;
app_data.screen_settings_scroll_pos = lv_obj_get_y(lv_page_get_scrl(page));
auto * s_data = reinterpret_cast<const setting_data_t *>(lv_obj_get_user_data(
lv_group_get_focused(app_data.group)
));
app_data.screen_settings_selected_id = s_data->type;
lv_group_set_focus_cb(app_data.group, NULL);
lv_group_set_style_mod_cb(app_data.group, NULL);
lv_group_remove_all_objs(app_data.group);
lv_obj_clean(lv_scr_act());
}
| 28.332542 | 102 | 0.618545 | puzrin |
20cd7b1f74e573bc0f0d699d4ce4f0fdddb9ffc6 | 1,655 | cpp | C++ | test/substring/longest_common_substring.test.cpp | camilne/cardigan | 6cb07095c3dc06e558108a9986ab0e434c4b13e1 | [
"MIT"
] | 2 | 2018-04-26T04:24:47.000Z | 2018-04-26T04:25:28.000Z | test/substring/longest_common_substring.test.cpp | camilne/cardigan | 6cb07095c3dc06e558108a9986ab0e434c4b13e1 | [
"MIT"
] | 22 | 2018-04-26T04:41:19.000Z | 2018-05-13T02:49:04.000Z | test/substring/longest_common_substring.test.cpp | camilne/cardigan | 6cb07095c3dc06e558108a9986ab0e434c4b13e1 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include "third_party/catch.hpp"
#include "substring/longest_common_substring.hpp"
using namespace cgn;
TEST_CASE("Longest Common Substring: Base cases", "[longest-common-substring]") {
std::string a;
auto substrings = longest_common_substring(a, a);
REQUIRE(substrings.size() == 0);
a = "a";
substrings = longest_common_substring(a, a);
REQUIRE(substrings.size() == 1);
REQUIRE(substrings[0] == a);
std::vector<int> b;
auto b_substrings = longest_common_substring(b.begin(), b.end(), b.begin(), b.end());
REQUIRE(b_substrings.size() == 0);
b = {0};
b_substrings = longest_common_substring(b.begin(), b.end(), b.begin(), b.end());
REQUIRE(b_substrings.size() == 1);
REQUIRE(b_substrings[0].first == b.begin());
REQUIRE(b_substrings[0].second == b.end());
}
TEST_CASE("Longest Common Substring: String cases", "[longest-common-substring]") {
std::string a = "asdfghjkl;";
std::string b = "fghasdjlk;";
auto substrings = longest_common_substring(a, b);
REQUIRE(substrings.size() == 2);
std::sort(substrings.begin(), substrings.end());
REQUIRE(substrings[0] == "asd");
REQUIRE(substrings[1] == "fgh");
}
TEST_CASE("Longest Common Substring: Container cases", "[longest-common-substring]") {
std::vector<int> a = {1, 2, 3, 4, 5, 6, 7};
std::vector<int> b = {3, 7, 4, 4, 3, 4, 5};
auto substrings = longest_common_substring(a.begin(), a.end(), b.begin(), b.end());
REQUIRE(substrings.size() == 1);
REQUIRE(std::vector<int>(substrings[0].first, substrings[0].second) == std::vector<int>{3, 4, 5});
}
| 31.226415 | 102 | 0.642296 | camilne |
20cd9bcaea5ce1bc2259d381a832ae6a18340fe1 | 2,742 | hpp | C++ | OptFrame/Util/ScalarEvaluator.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 2 | 2018-05-24T11:04:12.000Z | 2020-03-03T13:37:07.000Z | OptFrame/Util/ScalarEvaluator.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | null | null | null | OptFrame/Util/ScalarEvaluator.hpp | 216k155/bft-pos | 80c1c84b8ca9a5c1c7462b21b011c89ae97666ae | [
"MIT"
] | 1 | 2019-06-06T16:57:49.000Z | 2019-06-06T16:57:49.000Z | // OptFrame - Optimization Framework
// Copyright (C) 2009-2015
// http://optframe.sourceforge.net/
//
// This file is part of the OptFrame optimization framework. This framework
// is free software; you can redistribute it and/or modify it under the
// terms of the GNU Lesser General Public License v3 as published by the
// Free Software Foundation.
// This framework is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License v3 for more details.
// You should have received a copy of the GNU Lesser General Public License v3
// along with this library; see the file COPYING. If not, write to the Free
// Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
// USA.
#ifndef OPTFRAME_MULTIOBJECTIVEEVALUATOR_HPP_
#define OPTFRAME_MULTIOBJECTIVEEVALUATOR_HPP_
#include "Evaluator.hpp"
#include "Evaluation.hpp"
#include "Move.hpp"
#include <iostream>
using namespace std;
namespace optframe
{
template<class R, class ADS = OPTFRAME_DEFAULT_ADS, class DS = OPTFRAME_DEFAULT_DS>
class MultiObjectiveEvaluator: public Evaluator<R, ADS, DS>
{
protected:
vector<Evaluator<R, ADS, DS>*> partialEvaluators;
public:
using Evaluator<R, ADS, DS>::evaluate; // prevents name hiding
MultiObjectiveEvaluator(Evaluator<R, ADS, DS>& e)
{
partialEvaluators.push_back(&e);
}
virtual ~MultiObjectiveEvaluator()
{
}
void add(Evaluator<R, ADS, DS>& e)
{
partialEvaluators.push_back(&e);
}
virtual Evaluation<DS>& evaluate(const R& r)
{
double objFunction = 0;
double infMeasure = 0;
Evaluation<DS>& e = partialEvaluators.at(0)->evaluate(r);
objFunction += e.getObjFunction();
infMeasure += e.getInfMeasure();
for (unsigned i = 1; i < partialEvaluators.size(); i++)
{
partialEvaluators.at(i)->evaluate(e, r);
objFunction += e.getObjFunction();
infMeasure += e.getInfMeasure();
}
e.setObjFunction(objFunction);
e.setInfMeasure(infMeasure);
return e;
}
virtual void evaluate(Evaluation<DS>& e, const R& r)
{
double objFunction = 0;
double infMeasure = 0;
for (unsigned i = 0; i < partialEvaluators.size(); i++)
{
partialEvaluators[i]->evaluate(e, r);
objFunction += e.getObjFunction();
infMeasure += e.getInfMeasure();
}
e.setObjFunction(objFunction);
e.setInfMeasure(infMeasure);
}
virtual bool betterThan(double a, double b)
{
return partialEvaluators[0]->betterThan(a, b);
}
static string idComponent()
{
return "OptFrame:moev";
}
virtual string id() const
{
return idComponent();
}
};
}
#endif /*OPTFRAME_MULTIOBJECTIVEEVALUATOR_HPP_*/
| 23.435897 | 83 | 0.716265 | 216k155 |
20d0257f1178916f6dea3a51319aa56b1cdada3d | 726 | hpp | C++ | Framework/Common/BaseApplication.hpp | GameRay/GameEngineFromScratch | 96fe4990f743606683cbc93f6a4bdfc7e6ca55db | [
"MIT"
] | null | null | null | Framework/Common/BaseApplication.hpp | GameRay/GameEngineFromScratch | 96fe4990f743606683cbc93f6a4bdfc7e6ca55db | [
"MIT"
] | null | null | null | Framework/Common/BaseApplication.hpp | GameRay/GameEngineFromScratch | 96fe4990f743606683cbc93f6a4bdfc7e6ca55db | [
"MIT"
] | 1 | 2020-03-06T15:27:24.000Z | 2020-03-06T15:27:24.000Z | #pragma once
#include "IApplication.hpp"
namespace My {
class BaseApplication : implements IApplication
{
public:
BaseApplication(GfxConfiguration& cfg);
virtual int Initialize();
virtual void Finalize();
// One cycle of the main loop
virtual void Tick();
virtual bool IsQuit();
inline GfxConfiguration& GetConfiguration() { return m_Config; };
protected:
virtual void OnDraw() {};
protected:
// Flag if need quit the main loop of the application
static bool m_bQuit;
GfxConfiguration m_Config;
private:
// hide the default construct to enforce a configuration
BaseApplication(){};
};
}
| 22.6875 | 73 | 0.625344 | GameRay |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.