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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3788372b6c8beae2f46454b97a4d243b5e547177 | 1,861 | hpp | C++ | parser/operators.hpp | CobaltXII/cxcc | 2e8f34e851b3cbe6699e443fd3950d630ff170b7 | [
"MIT"
] | 3 | 2019-05-27T04:50:51.000Z | 2019-06-18T16:27:58.000Z | parser/operators.hpp | CobaltXII/cxcc | 2e8f34e851b3cbe6699e443fd3950d630ff170b7 | [
"MIT"
] | null | null | null | parser/operators.hpp | CobaltXII/cxcc | 2e8f34e851b3cbe6699e443fd3950d630ff170b7 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
// All binary operators.
enum binary_operator_t {
bi_addition,
bi_subtraction,
bi_multiplication,
bi_division,
bi_modulo,
bi_assignment,
bi_addition_assignment,
bi_subtraction_assignment,
bi_multiplication_assignment,
bi_division_assignment,
bi_modulo_assignment,
bi_logical_and,
bi_logical_or,
bi_relational_equal,
bi_relational_non_equal,
bi_relational_greater_than,
bi_relational_lesser_than,
bi_relational_greater_than_or_equal_to,
bi_relational_lesser_than_or_equal_to,
bi_binary_and,
bi_binary_or,
bi_binary_xor,
bi_binary_and_assignment,
bi_binary_or_assignment,
bi_binary_xor_assignment,
bi_binary_left_shift,
bi_binary_right_shift,
bi_binary_left_shift_assignment,
bi_binary_right_shift_assignment,
bi_error
};
// All binary operators as strings.
std::string binary_operator_str[] = {
"addition",
"subtraction",
"multiplication",
"division",
"modulo",
"assignment",
"addition assignment",
"subtraction assignment",
"multiplication assignment",
"division assignment",
"modulo assignment",
"logical and",
"logical or",
"relational equal",
"relational non-equal",
"relational greater-than",
"relational lesser-than",
"relational greater-than or equal-to",
"relational lesser-than or equal-to",
"binary AND",
"binary OR",
"binary XOR",
"binary AND assignment",
"binary OR assignment",
"binary XOR assignment"
"binary left-shift",
"binary right-shift",
"binary left-shift assignment",
"binary right-shift assignment"
};
// All unary operators.
enum unary_operator_t {
un_value_of,
un_arithmetic_positive,
un_arithmetic_negative,
un_address_of,
un_logical_not,
un_binary_not
};
// All unary operators as strings.
std::string unary_operator_str[] = {
"value-of",
"arithmetic positive",
"arithmetic negative",
"address-of",
"logical NOT",
"binary NOT"
}; | 20.910112 | 40 | 0.779688 | CobaltXII |
37926c6e01702a320a788f39146488ba5b6a0b58 | 469 | hpp | C++ | include/gkom/ShaderProgram.hpp | akowalew/mill-opengl | 91ef11e6cdbfe691e0073d9883e42c0a29d29b45 | [
"MIT"
] | null | null | null | include/gkom/ShaderProgram.hpp | akowalew/mill-opengl | 91ef11e6cdbfe691e0073d9883e42c0a29d29b45 | [
"MIT"
] | null | null | null | include/gkom/ShaderProgram.hpp | akowalew/mill-opengl | 91ef11e6cdbfe691e0073d9883e42c0a29d29b45 | [
"MIT"
] | null | null | null | #pragma once
#include <string_view>
namespace gkom {
//! Forward declarations
class Shader;
class Uniform;
class ShaderProgram
{
public:
explicit ShaderProgram(unsigned int handle) noexcept;
void attach(Shader shader);
void detach(Shader shader);
void link();
bool isLinked() const noexcept;
void use();
void unuse();
Uniform getUniform(std::string_view name);
operator unsigned int() const noexcept;
private:
unsigned int handle_;
};
} // gkom
| 12.675676 | 54 | 0.729211 | akowalew |
379d999398968fe22b83e1234e3e731b4bd13ff4 | 3,755 | cc | C++ | src/runtime/directx/directx_buffer.cc | wenxcs/tvm | bcbf4f9b1ddc4326364a3aa2fc82aaf4df8d53e8 | [
"Apache-2.0"
] | null | null | null | src/runtime/directx/directx_buffer.cc | wenxcs/tvm | bcbf4f9b1ddc4326364a3aa2fc82aaf4df8d53e8 | [
"Apache-2.0"
] | null | null | null | src/runtime/directx/directx_buffer.cc | wenxcs/tvm | bcbf4f9b1ddc4326364a3aa2fc82aaf4df8d53e8 | [
"Apache-2.0"
] | null | null | null | #include "directx_header.h"
using namespace tvm::runtime::dx;
DirectBuffer::DirectBuffer(DirectXDevice* _dev, UINT64 size, DLDataType type) : _dxdev(_dev) {
_res = _dev->device_allocate(size);
D3D12_RESOURCE_DESC desc = _res->GetDesc();
this->size = desc.Width;
this->type = type;
}
DirectBuffer::DirectBuffer(DirectXDevice* _dev, ComPtr<ID3D12Resource> res, DLDataType type)
: _dxdev(_dev), _res(res) {
D3D12_RESOURCE_DESC desc = _res->GetDesc();
this->size = desc.Width;
this->type = type;
}
DirectHostBuffer::DirectHostBuffer(DirectXDevice* _dev, UINT64 size, DLDataType type, hostbuffer_state state)
: _cur_state(state), ptr(nullptr) {
if (state == hostbuffer_state::upload)
_host_res = _dev->upload_allocate(size);
else if (state == hostbuffer_state::readback)
_host_res = _dev->readback_allocate(size);
else
throw std::invalid_argument(_msg_("Buffer state is not supported"));
D3D12_RESOURCE_DESC desc = _host_res->GetDesc();
this->size = desc.Width;
range = {0, static_cast<SIZE_T>(size)};
_dxdev = _dev;
this->type = type;
}
void* DirectHostBuffer::open_data_ptr() {
if (ptr != nullptr) return ptr;
ThrowIfFailed(_host_res->Map(0, &range, reinterpret_cast<void**>(&ptr)));
return ptr;
}
void DirectHostBuffer::close_data_ptr() {
ptr = nullptr;
if (_cur_state == hostbuffer_state::readback)
// Use begin = end to tell no data is changed;
{
D3D12_RANGE range = {0, 0};
_host_res->Unmap(0, &range);
} else
_host_res->Unmap(0, &range);
}
// todo(wenxh): use resource barrier to support call this transition in async way;
void DirectHostBuffer::change_state(hostbuffer_state hs) {
if (hs == _cur_state) return;
D3D12_RESOURCE_DESC desc = _host_res->GetDesc();
if (hs == hostbuffer_state::upload) {
// readback to upload, need to memcpy
auto tgt = _dxdev->upload_allocate(size);
// cpu memcpy
{
// open ptr
void* t_ptr = nullptr;
ThrowIfFailed(tgt->Map(0, &range, reinterpret_cast<void**>(&t_ptr)));
open_data_ptr();
memcpy(t_ptr, ptr, size);
// close ptr
close_data_ptr();
tgt->Unmap(0, &range);
}
_host_res = tgt;
} else if (hs == hostbuffer_state::readback) {
close_data_ptr();
auto tgt = _dxdev->readback_allocate(size);
_dxdev->copy(tgt, _host_res);
_host_res = tgt;
} else {
throw std::invalid_argument(_msg_("Target buffer state is not supported."));
}
_cur_state = hs;
}
DirectReadBackBuffer::DirectReadBackBuffer(DirectXDevice* _dev, UINT64 size, DLDataType type)
: DirectBuffer(_dev, size, type) {
_host_res = _dev->readback_allocate(size);
range = {0, static_cast<SIZE_T>(size)};
this->ptr = nullptr;
}
void* DirectReadBackBuffer::open_data_ptr() {
if (ptr != nullptr) return ptr;
ThrowIfFailed(_host_res->Map(0, &range, reinterpret_cast<void**>(&ptr)));
return ptr;
}
void DirectReadBackBuffer::to_host(bool async) { _dxdev->copy(_host_res, _res, async); }
void DirectReadBackBuffer::close_data_ptr() {
ptr = nullptr;
// Use begin = end to tell no data is changed;
D3D12_RANGE range = {0, 0};
_host_res->Unmap(0, &range);
}
DirectUploadBuffer::DirectUploadBuffer(DirectXDevice* _dev, UINT64 size, DLDataType type)
: DirectBuffer(_dev, size, type) {
_host_res = _dev->upload_allocate(size);
range = {0, static_cast<SIZE_T>(size)};
this->ptr = nullptr;
}
void* DirectUploadBuffer::open_data_ptr() {
if (ptr != nullptr) return ptr;
ThrowIfFailed(_host_res->Map(0, &range, reinterpret_cast<void**>(&ptr)));
return ptr;
}
void DirectUploadBuffer::close_data_ptr() {
ptr = nullptr;
_host_res->Unmap(0, &range);
}
void DirectUploadBuffer::to_device(bool async) { _dxdev->copy(_res, _host_res, async); }
| 30.282258 | 109 | 0.691877 | wenxcs |
37a80ab55c5fa7ba4985d1ab17263121be860830 | 1,377 | cpp | C++ | tests/SignalConverterTests.cpp | sbash64/phase-vocoder | ac9c11cd4d38c6827bfde815e559d3f1114e1cf4 | [
"MIT"
] | null | null | null | tests/SignalConverterTests.cpp | sbash64/phase-vocoder | ac9c11cd4d38c6827bfde815e559d3f1114e1cf4 | [
"MIT"
] | null | null | null | tests/SignalConverterTests.cpp | sbash64/phase-vocoder | ac9c11cd4d38c6827bfde815e559d3f1114e1cf4 | [
"MIT"
] | null | null | null | #include "assert-utility.hpp"
#include <sbash64/phase-vocoder/SignalConverter.hpp>
#include <gtest/gtest.h>
namespace sbash64::phase_vocoder {
namespace {
class SignalConverterTests : public ::testing::Test {
protected:
void assertExpanded(const std::vector<double> &x, index_type P,
const std::vector<double> &y) {
std::vector<double> expanded(x.size() * gsl::narrow_cast<size_t>(P), 1);
converter.expand(x, expanded);
assertEqual(y, expanded);
}
void assertDecimated(const std::vector<double> &x, index_type Q,
const std::vector<double> &y) {
std::vector<double> decimated(x.size() / gsl::narrow_cast<size_t>(Q));
converter.decimate(x, decimated);
assertEqual(y, decimated);
}
private:
SignalConverterImpl<double> converter;
};
// clang-format off
TEST_F(SignalConverterTests, extractsEveryQthElement) {
assertDecimated(
{ 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0 },
3,
{ 1, 2, 3, 4, 5 }
);
}
TEST_F(SignalConverterTests, insertsPMinusOneZeros) {
assertExpanded(
{ 1, 2, 3, 4, 5 },
3,
{ 1, 0, 0, 2, 0, 0, 3, 0, 0, 4, 0, 0, 5, 0, 0 }
);
}
TEST_F(SignalConverterTests, insertsNoZerosWhenPIsOne) {
assertExpanded(
{ 1, 2, 3, 4, 5 },
1,
{ 1, 2, 3, 4, 5 }
);
}
// clang-format on
}
}
| 24.157895 | 80 | 0.594771 | sbash64 |
37ad33aeccebf9570081da11802638ed6c0bc2fe | 609 | cpp | C++ | engine/src/core/mesh.cpp | AnisB/Donut | 335638df9eca74440ca0d9dc3928ae9b419b7307 | [
"MIT"
] | 3 | 2015-09-28T23:21:02.000Z | 2017-06-20T16:17:32.000Z | engine/src/core/mesh.cpp | AnisB/Donut | 335638df9eca74440ca0d9dc3928ae9b419b7307 | [
"MIT"
] | null | null | null | engine/src/core/mesh.cpp | AnisB/Donut | 335638df9eca74440ca0d9dc3928ae9b419b7307 | [
"MIT"
] | 2 | 2015-11-25T07:34:35.000Z | 2017-01-03T00:14:38.000Z | // Library includes
#include "core/Mesh.h"
#include "resource/resource_manager.h"
// External includes
#include <string.h>
namespace donut
{
TMesh::TMesh(MATERIAL_GUID material_guid, GEOMETRY_GUID _geometry)
: TDrawable()
, m_material(material_guid)
, m_geometry(_geometry)
{
}
TMesh::~TMesh()
{
}
void TMesh::Evaluate(TCollector& _request, const bento::Matrix4& _tm)
{
// Build our new render request
TRenderRequest newRequest;
newRequest.geometry = m_geometry;
newRequest.material = m_material;
newRequest.transform = _tm;
// Appent it
_request.Append(newRequest);
}
} | 19.03125 | 70 | 0.720854 | AnisB |
37ae65938574133f0b9790b155f54b47609aee78 | 1,004 | cpp | C++ | geometry/point.11.cpp | ivan100sic/competelib-snippets | e40170a63b37d92c91e2dfef08b2794e67ccb0b2 | [
"Unlicense"
] | 3 | 2022-01-17T01:56:05.000Z | 2022-02-23T07:30:02.000Z | geometry/point.11.cpp | ivan100sic/competelib-snippets | e40170a63b37d92c91e2dfef08b2794e67ccb0b2 | [
"Unlicense"
] | null | null | null | geometry/point.11.cpp | ivan100sic/competelib-snippets | e40170a63b37d92c91e2dfef08b2794e67ccb0b2 | [
"Unlicense"
] | null | null | null | // Planar point
using ll = long long;
/*snippet-begin*/
template<class P, class T = ll>
T det(const P& a, const P& b, const P& c) {
return (a-b).template vp<T>(a-c);
}
template<class T>
T sgn(T x) {
return x < 0 ? -1 : !!x;
}
template<class T>
struct point {
T x, y;
point operator- (const point& b) const { return {x-b.x, y-b.y}; }
point& operator-= (const point& b) { x -= b.x; y -= b.y; return *this; }
bool operator< (const point& b) const { return tie(x, y) < tie(b.x, b.y); }
bool operator== (const point& b) const { return tie(x, y) == tie(b.x, b.y); }
bool operator<= (const point& b) const { return tie(x, y) <= tie(b.x, b.y); }
template<class R = ll> R sp(const point& b) const { return (R)x*b.x + (R)y*b.y; }
template<class R = ll> R vp(const point& b) const { return (R)x*b.y - (R)y*b.x; }
};
using pti = point<int>;
using ptll = point<ll>;
/*snippet-end*/
int main() {
pti a = {1, 2}, b = {2, 5};
return a.sp(b) != 12 || a.vp(b) != 1;
}
| 27.888889 | 85 | 0.553785 | ivan100sic |
37b0e336737df256bc44e98d0a264c23822a78a2 | 485 | cpp | C++ | mj344/IOManager/Outputs/Host.cpp | Shakarang/mbed-mj344_a1 | d8217db644c08f3417fe5f4f3b51f59df9439408 | [
"MIT"
] | null | null | null | mj344/IOManager/Outputs/Host.cpp | Shakarang/mbed-mj344_a1 | d8217db644c08f3417fe5f4f3b51f59df9439408 | [
"MIT"
] | null | null | null | mj344/IOManager/Outputs/Host.cpp | Shakarang/mbed-mj344_a1 | d8217db644c08f3417fe5f4f3b51f59df9439408 | [
"MIT"
] | null | null | null | /**
* @Author: Maxime Junger <mj344>
* @Date: 2017-02-03T21:46:16+00:00
* @Email: mj344@kent.ac.uk
* @Last modified by: mj344
* @Last modified time: 2017-02-08T18:26:07+00:00
*/
#include <time.h>
#include "Host.hh"
Host::Host() {
this->host = new Serial(USBTX, USBRX);
}
Host::~Host() {
if (this->host != NULL) { delete this->host; }
}
void Host::print(const std::string &str) {
if (this->host != NULL) {
this->host->printf("\r%i : %s\n", time (NULL), str.c_str());
}
}
| 19.4 | 62 | 0.602062 | Shakarang |
37b5a3a5158024aace1be6ee2386633d7ea6992f | 4,308 | cpp | C++ | WOAP Host/Source/woap_gain_fader_view.cpp | ZonRobin/WOAP | f1bfb8dbe84e57826834ad3ca81f548b20b1afc6 | [
"MIT"
] | null | null | null | WOAP Host/Source/woap_gain_fader_view.cpp | ZonRobin/WOAP | f1bfb8dbe84e57826834ad3ca81f548b20b1afc6 | [
"MIT"
] | null | null | null | WOAP Host/Source/woap_gain_fader_view.cpp | ZonRobin/WOAP | f1bfb8dbe84e57826834ad3ca81f548b20b1afc6 | [
"MIT"
] | null | null | null | #include "woap_gain_fader_view.h"
#include "woap_gain_fader.h"
#include "woap_track.h"
#include "woap_track_level_indicator_view.h"
#include "woap_parameter_float.h"
#include "woap_vertical_db_scale.h"
#include "woap_track_send_node.h"
using namespace WOAP;
using namespace WOAP::GUI;
GainFaderView::GainFaderView(Track* tr)
: track(nullptr)
{
levelIndicator = new TrackLevelIndicatorView();
levelIndicator->setSkewFactor(1.5f);
levelIndicator->setRange(-80.0f, 17.0f);
addAndMakeVisible(levelIndicator);
fader = new GainFader();
fader->setThumbOpacity(0.75f);
fader->setSkewFactor(3.0f);
fader->setRange(-145, 10);
fader->addListener(this);
addAndMakeVisible(fader);
dbScale = new VerticalDbScale();
dbScale->setSkewFactor(3.0f);
dbScale->setRange(-145.0f, 10.0f);
addAndMakeVisible(dbScale);
setTrack(tr);
}
GainFaderView::~GainFaderView()
{
setTrack(nullptr);
}
void GainFaderView::resized()
{
const Rectangle<int> bounds = getLocalBounds();
const int width = getWidth();
const int halfWidth = (int)(width * 0.5f);
dbScale->setMargin(jmin(getHeight() / 8, 30));
dbScale->setBounds(bounds.withLeft(halfWidth + 5));
levelIndicator->setBounds(bounds.withWidth(halfWidth));
fader->setBounds(bounds.withWidth(halfWidth).withSizeKeepingCentre(halfWidth - 7, getHeight()));
}
void GainFaderView::setTrack(Track* tr)
{
if (track != nullptr)
track->getGainParameter()->removeListener(this);
track = tr;
levelIndicator->setTrack(tr);
if (tr != nullptr)
{
ParameterFloat* gainParameter = track->getGainParameter();
gainParameter->addListener(this);
fader->setRange(gainParameter->getMinValue(), gainParameter->getMaxValue(), 0.01f);
fader->setValue(gainParameter->get(), NotificationType::dontSendNotification);
}
}
void GainFaderView::sliderValueChanged(Slider*)
{
*track->getGainParameter() = (float)fader->getValue();
}
void GainFaderView::sliderDragStarted(Slider*)
{
dragging = true;
}
void GainFaderView::sliderDragEnded(Slider*)
{
dragging = false;
fader->setValue(track->getGainParameter()->get(), NotificationType::dontSendNotification);
}
void GainFaderView::parameterChanged(Parameter*)
{
if (!dragging)
fader->setValue((double)track->getGainParameter()->get(), NotificationType::dontSendNotification);
}
TrackSendNodeGainFaderView::TrackSendNodeGainFaderView(TrackSendNode* trackSend)
: trackSendNode(nullptr)
{
fader = new GainFader();
fader->setSkewFactor(3.0f);
fader->setRange(-145, 10);
fader->addListener(this);
fader->setColour(Slider::trackColourId, Colour(70, 70, 70));
addAndMakeVisible(fader);
dbScale = new VerticalDbScale();
dbScale->setSkewFactor(3.0f);
dbScale->setRange(-145.0f, 10.0f);
addAndMakeVisible(dbScale);
setTrackSendNode(trackSend);
}
TrackSendNodeGainFaderView::~TrackSendNodeGainFaderView()
{
setTrackSendNode(nullptr);
}
void TrackSendNodeGainFaderView::resized()
{
const Rectangle<int> bounds = getLocalBounds();
const int width = getWidth();
const int halfWidth = (int)(width * 0.5f);
dbScale->setMargin(getHeight() / 8);
dbScale->setBounds(bounds.withLeft(halfWidth + 5));
fader->setBounds(bounds.withWidth(halfWidth).withSizeKeepingCentre(halfWidth - 7, getHeight()));
}
void TrackSendNodeGainFaderView::setTrackSendNode(TrackSendNode* trackSend)
{
if (trackSendNode != nullptr)
trackSendNode->getGainParameter()->removeListener(this);
trackSendNode = trackSend;
if (trackSend != nullptr)
{
ParameterFloat* gainParameter = trackSendNode->getGainParameter();
gainParameter->addListener(this);
fader->setRange(gainParameter->getMinValue(), gainParameter->getMaxValue(), 0.01f);
fader->setValue(gainParameter->get(), NotificationType::dontSendNotification);
}
}
void TrackSendNodeGainFaderView::sliderValueChanged(Slider*)
{
*trackSendNode->getGainParameter() = (float)fader->getValue();
}
void TrackSendNodeGainFaderView::sliderDragStarted(Slider*)
{
dragging = true;
}
void TrackSendNodeGainFaderView::sliderDragEnded(Slider*)
{
dragging = false;
fader->setValue(trackSendNode->getGainParameter()->get(), NotificationType::dontSendNotification);
}
void TrackSendNodeGainFaderView::parameterChanged(Parameter*)
{
if (!dragging)
fader->setValue((double)trackSendNode->getGainParameter()->get(), NotificationType::dontSendNotification);
} | 24.338983 | 108 | 0.7565 | ZonRobin |
37b9fd0a59f9806b2227df06ef6c6415ba53b56f | 1,212 | cpp | C++ | examples/images/ImageOpenCVModel.cpp | teyenliu/nodeeditor | a1bf22f924f4911b8dd3f84ff88678f91cdd2c7e | [
"BSD-3-Clause"
] | null | null | null | examples/images/ImageOpenCVModel.cpp | teyenliu/nodeeditor | a1bf22f924f4911b8dd3f84ff88678f91cdd2c7e | [
"BSD-3-Clause"
] | null | null | null | examples/images/ImageOpenCVModel.cpp | teyenliu/nodeeditor | a1bf22f924f4911b8dd3f84ff88678f91cdd2c7e | [
"BSD-3-Clause"
] | null | null | null | #include "ImageOpenCVModel.hpp"
#include <QtCore/QEvent>
#include <QtCore/QDir>
#include <QDebug>
#include <QtWidgets/QFileDialog>
#include <nodes/DataModelRegistry>
#include "PixmapData.hpp"
ImageOpenCVModel::
ImageOpenCVModel()
{
}
bool
ImageOpenCVModel::
eventFilter(QObject *object, QEvent *event)
{
if (object == _panel)
{
int w = _panel->width();
int h = _panel->height();
if (event->type() == QEvent::Resize)
{
auto d = std::dynamic_pointer_cast<PixmapData>(_nodeData);
if (d)
{
_label->setPixmap(d->pixmap().scaled(w, h, Qt::KeepAspectRatio));
}
}
}
return false;
}
std::shared_ptr<NodeData>
ImageOpenCVModel::
outData(PortIndex)
{
return _nodeData;
}
void
ImageOpenCVModel::
setInData(std::shared_ptr<NodeData> nodeData, PortIndex)
{
_nodeData = nodeData;
if (_nodeData)
{
auto d = std::dynamic_pointer_cast<PixmapData>(_nodeData);
// Danny Implementation
if(!d->pixmap().isNull())
{
int w = _panel->width();
int h = _panel->height();
_label->setPixmap(d->pixmap().scaled(w, h, Qt::KeepAspectRatio));
}
}
else
{
_label->setPixmap(QPixmap());
}
Q_EMIT dataUpdated(0);
}
| 17.070423 | 75 | 0.643564 | teyenliu |
37bf813d9aa9a21833b19ba4e9f78654eb01aa91 | 31,278 | cpp | C++ | Math3D.cpp | joeriedel/Tread3.0A2 | 337c4aa74d554e21b50d6bd4406ce0f67aa39144 | [
"MIT"
] | 1 | 2020-07-19T10:19:18.000Z | 2020-07-19T10:19:18.000Z | Math3D.cpp | joeriedel/Tread3.0A2 | 337c4aa74d554e21b50d6bd4406ce0f67aa39144 | [
"MIT"
] | null | null | null | Math3D.cpp | joeriedel/Tread3.0A2 | 337c4aa74d554e21b50d6bd4406ce0f67aa39144 | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// Math3D.cpp
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008, Joe Riedel
// All rights reserved.
// Original Author: Andrew Meggs
//
// Redistribution and use in source and binary forms,
// with or without modification, are permitted provided
// that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// Neither the name of the <ORGANIZATION> nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
// OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#ifndef __math3d_h__
#include "math3d.h"
#endif
// Include inline functions in out-of-line form if mat3d.h
// didn't include them already as inlines.
#ifndef __math3d_inlines_i__
#define inline
#include "math3d_inlines.i"
#undef inline
#endif
static const float zero4x4[] =
{
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f,
0.0f, 0.0f, 0.0f, 0.0f
};
static const float ident4x4[] =
{
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f
};
const mat3x3 mat3x3::zero = *(mat3x3 *)zero4x4;
const mat3x3 mat3x3::identity = *(mat3x3 *)ident4x4;
const mat4x3 mat4x3::zero = *(mat4x3 *)zero4x4;
const mat4x3 mat4x3::identity = *(mat4x3 *)ident4x4;
const mat4x4 mat4x4::zero = *(mat4x4 *)zero4x4;
const mat4x4 mat4x4::identity = *(mat4x4 *)ident4x4;
const quat quat::zero(0,0,0,0);
const quat quat::identity(0,0,0,1);
const vec2 vec2::zero(0,0);
const vec3 vec3::zero(0,0,0);
const vec3 vec3::bogus_max(999999.0f, 999999.0f, 999999.0f);
const vec3 vec3::bogus_min(-999999.0f, -999999.0f, -999999.0f);
float plane3::tolerance = 1.0 / 65536.0;
OS_FNEXP void quaternion_to_matrix( mat3x3 *out, const quat *in )
{
float wx, wy, wz, xx, yy, yz, xy, xz, zz, x2, y2, z2;
// calculate coefficients
x2 = in->x + in->x;
y2 = in->y + in->y;
z2 = in->z + in->z;
xx = in->x * x2;
xy = in->x * y2;
xz = in->x * z2;
yy = in->y * y2;
yz = in->y * z2;
zz = in->z * z2;
wx = in->w * x2;
wy = in->w * y2;
wz = in->w * z2;
out->m[0][0] = 1.0f - (yy + zz);
out->m[0][1] = xy - wz;
out->m[0][2] = xz + wy;
out->m[1][0] = xy + wz;
out->m[1][1] = 1.0f - (xx + zz);
out->m[1][2] = yz - wx;
out->m[2][0] = xz - wy;
out->m[2][1] = yz + wx;
out->m[2][2] = 1.0f - (xx + yy);
}
// This code is reversed from what I can find in the literature!
// I feel really strongly that mat2quat( quat2mat( q ) ) should equal q
// and that quat2mat( mat2quat( m ) ) should equal m, but the set
// of functions that I copied from Game Developer instead gives me
// their respective inverses. It's possible I screwed something up
// in the process of copying things over (and the original mat2quat
// is reproduced below if someone wishes to attempt to find my typo),
// and it's possible I completely misunderstand the intention of
// the original functions. Either way, for now I'm making the code
// do what I want it to do by having mat2quat return the inverse of
// what my attempt at transcribing the original code does.
OS_FNEXP void matrix_to_quaternion( quat *out, const mat3x3 *in )
{
float tr, s, q[4];
int i, j, k;
static const int nxt[3] = {1, 2, 0};
tr = in->m[0][0] + in->m[1][1] + in->m[2][2];
// check the diagonal
if (tr > 0.0)
{
s = sqrtf(tr + 1.0f);
out->w = s / 2.0f;
s = 0.5f / s;
out->x = -(in->m[1][2] - in->m[2][1]) * s; // added minus sign (see above)
out->y = -(in->m[2][0] - in->m[0][2]) * s; // added minus sign (see above)
out->z = -(in->m[0][1] - in->m[1][0]) * s; // added minus sign (see above)
}
else
{
// diagonal is negative
i = 0;
if (in->m[1][1] > in->m[0][0]) i = 1;
if (in->m[2][2] > in->m[i][i]) i = 2;
j = nxt[i];
k = nxt[j];
s = sqrtf( (in->m[i][i] - (in->m[j][j] + in->m[k][k])) + 1.0f );
q[i] = s * 0.5f;
if (s != 0.0f) s = 0.5f / s;
q[3] = (in->m[j][k] - in->m[k][j]) * s;
q[j] = (in->m[i][j] + in->m[j][i]) * s;
q[k] = (in->m[i][k] + in->m[k][i]) * s;
out->x = -q[0]; // added minus sign (see above)
out->y = -q[1]; // added minus sign (see above)
out->z = -q[2]; // added minus sign (see above)
out->w = q[3];
}
}
/* original code (see above)
void matrix_to_quaternion( quat *out, const mat3x3 *in )
{
float tr, s, q[4];
int i, j, k;
static const int nxt[3] = {1, 2, 0};
tr = in->m[0][0] + in->m[1][1] + in->m[2][2];
// check the diagonal
if (tr > 0.0)
{
s = sqrtf(tr + 1.0f);
out->w = s / 2.0f;
s = 0.5f / s;
out->x = (in->m[1][2] - in->m[2][1]) * s;
out->y = (in->m[2][0] - in->m[0][2]) * s;
out->z = (in->m[0][1] - in->m[1][0]) * s;
}
else
{
// diagonal is negative
i = 0;
if (in->m[1][1] > in->m[0][0]) i = 1;
if (in->m[2][2] > in->m[i][i]) i = 2;
j = nxt[i];
k = nxt[j];
s = sqrtf( (in->m[i][i] - (in->m[j][j] + in->m[k][k])) + 1.0f );
q[i] = s * 0.5f;
if (s != 0.0f) s = 0.5f / s;
q[3] = (in->m[j][k] - in->m[k][j]) * s;
q[j] = (in->m[i][j] + in->m[j][i]) * s;
q[k] = (in->m[i][k] + in->m[k][i]) * s;
out->x = q[0];
out->y = q[1];
out->z = q[2];
out->w = q[3];
}
}
*/
OS_FNEXP vec3 euler_from_matrix( const mat3x3 &m )
{
float theta;
float cp;
float sp;
vec3 v;
sp = m[2][0];
if( sp > 1.0f )
sp = 1.0f;
if( sp < -1.0f )
sp = -1.0f;
theta = (float)-asin( sp );
cp = (float)cos( theta );
if( cp > (8192.0f*1.19209289550781250000e-07) )
{
v[0] = theta;// * 180.0f / PI;
v[1] = (float)atan2( m[1][0], m[0][0] );// * 180.0f / PI;
v[2] = (float)atan2( m[2][1], m[2][2] );// * 180.0f / PI;
}
else
{
v[0] = theta;// * 180.0f / PI;
v[1] = (float)-atan2( m[0][1], m[1][1] );// * 180.0f / PI;
v[2] = 0.0f;
}
return v;
}
OS_FNEXP void slerp_quaternion( quat *out, const quat *from, const quat *to, float t )
{
float to1[4];
double omega, cosom, sinom, scale0, scale1;
// calc cosine
cosom = (from->x * to->x) + (from->y * to->y) + (from->z * to->z) + (from->w * to->w);
// adjust signs (if necessary)
if (cosom < 0.0f)
{
cosom = -cosom;
to1[0] = -to->x;
to1[1] = -to->y;
to1[2] = -to->z;
to1[3] = -to->w;
}
else
{
to1[0] = to->x;
to1[1] = to->y;
to1[2] = to->z;
to1[3] = to->w;
}
// calculate coefficients
// This particular definition of "close" was chosen
// to match the keyframe tolerance of the skelanim
// library.
if ( (1.0 - cosom) > 0.0006f )
{
// standard case (slerp)
omega = acosf((float)cosom);
sinom = sinf((float)omega);
scale0 = sinf((float)((1.0f - t) * omega)) / sinom;
scale1 = sinf((float)(t * omega)) / sinom;
}
else
{
// "from" and "to" quaternions are very close
// ... so we can do a linear interpolation
scale0 = 1.0f - t;
scale1 = t;
}
// calculate final values
out->x = (float)(scale0 * from->x + scale1 * to1[0]);
out->y = (float)(scale0 * from->y + scale1 * to1[1]);
out->z = (float)(scale0 * from->z + scale1 * to1[2]);
out->w = (float)(scale0 * from->w + scale1 * to1[3]);
}
OS_FNEXP void quaternion_mul( quat *out, const quat *q1, const quat *q2 )
{
float A, B, C, D, E, F, G, H;
A = (q1->w + q1->x) * (q2->w + q2->x);
B = (q1->z - q1->y) * (q2->y - q2->z);
C = (q1->w - q1->x) * (q2->y + q2->z);
D = (q1->y + q1->z) * (q2->w - q2->x);
E = (q1->x + q1->z) * (q2->x + q2->y);
F = (q1->x - q1->z) * (q2->x - q2->y);
G = (q1->w + q1->y) * (q2->w - q2->z);
H = (q1->w - q1->y) * (q2->w + q2->z);
out->w = B + (-E - F + G + H) * 0.5f;
out->x = A - (E + F + G + H) * 0.5f;
out->y = C + (E - F + G - H) * 0.5f;
out->z = D + (E - F - G + H) * 0.5f;
}
#define MAX_INVERTIBLE 8
OS_FNEXP void matrix_invert( float *m, int size, int column_stride, int row_stride )
{
if (!column_stride) column_stride = 1;
if (!row_stride) row_stride = size * column_stride;
MATH3D_ASSERT( size > 1 && size <= MAX_INVERTIBLE );
int indxc[MAX_INVERTIBLE];
int indxr[MAX_INVERTIBLE];
int ipiv[MAX_INVERTIBLE];
int i, icol, irow, j, k;
float big, pivinv, temp;
memset( ipiv, 0, sizeof(ipiv) );
for (i = 0; i < size; ++i)
{
big = 0.0f;
for (j = 0; j < size; ++j)
{
if (ipiv[j] != 1)
{
for (k = 0; k < size; ++k)
{
if (!ipiv[k])
{
float fa = (float)fabs( m[ j * row_stride + k * column_stride ] );
if (fa > big)
{
big = fa;
irow = j;
icol = k;
}
}
else if (ipiv[k] > 1)
{
// error, singular matrix
return;
}
}
}
}
ipiv[icol] += 1;
if (irow != icol)
{
for (j = 0; j < size; ++j)
{
temp = m[icol * row_stride + j * column_stride];
m[icol * row_stride + j * column_stride] = m[irow * row_stride + j * column_stride];
m[irow * row_stride + j * column_stride] = temp;
}
}
indxr[i] = irow;
indxc[i] = icol;
pivinv = m[icol * row_stride + icol * column_stride];
if (pivinv == 0.0f)
{
// error, singular matrix
return;
}
pivinv = 1.0f / pivinv;
m[icol * row_stride + icol * column_stride] = 1.0f;
for (j = 0; j < size; ++j)
{
m[icol * row_stride + j * column_stride] *= pivinv;
}
for (j = 0; j < size; ++j)
{
if (j != icol)
{
temp = m[j * row_stride + icol * column_stride];
m[j * row_stride + icol * column_stride] = 0.0f;
for (k = 0; k < size; ++k)
{
m[j * row_stride + k * column_stride] -= m[icol * row_stride + k * column_stride] * temp;
}
}
}
}
for (i = size-1; i >= 0; --i)
{
if (indxr[i] != indxc[i])
{
for (j = 0; j < size; ++j)
{
temp = m[j * row_stride + indxr[i] * column_stride];
m[j * row_stride + indxr[i] * column_stride] = m[j * row_stride + indxc[i] * column_stride];
m[j * row_stride + indxc[i] * column_stride] = temp;
}
}
}
}
OS_FNEXP void matrix_invert( mat4x4 *out, const mat4x4 *in )
{
if (out != in) *out = *in;
matrix_invert( &(*out)[0][0], 4, 4, 1 );
}
OS_FNEXP void matrix_invert( mat4x3 *out, const mat4x3 *in )
{
mat4x4 temp = *in;
matrix_invert( &temp[0][0], 4, 4, 1 );
*out = temp;
}
OS_FNEXP void matrix_invert( mat3x3 *out, const mat3x3 *in )
{
if (out != in) *out = *in;
matrix_invert( &(*out)[0][0], 3, 4, 1 );
}
OS_FNEXP void matrix_mul( mat4x4 *out, const mat4x4 *left, const mat4x4 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]) + (left->m[3][0] * right->m[0][3]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]) + (left->m[3][1] * right->m[0][3]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]) + (left->m[3][2] * right->m[0][3]);
out->m[0][3] = (left->m[0][3] * right->m[0][0]) + (left->m[1][3] * right->m[0][1]) + (left->m[2][3] * right->m[0][2]) + (left->m[3][3] * right->m[0][3]);
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]) + (left->m[3][0] * right->m[1][3]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]) + (left->m[3][1] * right->m[1][3]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]) + (left->m[3][2] * right->m[1][3]);
out->m[1][3] = (left->m[0][3] * right->m[1][0]) + (left->m[1][3] * right->m[1][1]) + (left->m[2][3] * right->m[1][2]) + (left->m[3][3] * right->m[1][3]);
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]) + (left->m[3][0] * right->m[2][3]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]) + (left->m[3][1] * right->m[2][3]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]) + (left->m[3][2] * right->m[2][3]);
out->m[2][3] = (left->m[0][3] * right->m[2][0]) + (left->m[1][3] * right->m[2][1]) + (left->m[2][3] * right->m[2][2]) + (left->m[3][3] * right->m[2][3]);
out->m[3][0] = (left->m[0][0] * right->m[3][0]) + (left->m[1][0] * right->m[3][1]) + (left->m[2][0] * right->m[3][2]) + (left->m[3][0] * right->m[3][3]);
out->m[3][1] = (left->m[0][1] * right->m[3][0]) + (left->m[1][1] * right->m[3][1]) + (left->m[2][1] * right->m[3][2]) + (left->m[3][1] * right->m[3][3]);
out->m[3][2] = (left->m[0][2] * right->m[3][0]) + (left->m[1][2] * right->m[3][1]) + (left->m[2][2] * right->m[3][2]) + (left->m[3][2] * right->m[3][3]);
out->m[3][3] = (left->m[0][3] * right->m[3][0]) + (left->m[1][3] * right->m[3][1]) + (left->m[2][3] * right->m[3][2]) + (left->m[3][3] * right->m[3][3]);
}
OS_FNEXP void matrix_mul( mat4x4 *out, const mat4x4 *left, const mat4x3 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]) + (left->m[3][0] * right->m[0][3]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]) + (left->m[3][1] * right->m[0][3]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]) + (left->m[3][2] * right->m[0][3]);
out->m[0][3] = (left->m[0][3] * right->m[0][0]) + (left->m[1][3] * right->m[0][1]) + (left->m[2][3] * right->m[0][2]) + (left->m[3][3] * right->m[0][3]);
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]) + (left->m[3][0] * right->m[1][3]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]) + (left->m[3][1] * right->m[1][3]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]) + (left->m[3][2] * right->m[1][3]);
out->m[1][3] = (left->m[0][3] * right->m[1][0]) + (left->m[1][3] * right->m[1][1]) + (left->m[2][3] * right->m[1][2]) + (left->m[3][3] * right->m[1][3]);
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]) + (left->m[3][0] * right->m[2][3]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]) + (left->m[3][1] * right->m[2][3]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]) + (left->m[3][2] * right->m[2][3]);
out->m[2][3] = (left->m[0][3] * right->m[2][0]) + (left->m[1][3] * right->m[2][1]) + (left->m[2][3] * right->m[2][2]) + (left->m[3][3] * right->m[2][3]);
out->m[3][0] = left->m[3][0];
out->m[3][1] = left->m[3][1];
out->m[3][2] = left->m[3][2];
out->m[3][3] = left->m[3][3];
}
OS_FNEXP void matrix_mul( mat4x4 *out, const mat4x4 *left, const mat3x3 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[0][3] = (left->m[0][3] * right->m[0][0]) + (left->m[1][3] * right->m[0][1]) + (left->m[2][3] * right->m[0][2]);
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[1][3] = (left->m[0][3] * right->m[1][0]) + (left->m[1][3] * right->m[1][1]) + (left->m[2][3] * right->m[1][2]);
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
out->m[2][3] = (left->m[0][3] * right->m[2][0]) + (left->m[1][3] * right->m[2][1]) + (left->m[2][3] * right->m[2][2]);
out->m[3][0] = left->m[3][0];
out->m[3][1] = left->m[3][1];
out->m[3][2] = left->m[3][2];
out->m[3][3] = left->m[3][3];
}
OS_FNEXP void matrix_mul( mat4x4 *out, const mat4x3 *left, const mat4x4 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[0][3] = (left->m[0][3] * right->m[0][0]) + (left->m[1][3] * right->m[0][1]) + (left->m[2][3] * right->m[0][2]) + right->m[0][3];
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[1][3] = (left->m[0][3] * right->m[1][0]) + (left->m[1][3] * right->m[1][1]) + (left->m[2][3] * right->m[1][2]) + right->m[1][3];
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
out->m[2][3] = (left->m[0][3] * right->m[2][0]) + (left->m[1][3] * right->m[2][1]) + (left->m[2][3] * right->m[2][2]) + right->m[2][3];
out->m[3][0] = (left->m[0][0] * right->m[3][0]) + (left->m[1][0] * right->m[3][1]) + (left->m[2][0] * right->m[3][2]);
out->m[3][1] = (left->m[0][1] * right->m[3][0]) + (left->m[1][1] * right->m[3][1]) + (left->m[2][1] * right->m[3][2]);
out->m[3][2] = (left->m[0][2] * right->m[3][0]) + (left->m[1][2] * right->m[3][1]) + (left->m[2][2] * right->m[3][2]);
out->m[3][3] = (left->m[0][3] * right->m[3][0]) + (left->m[1][3] * right->m[3][1]) + (left->m[2][3] * right->m[3][2]) + right->m[3][3];
}
OS_FNEXP void matrix_mul( mat4x3 *out, const mat4x3 *left, const mat4x3 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[0][3] = (left->m[0][3] * right->m[0][0]) + (left->m[1][3] * right->m[0][1]) + (left->m[2][3] * right->m[0][2]) + right->m[0][3];
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[1][3] = (left->m[0][3] * right->m[1][0]) + (left->m[1][3] * right->m[1][1]) + (left->m[2][3] * right->m[1][2]) + right->m[1][3];
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
out->m[2][3] = (left->m[0][3] * right->m[2][0]) + (left->m[1][3] * right->m[2][1]) + (left->m[2][3] * right->m[2][2]) + right->m[2][3];
}
OS_FNEXP void matrix_mul( mat4x3 *out, const mat4x3 *left, const mat3x3 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[0][3] = (left->m[0][3] * right->m[0][0]) + (left->m[1][3] * right->m[0][1]) + (left->m[2][3] * right->m[0][2]);
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[1][3] = (left->m[0][3] * right->m[1][0]) + (left->m[1][3] * right->m[1][1]) + (left->m[2][3] * right->m[1][2]);
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
out->m[2][3] = (left->m[0][3] * right->m[2][0]) + (left->m[1][3] * right->m[2][1]) + (left->m[2][3] * right->m[2][2]);
}
OS_FNEXP void matrix_mul( mat4x4 *out, const mat3x3 *left, const mat4x4 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[0][3] = right->m[0][3];
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[1][3] = right->m[1][3];
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
out->m[2][3] = right->m[2][3];
out->m[3][0] = (left->m[0][0] * right->m[3][0]) + (left->m[1][0] * right->m[3][1]) + (left->m[2][0] * right->m[3][2]);
out->m[3][1] = (left->m[0][1] * right->m[3][0]) + (left->m[1][1] * right->m[3][1]) + (left->m[2][1] * right->m[3][2]);
out->m[3][2] = (left->m[0][2] * right->m[3][0]) + (left->m[1][2] * right->m[3][1]) + (left->m[2][2] * right->m[3][2]);
out->m[3][3] = right->m[3][3];
}
OS_FNEXP void matrix_mul( mat4x3 *out, const mat3x3 *left, const mat4x3 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[0][3] = right->m[0][3];
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[1][3] = right->m[1][3];
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
out->m[2][3] = right->m[2][3];
}
OS_FNEXP void matrix_mul( mat3x3 *out, const mat3x3 *left, const mat3x3 *right )
{
MATH3D_ASSERT( (char *)left >= (char *)out + sizeof(*out) || (char *)out >= (char *)left + sizeof(*left) );
MATH3D_ASSERT( (char *)right >= (char *)out + sizeof(*out) || (char *)out >= (char *)right + sizeof(*right) );
out->m[0][0] = (left->m[0][0] * right->m[0][0]) + (left->m[1][0] * right->m[0][1]) + (left->m[2][0] * right->m[0][2]);
out->m[0][1] = (left->m[0][1] * right->m[0][0]) + (left->m[1][1] * right->m[0][1]) + (left->m[2][1] * right->m[0][2]);
out->m[0][2] = (left->m[0][2] * right->m[0][0]) + (left->m[1][2] * right->m[0][1]) + (left->m[2][2] * right->m[0][2]);
out->m[1][0] = (left->m[0][0] * right->m[1][0]) + (left->m[1][0] * right->m[1][1]) + (left->m[2][0] * right->m[1][2]);
out->m[1][1] = (left->m[0][1] * right->m[1][0]) + (left->m[1][1] * right->m[1][1]) + (left->m[2][1] * right->m[1][2]);
out->m[1][2] = (left->m[0][2] * right->m[1][0]) + (left->m[1][2] * right->m[1][1]) + (left->m[2][2] * right->m[1][2]);
out->m[2][0] = (left->m[0][0] * right->m[2][0]) + (left->m[1][0] * right->m[2][1]) + (left->m[2][0] * right->m[2][2]);
out->m[2][1] = (left->m[0][1] * right->m[2][0]) + (left->m[1][1] * right->m[2][1]) + (left->m[2][1] * right->m[2][2]);
out->m[2][2] = (left->m[0][2] * right->m[2][0]) + (left->m[1][2] * right->m[2][1]) + (left->m[2][2] * right->m[2][2]);
}
void fprint_matrix( FILE *f, const mat3x3 &m )
{
for (int i = 0; i < 3; ++i)
{
fprintf( f, "\n " );
for (int j = 0; j < 3; ++j)
{
fprintf( f, "%10.5f", m[j][i] );
}
}
fprintf( f, "\n" );
}
void fprint_matrix( FILE *f, const mat4x3 &m )
{
for (int i = 0; i < 4; ++i)
{
fprintf( f, "\n " );
for (int j = 0; j < 3; ++j)
{
fprintf( f, "%10.5f", m[j][i] );
}
}
fprintf( f, "\n" );
}
void fprint_matrix( FILE *f, const mat4x4 &m )
{
for (int i = 0; i < 4; ++i)
{
fprintf( f, "\n " );
for (int j = 0; j < 4; ++j)
{
fprintf( f, "%10.5f", m[j][i] );
}
}
fprintf( f, "\n" );
}
OS_FNEXP void factor_matrix( vec3 *out_scale, quat *out_orient, vec3 *out_offset, const mat4x3 &in )
{
int i;
vec3 scale;
mat4x3 m = in;
for (i = 0; i < 3; ++i)
{
double s = sqrt( in[0][i] * in[0][i] + in[1][i] * in[1][i] + in[2][i] * in[2][i] );
scale[i] = (float)s;
m[0][i] = (float)(in[0][i] / s);
m[1][i] = (float)(in[1][i] / s);
m[2][i] = (float)(in[2][i] / s);
}
if (out_scale) *out_scale = scale;
if (out_orient)
{
*out_orient = m;
mat3x3 test_m(*out_orient);
}
if (out_offset)
{
for (i = 0; i < 3; ++i)
{
(*out_offset)[i] = m[i][3];
}
}
}
OS_FNEXP void make_orthonormal( float *m, int size, int column_stride, int row_stride );
OS_FNEXP void make_orthonormal( float *m, int size, int column_stride, int row_stride )
{
int i, j, k;
for (i = 0; i < size; ++i)
{
// make othogonal to earlier columns
for (j = 0; j < i; ++j)
{
// compute the dot product of columns j and i. note that column j is normalized
float proj = 0.0f;
for (k = 0; k < size; ++k)
{
proj += m[(i*column_stride) + (k*row_stride)] * m[(j*column_stride) + (k*row_stride)];
}
// subtract out the projection of column j onto column i
for (k = 0; k < size; ++k)
{
m[(i*column_stride) + (k*row_stride)] -= proj * m[(j*column_stride) + (k*row_stride)];
}
}
// normalize column i
float len = 0.0f;
for (j = 0; j < size; ++j)
{
len += m[(i*column_stride) + (j*row_stride)] * m[(i*column_stride) + (j*row_stride)];
}
float n = 1.0f / sqrtf(len);
for (j = 0; j < size; ++j)
{
m[(i*column_stride) + (j*row_stride)] *= n;
}
}
}
| 39.442623 | 154 | 0.494437 | joeriedel |
37c6f073046f522293840ddcc5e4216519ae3012 | 4,715 | cpp | C++ | test/source/game_state_unit_tests.cpp | ahelwer/pason2012 | 9e7d76589c3a9c81adc9b37e8770239b346801c0 | [
"MIT"
] | 1 | 2020-09-15T05:48:22.000Z | 2020-09-15T05:48:22.000Z | test/source/game_state_unit_tests.cpp | ahelwer/pason2012 | 9e7d76589c3a9c81adc9b37e8770239b346801c0 | [
"MIT"
] | 4 | 2019-07-03T17:06:25.000Z | 2019-07-03T17:06:45.000Z | test/source/game_state_unit_tests.cpp | ahelwer/pason2012 | 9e7d76589c3a9c81adc9b37e8770239b346801c0 | [
"MIT"
] | null | null | null | #include <test/game_state_unit_tests.hpp>
#include <model/tetromino.hpp>
#include <util/constants.hpp>
#include <util/vector.hpp>
#include <iostream>
CPPUNIT_TEST_SUITE_REGISTRATION(GameStateUnitTests);
void GameStateUnitTests::setUp() {
m_pState = new GameState();
}
void GameStateUnitTests::tearDown() {
if (m_pState != NULL) {
delete m_pState;
m_pState = NULL;
}
}
void GameStateUnitTests::TestInit() {
CPPUNIT_ASSERT(m_pState->GetPieceInPlay() == NULL);
std::vector<int> const& last = m_pState->LastClearedRows();
int lastSize = last.size();
CPPUNIT_ASSERT_EQUAL(0, lastSize);
CPPUNIT_ASSERT_EQUAL(-1, m_pState->GetCurrentPieceNumber());
CPPUNIT_ASSERT(!m_pState->WasRowClearEvent());
CPPUNIT_ASSERT(!m_pState->PieceHasChanged());
}
void GameStateUnitTests::TestAssignment() {
GameState a;
Tetromino t ('O', 0, 5, COLS-2);
a.SetPieceInPlay(&t);
std::vector<Tetromino> queue;
queue.push_back(t);
a.SetQueueInPlay(queue);
std::vector<int> cleared;
cleared.push_back(0);
a.SetLastClearedRows(cleared);
a.SetCurrentPieceNumber(4);
GameState b = a;
CPPUNIT_ASSERT(b == a);
}
void GameStateUnitTests::TestApplyMove() {
Tetromino t ('I', 0, 2, ROWS-1);
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftUp();
t.ShiftUp();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftDown();
t.ShiftDown();
t.ShiftRight();
t.ShiftRight();
t.ShiftUp();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftUp();
t.ShiftUp();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftDown();
t.ShiftDown();
t.ShiftDown();
t.ShiftRight();
t.ShiftRight();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftUp();
t.ShiftUp();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftDown();
t.ShiftDown();
t.ShiftRight();
t.ShiftRight();
t.RotateRight();
t.ShiftUp();
t.ShiftUp();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(0, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
t.ShiftRight();
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT_EQUAL(2, m_pState->ApplyMove(t));
CPPUNIT_ASSERT(m_pState->LastPiecePlayed() == t);
std::vector<int> const& cleared = m_pState->LastClearedRows();
CPPUNIT_ASSERT_EQUAL(ROWS-3, cleared.at(0));
CPPUNIT_ASSERT_EQUAL(ROWS-1, cleared.at(1));
}
void GameStateUnitTests::TestFeedFromQueue() {
Tetromino t1 ('I', 0, 5, 1);
Tetromino t2 ('S', 0, 5, 1);
std::vector<Tetromino> queue;
queue.push_back(t1);
queue.push_back(t2);
CPPUNIT_ASSERT_EQUAL(0, m_pState->QueuedPieceCount());
m_pState->SetQueueInPlay(queue);
CPPUNIT_ASSERT_EQUAL(2, m_pState->QueuedPieceCount());
CPPUNIT_ASSERT(m_pState->GetPieceInPlay() == NULL);
CPPUNIT_ASSERT(!m_pState->FeedFromQueue(-1));
CPPUNIT_ASSERT(!m_pState->FeedFromQueue(2));
CPPUNIT_ASSERT(m_pState->FeedFromQueue(0));
CPPUNIT_ASSERT(m_pState->GetPieceInPlay() != NULL);
CPPUNIT_ASSERT(*(m_pState->GetPieceInPlay()) == t1);
CPPUNIT_ASSERT_EQUAL(2, m_pState->QueuedPieceCount());
CPPUNIT_ASSERT(m_pState->FeedFromQueue(1));
CPPUNIT_ASSERT(m_pState->GetPieceInPlay() != NULL);
CPPUNIT_ASSERT(*(m_pState->GetPieceInPlay()) == t2);
CPPUNIT_ASSERT_EQUAL(2, m_pState->QueuedPieceCount());
}
void GameStateUnitTests::TestEventMethods() {
// Tests piece number methods
m_pState->SetCurrentPieceNumber(3);
CPPUNIT_ASSERT(m_pState->PieceHasChanged());
CPPUNIT_ASSERT(!m_pState->PieceHasChanged());
m_pState->SetCurrentPieceNumber(3);
CPPUNIT_ASSERT(!m_pState->PieceHasChanged());
Tetromino t ('T', 0, 5, 1);
m_pState->SetPieceInPlay(&t);
CPPUNIT_ASSERT(m_pState->GetPieceInPlay() != NULL);
m_pState->SetCurrentPieceNumber(-1);
CPPUNIT_ASSERT(m_pState->GetPieceInPlay() == NULL);
// Tests row clearing events
CPPUNIT_ASSERT(!m_pState->WasRowClearEvent());
m_pState->SetRowClearEvent();
CPPUNIT_ASSERT(m_pState->WasRowClearEvent());
CPPUNIT_ASSERT(!m_pState->WasRowClearEvent());
}
| 32.517241 | 66 | 0.68526 | ahelwer |
37c78d02abb275b9a1ce9a4790d8e4b2f8db64df | 1,999 | hh | C++ | Framework/AbsModuleMemento.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | Framework/AbsModuleMemento.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | Framework/AbsModuleMemento.hh | brownd1978/FastSim | 05f590d72d8e7f71856fd833114a38b84fc7fd48 | [
"Apache-2.0"
] | null | null | null | //--------------------------------------------------------------------------
// File and Version Information:
// $Id: AbsModuleMemento.hh 509 2010-01-14 15:18:55Z stroili $
//
// Description:
// Class AbsModuleMemento. Abstract base class for Memento classes
// Do not use this for Template class (foo<T>). use TemplateTemplate.hh
// instead.
//
// Environment:
// Software developed for the BaBar Detector at the SLAC B-Factory.
//
// Author List:
// Akbar Mokhtarani originator
// <Author2> <originator/contributor etc.>
//
// Copyright Information:
// Copyright (C) 1998 LBNL
//
//------------------------------------------------------------------------
#ifndef ABSMODULEMEMENTO_HH
#define ABSMODULEMEMENTO_HH
//-------------
// C Headers --
//-------------
extern "C" {
}
//---------------
// C++ Headers --
//---------------
//----------------------
// Base Class Headers --
//----------------------
//-------------------------------
// Collaborating Class Headers --
//-------------------------------
#include "Framework/AppExecutable.hh"
//------------------------------------
// Collaborating Class Declarations --
//------------------------------------
#include <iosfwd>
// ---------------------
// -- Class Interface --
// ---------------------
class AbsModuleMemento {
public:
// Constructors
AbsModuleMemento(AppExecutable* theExec);
// Destructor
virtual ~AbsModuleMemento( );
// Operators
virtual void Dump(std::ostream&)const = 0;
virtual void Dump_tcl(std::ostream&)const = 0;
const char* name() const { return _theExec->name();}
AppExecutable::ExecType exectype() const { return _theExec->execType();}
bool isEnabled() const {return _theExec->isEnabled();}
AppExecutable* exec() const {return _theExec;}
private:
// Not implemented.
AbsModuleMemento( const AbsModuleMemento& );
AbsModuleMemento& operator=( const AbsModuleMemento& );
AppExecutable* _theExec;
};
#endif // ABSMODULEMEMENTO_HH
| 23.517647 | 77 | 0.533267 | brownd1978 |
37c9772c6ca09ef7c9f20fb3a952c0c76bb4f79e | 928 | cpp | C++ | src/classes/socket/ClientTCPSocket.cpp | thibautcornolti/plazza | 253b0dd9f76179aa2ef7e98050fcb7c2bc6c4b25 | [
"MIT"
] | null | null | null | src/classes/socket/ClientTCPSocket.cpp | thibautcornolti/plazza | 253b0dd9f76179aa2ef7e98050fcb7c2bc6c4b25 | [
"MIT"
] | null | null | null | src/classes/socket/ClientTCPSocket.cpp | thibautcornolti/plazza | 253b0dd9f76179aa2ef7e98050fcb7c2bc6c4b25 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2018
** cpp_plazza
** File description:
** ClientTCPSocket
*/
#include "ClientTCPSocket.hpp"
ClientTCPSocket::ClientTCPSocket() : TCPSocket()
{
}
ClientTCPSocket::ClientTCPSocket(const std::string &host, int port)
: TCPSocket()
{
ClientTCPSocket::connect(host, port);
}
ClientTCPSocket::ClientTCPSocket(int fd) : TCPSocket(fd)
{
}
ClientTCPSocket::~ClientTCPSocket()
{
close();
}
bool ClientTCPSocket::connect(const std::string &host, int port)
{
struct sockaddr_in addr;
struct addrinfo req;
struct addrinfo *ret = 0;
memset(&req, 0, sizeof(req));
req.ai_family = AF_INET;
req.ai_socktype = SOCK_STREAM;
if (getaddrinfo(host.c_str(), 0, &req, &ret) != 0 || ret == 0)
return false;
addr = *(struct sockaddr_in *)ret->ai_addr;
addr.sin_port = htons(port);
addr.sin_family = AF_INET;
if (::connect(_socket, (const sockaddr *)&addr, sizeof(addr)) != 0)
return false;
return true;
}
| 19.744681 | 68 | 0.700431 | thibautcornolti |
37ca07a23fb9693304bb70cde961086de5536e1d | 1,505 | cpp | C++ | source/plugin/squarexorx4/squarexor.cpp | lostjared/acidcamGL | dbd06c24bfc4a0b1afc137e906f1a9a9cb98a14b | [
"BSD-2-Clause"
] | 12 | 2020-06-29T03:58:26.000Z | 2022-01-15T17:03:16.000Z | source/plugin/squarexorx4/squarexor.cpp | lostjared/acidcamGL | dbd06c24bfc4a0b1afc137e906f1a9a9cb98a14b | [
"BSD-2-Clause"
] | 1 | 2020-11-05T01:51:58.000Z | 2020-12-14T18:20:54.000Z | source/plugin/squarexorx4/squarexor.cpp | lostjared/acidcamGL | dbd06c24bfc4a0b1afc137e906f1a9a9cb98a14b | [
"BSD-2-Clause"
] | 3 | 2020-02-27T18:27:45.000Z | 2021-08-18T01:24:52.000Z | #include"ac.h"
#include<cstdlib>
#include<ctime>
extern "C" void filter(cv::Mat &frame) {
static double alpha = 1.0;
for(int z = 0; z < frame.rows-4; z += 3) {
for(int i = 0; i < frame.cols-4; i += 3) {
if(i+1 < frame.cols && z+1 < frame.rows) {
cv::Vec3b source = frame.at<cv::Vec3b>(z, i);
cv::Vec3b *colors[] = {
&frame.at<cv::Vec3b>(z, i),
&frame.at<cv::Vec3b>(z, i+1),
&frame.at<cv::Vec3b>(z+1, i),
&frame.at<cv::Vec3b>(z+1, i+1)
};
cv::Vec3b total;
for(int q = 0; q < 4; ++q) {
for(int j = 0; j < 3; ++j)
total[j] += (*colors[q])[j];
}
for(int q = 0; q < 4; ++q) {
for(int j = 0; j < 3; ++j) {
(*colors[q])[j] ^= static_cast<unsigned char>(alpha*total[j]);
// (*colors[q])[j] = static_cast<unsigned char>((0.5 * source[j]) + (0.5 * (*colors[q])[j]));
}
}
}
static int dir = 1;
if(dir == 1) {
alpha += 0.05;
if(alpha > 25)
dir = 0;
} else {
alpha -= 0.05;
if(alpha <= 1.0)
dir = 1;
}
}
}
}
| 32.021277 | 116 | 0.322259 | lostjared |
37caa01c67b60d9dc807fc724d2a41b71d96f253 | 811 | cpp | C++ | SmallPetsHealthcare/AmbentController.cpp | mihotoyama/doingio-small-pets-healthcare | 94f88e8ce10265a022cbc2c75554b9819f335cc6 | [
"Apache-2.0"
] | 6 | 2020-09-26T02:31:46.000Z | 2022-03-17T07:20:08.000Z | SmallPetsHealthcare/AmbentController.cpp | mihotoyama/doingio-small-pets-healthcare | 94f88e8ce10265a022cbc2c75554b9819f335cc6 | [
"Apache-2.0"
] | 1 | 2020-10-06T07:20:34.000Z | 2020-10-06T07:20:34.000Z | SmallPetsHealthcare/AmbentController.cpp | mihotoyama/doingio-small-pets-healthcare | 94f88e8ce10265a022cbc2c75554b9819f335cc6 | [
"Apache-2.0"
] | 3 | 2020-10-02T16:04:24.000Z | 2021-12-11T00:16:53.000Z | #include "AmbentController.h"
void AmbentController::setup(DayDataModel *_dayDataRef, int channelid, char *writekey, WiFiClient *wclient)
{
dayDataRef = _dayDataRef;
if(channelid >= 0)
{
Serial.print("ambient setup");
const char* cwriteKey = writekey;
int b = ambient.begin(channelid, cwriteKey, wclient);
Serial.println(b);
}else
{
isEnable = false;
}
}
void AmbentController::send()
{
if(!isEnable) return;
Serial.print("ambient send:");
ambient.set(1, dayDataRef->sensorsValue[0]);
ambient.set(2, dayDataRef->sensorsValue[1]);
ambient.set(3, dayDataRef->sensorsValue[2]);
ambient.set(4, dayDataRef->sensorsValue[3]);
ambient.set(5, dayDataRef->sensorsValue[4]);
ambient.set(6, dayDataRef->sensorsValue[5]);
bool b = ambient.send();
Serial.println(b);
}
| 25.34375 | 107 | 0.694205 | mihotoyama |
56cbd8c0aee4ca2b1a04dbfd6b30f6eda17af25b | 323 | cpp | C++ | WBF/src/WBF_DATA/ModuleElement.cpp | heesok2/OpenGL | 6ba159a77428635bf73eab9a0080203b248b015c | [
"MIT"
] | null | null | null | WBF/src/WBF_DATA/ModuleElement.cpp | heesok2/OpenGL | 6ba159a77428635bf73eab9a0080203b248b015c | [
"MIT"
] | null | null | null | WBF/src/WBF_DATA/ModuleElement.cpp | heesok2/OpenGL | 6ba159a77428635bf73eab9a0080203b248b015c | [
"MIT"
] | 1 | 2019-11-25T02:03:08.000Z | 2019-11-25T02:03:08.000Z | #include "stdafx.h"
#include "ModuleElement.h"
#include "EntityDefine.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
CModuleElement::CModuleElement(CPackage * pPackage)
: CModuleData<CEntityElement>(pPackage, E_TYPE_ELEMENT)
{
}
CModuleElement::~CModuleElement()
{
}
| 17 | 56 | 0.770898 | heesok2 |
56d6349b11bb21c869c0258aa3f8e3bc3572c2bf | 1,486 | hpp | C++ | src/feata-gui/gui/wgt/basewidgetgeomsel.hpp | master-clown/ofeata | 306cbc3a402551fb62b3925d23a2d4f63f60d525 | [
"MIT"
] | 1 | 2021-08-30T13:51:42.000Z | 2021-08-30T13:51:42.000Z | src/feata-gui/gui/wgt/basewidgetgeomsel.hpp | master-clown/ofeata | 306cbc3a402551fb62b3925d23a2d4f63f60d525 | [
"MIT"
] | null | null | null | src/feata-gui/gui/wgt/basewidgetgeomsel.hpp | master-clown/ofeata | 306cbc3a402551fb62b3925d23a2d4f63f60d525 | [
"MIT"
] | 1 | 2021-08-30T13:51:35.000Z | 2021-08-30T13:51:35.000Z | #pragma once
#include "gui/wgt/basewidget.hpp"
#include "geom/geom_ent_type.hpp"
namespace gui::wgt
{
class BaseWidgetGeomSel
: public BaseWidget
{
public:
BaseWidgetGeomSel(QWidget* parent = nullptr);
virtual void SetGeomSelType(const geom::GeomEntityType geom_type);
virtual bool GetSelectionState() const;
virtual geom::GeomEntityType GetGeomSelType() const;
public slots:
virtual void SetSelectionState(const bool is_on);
signals:
/**
* \brief SelectionToggled
* Emit it every time the selection is toggled.
*/
void SelectionToggled(const bool is_on);
protected:
bool selection_state_ = false;
geom::GeomEntityType geom_type_ = geom::GEOM_ENT_TYPE_INVALID;
private:
Q_OBJECT
using Base = BaseWidget;
};
}
// impl
namespace gui::wgt
{
inline BaseWidgetGeomSel::BaseWidgetGeomSel(QWidget* parent)
: BaseWidget(parent)
{}
inline void BaseWidgetGeomSel::SetSelectionState(const bool is_on) { selection_state_ = is_on; }
inline void BaseWidgetGeomSel::SetGeomSelType(const geom::GeomEntityType geom_type)
{ geom_type_ = geom_type; }
inline bool BaseWidgetGeomSel::GetSelectionState() const { return selection_state_; }
inline geom::GeomEntityType BaseWidgetGeomSel::GetGeomSelType() const
{ return geom_type_; }
}
| 26.070175 | 101 | 0.653432 | master-clown |
56d93b499e9c428f2504811b1da595c4bb1f885b | 2,910 | cpp | C++ | Real-Time Corruptor/BizHawk_RTC/lynx/rom.cpp | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 1,414 | 2015-06-28T09:57:51.000Z | 2021-10-14T03:51:10.000Z | Real-Time Corruptor/BizHawk_RTC/lynx/rom.cpp | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 2,369 | 2015-06-25T01:45:44.000Z | 2021-10-16T08:44:18.000Z | Real-Time Corruptor/BizHawk_RTC/lynx/rom.cpp | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 430 | 2015-06-29T04:28:58.000Z | 2021-10-05T18:24:17.000Z | //
// Copyright (c) 2004 K. Wilkins
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from
// the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
//////////////////////////////////////////////////////////////////////////////
// Handy - An Atari Lynx Emulator //
// Copyright (c) 1996,1997 //
// K. Wilkins //
//////////////////////////////////////////////////////////////////////////////
// ROM emulation class //
//////////////////////////////////////////////////////////////////////////////
// //
// This class emulates the system ROM (512B), the interface is pretty //
// simple: constructor, reset, peek, poke. //
// //
// K. Wilkins //
// August 1997 //
// //
//////////////////////////////////////////////////////////////////////////////
// Revision History: //
// ----------------- //
// //
// 01Aug1997 KW Document header added & class documented. //
// //
//////////////////////////////////////////////////////////////////////////////
#include "system.h"
#include "rom.h"
CRom::CRom(const uint8 *romfile, uint32 length)
{
//mWriteEnable = false;
Reset();
std::memset(mRomData, DEFAULT_ROM_CONTENTS, ROM_SIZE);
std::memcpy(mRomData, romfile, std::min<uint32>(ROM_SIZE, length));
}
void CRom::Reset(void)
{
}
SYNCFUNC(CRom)
{
//NSS(mWriteEnable);
//NSS(mRomData);
}
| 43.432836 | 78 | 0.390378 | redscientistlabs |
56daed38cdd38fa0f2c902776411b848bdc1e0fc | 4,254 | cpp | C++ | SelectionDialog.cpp | Landgraf132/ScreenTranslator | fa894604666baaa5426057015cc181be93a62785 | [
"MIT"
] | null | null | null | SelectionDialog.cpp | Landgraf132/ScreenTranslator | fa894604666baaa5426057015cc181be93a62785 | [
"MIT"
] | null | null | null | SelectionDialog.cpp | Landgraf132/ScreenTranslator | fa894604666baaa5426057015cc181be93a62785 | [
"MIT"
] | null | null | null | #include "SelectionDialog.h"
#include "ui_SelectionDialog.h"
#include "LanguageHelper.h"
#include "StAssert.h"
#include <QMouseEvent>
#include <QPainter>
#include <QDebug>
#include <QMenu>
SelectionDialog::SelectionDialog (const LanguageHelper &dictionary, QWidget *parent) :
QDialog (parent),
ui (new Ui::SelectionDialog), dictionary_ (dictionary),
languageMenu_ (new QMenu), swapLanguagesAction_ (NULL) {
ui->setupUi (this);
setWindowFlags (Qt::FramelessWindowHint | Qt::NoDropShadowWindowHint |
Qt::WindowStaysOnTopHint | Qt::X11BypassWindowManagerHint);
ui->label->setAutoFillBackground (false);
ui->label->installEventFilter (this);
applySettings ();
}
SelectionDialog::~SelectionDialog () {
delete languageMenu_;
delete ui;
}
void SelectionDialog::applySettings () {
dictionary_.updateMenu (languageMenu_, dictionary_.availableOcrLanguagesUi ());
if (!languageMenu_->isEmpty ()) {
swapLanguagesAction_ = languageMenu_->addAction (tr ("Поменять язык текста и перевода"));
}
}
bool SelectionDialog::eventFilter (QObject *object, QEvent *event) {
if (object != ui->label) {
return QDialog::eventFilter (object, event);
}
if (event->type () == QEvent::Show) {
startSelectPos_ = currentSelectPos_ = QPoint ();
}
else if (event->type () == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event);
if ((mouseEvent->button () == Qt::LeftButton ||
mouseEvent->button () == Qt::RightButton) && startSelectPos_.isNull ()) {
startSelectPos_ = mouseEvent->pos ();
}
}
else if (event->type () == QEvent::MouseMove) {
QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event);
if ((mouseEvent->buttons () & Qt::LeftButton ||
mouseEvent->buttons () & Qt::RightButton) && !startSelectPos_.isNull ()) {
currentSelectPos_ = mouseEvent->pos ();
ui->label->repaint ();
}
}
else if (event->type () == QEvent::Paint) {
QRect selection = QRect (startSelectPos_, currentSelectPos_).normalized ();
if (selection.isValid ()) {
QPainter painter (ui->label);
painter.setPen (Qt::red);
painter.drawRect (selection);
}
}
else if (event->type () == QEvent::MouseButtonRelease) {
QMouseEvent *mouseEvent = static_cast <QMouseEvent *> (event);
if (mouseEvent->button () == Qt::LeftButton ||
mouseEvent->button () == Qt::RightButton) {
if (startSelectPos_.isNull () || currentPixmap_.isNull ()) {
return QDialog::eventFilter (object, event);
}
QPoint endPos = mouseEvent->pos ();
QRect selection = QRect (startSelectPos_, endPos).normalized ();
startSelectPos_ = currentSelectPos_ = QPoint ();
QPixmap selectedPixmap = currentPixmap_.copy (selection);
if (selectedPixmap.width () < 3 || selectedPixmap.height () < 3) {
reject ();
return QDialog::eventFilter (object, event);
}
ProcessingItem item;
item.source = selectedPixmap;
item.screenPos = pos () + selection.topLeft ();
item.modifiers = mouseEvent->modifiers ();
if (mouseEvent->button () == Qt::RightButton &&
!languageMenu_->children ().isEmpty ()) {
QAction *action = languageMenu_->exec (QCursor::pos ());
if (action == NULL) {
reject ();
return QDialog::eventFilter (object, event);
}
if (action == swapLanguagesAction_) {
item.swapLanguages_ = true;
}
else {
item.ocrLanguage = dictionary_.ocrUiToCode (action->text ());
ST_ASSERT (!item.ocrLanguage.isEmpty ());
item.sourceLanguage = dictionary_.ocrToTranslateCodes (item.ocrLanguage);
ST_ASSERT (!item.sourceLanguage.isEmpty ());
}
}
emit selected (item);
}
}
return QDialog::eventFilter (object, event);
}
void SelectionDialog::setPixmap (QPixmap pixmap, const QRect &showGeometry) {
ST_ASSERT (!pixmap.isNull ());
ST_ASSERT (!showGeometry.isEmpty ());
currentPixmap_ = pixmap;
QPalette palette = this->palette ();
palette.setBrush (this->backgroundRole (), pixmap);
this->setPalette (palette);
this->setGeometry (showGeometry);
show ();
activateWindow ();
}
| 34.585366 | 93 | 0.649741 | Landgraf132 |
56e1376d70867d0a2d08e92bea404630f986a9f5 | 4,894 | cpp | C++ | src/Drawing.cpp | karjonas/ld35 | e6ea8334199bd636bde16412a642ba2f94756211 | [
"MIT"
] | 2 | 2021-09-03T12:33:58.000Z | 2021-12-26T12:44:20.000Z | src/Drawing.cpp | karjonas/ld35 | e6ea8334199bd636bde16412a642ba2f94756211 | [
"MIT"
] | null | null | null | src/Drawing.cpp | karjonas/ld35 | e6ea8334199bd636bde16412a642ba2f94756211 | [
"MIT"
] | null | null | null | #include "Drawing.h"
#include "GlobalState.h"
#include "allegro5/allegro.h"
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <vector>
#include <algorithm>
struct ShapePoints
{
std::vector<Point> points;
ALLEGRO_COLOR color;
int mid_x;
};
struct LineColor
{
LineColor(Point p0_in, Point p1_in, ALLEGRO_COLOR color_in)
: p0(p0_in), p1(p1_in), color(color_in) {}
Point p0;
Point p1;
ALLEGRO_COLOR color;
};
void Drawing::draw_user(int w, int h, User& user)
{
std::vector<Point> points;
if (user.user_shape == Shape::TRIANGLE)
points = calc_user_triangle_points(user.user_x, h/2, false, user.rect_size);
else
points = calc_user_rectangle_points(user.user_x, h/2, false, user.rect_size);
points.insert(points.begin(), Point(100,h/2));
points.push_back(Point(w-100,h/2));
const size_t num_pts = points.size();
for (int i = 0; i < num_pts - 1; i++)
{
auto fst = points[i];
auto snd = points[i+1];
al_draw_line(fst.x, fst.y, snd.x, snd.y, ColorScheme::color0(), 1.0f);
}
}
void Drawing::draw_opponent(int /* w */, int h, Opponent& opponent)
{
std::vector<Point> points;
if (opponent.shape == Shape::TRIANGLE)
points = calc_user_triangle_points(opponent.x, h/2, false, opponent.rect_size);
else
points = calc_user_rectangle_points(opponent.x, h/2, false, opponent.rect_size);
const size_t num_pts = points.size();
for (int i = 0; i < num_pts - 1; i++)
{
auto fst = points[i];
auto snd = points[i+1];
al_draw_line(fst.x, fst.y, snd.x, snd.y, opponent.is_shapeshifter ? ColorScheme::color0() : ColorScheme::color1(), 1.0f);
}
}
void Drawing::draw_tutorial_texts(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y, double time)
{
if (time < 2.0 && time < 3.5)
al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Welcome!");
else if (time > 4.0 && time < 9.5)
al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Move using arrow keys.");
else if (time > 10.0 && time < 16.5)
{
al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Collide with a same color shape");
al_draw_text(font, color, x, y + 30, ALLEGRO_ALIGN_CENTRE, "to morph into it.");
}
else if (time > 17.0 && time < 23.5)
{
al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Collide with same shape to kill it.");
}
else if (time > 24.0 && time < 30)
{
al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Collide with another shape and ");
al_draw_text(font, color, x, y + 30, ALLEGRO_ALIGN_CENTRE, "color and it kills you!");
}
}
void Drawing::draw_score_texts(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y, int score)
{
al_draw_textf(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Score: %d", score);
}
void Drawing::draw_level_texts(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y, int level, double time)
{
if (time < 3)
al_draw_textf(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Level %d", level);
}
void Drawing::draw_credits(ALLEGRO_FONT* font, ALLEGRO_COLOR color, int x, int y)
{
al_draw_text(font, color, x, y, ALLEGRO_ALIGN_CENTRE, "Thanks for playing!");
}
void Drawing::draw_all(int w, int h, User& user, const std::vector<Opponent>& opponents)
{
std::vector<ShapePoints> sps;
{
std::vector<Point> points =
calc_shape_points(user.user_x, h/2, false, user.rect_size, user.user_shape);
ShapePoints p;
p.color = ColorScheme::color0();
p.mid_x = user.user_x;
p.points = points;
sps.push_back(p);
}
for (auto& opponent : opponents)
{
if (!opponent.active)
continue;
std::vector<Point> points =
calc_shape_points(opponent.x, h/2, false, opponent.rect_size, opponent.shape);
ShapePoints p;
p.color = opponent.is_shapeshifter ? ColorScheme::color0() : ColorScheme::color1();
p.mid_x = opponent.x;
p.points = points;
sps.push_back(p);
}
std::sort(sps.begin(), sps.end(), [](const auto& sp0,const auto& sp1)
{
return sp0.mid_x < sp1.mid_x;
});
std::vector<LineColor> lcs;
auto last_pt = Point(100,h/2);
for (auto& sp : sps)
{
lcs.emplace_back(last_pt, sp.points[0], ColorScheme::color0());
const int nums = static_cast<int>(sp.points.size()) - 1;
for (int i = 0; i < nums; i++)
{
lcs.emplace_back(sp.points[i], sp.points[i+1], sp.color);
}
last_pt = sp.points.back();
}
lcs.emplace_back(last_pt, Point(w-100, h/2), ColorScheme::color0());
for (auto& lc : lcs)
{
auto fst = lc.p0;
auto snd = lc.p1;
al_draw_line(fst.x, fst.y, snd.x, snd.y, lc.color, 1.0f);
}
}
| 29.305389 | 125 | 0.62076 | karjonas |
56e26e15b2781256469ba26b3a0551893914d35c | 975 | hpp | C++ | include/gkom/ShaderLoader.hpp | akowalew/mill-opengl | 91ef11e6cdbfe691e0073d9883e42c0a29d29b45 | [
"MIT"
] | null | null | null | include/gkom/ShaderLoader.hpp | akowalew/mill-opengl | 91ef11e6cdbfe691e0073d9883e42c0a29d29b45 | [
"MIT"
] | null | null | null | include/gkom/ShaderLoader.hpp | akowalew/mill-opengl | 91ef11e6cdbfe691e0073d9883e42c0a29d29b45 | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <unordered_map>
#include <vector>
#include <string_view>
namespace gkom {
//! Forward declarations
class GraphicsManager;
class Logger;
class ShaderLoader
{
public:
ShaderLoader(GraphicsManager& graphicsManager);
unsigned int loadShaderProgram(std::string_view vertexShaderName,
std::string_view fragmentShaderName);
private:
unsigned int makeShaderProgram(std::string_view vertexShaderName,
std::string_view fragmentShaderName);
std::string loadShaderCode(std::string_view name);
std::string getShaderPath(std::string_view name);
unsigned int findShaderProgram(std::string_view vertexShaderName,
std::string_view fragmentShaderName) const;
std::unordered_map<
std::string /*vertexShaderName*/,
std::unordered_map<
std::string /*fragmentShaderName*/,
unsigned int /*shaderProgram*/
>
> shaderPrograms_;
GraphicsManager& graphicsManager_;
Logger& logger_;
};
} // gkom
| 21.195652 | 66 | 0.754872 | akowalew |
56e466326b75fbd4a90de96bbf77cb6ac88668c7 | 2,125 | cpp | C++ | test/basic4.cpp | armos-db/libpaxos-cpp | 31e8a3f9664e3e6563d26dbc1323457f596b8eef | [
"BSD-3-Clause"
] | 54 | 2015-02-09T11:46:30.000Z | 2021-08-13T14:08:52.000Z | test/basic4.cpp | armos-db/libpaxos-cpp | 31e8a3f9664e3e6563d26dbc1323457f596b8eef | [
"BSD-3-Clause"
] | null | null | null | test/basic4.cpp | armos-db/libpaxos-cpp | 31e8a3f9664e3e6563d26dbc1323457f596b8eef | [
"BSD-3-Clause"
] | 17 | 2015-01-13T03:18:49.000Z | 2022-03-23T02:20:57.000Z | /*!
Tests whether the quorum will properly handle a dead node and it coming alive in a later stadium,
including a proper catch up.
*/
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <paxos++/client.hpp>
#include <paxos++/server.hpp>
#include <paxos++/configuration.hpp>
#include <paxos++/detail/util/debug.hpp>
int main ()
{
uint16_t calls = 0;
uint16_t response_count = 0;
paxos::server::callback_type callback =
[& response_count](int64_t, std::string const &) -> std::string
{
++response_count;
return "bar";
};
paxos::server server1 ("127.0.0.1", 1337, callback);
paxos::server server2 ("127.0.0.1", 1338, callback);
paxos::client client;
server1.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
server2.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
client.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
PAXOS_DEBUG ("response_count = " << response_count);
calls = 7;
PAXOS_ASSERT_EQ (response_count, 2 * calls);
paxos::server server3 ("127.0.0.1", 1339, callback);
server3.add ({{"127.0.0.1", 1337}, {"127.0.0.1", 1338}, {"127.0.0.1", 1339}});
/*!
Let's wait a few seconds for 3 handshakes to occur
*/
boost::this_thread::sleep (
boost::posix_time::milliseconds (
paxos::configuration ().timeout ()));
do
{
PAXOS_ASSERT_EQ (client.send ("foo").get (), "bar");
++calls;
} while (response_count != 3 * calls && calls < 50);
PAXOS_ASSERT_EQ (response_count, 3 * calls);
PAXOS_INFO ("test succeeded");
}
| 31.25 | 100 | 0.585412 | armos-db |
56e6c51577d68c2427821b8aa06715c7acfb538f | 18,164 | cpp | C++ | Backups/DxGuiFramework - 17.2.01/DGGraphics.cpp | Maultasche/SeniorProject | 1bdb3c5e5d2298906f361af6fdda79438a56cb7c | [
"MIT"
] | null | null | null | Backups/DxGuiFramework - 17.2.01/DGGraphics.cpp | Maultasche/SeniorProject | 1bdb3c5e5d2298906f361af6fdda79438a56cb7c | [
"MIT"
] | null | null | null | Backups/DxGuiFramework - 17.2.01/DGGraphics.cpp | Maultasche/SeniorProject | 1bdb3c5e5d2298906f361af6fdda79438a56cb7c | [
"MIT"
] | null | null | null | /*------------------------------------------------------------------------
File Name: DGGraphics.h
Description: This file contains the DGGraphics class implementation,
which manages the DirectDraw surfaces and controls and what is drawn
to the screen.
Version:
1.0.0 10.02.2000 Created the file
------------------------------------------------------------------------*/
#include "DxGuiFramework.h"
DGGraphics::DGGraphics()
{
OutputDebugString("DGGraphics constructor\n");
hWnd = DGGetApp()->GetWindowsHandle();
//Initialize DirectDraw object
HRESULT result = DirectDrawCreateEx(NULL, (void**)&lpDD,
IID_IDirectDraw7, NULL);
if(result != DD_OK)
HandleDDrawError(EC_DDINIT, result, __FILE__, __LINE__);
//Set the cooperative level.
result = lpDD->SetCooperativeLevel(hWnd, DDSCL_ALLOWREBOOT | DDSCL_EXCLUSIVE |
DDSCL_FULLSCREEN);
if(result != DD_OK)
HandleDDrawError(EC_DDINIT, result, __FILE__, __LINE__);
//Get the hardware capabilities
ddCaps.dwSize = sizeof(DDCAPS);
result = lpDD->GetCaps(&ddCaps, NULL);
SetGraphicsMode(DGPoint(640, 480), WS_WINDOWED, CD_16BIT, BT_SINGLE);
}
DGGraphics::~DGGraphics()
{
OutputDebugString("DGGraphics destructor\n");
lpDD->Release();
lpDD = NULL;
}
void DGGraphics::Initialize()
{
}
void DGGraphics::SetGraphicsMode(DGPoint res, UINT winState, UINT clrDepth,
UINT bufferMode)
{
screenRes.x = res.x;
screenRes.y = res.y;
windowedState = winState;
HWND desktopWindow;
int desktopClrDepth;
//If we are switching to windowed mode, we need to question the desktop
//about its color depth
if(windowedState == WS_WINDOWED)
{
desktopWindow = GetDesktopWindow();
HDC desktopDC = GetDC(desktopWindow);
desktopClrDepth = GetDeviceCaps(desktopDC, BITSPIXEL);
ReleaseDC(desktopWindow, desktopDC);
}
if(clrDepth == CD_16BIT)
{
}
else
colorDepth = clrDepth;
UINT appColorDepth = clrDepth;
//UINT bufferingMode;
}
void DGGraphics::HandleDDrawError(UINT errorCode, HRESULT error,
char* fileName, UINT lineNumber)
{
if(error == DD_OK)
return;
char errorText[512];
switch(error)
{
case DDERR_ALREADYINITIALIZED:
strcpy(errorText, "DirectDraw object has already been initialized.");
break;
case DDERR_BLTFASTCANTCLIP:
strcpy(errorText, "BltFast() cannot be used with a surface "\
"that has a DirectDrawClipper object attached.");
break;
case DDERR_CANNOTATTACHSURFACE:
strcpy(errorText, "The surface cannot be attached.");
break;
case DDERR_CANNOTDETACHSURFACE:
strcpy(errorText, "The surface cannot be detached.");
break;
case DDERR_CANTCREATEDC:
strcpy(errorText, "The Windows device context could not be "\
"created.");
break;
case DDERR_CANTDUPLICATE:
strcpy(errorText, "This surface cannot be duplicated.");
break;
case DDERR_CANTLOCKSURFACE:
strcpy(errorText, "The surface cannot be locked.");
break;
case DDERR_CANTPAGELOCK:
strcpy(errorText, "Page lock failed.");
break;
case DDERR_CANTPAGEUNLOCK:
strcpy(errorText, "Page unlock failed.");
break;
case DDERR_CLIPPERISUSINGHWND:
strcpy(errorText, "The clip list could not be added, as the "\
"DirectDrawClipper object is already monitoring a window "\
"handle.");
break;
case DDERR_COLORKEYNOTSET:
strcpy(errorText, "No source color key has been set");
break;
case DDERR_CURRENTLYNOTAVAIL:
strcpy(errorText, "No support is currently available for this "\
"operation");
break;
case DDERR_DDSCAPSCOMPLEXREQUIRED:
strcpy(errorText, "This surface needs to be a complex surface");
break;
case DDERR_DCALREADYCREATED:
strcpy(errorText, "A device context has already been created for "\
"this surface");
break;
case DDERR_DEVICEDOESNTOWNSURFACE:
strcpy(errorText, "This surface is owned by another DirectDraw device "\
"and cannot be used");
break;
case DDERR_DIRECTDRAWALREADYCREATED:
strcpy(errorText, "A DirectDraw object representing this driver has "\
"already been created.");
break;
case DDERR_EXCEPTION:
strcpy(errorText, "An exception was encountered while performing "\
"the requested operation.");
break;
case DDERR_EXCLUSIVEMODEALREADYSET:
strcpy(errorText, "Exclusive mode has already been set.");
break;
case DDERR_EXPIRED:
strcpy(errorText, "The data has expired and is invalid.");
break;
case DDERR_GENERIC:
strcpy(errorText, "An undefined error condition has occurred.");
break;
case DDERR_HEIGHTALIGN:
strcpy(errorText, "The height of the provided rectangle is not a "\
"multiple of the required alignment.");
break;
case DDERR_HWNDALREADYSET:
strcpy(errorText, "The cooperative-level window handle has already been "\
"set.");
break;
case DDERR_HWNDSUBCLASSED:
strcpy(errorText, "DirectDraw cannot restore because the DirectDraw "\
"cooperative-level window handle has been subclassed.");
break;
case DDERR_IMPLICITLYCREATED:
strcpy(errorText, "Surface cannot be restored because it was implicitly "\
"created");
break;
case DDERR_INCOMPATIBLEPRIMARY:
strcpy(errorText, "The primary surface creation request does not match "\
"the existing primary surface.");
break;
case DDERR_INVALIDCAPS:
strcpy(errorText, "One or more of the capability bits passed to the "\
"callback function are incorrect.");
break;
case DDERR_INVALIDCLIPLIST:
strcpy(errorText, "DirectDraw does not support the provided clip list.");
break;
case DDERR_INVALIDDIRECTDRAWGUID:
strcpy(errorText, "The provided GUID is an invalid DirectDraw GUID");
break;
case DDERR_INVALIDMODE:
strcpy(errorText, "DirectDraw does not support the requested mode.");
break;
case DDERR_INVALIDOBJECT:
strcpy(errorText, "DirectDraw received a pointer to an invalid object.");
break;
case DDERR_INVALIDPARAMS:
strcpy(errorText, "One or more parameters passed to this method are "\
"incorrect.");
break;
case DDERR_INVALIDPIXELFORMAT:
strcpy(errorText, "The specified pixel format was invalid.");
break;
case DDERR_INVALIDPOSITION:
strcpy(errorText, "The position of the overlay on the destination is "\
"no longer legal.");
break;
case DDERR_INVALIDRECT:
strcpy(errorText, "The provided rectangle was invalid.");
break;
case DDERR_INVALIDSTREAM:
strcpy(errorText, "The specified stream contains invalid data.");
break;
case DDERR_INVALIDSURFACETYPE:
strcpy(errorText, "The surface was of the wrong type.");
break;
case DDERR_LOCKEDSURFACES:
strcpy(errorText, "This operation failed due to a locked surface.");
break;
case DDERR_MOREDATA:
strcpy(errorText, "There is more data available than the specified buffer "\
"can hold.");
break;
case DDERR_NO3D:
strcpy(errorText, "No 3-D hardware or emulation is present.");
break;
case DDERR_NOALPHAHW:
strcpy(errorText, "No alpha-acceleration hardware is present or available.");
break;
case DDERR_NOBLTHW:
strcpy(errorText, "No blitter hardware is present.");
break;
case DDERR_NOCLIPLIST:
strcpy(errorText, "No clip list is available.");
break;
case DDERR_NOCLIPPERATTACHED:
strcpy(errorText, "No DirectDrawClipper is attached to the surface.");
break;
case DDERR_NOCOLORCONVHW:
strcpy(errorText, "No color-conversion hardware is present or available.");
break;
case DDERR_NOCOLORKEY:
strcpy(errorText, "The surface does not currently have a color key.");
break;
case DDERR_NOCOLORKEYHW:
strcpy(errorText, "There is no hardware support for the destination color "\
"key.");
break;
case DDERR_NOCOOPERATIVELEVELSET:
strcpy(errorText, "No cooperative level had been set.");
break;
case DDERR_NODC:
strcpy(errorText, "No device context exists for this surface.");
break;
case DDERR_NODDROPSHW:
strcpy(errorText, "No DirectDraw raster-operation (ROP) hardware is"\
"available.");
break;
case DDERR_NODIRECTDRAWHW:
strcpy(errorText, "Hardware-only DirectDraw creation not possible.");
break;
case DDERR_NODIRECTDRAWSUPPORT:
strcpy(errorText, "DirectDraw support is not possible with the current"\
"display driver.");
break;
case DDERR_NODRIVERSUPPORT:
strcpy(errorText, "Testing cannot proceed due to no display driver support.");
break;
case DDERR_NOEMULATION:
strcpy(errorText, "Software emulation not available.");
break;
case DDERR_NOEXCLUSIVEMODE:
strcpy(errorText, "This operation requires the application to have "\
"exclusive mode.");
break;
case DDERR_NOFLIPHW:
strcpy(errorText, "Flipping visible surfaces not supported.");
break;
case DDERR_NOFOCUSWINDOW:
strcpy(errorText, "Cannot create or set a device window without having "\
"first set the focus window.");
break;
case DDERR_NOGDI:
strcpy(errorText, "No GDI is present.");
break;
case DDERR_NOHWND:
strcpy(errorText, "No cooperative-level window handle.");
break;
case DDERR_NOMIPMAPHW:
strcpy(errorText, "No mipmap-capable texture mapping hardware is present "\
"or available.");
break;
case DDERR_NOMIRRORHW:
strcpy(errorText, "No mirroring hardware is present of available.");
break;
case DDERR_NOMONITORINFORMATION:
strcpy(errorText, "No monitor information exists.");
break;
case DDERR_NONONLOCALVIDMEM:
strcpy(errorText, "No nonlocal video memory is available.");
break;
case DDERR_NOOPTIMIZEHW:
strcpy(errorText, "Optimized surfaces not supported.");
break;
case DDERR_NOOVERLAYDEST:
strcpy(errorText, "Overlay is not a destination.");
break;
case DDERR_NOOVERLAYHW:
strcpy(errorText, "No overlay hardware present or available.");
break;
case DDERR_NOPALETTEATTACHED:
strcpy(errorText, "No palette object is attached to the surface.");
break;
case DDERR_NOPALETTEHW:
strcpy(errorText, "No hardware support for 16- or 256-color palettes.");
break;
case DDERR_NORASTEROPHW:
strcpy(errorText, "No appropriate raster-operation hardware is present "\
" or available.");
break;
case DDERR_NOROTATIONHW:
strcpy(errorText, "No rotation hardware is present or available.");
break;
case DDERR_NOSTEREOHARDWARE:
strcpy(errorText, "No stereo hardware is present or available.");
break;
case DDERR_NOSTRETCHHW:
strcpy(errorText, "No hardware support for stretching.");
break;
case DDERR_NOSURFACELEFT:
strcpy(errorText, "No hardware that supports stereo surfaces.");
break;
case DDERR_NOT4BITCOLOR:
strcpy(errorText, "This operation requires a 4-bit color palette.");
break;
case DDERR_NOT4BITCOLORINDEX:
strcpy(errorText, "This operation requires a 4-bit color *index* palette.");
break;
case DDERR_NOT8BITCOLOR:
strcpy(errorText, "This operation requires an 8-bit color palette.");
break;
case DDERR_NOTAOVERLAYSURFACE:
strcpy(errorText, "Not an overlay surface.");
break;
case DDERR_NOTEXTUREHW:
strcpy(errorText, "No texture-mapping hardware is present or available.");
break;
case DDERR_NOTFLIPPABLE:
strcpy(errorText, "This surface cannot be flipped.");
break;
case DDERR_NOTFOUND:
strcpy(errorText, "The requested item was not found.");
break;
case DDERR_NOTINITIALIZED:
strcpy(errorText, "DirectDraw object has not been initialized.");
break;
case DDERR_NOTLOADED:
strcpy(errorText, "Surface has not been allocated any memory.");
break;
case DDERR_NOTLOCKED:
strcpy(errorText, "Surface was not locked.");
break;
case DDERR_NOTPAGELOCKED:
strcpy(errorText, "Surface was not page-locked.");
break;
case DDERR_NOTPALETTIZED:
strcpy(errorText, "Surface is not palette-based.");
break;
case DDERR_NOVSYNCHW:
strcpy(errorText, "There is no hardware support for vertical blank or "\
"synchronized operations.");
break;
case DDERR_NOZBUFFERHW:
strcpy(errorText, "There is no z-buffer hardware support.");
break;
case DDERR_NOZOVERLAYHW:
strcpy(errorText, "Overlay surfaces cannot be z-layered: no hardware "\
"support.");
break;
case DDERR_OUTOFCAPS:
strcpy(errorText, "The hardware needed for this operation has already "\
"been allocated.");
break;
case DDERR_OUTOFMEMORY:
strcpy(errorText, "There is not enough memory to perform this operation.");
break;
case DDERR_OUTOFVIDEOMEMORY:
strcpy(errorText, "There is not enough *display* memory to perform this "\
"operation.");
break;
case DDERR_OVERLAPPINGRECTS:
strcpy(errorText, "Source and destination rectangles are on the same "\
"surface and overlap each other.");
break;
case DDERR_OVERLAYCANTCLIP:
strcpy(errorText, "The hardware does not support clipped overlays.");
break;
case DDERR_OVERLAYCOLORKEYONLYONEACTIVE:
strcpy(errorText, "Only one color key can be active on an overlay.");
break;
case DDERR_OVERLAYNOTVISIBLE :
strcpy(errorText, "The specified overlay is hidden.");
break;
case DDERR_PALETTEBUSY:
strcpy(errorText, "The palette is busy.");
break;
case DDERR_PRIMARYSURFACEALREADYEXISTS:
strcpy(errorText, "A primary surface already exists.");
break;
case DDERR_REGIONTOOSMALL:
strcpy(errorText, "The specified clip region is too small.");
break;
case DDERR_SURFACEALREADYATTACHED:
strcpy(errorText, "The surface was already attached.");
break;
case DDERR_SURFACEALREADYDEPENDENT:
strcpy(errorText, "The surface was already dependent.");
break;
case DDERR_SURFACEBUSY:
strcpy(errorText, "The surface is busy.");
break;
case DDERR_SURFACEISOBSCURED:
strcpy(errorText, "Access to surface denied: surface is obscured.");
break;
case DDERR_SURFACELOST:
strcpy(errorText, "The surface had been lost: it must be restored.");
break;
case DDERR_SURFACENOTATTACHED:
strcpy(errorText, "The requested surface is not attached.");
break;
case DDERR_TOOBIGHEIGHT:
strcpy(errorText, "The requested height is too large.");
break;
case DDERR_TOOBIGSIZE:
strcpy(errorText, "The requested size is too large.");
break;
case DDERR_TOOBIGWIDTH:
strcpy(errorText, "The requested width is too large.");
break;
case DDERR_UNSUPPORTED:
strcpy(errorText, "This operation is not supported.");
break;
case DDERR_UNSUPPORTEDFORMAT:
strcpy(errorText, "The pixel format is not supported by DirectDraw.");
break;
case DDERR_UNSUPPORTEDMASK:
strcpy(errorText, "The bitmask in the pixel format is not supported by "\
"DirectDraw.");
break;
case DDERR_UNSUPPORTEDMODE:
strcpy(errorText, "The display is currently in an unsupported mode.");
break;
case DDERR_VERTICALBLANKINPROGRESS:
strcpy(errorText, "A vertical blank is in progress.");
break;
case DDERR_VIDEONOTACTIVE:
strcpy(errorText, "The video port is not active.");
break;
case DDERR_WASSTILLDRAWING:
strcpy(errorText, "The operation was still drawing.");
break;
case DDERR_WRONGMODE:
strcpy(errorText, "This surface cannot be restored: it was created in "\
"a different mode.");
break;
case DDERR_XALIGN:
strcpy(errorText, "The rectangle was not horizontally aligned on a "\
"required boundary.");
break;
default:
strcpy(errorText, "Unknown Error");
break;
}
throw(new DGException(errorText, errorCode, ET_DIRECTDRAW, fileName,
lineNumber));
}
| 37.451546 | 88 | 0.609998 | Maultasche |
56ec4a59ede740735759a7b7a5e5195c78e13b84 | 1,960 | cpp | C++ | ToyRenderer/src/Audio/AudioEngine.cpp | IRCSS/ToyRenderer | 39b919a99cae47f9da34229b427958ea720d98d0 | [
"MIT"
] | 40 | 2020-03-19T20:05:22.000Z | 2022-03-27T07:52:38.000Z | ToyRenderer/src/Audio/AudioEngine.cpp | IRCSS/ToyRenderer | 39b919a99cae47f9da34229b427958ea720d98d0 | [
"MIT"
] | null | null | null | ToyRenderer/src/Audio/AudioEngine.cpp | IRCSS/ToyRenderer | 39b919a99cae47f9da34229b427958ea720d98d0 | [
"MIT"
] | 5 | 2021-09-25T01:32:25.000Z | 2021-11-18T13:42:18.000Z | #include "AudioEngine.h"
#include "vendor/soloud/soloud.h"
#include "Audio/AudioClip.h"
#include "vendor/soloud/soloud_wav.h"
#include "Components/Transform.h"
#include "log/Log.h"
namespace ToyRenderer {
AudioEngine* AudioEngine::m_pSingelton = nullptr;
AudioEngine::AudioEngine() : m_soLoudBackend(nullptr)
{
SoLoud::Soloud::FLAGS flags = static_cast<SoLoud::Soloud::FLAGS>(static_cast<int>(SoLoud::Soloud::FLAGS::CLIP_ROUNDOFF) | static_cast<int>(SoLoud::Soloud::FLAGS::LEFT_HANDED_3D));
m_soLoudBackend = new SoLoud::Soloud; // object created
m_soLoudBackend->init(flags); // back-end initialization
}
AudioEngine::~AudioEngine()
{
m_soLoudBackend->deinit(); // Clean up!
delete m_soLoudBackend;
}
void AudioEngine::OnUpdate(float deltaTime)
{
m_soLoudBackend->update3dAudio();
}
int AudioEngine::Play(AudioClip* toPlay)
{
return m_soLoudBackend->play(toPlay->GetBackEndAudioSourceHandel());
}
int AudioEngine::Play(AudioClip * toPlay, const Transform * transform)
{
int handel = m_soLoudBackend->play3d(toPlay->GetBackEndAudioSourceHandel(), transform->position.x, transform->position.y, transform->position.z);
m_soLoudBackend->set3dSourceAttenuation(handel, 1, 1);
return handel;
}
void AudioEngine::SetAudioListner(const Transform * listnerTransform)
{
m_soLoudBackend->set3dListenerPosition(listnerTransform->position.x , listnerTransform->position.y , listnerTransform->position.z );
m_soLoudBackend->set3dListenerAt (listnerTransform->Foward().x , listnerTransform->Foward().y , listnerTransform->Foward().z );
m_soLoudBackend->set3dListenerUp (listnerTransform->Up().x , listnerTransform->Up().y , listnerTransform->Up().z );
}
AudioEngine & AudioEngine::Instance()
{
if (!m_pSingelton) m_pSingelton = new AudioEngine();
return *m_pSingelton;
}
void AudioEngine::Clear()
{
delete m_pSingelton;
m_pSingelton = nullptr;
}
}
| 29.253731 | 181 | 0.729082 | IRCSS |
56f65353c1b604263049631bc31f9b911eef7970 | 1,608 | cpp | C++ | tests/api/evaluator/debug.cpp | SalusaSecondus/homomorphic-implementors-toolkit | b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b | [
"Apache-2.0"
] | 38 | 2020-12-02T12:43:16.000Z | 2022-03-15T19:27:39.000Z | tests/api/evaluator/debug.cpp | SalusaSecondus/homomorphic-implementors-toolkit | b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b | [
"Apache-2.0"
] | 15 | 2020-12-03T05:04:12.000Z | 2021-08-20T21:26:27.000Z | tests/api/evaluator/debug.cpp | SalusaSecondus/homomorphic-implementors-toolkit | b7775b77cb0ff4ff42a1b47bf958bb0e3c75fb9b | [
"Apache-2.0"
] | 6 | 2021-01-06T18:37:00.000Z | 2021-09-20T06:43:13.000Z | // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
#include <iostream>
#include "../../testutil.h"
#include "gtest/gtest.h"
#include "hit/hit.h"
using namespace std;
using namespace hit;
// Test variables.
const int RANGE = 16;
const int NUM_OF_SLOTS = 4096;
const int ONE_MULTI_DEPTH = 1;
const int LOG_SCALE = 30;
TEST(DebugTest, Serialization) {
DebugEval ckks_instance1 = DebugEval(NUM_OF_SLOTS, ONE_MULTI_DEPTH, LOG_SCALE);
// serialize instance to files
stringstream paramsStream(ios::in | ios::out | ios::binary);
stringstream galoisKeyStream(ios::in | ios::out | ios::binary);
stringstream relinKeyStream(ios::in | ios::out | ios::binary);
stringstream secretKeyStream(ios::in | ios::out | ios::binary);
ckks_instance1.save(paramsStream, galoisKeyStream, relinKeyStream, secretKeyStream);
DebugEval ckks_instance2 = DebugEval(paramsStream, galoisKeyStream, relinKeyStream, secretKeyStream);
vector<double> vector_input = random_vector(NUM_OF_SLOTS, RANGE);
CKKSCiphertext ciphertext = ckks_instance2.encrypt(vector_input);
ckks_instance2.square_inplace(ciphertext);
ckks_instance2.relinearize_inplace(ciphertext);
ckks_instance2.rescale_to_next_inplace(ciphertext);
vector<double> vector_output = ckks_instance2.decrypt(ciphertext);
vector<double> expected_output(NUM_OF_SLOTS);
transform(vector_input.begin(), vector_input.end(), vector_input.begin(), expected_output.begin(), multiplies<>());
ASSERT_LE(relative_error(expected_output, vector_output), MAX_NORM);
}
| 39.219512 | 119 | 0.758085 | SalusaSecondus |
56fcf68c14a83e2d81bcf4fc60c0157e0e6f41ff | 2,910 | cpp | C++ | liblumi/sources/Bmp.cpp | Rertsyd/LumiRT | d562fd786f769b385bc051e2ea8bcd26162a9dc6 | [
"MIT"
] | null | null | null | liblumi/sources/Bmp.cpp | Rertsyd/LumiRT | d562fd786f769b385bc051e2ea8bcd26162a9dc6 | [
"MIT"
] | null | null | null | liblumi/sources/Bmp.cpp | Rertsyd/LumiRT | d562fd786f769b385bc051e2ea8bcd26162a9dc6 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* ,, */
/* `7MMF' db `7MM"""Mq. MMP""MM""YMM */
/* MM MM `MM.P' MM `7 */
/* MM `7MM `7MM `7MMpMMMb.pMMMb. `7MM MM ,M9 MM */
/* MM MM MM MM MM MM MM MMmmdM9 MM */
/* MM , MM MM MM MM MM MM MM YM. MM */
/* MM ,M MM MM MM MM MM MM MM `Mb. MM */
/* .JMMmmmmMMM `Mbod"YML..JMML JMML JMML..JMML..JMML. .JMM. .JMML. */
/* */
/* ************************************************************************** */
#include <fstream>
#include "Bmp.hpp"
Bmp::Bmp() : FHeader(), IHeader(), Data(nullptr)
{
memset(&FHeader, 0u, sizeof(FHeader));
memset(&IHeader, 0u, sizeof(InfoHeader));
}
void Bmp::InitHeader(const uint32_t width, const uint32_t height)
{
IHeader.Size = 40u;
IHeader.Width = width;
IHeader.Height = height;
IHeader.Planes = 1u;
IHeader.BitCount = 24u;
IHeader.SizeImage = width * height * (IHeader.BitCount / 8u);
Data.reset(new uint8_t[IHeader.SizeImage]);
memset(Data.get(), 0x00u, IHeader.SizeImage);
FHeader[0] = 'B';
FHeader[1] = 'M';
// OffBits
FHeader[10] = static_cast<uint8_t>(54u);
// Size
const uint32_t sz = IHeader.SizeImage + FHeader[10];
FHeader[2] = sz & 0xFFu;
FHeader[3] = (sz >> 8u) & 0xFFu;
FHeader[4] = (sz >> 16u) & 0xFFu;
FHeader[5] = (sz >> 24u) & 0xFFu;
}
void Bmp::Save(const char* path)
{
std::ofstream ofs(path, std::ios::binary);
ofs.write(reinterpret_cast<char*>(FHeader), sizeof(FHeader));
ofs.write(reinterpret_cast<char*>(&IHeader), sizeof(InfoHeader));
const uint32_t bytesPerPixel = IHeader.BitCount / 8u;
const uint32_t sizeLine = IHeader.Width * bytesPerPixel;
const uint32_t padding = (4u - ((3u * IHeader.Width) % 4u)) % 4u;
const char paddingData[4] = { 0x00, 0x00, 0x00, 0x00 };
for (uint32_t i = 0; i < IHeader.Height; ++i)
{
const uint8_t* ptr = &(Data.get()[(sizeLine * (IHeader.Height - i - 1u))]);
ofs.write(reinterpret_cast<const char*>(ptr), sizeof(uint8_t) * sizeLine);
ofs.write(paddingData, padding);
}
ofs.close();
}
void Bmp::PutPixel(const uVec2 coord, const RGBColor clr) const
{
const uint32_t bytesPerPixel = IHeader.BitCount / 8u;
const uint32_t sizeLine = IHeader.Width * bytesPerPixel;
const uint32_t id = ((coord.y * sizeLine) + coord.x * bytesPerPixel);
Data.get()[id + 2] = (clr.red >= 255.) ? 255u : static_cast<uint8_t>(clr.red);
Data.get()[id + 1] = (clr.green >= 255.) ? 255u : static_cast<uint8_t>(clr.green);
Data.get()[id] = (clr.blue >= 255.) ? 255u : static_cast<uint8_t>(clr.blue);
}
| 35.060241 | 83 | 0.521993 | Rertsyd |
56fcfdbb0ae5310cd0986c36752dd5a390749e89 | 619 | cpp | C++ | MeetingCodes/Meeting3/Main.cpp | SubhoB/spectre-cpp-basics | 0f581b879e83e88d1491b31e22aa447419d471a3 | [
"MIT"
] | 15 | 2020-06-01T19:48:57.000Z | 2021-11-01T07:33:42.000Z | MeetingCodes/Meeting3/Main.cpp | SubhoB/spectre-cpp-basics | 0f581b879e83e88d1491b31e22aa447419d471a3 | [
"MIT"
] | 1 | 2020-06-02T02:43:41.000Z | 2020-06-02T03:55:50.000Z | MeetingCodes/Meeting3/Main.cpp | SubhoB/spectre-cpp-basics | 0f581b879e83e88d1491b31e22aa447419d471a3 | [
"MIT"
] | 6 | 2020-06-23T22:36:56.000Z | 2021-06-14T14:46:49.000Z | #include <iomanip>
#include <iostream>
#include "Rectangle.hpp"
int main() {
const Rectangle rect{4.0, 3.0};
Rectangle rect2{5.0, 6.0};
double x{4.0};
std::cout << std::setprecision(15) << std::fixed;
std::cout << "Width of rect: " << rect.width() << "\n";
std::cout << "Width of height: " << rect.height() << "\n";
std::cout << "Perimeter of rect: " << rect.perimeter() << "\n";
std::cout << "Perimeter of rect2: " << rect2.evil_perimeter() << "\n";
std::cout << "Perimeter of rect2: " << rect2.evil_perimeter() << "\n";
std::cout << "Number of sides: " << rect.number_of_sides() << "\n";
}
| 26.913043 | 72 | 0.576737 | SubhoB |
71045a5127c78b16379afa0ea5c27e8be27cafa8 | 4,913 | cpp | C++ | Source/WinWakerLib/codec.cpp | bingart/WinWaker | dc3f6c067a5f215c17aa2e0c3386f92f158ec941 | [
"Apache-2.0"
] | null | null | null | Source/WinWakerLib/codec.cpp | bingart/WinWaker | dc3f6c067a5f215c17aa2e0c3386f92f158ec941 | [
"Apache-2.0"
] | null | null | null | Source/WinWakerLib/codec.cpp | bingart/WinWaker | dc3f6c067a5f215c17aa2e0c3386f92f158ec941 | [
"Apache-2.0"
] | null | null | null |
#include <windows.h>
#include <io.h>
#include <string>
#include "scrambler.h"
#include "base64.h"
#include "codec.h"
#include "easylog.hpp"
#include "libstr.h"
#include "key.h"
#define MAX_CODEC_LENGTH 20480000
#define MOD 13
BOOL Encode(const char* exe_file_path, const char* txt_file_path)
{
FILE* in = NULL;
FILE* out = NULL;
int rc = -1;
do
{
in = fopen(exe_file_path, "rb");
if (in == NULL)
{
// "encode file fail, open exe file %s error\n"
EasyLog::Format(GetLibStrById(401), exe_file_path);
break;
}
out = fopen(txt_file_path, "w");
if (out == NULL)
{
// "encode file fail, open txt file %s error\n"
EasyLog::Format(GetLibStrById(402), txt_file_path);
break;
}
// Write KEY at fist line
// "%d\n"
fprintf(out, GetLibStrById(552), KEY);
char ibuffer[BLOCK_SIZE];
char obuffer[2*BLOCK_SIZE];
rc = 0;
while (!feof(in) && rc >= 0)
{
memset(ibuffer, 0, sizeof ibuffer);
memset(obuffer, 0, sizeof obuffer);
size_t len = fread(ibuffer, 1, BLOCK_SIZE, in);
if (len > 0)
{
// encrypt
for (size_t i = 0; i < len; i++)
{
ibuffer[i] = ibuffer[i] ^ (i % MOD) ^ KEY;
}
// convert to base64
rc = encode64(obuffer, sizeof obuffer, ibuffer, len);
if (rc > 0)
{
// write into txt file
// "%s\n"
fprintf(out, GetLibStrById(403), obuffer);
}
else if (rc == 0)
{
// "encode file, encode64 rc %d\n"
EasyLog::Format(GetLibStrById(404), rc);
}
else
{
// "encode file fails, encode64 rc %d < 0\n"
EasyLog::Format(GetLibStrById(405), rc);
break;
}
}
}
}
while (FALSE);
// close files
if (in != NULL) fclose(in);
if (out != NULL)
{
_commit(_fileno(out));
fclose(out);
}
return rc >= 0;
}
BOOL Decode(const char* txt_file_path, const char* exe_file_path)
{
FILE* in = NULL;
FILE* out = NULL;
char* cache = NULL; // cache
int total_length = 0;
int key = 0;
do
{
in = fopen(txt_file_path, "r");
if (in == NULL)
{
// "decode file fail, open txt file %s error\n"
EasyLog::Format(GetLibStrById(406), txt_file_path);
break;
}
out = fopen(exe_file_path, "wb");
if (out == NULL)
{
// "decode file fail, open exe file %s error\n"
EasyLog::Format(GetLibStrById(407), exe_file_path);
break;
}
char ibuffer[2*BLOCK_SIZE];
char obuffer[2*BLOCK_SIZE];
cache = new char [MAX_CODEC_LENGTH];
// Read key from first line
bool keyFound = false;
if (!feof(in))
{
memset(ibuffer, 0, sizeof ibuffer);
char* str = fgets(ibuffer, sizeof ibuffer, in);
if (str != NULL)
{
size_t len2 = strlen(ibuffer);
// remove the line feed
ibuffer[len2 - 1] = '\0';
key = atoi(ibuffer);
}
}
if (key == 0)
{
// "decode fails, key not fould\n"
EasyLog::Format(GetLibStrById(553));
}
while (!feof(in) && total_length < MAX_CODEC_LENGTH)
{
memset(ibuffer, 0, sizeof ibuffer);
memset(obuffer, 0, sizeof obuffer);
char* str = fgets(ibuffer, sizeof ibuffer, in);
if (str != NULL)
{
size_t len2 = strlen(ibuffer);
// remove the line feed
ibuffer[len2 - 1] = '\0';
// revert base64
int rc = decode64(obuffer, sizeof obuffer, ibuffer, strlen(ibuffer));
if (rc > 0)
{
memcpy(cache + total_length, obuffer, rc);
total_length += rc;
// Decrypt
for (size_t i = 0; i < rc; i++)
{
obuffer[i] = obuffer[i] ^ (i % MOD) ^ (key & 0xff);
}
fwrite(obuffer, 1, rc, out);
}
else if (rc == 0)
{
// "decode file, decode64 rc %d\n"
EasyLog::Format(GetLibStrById(408), rc);
}
else
{
// "decode file fails, decode64 rc %d < 0\n"
EasyLog::Format(GetLibStrById(409), rc);
break;
}
}
}
}
while (FALSE);
if (cache != NULL)
{
delete []cache;
}
// close files
if (in != NULL) fclose(in);
if (out != NULL)
{
fflush(out);
_commit(_fileno(out));
fclose(out);
}
return total_length > 0 && total_length < MAX_CODEC_LENGTH;
}
BOOL DecodePHP(std::string szSrcLine, std::string& szDstLine)
{
char buffer[1024] = {0};
char buffer2[1024] = {0};
// Decode base64
memset(buffer, 0, sizeof buffer);
int rc = decode64(buffer, sizeof buffer, szSrcLine.c_str(), szSrcLine.size());
if (rc <= 6)
{
// prefix + suffix
return FALSE;
}
// Remove prefix and suffix
memset(buffer2, 0, sizeof buffer2);
memcpy(buffer2, buffer + 3, rc - 6);
// Decode base64
memset(buffer, 0, sizeof buffer);
rc = decode64(buffer, sizeof buffer, buffer2, rc - 6);
if (rc <= 6)
{
// prefix + suffix
return FALSE;
}
// Remove prefix and suffix
memset(buffer2, 0, sizeof buffer2);
memcpy(buffer2, buffer + 3, rc - 6);
// Decode base64
memset(buffer, 0, sizeof buffer);
rc = decode64(buffer, sizeof buffer, buffer2, rc - 6);
if (rc <= 0)
{
// prefix + suffix
return FALSE;
}
// Output
szDstLine = buffer;
return TRUE;
} | 19.34252 | 79 | 0.594342 | bingart |
7104938da106909fca42fe6914e1336cb08b4fb8 | 2,416 | cpp | C++ | solutions/course-schedule-ii/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/course-schedule-ii/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | solutions/course-schedule-ii/solution.cpp | locker/leetcode | bf34a697de47aaf32823224d054f9a45613ce180 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2019-08-30T06:53:23.000Z | 2019-08-30T06:53:23.000Z | #include <iostream>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
template<typename T>
ostream& operator<<(ostream& out, const vector<T>& v)
{
out << '[';
for (auto it = v.begin(); it != v.end(); ++it) {
if (it != v.begin())
out << ',';
out << *it;
}
out << ']';
return out;
}
class Solution {
public:
vector<int> findOrder(int count, const vector<vector<int>>& prerequisites) {
//
// What we have is a graph in which vertexes represent courses
// and edges represent dependencies: there's an edge coming
// from vertex i to vertex j iff course i depends on course j.
// The algorithm is trivial:
//
// 1. Take any vertex which doesn't any incoming edges
// (a course that doesn't depend on any other course).
// 2. Remove the vertex and all edges originating from it.
// 3. Add the course corresponding to the vertex to the
// resulting schedule.
// 4. Unless the graph is empty, go to step 1.
//
// Map: vertex i => array of vertexes j such that there's
// an edge coming from i to j.
vector<vector<int>> edges(count);
// Map: vertex i => number of incoming edges.
vector<int> order(count);
for (const auto& it: prerequisites) {
edges[it[1]].push_back(it[0]);
++order[it[0]];
}
queue<int> todo;
for (int i = 0; i < count; ++i) {
if (order[i] == 0)
todo.push(i);
}
vector<int> schedule;
schedule.reserve(count);
while (!todo.empty()) {
auto i = todo.front();
todo.pop();
for (auto j: edges[i]) {
if (--order[j] == 0)
todo.push(j);
}
schedule.push_back(i);
}
if (static_cast<int>(schedule.size()) < count) {
// Looks like there's a cycle in the graph
// hence there's no schedule such that all
// courses are finished.
schedule.clear();
}
return schedule;
}
};
int main()
{
pair<int, vector<vector<int>>> input[] = {
{1, {{0,0}}}, // []
{2, {{1,0}}}, // [0,1]
{2, {{1,0},{0,1}}}, // []
{3, {{1,0},{2,0},{2,1}}}, // [0,1,2]
{3, {{1,0},{0,2},{2,1}}}, // []
{4, {{1,0},{3,1},{3,2},{3,0}}}, // [0,2,1,3]
{4, {{1,0},{2,1},{3,2},{1,3}}}, // []
};
Solution solution;
for (const auto& p: input) {
auto count = p.first;
const auto& prerequisites = p.second;
auto order = solution.findOrder(count, prerequisites);
cout << "Input: " << count << ", " << prerequisites << endl <<
"Output: " << order << endl;
}
return 0;
}
| 24.16 | 77 | 0.577815 | locker |
710508bb4cb3f037bb877de0dfb45bf0e516d871 | 439 | cc | C++ | fft/utils/Signals.cc | ddamiani/fft-tests | 5f119271c12b4a8ae1caf3edb7c727d59d4f2170 | [
"BSD-3-Clause"
] | null | null | null | fft/utils/Signals.cc | ddamiani/fft-tests | 5f119271c12b4a8ae1caf3edb7c727d59d4f2170 | [
"BSD-3-Clause"
] | null | null | null | fft/utils/Signals.cc | ddamiani/fft-tests | 5f119271c12b4a8ae1caf3edb7c727d59d4f2170 | [
"BSD-3-Clause"
] | null | null | null | #include "Signals.hh"
#define _USE_MATH_DEFINES
#include <cmath>
void fft::math::signal(double& re, double& im, double frac) {
double theta = frac * M_PI; re = 1.0 * std::cos(10.0 * theta) +0.5 * std::cos(25.0 * theta); im = 1.0 * std::sin(10.0 * theta) +0.5 * std::sin(25.0 * theta);
}
| 54.875 | 308 | 0.412301 | ddamiani |
71051b2400d6e0116bd99945bfa47dd6f5794812 | 2,391 | cpp | C++ | Source/Pineapple/Engine/Graphics/TextureAtlas.cpp | JoshYaxley/Pineapple | 490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec | [
"Zlib"
] | 11 | 2017-04-15T14:44:19.000Z | 2022-02-04T13:16:04.000Z | Source/Pineapple/Engine/Graphics/TextureAtlas.cpp | JoshYaxley/Pineapple | 490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec | [
"Zlib"
] | 25 | 2017-04-19T12:48:42.000Z | 2020-05-09T05:28:29.000Z | Source/Pineapple/Engine/Graphics/TextureAtlas.cpp | JoshYaxley/Pineapple | 490b0ccdfa26e2bb6fd9ec290b43b355462dd9ec | [
"Zlib"
] | 1 | 2019-04-21T21:14:04.000Z | 2019-04-21T21:14:04.000Z | /*------------------------------------------------------------------------------
Pineapple Game Engine - Copyright (c) 2011-2017 Adam Yaxley
This software is licensed under the Zlib license (see license.txt for details)
------------------------------------------------------------------------------*/
#include <Pineapple/Engine/Graphics/Texture.h>
#include <Pineapple/Engine/Graphics/TextureAtlas.h>
#include <Pineapple/Engine/Platform/Platform.h>
#include <rapidjson/document.h>
#include <rapidjson/rapidjson.h>
struct pa::Document
{
rapidjson::Document json;
};
pa::TextureAtlas::TextureAtlas(std::shared_ptr<pa::Texture> texture, const pa::FilePath& path)
: m_texture(texture)
, m_isLoaded(false)
, m_path(path)
{
m_document = std::make_unique<pa::Document>();
}
pa::TextureAtlas::~TextureAtlas()
{
}
bool pa::TextureAtlas::load()
{
std::string contents;
{
pa::FileBuffer buffer;
auto result = m_path.read(buffer);
if (result != pa::FileResult::Success)
{
pa::Log::info("{}: {}", pa::FileSystem::getResultString(result), m_path.asString());
return false;
}
contents = buffer.createString();
}
// Load json
m_document->json.Parse<0>(contents.c_str());
if (m_document->json.HasParseError())
{
pa::Log::info("Failed to parse {}, error was: {}", m_path.asString(), m_document->json.GetParseError());
m_isLoaded = false;
}
else
{
m_isLoaded = true;
}
return m_isLoaded;
}
std::shared_ptr<pa::Texture> pa::TextureAtlas::createTexture(const char* filename)
{
PA_ASSERTF(m_isLoaded, "You must load a texture atlas first.");
if (m_document->json.IsObject())
{
if (m_document->json.HasMember("frames"))
{
rapidjson::Value& frames = m_document->json["frames"];
if (frames.IsArray())
{
// find path
for (unsigned int i = 0; i < frames.Size(); i++)
{
rapidjson::Value& element = frames[i];
if (element.HasMember("filename"))
{
const char* elementFilename = element["filename"].GetString();
if (strcmp(elementFilename, filename) == 0)
{
// Same! Load this information
rapidjson::Value& frame = element["frame"];
int x = frame["x"].GetInt();
int y = frame["y"].GetInt();
int w = frame["w"].GetInt();
int h = frame["h"].GetInt();
return m_texture->createTexture({ x, y }, { w, h });
}
}
}
}
}
}
return nullptr;
} | 24.397959 | 106 | 0.60435 | JoshYaxley |
7106db184bf174c54734760b9d196b1e6e9221ef | 1,121 | cpp | C++ | C-PhotoDeal_level2_APP/C-PhotoDeal_level2/main.cpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | 8 | 2016-03-12T08:39:56.000Z | 2021-07-12T01:48:20.000Z | C-PhotoDeal_level2_APP/C-PhotoDeal_level2/main.cpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | null | null | null | C-PhotoDeal_level2_APP/C-PhotoDeal_level2/main.cpp | numberwolf/iOSDealFace | 5a109690d143ac125a4b679a8ea6ef28a9f147e3 | [
"Apache-2.0"
] | 2 | 2016-03-15T09:48:38.000Z | 2017-02-04T23:53:32.000Z | //
// main.cpp
// C-PhotoDeal_level2
//
// Created by numberwolf on 2016/10/12.
// Copyright © 2016年 numberwolf. All rights reserved.
//
#include <iostream>
#include "canny_door.hpp"
#include "numberPhoto.hpp"
#include "tess_ocr.hpp"
using namespace cv;
using namespace std;
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
char *path = "/Users/numberwolf/Documents/XCode&C++/C-PhotoDeal/C-PhotoDeal_level2_APP/img/cro.jpg";
// canny_door *CannyDoor = new canny_door(path);
IplImage *ColorImage = cvLoadImage(path);
int height = ColorImage->height;
int width = ColorImage->width;
// numberPhoto::sobelCanny(ColorImage, width, height);
// numberPhoto::otsuBinary(ColorImage, width, height, false, 80, 80);
// numberPhoto::method_two(ColorImage, width, height, false, 800, 800, 1);
char *ocr_filename = "/Users/numberwolf/Documents/XCode&C++/C-PhotoDeal/C-PhotoDeal_level2_APP/img/testocr.png";
// tess_orc *ocr = new tess_orc();
// ocr->scan_eng_string_by_img(ocr_filename);
return 0;
}
| 28.74359 | 116 | 0.676182 | numberwolf |
7108d320e449735ac0586fe26b0123887828fa19 | 3,425 | cpp | C++ | test/variant.cpp | jmairboeck/PTL | fed731de5cf73219fad1f2006e2978d981c02535 | [
"BSL-1.0"
] | null | null | null | test/variant.cpp | jmairboeck/PTL | fed731de5cf73219fad1f2006e2978d981c02535 | [
"BSL-1.0"
] | null | null | null | test/variant.cpp | jmairboeck/PTL | fed731de5cf73219fad1f2006e2978d981c02535 | [
"BSL-1.0"
] | null | null | null |
// Copyright Michael Florian Hava.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file ../LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/test/unit_test.hpp>
#include "ptl/variant.hpp"
#include "moveable.hpp"
BOOST_AUTO_TEST_SUITE(variant)
BOOST_AUTO_TEST_CASE(ctor) {
ptl::variant<int, double> var1;
BOOST_TEST(!var1.valueless_by_exception());
BOOST_TEST(ptl::get<int>(var1) == 0);
var1 = 10.;
BOOST_TEST(ptl::holds_alternative<double>(var1));
BOOST_TEST(ptl::get<double>(var1) == 10.);
var1 = 10;
BOOST_TEST(ptl::holds_alternative<int>(var1));
BOOST_TEST(ptl::get<int>(var1) == 10);
struct X {
X() {}
X(int, int) {}
};
struct Y {
Y() {}
Y(int, int, int) {}
};
ptl::variant<int, double, X, Y> var2{std::in_place_type<X>, 4, 5};
BOOST_TEST(ptl::holds_alternative<X>(var2));
var2.emplace<Y>(1, 2, 3);
BOOST_TEST(ptl::holds_alternative<Y>(var2));
}
BOOST_AUTO_TEST_CASE(copy) {
ptl::variant<double, int> var{1000};
BOOST_TEST(!var.valueless_by_exception());
BOOST_TEST(!ptl::holds_alternative<double>(var));
auto copy1 = var;
BOOST_TEST(!copy1.valueless_by_exception());
BOOST_TEST(!ptl::holds_alternative<double>(copy1));
BOOST_TEST(ptl::get<int>(var) == ptl::get<int>(copy1));
decltype(var) copy2; copy2 = copy1;
BOOST_TEST(!copy2.valueless_by_exception());
BOOST_TEST(!ptl::holds_alternative<double>(copy2));
BOOST_TEST(ptl::get<int>(var) == ptl::get<int>(copy2));
}
BOOST_AUTO_TEST_CASE(move) {
using ptl::test::moveable;
ptl::variant<moveable> var1;
decltype(var1) var2{std::move(var1)};
BOOST_TEST( ptl::get<moveable>(var1).moved);
BOOST_TEST(!ptl::get<moveable>(var2).moved);
var1 = std::move(var2);
BOOST_TEST(!ptl::get<moveable>(var1).moved);
BOOST_TEST( ptl::get<moveable>(var2).moved);
}
BOOST_AUTO_TEST_CASE(visit) {
ptl::variant<int, double> var;
var.visit(
[](int) { BOOST_TEST(true); },
[](double) { BOOST_TEST(false); }
);
var = 1.5;
var.visit(
[](int) { BOOST_TEST(false); },
[](double) { BOOST_TEST(true); }
);
BOOST_TEST(var.visit([](const auto & value) -> double { return value; }) == 1.5);
var = 1;
var.visit(
[](int) { BOOST_TEST(true); },
[](double) { BOOST_TEST(false); }
);
BOOST_TEST(var.visit([](const auto & value) -> double { return value; }) == 1.0);
}
BOOST_AUTO_TEST_CASE(swapping) {
ptl::variant<int, double> var1{10}, var2{20.2};
BOOST_TEST(ptl::holds_alternative<int>(var1));
BOOST_TEST(ptl::holds_alternative<double>(var2));
swap(var1, var2);
BOOST_TEST(ptl::holds_alternative<double>(var1));
BOOST_TEST(ptl::get<double>(var1) == 20.2);
BOOST_TEST(ptl::holds_alternative<int>(var2));
BOOST_TEST(ptl::get<int>(var2) == 10);
decltype(var1) var3{20};
swap(var2, var3);
BOOST_TEST(ptl::holds_alternative<int>(var2));
BOOST_TEST(ptl::get<int>(var2) == 20);
BOOST_TEST(ptl::holds_alternative<int>(var3));
BOOST_TEST(ptl::get<int>(var3) == 10);
}
BOOST_AUTO_TEST_CASE(comparison) {
const ptl::variant<int, double> var1{10}, var2{10.};
BOOST_TEST(!(var1 == var2));
BOOST_TEST( var1 != var2);
const auto var3{var1};
BOOST_TEST( var1 == var3);
BOOST_TEST(!(var1 != var3));
BOOST_TEST( var1 < var2);
BOOST_TEST(!(var1 > var2));
BOOST_TEST( var2 > var1);
BOOST_TEST(!(var2 < var1));
decltype(var1) var4{1};
BOOST_TEST(var1 > var4);
BOOST_TEST(var4 < var1);
}
BOOST_AUTO_TEST_SUITE_END()
| 25.94697 | 82 | 0.675912 | jmairboeck |
711340b5d95cde832fd8f7900d9a3eb017149ef3 | 845 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR/File GetAttributes/CPP/file getattributes.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR/File GetAttributes/CPP/file getattributes.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR/File GetAttributes/CPP/file getattributes.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
// <Snippet1>
using namespace System;
using namespace System::IO;
using namespace System::Text;
int main()
{
String^ path = "c:\\temp\\MyTest.txt";
// Create the file if it does not exist.
if ( !File::Exists( path ) )
{
File::Create( path );
}
if ( (File::GetAttributes( path ) & FileAttributes::Hidden) == FileAttributes::Hidden )
{
// Show the file.
File::SetAttributes(path, File::GetAttributes( path ) & ~FileAttributes::Hidden);
Console::WriteLine( "The {0} file is no longer hidden.", path );
}
else
{
// Hide the file.
File::SetAttributes( path, static_cast<FileAttributes>(File::GetAttributes( path ) | FileAttributes::Hidden) );
Console::WriteLine( "The {0} file is now hidden.", path );
}
}
// </Snippet1>
| 25.606061 | 118 | 0.583432 | hamarb123 |
7115ab51860209c3f30e6ca6e06bb72e15cfe21a | 712 | hpp | C++ | include/complex.hpp | BURNINGTIGER/Complex | c87aa365aa123a89608aa176342dc4ee9db019fb | [
"MIT"
] | null | null | null | include/complex.hpp | BURNINGTIGER/Complex | c87aa365aa123a89608aa176342dc4ee9db019fb | [
"MIT"
] | null | null | null | include/complex.hpp | BURNINGTIGER/Complex | c87aa365aa123a89608aa176342dc4ee9db019fb | [
"MIT"
] | null | null | null | #include <iostream>
#include <conio.h>
#include <locale>
using namespace std;
class Complex
{
double rel, img;
public:
Complex();
Complex(double real, double imag);
Complex add(const Complex) const;
Complex sub(const Complex) const;
Complex mult(const int) const;
Complex divd(const int) const;
Complex(const Complex&);
Complex operator*(Complex&);
Complex operator/(Complex&);
bool operator==(Complex&);
Complex operator=(Complex&);
Complex operator+=(Complex&);
Complex operator-=(Complex&);
Complex operator*=(Complex&);
Complex operator/=(Complex&);
friend ostream& operator<<(ostream&, Complex&);
friend istream& operator>>(istream&, Complex &);
double real();
double imag();
};
| 21.575758 | 49 | 0.710674 | BURNINGTIGER |
7122261a541cb87857a672832aedfaf08f6dd602 | 13,620 | hpp | C++ | src/mlpack/methods/ann/cnn.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/ann/cnn.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | src/mlpack/methods/ann/cnn.hpp | vj-ug/Contribution-to-mlpack | 0ddb5ed463861f459ff2829712bdc59ba9d810b0 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file cnn.hpp
* @author Shangtong Zhang
* @author Marcus Edel
*
* Definition of the CNN class, which implements convolutional neural networks.
*/
#ifndef __MLPACK_METHODS_ANN_CNN_HPP
#define __MLPACK_METHODS_ANN_CNN_HPP
#include <mlpack/core.hpp>
#include <mlpack/methods/ann/network_traits.hpp>
#include <mlpack/methods/ann/layer/layer_traits.hpp>
#include <mlpack/methods/ann/performance_functions/cee_function.hpp>
namespace mlpack {
namespace ann /** Artificial Neural Network. */ {
/**
* An implementation of a standard convolutional network.
*
* @tparam LayerTypes Contains all layer modules used to construct the network.
* @tparam OutputLayerType The outputlayer type used to evaluate the network.
* @tparam PerformanceFunction Performance strategy used to claculate the error.
*/
template <
typename LayerTypes,
typename OutputLayerType,
class PerformanceFunction = CrossEntropyErrorFunction<>
>
class CNN
{
public:
/**
* Construct the CNN object, which will construct a feed forward neural
* network with the specified layers.
*
* @param network The network modules used to construct the network.
* @param outputLayer The outputlayer used to evaluate the network.
*/
CNN(const LayerTypes& network, OutputLayerType& outputLayer)
: network(network), outputLayer(outputLayer), trainError(0)
{
// Nothing to do here.
}
/**
* Run a single iteration of the feed forward algorithm, using the given
* input and target vector, store the calculated error into the error
* parameter.
*
* @param input Input data used to evaluate the network.
* @param target Target data used to calculate the network error.
* @param error The calulated error of the output layer.
*/
template <typename InputType, typename TargetType, typename ErrorType>
void FeedForward(const InputType& input,
const TargetType& target,
ErrorType& error)
{
deterministic = false;
trainError += Evaluate(input, target, error);
}
/**
* Run a single iteration of the feed backward algorithm, using the given
* error of the output layer.
*
* @param error The calulated error of the output layer.
*/
template <typename InputType, typename ErrorType>
void FeedBackward(const InputType& /* unused */, const ErrorType& error)
{
Backward(error, network);
UpdateGradients(network);
}
/**
* Update the weights using the layer defined optimizer.
*/
void ApplyGradients()
{
ApplyGradients(network);
// Reset the overall error.
trainError = 0;
}
/**
* Evaluate the network using the given input. The output activation is
* stored into the output parameter.
*
* @param input Input data used to evaluate the network.
* @param output Output data used to store the output activation
*/
template <typename InputDataType, typename OutputDataType>
void Predict(const InputDataType& input, OutputDataType& output)
{
deterministic = true;
ResetParameter(network);
Forward(input, network);
OutputPrediction(output, network);
}
/**
* Evaluate the trained network using the given input and compare the output
* with the given target vector.
*
* @param input Input data used to evaluate the trained network.
* @param target Target data used to calculate the network error.
* @param error The calulated error of the output layer.
*/
template <typename InputType, typename TargetType, typename ErrorType>
double Evaluate(const InputType& input,
const TargetType& target,
ErrorType& error)
{
deterministic = false;
ResetParameter(network);
Forward(input, network);
return OutputError(target, error, network);
}
//! Get the error of the network.
double Error() const { return trainError; }
private:
/**
* Reset the network by setting the layer status.
*
* enable_if (SFINAE) is used to iterate through the network. The general
* case peels off the first type and recurses, as usual with
* variadic function templates.
*/
template<size_t I = 0, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
ResetParameter(std::tuple<Tp...>& /* unused */) { /* Nothing to do here */ }
template<size_t I = 0, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
ResetParameter(std::tuple<Tp...>& t)
{
ResetDeterministic(std::get<I>(t));
ResetParameter<I + 1, Tp...>(t);
}
/**
* Reset the layer status by setting the current deterministic parameter
* through all layer that implement the Deterministic function.
*
* enable_if (SFINAE) is used to iterate through the network. The general
* case peels off the first type and recurses, as usual with
* variadic function templates.
*/
template<typename T>
typename std::enable_if<
HasDeterministicCheck<T, bool&(T::*)(void)>::value, void>::type
ResetDeterministic(T& t)
{
t.Deterministic() = deterministic;
}
template<typename T>
typename std::enable_if<
not HasDeterministicCheck<T, bool&(T::*)(void)>::value, void>::type
ResetDeterministic(T& /* unused */) { /* Nothing to do here */ }
/**
* Run a single iteration of the feed forward algorithm, using the given
* input and target vector, store the calculated error into the error
* vector.
*
* enable_if (SFINAE) is used to select between two template overloads of
* the get function - one for when I is equal the size of the tuple of
* layer, and one for the general case which peels off the first type
* and recurses, as usual with variadic function templates.
*/
template<size_t I = 0, typename DataType, typename... Tp>
void Forward(const DataType& input, std::tuple<Tp...>& t)
{
std::get<I>(t).InputParameter() = input;
std::get<I>(t).Forward(std::get<I>(t).InputParameter(),
std::get<I>(t).OutputParameter());
ForwardTail<I + 1, Tp...>(t);
}
template<size_t I = 1, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
ForwardTail(std::tuple<Tp...>& /* unused */)
{
LinkParameter(network);
}
template<size_t I = 1, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
ForwardTail(std::tuple<Tp...>& t)
{
std::get<I>(t).Forward(std::get<I - 1>(t).OutputParameter(),
std::get<I>(t).OutputParameter());
ForwardTail<I + 1, Tp...>(t);
}
/**
* Link the calculated activation with the connection layer.
*
* enable_if (SFINAE) is used to iterate through the network. The general
* case peels off the first type and recurses, as usual with
* variadic function templates.
*/
template<size_t I = 1, typename... Tp>
typename std::enable_if<I == sizeof...(Tp), void>::type
LinkParameter(std::tuple<Tp...>& /* unused */) { /* Nothing to do here */ }
template<size_t I = 1, typename... Tp>
typename std::enable_if<I < sizeof...(Tp), void>::type
LinkParameter(std::tuple<Tp...>& t)
{
if (!LayerTraits<typename std::remove_reference<
decltype(std::get<I>(t))>::type>::IsBiasLayer)
{
std::get<I>(t).InputParameter() = std::get<I - 1>(t).OutputParameter();
}
LinkParameter<I + 1, Tp...>(t);
}
/*
* Calculate the output error and update the overall error.
*/
template<typename DataType, typename ErrorType, typename... Tp>
double OutputError(const DataType& target,
ErrorType& error,
const std::tuple<Tp...>& t)
{
// Calculate and store the output error.
outputLayer.CalculateError(
std::get<sizeof...(Tp) - 1>(t).OutputParameter(), target, error);
// Masures the network's performance with the specified performance
// function.
return PerformanceFunction::Error(
std::get<sizeof...(Tp) - 1>(t).OutputParameter(), target);
}
/**
* Run a single iteration of the feed backward algorithm, using the given
* error of the output layer. Note that we iterate backward through the
* layer modules.
*
* enable_if (SFINAE) is used to select between two template overloads of
* the get function - one for when I is equal the size of the tuple of
* layer, and one for the general case which peels off the first type
* and recurses, as usual with variadic function templates.
*/
template<size_t I = 1, typename DataType, typename... Tp>
typename std::enable_if<I < (sizeof...(Tp) - 1), void>::type
Backward(const DataType& error, std::tuple<Tp...>& t)
{
std::get<sizeof...(Tp) - I>(t).Backward(
std::get<sizeof...(Tp) - I>(t).OutputParameter(), error,
std::get<sizeof...(Tp) - I>(t).Delta());
BackwardTail<I + 1, DataType, Tp...>(error, t);
}
template<size_t I = 1, typename DataType, typename... Tp>
typename std::enable_if<I == (sizeof...(Tp)), void>::type
BackwardTail(const DataType& /* unused */,
std::tuple<Tp...>& /* unused */) { }
template<size_t I = 1, typename DataType, typename... Tp>
typename std::enable_if<I < (sizeof...(Tp)), void>::type
BackwardTail(const DataType& error, std::tuple<Tp...>& t)
{
std::get<sizeof...(Tp) - I>(t).Backward(
std::get<sizeof...(Tp) - I>(t).OutputParameter(),
std::get<sizeof...(Tp) - I + 1>(t).Delta(),
std::get<sizeof...(Tp) - I>(t).Delta());
BackwardTail<I + 1, DataType, Tp...>(error, t);
}
/**
* Iterate through all layer modules and update the the gradient using the
* layer defined optimizer.
*
* enable_if (SFINAE) is used to iterate through the network layer.
* The general case peels off the first type and recurses, as usual with
* variadic function templates.
*/
template<size_t I = 0, typename... Tp>
typename std::enable_if<I == (sizeof...(Tp) - 1), void>::type
UpdateGradients(std::tuple<Tp...>& /* unused */) { }
template<size_t I = 0, typename... Tp>
typename std::enable_if<I < (sizeof...(Tp) - 1), void>::type
UpdateGradients(std::tuple<Tp...>& t)
{
Update(std::get<I>(t), std::get<I>(t).OutputParameter(),
std::get<I + 1>(t).Delta());
UpdateGradients<I + 1, Tp...>(t);
}
template<typename T, typename P, typename D>
typename std::enable_if<
HasGradientCheck<T, void(T::*)(const D&, P&)>::value, void>::type
Update(T& t, P& /* unused */, D& delta)
{
t.Gradient(delta, t.Gradient());
t.Optimizer().Update();
}
template<typename T, typename P, typename D>
typename std::enable_if<
not HasGradientCheck<T, void(T::*)(const P&, D&)>::value, void>::type
Update(T& /* unused */, P& /* unused */, D& /* unused */)
{
/* Nothing to do here */
}
/**
* Update the weights using the calulated gradients.
*
* enable_if (SFINAE) is used to iterate through the network connections.
* The general case peels off the first type and recurses, as usual with
* variadic function templates.
*/
template<size_t I = 0, typename... Tp>
typename std::enable_if<I == (sizeof...(Tp) - 1), void>::type
ApplyGradients(std::tuple<Tp...>& /* unused */)
{
/* Nothing to do here */
}
template<size_t I = 0, typename... Tp>
typename std::enable_if<I < (sizeof...(Tp) - 1), void>::type
ApplyGradients(std::tuple<Tp...>& t)
{
Apply(std::get<I>(t), std::get<I>(t).OutputParameter(),
std::get<I + 1>(t).Delta());
ApplyGradients<I + 1, Tp...>(t);
}
template<typename T, typename P, typename D>
typename std::enable_if<
HasGradientCheck<T, void(T::*)(const D&, P&)>::value, void>::type
Apply(T& t, P& /* unused */, D& /* unused */)
{
t.Optimizer().Optimize();
t.Optimizer().Reset();
}
template<typename T, typename P, typename D>
typename std::enable_if<
not HasGradientCheck<T, void(T::*)(const P&, D&)>::value, void>::type
Apply(T& /* unused */, P& /* unused */, D& /* unused */)
{
/* Nothing to do here */
}
/*
* Calculate and store the output activation.
*/
template<typename DataType, typename... Tp>
void OutputPrediction(DataType& output, std::tuple<Tp...>& t)
{
// Calculate and store the output prediction.
outputLayer.OutputClass(std::get<sizeof...(Tp) - 1>(t).OutputParameter(),
output);
}
//! The layer modules used to build the network.
LayerTypes network;
//! The outputlayer used to evaluate the network
OutputLayerType& outputLayer;
//! The current training error of the network.
double trainError;
//! The current evaluation mode (training or testing).
bool deterministic;
}; // class CNN
//! Network traits for the CNN network.
template <
typename LayerTypes,
typename OutputLayerType,
class PerformanceFunction
>
class NetworkTraits<
CNN<LayerTypes, OutputLayerType, PerformanceFunction> >
{
public:
static const bool IsFNN = false;
static const bool IsRNN = false;
static const bool IsCNN = true;
};
}; // namespace ann
}; // namespace mlpack
#endif
| 33.058252 | 80 | 0.624156 | vj-ug |
7123259643cb93a1b3dda4dd1b15381b22bc0887 | 1,765 | cc | C++ | cpp/server/debug_server.cc | propaganda-gold/deeprev | 0c6ccf83131a879ed858acdb0675e75ebf2f2d3d | [
"BSD-3-Clause"
] | null | null | null | cpp/server/debug_server.cc | propaganda-gold/deeprev | 0c6ccf83131a879ed858acdb0675e75ebf2f2d3d | [
"BSD-3-Clause"
] | 2 | 2021-05-11T16:29:38.000Z | 2022-01-22T12:28:49.000Z | cpp/server/debug_server.cc | propaganda-gold/deeprev | 0c6ccf83131a879ed858acdb0675e75ebf2f2d3d | [
"BSD-3-Clause"
] | null | null | null | #include "absl/flags/flag.h"
#include "absl/flags/parse.h"
#include "api/router.h"
#include "data/connection.h"
#include "data/globals.h"
#include "data/vectorbook.pb.h"
#include "handlers/api.h"
#include "handlers/delegating_handler.h"
#include "handlers/requests.h"
#include "network/init.h"
#include "server/http_server.h"
#include "server/options.h"
#include "server/server_https.hpp"
#include "util/includes.h"
#include "util/mongo_adapter.h"
#include <boost/filesystem.hpp>
#include <memory>
ABSL_FLAG(std::string, rest_options, "", "");
ABSL_FLAG(std::string, secrets, "", "Path to a pbtxt of type 'Secrets'.");
ABSL_FLAG(std::string, model_spec, "", "");
ABSL_FLAG(int, port, 8090, "The port number for the server.");
using SimpleHttpServer = SimpleWeb::Server<SimpleWeb::HTTP>;
using namespace std;
using namespace vectorbook;
Void Main() {
auto rest_options = absl::GetFlag(FLAGS_rest_options);
ASSERT(!rest_options.empty());
auto secrets = absl::GetFlag(FLAGS_secrets);
ASSERT(!secrets.empty());
ASSERT_SUCCEEDS(curl::Initialize());
ASSERT_SUCCEEDS(statics::LoadRestOptions(rest_options));
ASSERT_SUCCEEDS(statics::LoadSecrets(secrets));
ASSERT_SUCCEEDS(CreateRedisConnection());
ASSERT_SUCCEEDS(mongodb::Initialize(statics::secrets().mongodb_uri()));
HttpServerConfig config;
config.address = "0.0.0.0";
config.port = absl::GetFlag(FLAGS_port);
auto handler = RestRouter();
ASSERT_OK(handler);
auto server = CreateHttpServer(config, handler.get());
// ASSERT(server != nullptr);
Output_() << "Starting server: http://" << config.address << ":"
<< config.port << "\n";
auto start = server->Start();
ASSERT_OK(start);
ASSERT_SUCCEEDS(curl::CleanUp());
return Ok();
}
#include "util/main_incl.h"
| 28.934426 | 74 | 0.717847 | propaganda-gold |
712631463cd05be873393e3f95c1e72b548a884f | 2,759 | cpp | C++ | OpenTESArena/src/Media/Font.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/Media/Font.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | OpenTESArena/src/Media/Font.cpp | Digital-Monk/OpenTESArena | 95f0bdaa642ff090b94081795a53b00f10dc4b03 | [
"MIT"
] | null | null | null | #include <unordered_map>
#include "SDL.h"
#include "Font.h"
#include "FontName.h"
#include "../Assets/FontFile.h"
#include "../Rendering/Renderer.h"
#include "../Rendering/Surface.h"
#include "components/debug/Debug.h"
namespace
{
const std::unordered_map<FontName, std::string> FontFilenames =
{
{ FontName::A, "FONT_A.DAT" },
{ FontName::Arena, "ARENAFNT.DAT" },
{ FontName::B, "FONT_B.DAT" },
{ FontName::C, "FONT_C.DAT" },
{ FontName::Char, "CHARFNT.DAT" },
{ FontName::D, "FONT_D.DAT" },
{ FontName::Four, "FONT4.DAT" },
{ FontName::S, "FONT_S.DAT" },
{ FontName::Teeny, "TEENYFNT.DAT" }
};
}
Font::Font(FontName fontName)
{
this->fontName = fontName;
// Load the font file for this font name.
const std::string &filename = FontFilenames.at(fontName);
FontFile fontFile;
if (!fontFile.init(filename.c_str()))
{
DebugCrash("Could not init font file \"" + filename + "\".");
}
const int elementHeight = fontFile.getHeight();
this->characterHeight = elementHeight;
// There are 95 characters, plus space.
this->characters.resize(96);
// Create an SDL surface for each character image. Start with space (ASCII 32),
// and end with delete (ASCII 127).
for (int i = 0; i < 96; i++)
{
const char c = i + 32;
const int elementWidth = fontFile.getWidth(c);
const uint32_t *elementPixels = fontFile.getPixels(c);
Surface surface = Surface::createWithFormat(elementWidth, elementHeight,
Renderer::DEFAULT_BPP, Renderer::DEFAULT_PIXELFORMAT);
uint32_t *pixels = static_cast<uint32_t*>(surface.get()->pixels);
const int pixelCount = surface.getWidth() * surface.getHeight();
for (int index = 0; index < pixelCount; index++)
{
pixels[index] = elementPixels[index];
}
this->characters.at(i) = std::move(surface);
}
}
Font::Font(Font &&font)
{
this->characters = std::move(font.characters);
this->characterHeight = font.characterHeight;
this->fontName = font.fontName;
}
const std::string &Font::fromName(FontName fontName)
{
const std::string &filename = FontFilenames.at(fontName);
return filename;
}
int Font::getCharacterHeight() const
{
return this->characterHeight;
}
FontName Font::getFontName() const
{
return this->fontName;
}
SDL_Surface *Font::getSurface(char c) const
{
// If an invalid character is requested, print a warning and return
// a default character.
if ((c < 32) || (c > 127))
{
DebugLogWarning("Character value \"" + std::to_string(c) +
"\" out of range (must be ASCII 32-127).");
return this->characters.at(0).get();
}
// Space (ASCII 32) is at index 0.
SDL_Surface *surface = this->characters.at(c - 32).get();
return surface;
}
| 25.546296 | 82 | 0.654223 | Digital-Monk |
7128adf5c1f9d10dd50b9ce20fc49699b7eb1eb1 | 513 | cpp | C++ | compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp | rohinikumar4073/CppMicroServices | f8ce77814c65eb8273823c7ca5df256ec9768956 | [
"Apache-2.0"
] | 1 | 2020-12-08T16:21:45.000Z | 2020-12-08T16:21:45.000Z | compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp | iHouLei/CppMicroServices | aa9cc47dde75ba9ead18df399ce08269c15e3aa1 | [
"Apache-2.0"
] | null | null | null | compendium/test_bundles/ManagedServiceAndFactoryBundle/src/ManagedServiceFactoryServiceImpl.cpp | iHouLei/CppMicroServices | aa9cc47dde75ba9ead18df399ce08269c15e3aa1 | [
"Apache-2.0"
] | null | null | null | #include "ManagedServiceFactoryServiceImpl.hpp"
namespace cppmicroservices {
namespace service {
namespace cm {
namespace test {
TestManagedServiceFactoryServiceImpl::TestManagedServiceFactoryServiceImpl(int initialValue)
: value{initialValue} {}
TestManagedServiceFactoryServiceImpl::~TestManagedServiceFactoryServiceImpl() = default;
int TestManagedServiceFactoryServiceImpl::getValue() {
return value;
}
} // namespace test
} // namespace cm
} // namespace service
} // namespace cppmicroservices
| 24.428571 | 92 | 0.805068 | rohinikumar4073 |
71297894429bf2299c8e6b641c7a3a9cf26b29c1 | 981 | cpp | C++ | cloud_processing/cpp/ground_removal.cpp | MinesNicaicai/large-scale-pointcloud-matching | cfe140f2be1110ed75b6edd27538021e513a31c9 | [
"MIT"
] | 1 | 2020-11-21T16:39:51.000Z | 2020-11-21T16:39:51.000Z | cloud_processing/cpp/ground_removal.cpp | MinesNicaicai/large-scale-pointcloud-matching | cfe140f2be1110ed75b6edd27538021e513a31c9 | [
"MIT"
] | null | null | null | cloud_processing/cpp/ground_removal.cpp | MinesNicaicai/large-scale-pointcloud-matching | cfe140f2be1110ed75b6edd27538021e513a31c9 | [
"MIT"
] | 1 | 2020-12-13T14:51:44.000Z | 2020-12-13T14:51:44.000Z |
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <string>
using PointT = pcl::PointXYZ;
int main(int argc, char **argv)
{
if (argc != 2) {
std::cout << "usage: ./ground_removal pcd-file\n";
return 0;
}
// Read in the cloud data
pcl::PCDReader reader;
pcl::PointCloud<PointT>::Ptr in_cloud(new pcl::PointCloud<PointT>());
pcl::PointCloud<PointT>::Ptr out_cloud(new pcl::PointCloud<PointT>());
reader.read(argv[1], *in_cloud);
for (const auto& point : in_cloud->points) {
if (point.z > 0) {
out_cloud->points.emplace_back(point);
}
}
out_cloud->width = out_cloud->points.size();
out_cloud->height = 1;
out_cloud->is_dense = true;
pcl::PCDWriter writer;
std::string out_file_name(argv[1]);
out_file_name = out_file_name.substr(0, out_file_name.size()-4) + "_wo_ground.pcd";
writer.write<PointT>(out_file_name, *out_cloud, false);
return (0);
} | 25.815789 | 87 | 0.623853 | MinesNicaicai |
712ab680f4ba1b33a33efb844bc787502179d0a0 | 363 | hpp | C++ | libmsr145/headers/libmsr145_structs.hpp | StefanRvO/libmsr145 | f9e49c1b116cdb8bb991084e9de11d5df8cd3b37 | [
"Beerware"
] | null | null | null | libmsr145/headers/libmsr145_structs.hpp | StefanRvO/libmsr145 | f9e49c1b116cdb8bb991084e9de11d5df8cd3b37 | [
"Beerware"
] | null | null | null | libmsr145/headers/libmsr145_structs.hpp | StefanRvO/libmsr145 | f9e49c1b116cdb8bb991084e9de11d5df8cd3b37 | [
"Beerware"
] | null | null | null | #pragma once
#include <cstdint>
#include "libmsr145_enums.hpp"
struct rec_entry
{
uint16_t address;
struct tm time;
uint16_t length;
bool isRecording;
};
struct sample
{
sampletype type;
int16_t value;
uint64_t timestamp; //this is the time since the start of the recording in 1/512 seconds
uint32_t rawsample; //for debugging
};
| 19.105263 | 92 | 0.707989 | StefanRvO |
71311f1d13a7e8e83939ef6b87d92c0f10fbb72c | 224 | cpp | C++ | 2521/1683225_AC_0MS_68K.cpp | vandreas19/POJ_sol | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 18 | 2017-08-14T07:34:42.000Z | 2022-01-29T14:20:29.000Z | 2521/1683225_AC_0MS_68K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | null | null | null | 2521/1683225_AC_0MS_68K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 14 | 2016-12-21T23:37:22.000Z | 2021-07-24T09:38:57.000Z | #include<iostream.h>
void main()
{
int iCost,iSell,iFake,iBack;
while(1)
{
cin>>iCost>>iSell>>iFake>>iBack;
if(iCost==0 && iSell==0 && iFake==0 && iBack==0)
break;
cout<<iCost-iSell+iFake<<endl;
}
} | 17.230769 | 51 | 0.580357 | vandreas19 |
71376ccf83770aa04107f163ca946c1244c462a5 | 2,147 | cpp | C++ | progpar/test/progpar-test.cpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 19 | 2019-07-21T15:38:12.000Z | 2022-01-06T05:24:48.000Z | progpar/test/progpar-test.cpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 6 | 2019-12-07T22:12:37.000Z | 2022-01-10T22:31:48.000Z | progpar/test/progpar-test.cpp | dmitigr/cefeika | 6189843d4244f7334558708e57e952584561b1e0 | [
"Zlib"
] | 1 | 2019-08-15T14:49:00.000Z | 2019-08-15T14:49:00.000Z | // -*- C++ -*-
// Copyright (C) 2021 Dmitry Igrishin
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// Dmitry Igrishin
// dmitigr@gmail.com
#include "../../progpar.hpp"
#include "../../testo.hpp"
#include <iostream>
int main(int argc, char* argv[])
{
namespace progpar = dmitigr::progpar;
using namespace dmitigr::testo;
try {
const progpar::Program_parameters po{argc, argv};
const auto epath = po.path();
ASSERT(!epath.empty());
std::cout << "Executable path: " << epath << std::endl;
const auto& opts = po.options();
std::cout << opts.size() << " options specified";
if (!opts.empty()) {
std::cout << ":" << std::endl;
for (const auto& o : opts) {
std::cout << " " << o.first;
if (o.second)
std::cout << " = " << *o.second;
std::cout << std::endl;
}
} else
std::cout << "." << std::endl;
const auto& args = po.arguments();
std::cout << args.size() << " arguments specified";
if (!args.empty()) {
std::cout << ":" << std::endl;
for (const auto& a : args)
std::cout << " " << a << std::endl;
} else
std::cout << "." << std::endl;
} catch (const std::exception& e) {
report_failure(argv[0], e);
return 1;
} catch (...) {
report_failure(argv[0]);
return 2;
}
}
| 32.044776 | 77 | 0.616209 | dmitigr |
7143ac46680ebf63717201570aae8b1099c84a9e | 6,537 | cpp | C++ | gddm/netlib_server.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | 3 | 2017-06-05T13:49:43.000Z | 2017-06-19T22:31:58.000Z | gddm/netlib_server.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | 1 | 2017-06-19T12:36:46.000Z | 2017-06-30T22:34:06.000Z | gddm/netlib_server.cpp | asm128/nwol | a28d6df356bec817393adcd2e6573a65841832e2 | [
"MIT"
] | null | null | null | #include "netlib_server.h"
#include "nwol_sleep.h"
#include "gref_definition.h"
#include <time.h>
#if defined(__WINDOWS__)
#include <process.h>
#include <WinSock2.h>
#endif
void gdnet::disconnectClient (SServer& serverInstance, int32_t clientId) {
::nwol::CMutexGuard lockClients (serverInstance.ConnectionsMutex);
for(uint32_t i = 0; i < serverInstance.ClientConnections.size(); ++i) {
::gdnet::SNetworkNode * client = serverInstance.ClientConnections[i];
if(client && client->Id == clientId) {
GPNCO(::gdnet, SNetworkNode) endClient = 0;
error_if(0 > serverInstance.ClientConnections.pop(&endClient), "This is broken! No elements to pop?")
else
re_if(errored(serverInstance.ClientConnections.set(endClient, i)), "Failed to set client! Out of memory?");
}
}
}
int32_t gdnet::SServer::InitServer (uint16_t listeningPort, ::gdnet::TRANSPORT_PROTOCOL mode) {
::gethostname(HostName, sizeof(HostName)); // Get host name of this computer
QueuedConnectionCount = 0;
GPNCO(::gdnet, IEndpoint) endpointListener = nullptr; // Information about the client
nwol_necall(::gdnet::endpointCreate(HostName, (uint16_t)listeningPort, 0, mode, &endpointListener) , "Failed to initialize listening endpoint on %u:.%s." , (uint32_t)listeningPort, ::nwol::get_value_label(mode).begin());
nwol_necall(::gdnet::endpointInit(endpointListener) , "Failed to initialize listening endpoint on %u:.%s." , (uint32_t)listeningPort, ::nwol::get_value_label(mode).begin());
nwol_necall(::gdnet::endpointBind(endpointListener) , "Failed to bind listening endpoint on %u:.%s." , (uint32_t)listeningPort, ::nwol::get_value_label(mode).begin());
EndpointListener = endpointListener;
bListening = true;
return 0;
}
int32_t gdnet::SServer::Listen () {
if(!bListening)
return 1;
::gdnet::SCommand command = ::gdnet::INVALID_COMMAND;
GPNCO(::gdnet, IEndpoint) endpointToAccept = nullptr; // Information about the client
int32_t bytes_received = 0;
{
::gdnet::SIPv4 addressListener = {};
::gdnet::endpointAddress(EndpointListener, addressListener);
info_printf("Server listening on %u.%u.%u.%u:%u.", NWOL_EXPAND_IPV4_UINT32(addressListener));
// -- Receive bytes from client
::nwol::error_t errMy = ::gdnet::endpointReceive( EndpointListener.get_address(), (byte_t*)&command, sizeof(::gdnet::SCommand), &bytes_received, ::gdnet::RECEIVE_FLAG_REMOVE, &endpointToAccept );
ree_if(bytes_received < 0, "Could not receive datagram. 0x%x.", errMy);
rww_if(bytes_received == 0, "Server listener may have been closed. 0x%x.", errMy);
}
{
::gdnet::SIPv4 addressToAccept = {};
error_if(errored(::gdnet::endpointAddress(endpointToAccept, addressToAccept)), "I have no idea why this would ever fail.");
info_printf("Received %u bytes from %u.%u.%u.%u:%u. Command: %s:%s.", (uint32_t)bytes_received, NWOL_EXPAND_IPV4_UINT32(addressToAccept)
, ::nwol::get_value_label(command.Type ).c_str()
, ::nwol::get_value_label(command.Command ).c_str()
);
if(bListening && command.Command == ::gdnet::NWON_COMMAND_CONNECT && QueuedConnectionCount < (int64_t)::nwol::size(QueuedConnectionList))
QueuedConnectionList[sync_increment(QueuedConnectionCount) - 1] = endpointToAccept;
}
return 0;
}
int32_t gdnet::SServer::Accept () {
if( 0 == QueuedConnectionCount )
return 1;
static int32_t connectionsAccepted = 0;
::gdnet::SConnectionAddress address = {};
GPNCO(::gdnet, IEndpoint) endpointListener = 0;
GPNCO(::gdnet, IEndpoint) endpointRemote = QueuedConnectionList[sync_decrement(QueuedConnectionCount)];
nwol_necall(::gdnet::endpointAddress (EndpointListener, address.Local) , "Failed to resolve local address.");
nwol_necall(::gdnet::endpointAddress (endpointRemote, address.Remote) , "Failed to resolve remote address.");
address.Local.Port = 0; // Let the system pick the port number.
nwol_necall(::gdnet::endpointCreate (address.Local, TRANSPORT_PROTOCOL_UDP, &endpointListener) , "%s", "Failed to create client listener.");
nwol_necall(::gdnet::endpointInit (endpointListener) , "%s", "Failed to initialize client listener connection.");
nwol_necall(::gdnet::endpointBind (endpointListener) , "%s", "Failed to bind client listener connection.");
GPObj(::gdnet, SNetworkNode) newClient;
uint32_t indexFound = (uint32_t)-1;
{
::nwol::CMutexGuard lockClients (ConnectionsMutex);
for(uint32_t iClient = 0, clientCount = ClientConnections.size(); iClient<clientCount; ++iClient) {
::gdnet::GREF(SNetworkNode) * refClient = ClientConnections.begin()[iClient];
if(0 == refClient) {
indexFound = iClient;
break;
}
else if(refClient->get()->Endpoints.Local == 0 || refClient->get()->Endpoints.Remote == 0) {
newClient = ::nwol::acquire(refClient);
break;
}
}
if(0 == newClient) {
newClient.create();
if(indexFound != (uint32_t)-1)
nwol_necall(ClientConnections.set(newClient, indexFound), "Failed to set client to connection list! Why would this ever happen?");
else
nwol_necall(ClientConnections.push_back(newClient), "Failed to push client connection. Out of memory?");
}
uint64_t newClientId = connectionsAccepted++;
nwol_necall(::gdnet::nodeInit(newClient, {endpointListener, endpointRemote}, newClientId), "Failed to initialize node. This may be due to the socket being closed before fully initializing.");
}
Sleep(10);
return 0;
};
::nwol::error_t gdnet::SServer::ShutdownServer () {
bListening = false;
EndpointListener = {};
::nwol::sleep(100);
while(QueuedConnectionCount > 0)
QueuedConnectionList[sync_decrement(QueuedConnectionCount)] = 0;
{
::nwol::CMutexGuard lockClients (ConnectionsMutex);
for(uint32_t iClient = 0, clientCount = ClientConnections.size(); iClient < clientCount; ++iClient) {
::gdnet::SNetworkNode * nodeToDisconnect = ClientConnections[iClient];
if (nodeToDisconnect)
nodeToDisconnect->Endpoints = {};
}
::nwol::sleep(100);
}
return 0;
}
| 50.284615 | 221 | 0.659936 | asm128 |
714a23b2269a75ab0a6137842ce74562b0f9f337 | 1,895 | cpp | C++ | Beeftext/Snippet/ShortcutSnippetFragment.cpp | sharpsteve/Beeftext | 9f4c7abfe6f33914cd49956f9c576ab5b10ff660 | [
"MIT"
] | 546 | 2017-12-19T15:44:56.000Z | 2022-03-29T20:38:01.000Z | Beeftext/Snippet/ShortcutSnippetFragment.cpp | sharpsteve/Beeftext | 9f4c7abfe6f33914cd49956f9c576ab5b10ff660 | [
"MIT"
] | 455 | 2017-12-30T07:47:49.000Z | 2022-03-24T15:53:14.000Z | Beeftext/Snippet/ShortcutSnippetFragment.cpp | sharpsteve/Beeftext | 9f4c7abfe6f33914cd49956f9c576ab5b10ff660 | [
"MIT"
] | 45 | 2018-03-04T15:07:22.000Z | 2022-03-16T22:13:58.000Z | /// \file
/// \author
///
/// \brief Implementation of shortcut snippet fragment class.
///
/// Copyright (c) . All rights reserved.
/// Licensed under the MIT License. See LICENSE file in the project root for full license information.
#include "stdafx.h"
#include "ShortcutSnippetFragment.h"
#include "BeeftextUtils.h"
//**********************************************************************************************************************
/// \param[in] shortcut The shortcut.
//**********************************************************************************************************************
ShortcutSnippetFragment::ShortcutSnippetFragment(SpShortcut const& shortcut)
: shortcut_(shortcut)
{
}
//**********************************************************************************************************************
/// \return The type of snippet fragment.
//**********************************************************************************************************************
SnippetFragment::EType ShortcutSnippetFragment::type() const
{
return EType::Shortcut;
}
//**********************************************************************************************************************
/// \return A string describing the shortcut snippet fragment
//**********************************************************************************************************************
QString ShortcutSnippetFragment::toString() const
{
return QString("Shortcut fragment : %1").arg(shortcut_ ? shortcut_->toString() : "null");
}
//**********************************************************************************************************************
//
//**********************************************************************************************************************
void ShortcutSnippetFragment::render() const
{
if (shortcut_)
renderShortcut(shortcut_);
}
| 37.9 | 120 | 0.355145 | sharpsteve |
7150dc8663ec4dddc2f9528a8cdb214f9023ad50 | 1,264 | cpp | C++ | leetcode/128_Longest_Consecutive_Sequence.cpp | wllvcxz/leetcode | 82358a0946084ba935ca1870b5e3f7c29c03fac3 | [
"MIT"
] | null | null | null | leetcode/128_Longest_Consecutive_Sequence.cpp | wllvcxz/leetcode | 82358a0946084ba935ca1870b5e3f7c29c03fac3 | [
"MIT"
] | null | null | null | leetcode/128_Longest_Consecutive_Sequence.cpp | wllvcxz/leetcode | 82358a0946084ba935ca1870b5e3f7c29c03fac3 | [
"MIT"
] | null | null | null | #include <unordered_map>
#include <vector>
using namespace std;
class Solution {
public:
int longestConsecutive(const vector<int> &nums) {
unordered_map<int, bool> used;
used.find(123);
for(auto i : nums)
used[i] = false;
int maxlen = 0;
for(auto i: nums){
if(used[i] == false){
used[i] = true;
int len = 1;
len += find_left(i, used);
len += find_right(i, used);
maxlen = maxlen < len? len: maxlen;
}
}
return maxlen;
}
int find_left(int i, unordered_map<int, bool>& used){
int count = 0;
while(true){
i = i + 1;
if(used.find(i) == used.end() || used[i] == true){
return count;
}else{
count++;
used[i] = true;
}
}
}
int find_right(int i, unordered_map<int, bool>& used){
int count = 0;
while(true){
i = i - 1;
if(used.find(i) == used.end() || used[i] == true){
return count;
}else{
count++;
used[i] = true;
}
}
}
};
| 25.28 | 62 | 0.412184 | wllvcxz |
715ef9818033fa5e738ed84fdd366620ae9afdc4 | 657 | cpp | C++ | src/servo/ServoPublisher.cpp | CatixBot/KinematicsNode | 451d109a472807029de8dc7392dd851f3039c3db | [
"MIT"
] | null | null | null | src/servo/ServoPublisher.cpp | CatixBot/KinematicsNode | 451d109a472807029de8dc7392dd851f3039c3db | [
"MIT"
] | null | null | null | src/servo/ServoPublisher.cpp | CatixBot/KinematicsNode | 451d109a472807029de8dc7392dd851f3039c3db | [
"MIT"
] | null | null | null | #include "servo/ServoPublisher.h"
#include <catix_messages/ServoState.h>
servo::ServoPublisher::ServoPublisher(size_t servoIndex, ros::NodeHandle& node)
: servoIndex(servoIndex)
, publisherServoState(node.advertise<catix_messages::ServoState>("Catix/Servo", 1))
{
}
bool servo::ServoPublisher::setAngle(double servoAngle)
{
catix_messages::ServoState servoStateMessage;
servoStateMessage.servo_index = static_cast<uint8_t>(this->servoIndex);
servoStateMessage.rotate_angle = servoAngle;
this->publisherServoState.publish(servoStateMessage);
ROS_INFO("Joint %d: [%frad]", this->servoIndex, servoAngle);
return true;
}
| 31.285714 | 87 | 0.757991 | CatixBot |
716a4f48a8db46c8577cc5bb2b5ef1ef5f698de7 | 28,586 | cpp | C++ | src/ofxRemoteUI.cpp | bensnell/ofxRemoteUI | 748c2da201d7568370610212efef4e4ea9710265 | [
"MIT"
] | 74 | 2015-01-06T05:08:42.000Z | 2022-01-09T03:29:14.000Z | src/ofxRemoteUI.cpp | bensnell/ofxRemoteUI | 748c2da201d7568370610212efef4e4ea9710265 | [
"MIT"
] | 15 | 2015-01-22T20:37:32.000Z | 2020-02-06T12:25:58.000Z | src/ofxRemoteUI.cpp | bensnell/ofxRemoteUI | 748c2da201d7568370610212efef4e4ea9710265 | [
"MIT"
] | 12 | 2015-02-22T16:52:14.000Z | 2020-06-30T04:19:10.000Z | //
// ofxRemoteUI.cpp
// emptyExample
//
// Created by Oriol Ferrer Mesià on 09/01/13.
//
//
#include "ofxRemoteUI.h"
#include <iostream>
#include <stdlib.h>
#include "uriencode.h"
#include <sstream>
#ifdef _WIN32
#include <windows.h>
#include <iphlpapi.h>
#include <WinSock2.h>
#pragma comment(lib, "iphlpapi.lib")
#endif
using namespace std;
void split(vector<std::string> &tokens, const std::string &text, char separator) {
std::size_t start = 0, end = 0;
while ((end = text.find(separator, start)) != std::string::npos) {
tokens.emplace_back(text.substr(start, end - start));
start = end + 1;
}
tokens.emplace_back(text.substr(start));
}
bool ofxRemoteUI::ready(){
return readyToSend;
}
void ofxRemoteUI::setVerbose(bool b){
verbose_ = b;
}
float ofxRemoteUI::connectionLag(){
return avgTimeSinceLastReply;
}
vector<std::string> ofxRemoteUI::getPresetsList(){
return presetNames;
}
void ofxRemoteUI::printAllParamsDebug(){
if(orderedKeys.size() == 0) return;
dataMutex.lock();
cout << "#### FULL PARAM LIST ################################" << endl;
for(size_t i = 0; i < orderedKeys.size(); i++){
string key = orderedKeys[i];
RemoteUIParam thisP = params[key];
cout << " index: " << i << " list: " << key << " > "; thisP.print();
}
dataMutex.unlock();
cout << "####################################################" << endl;
}
bool ofxRemoteUI::addParamToDB(const RemoteUIParam & p, const std::string & thisParamName){
//see if we already had it, if we didnt, set its add order #
dataMutex.lock();
bool ok;
auto it = params.find(thisParamName);
if ( it == params.end() ){ //not found!
params[thisParamName] = p;
orderedKeys[ (int)orderedKeys.size() ] = thisParamName;
paramsFromCode[thisParamName] = p; //cos this didnt exist before, we store it as "from code"
ok = true;
}else{
RLOG_ERROR << "already have a Param with that name on the DB : '" << thisParamName << "'. Ignoring it!";
ok = false;
}
dataMutex.unlock();
return ok;
}
void ofxRemoteUI::setParamDescription(const std::string & paramName, const std::string & description){
dataMutex.lock();
auto it = params.find(paramName);
if ( it != params.end() ){ //not found!
it->second.description = description;
}
dataMutex.unlock();
}
void ofxRemoteUI::clearOscReceiverMsgQueue(){
ofxOscMessage tempM;
//int c = 0;
//delete all pending messages
while (oscReceiver.getNextMessage(tempM)) {
//cout << "clearOscReceiverMsgQueue " << c << endl;
//c++;
}
}
vector<std::string> ofxRemoteUI::getChangedParamsList(){
std::vector<std::string> result (paramsChangedSinceLastCheck.begin(), paramsChangedSinceLastCheck.end());
paramsChangedSinceLastCheck.clear();
return result;
}
DecodedMessage ofxRemoteUI::decode(const ofxOscMessage & m) const{
std::string msgAddress = m.getAddress();
if((int)msgAddress.size() > 0){
if(msgAddress[0] == '/'){ //if address starts with "/", drop it to match the fucked up remoteUI protocol
msgAddress = msgAddress.substr(1, msgAddress.size() - 1);
}
//allow address to use the standard style /SEND/FLT/paramName instead of the legacy "SEND FLT paramName"
//allow /bbb/jjj/ syntax, but convert to space-based to avoid changing all the internal logic
for(int i = 0; i < (int)msgAddress.size(); i++){
if(msgAddress[i] == '/') msgAddress[i] = ' ';
}
}
std::string action = msgAddress.substr(0, 4);
//cout <<"Decode: "<< msgAddress << " action >> " << action << endl;
DecodedMessage dm;
//this is the lazynes maximus!
if (msgAddress.length() >= 3) {
if (action == "HELO") dm.action = HELO_ACTION;
else if (action == "REQU") dm.action = REQUEST_ACTION;
else if (action == "SEND") dm.action = SEND_PARAM_ACTION;
else if (action == "CIAO") dm.action = CIAO_ACTION;
else if (action == "TEST") dm.action = TEST_ACTION;
else if (action == "PREL") dm.action = PRESET_LIST_ACTION;
else if (action == "DELP") dm.action = DELETE_PRESET_ACTION;
else if (action == "SAVP") dm.action = SAVE_PRESET_ACTION;
else if (action == "SETP") dm.action = SET_PRESET_ACTION;
else if (action == "RESX") dm.action = RESET_TO_XML_ACTION;
else if (action == "RESD") dm.action = RESET_TO_DEFAULTS_ACTION;
else if (action == "SAVE") dm.action = SAVE_CURRENT_STATE_ACTION;
else if (action == "MISP") dm.action = GET_MISSING_PARAMS_IN_PRESET;
//groups (note lower case p, l)
else if (action == "DELp") dm.action = DELETE_GROUP_PRESET_ACTION;
else if (action == "SAVp") dm.action = SAVE_GROUP_PRESET_ACTION;
else if (action == "SETp") dm.action = SET_GROUP_PRESET_ACTION;
//log
else if (action == "LOG_") dm.action = SEND_LOG_LINE_ACTION;
//remove params
else if (action == "REMp") {
dm.action = REMOVE_PARAM;
dm.paramName = m.getArgAsString(0);
}
}
if (msgAddress.length() >= 8) {
std::string arg1 = msgAddress.substr(5, 3);
//cout << "Decode" << msgAddress << " arg1 >> " << arg1 << endl;
dm.argument = NULL_ARG;
if (arg1 == "FLT") dm.argument = FLT_ARG;
else if (arg1 == "INT") dm.argument = INT_ARG;
else if (arg1 == "BOL") dm.argument = BOL_ARG;
else if (arg1 == "STR") dm.argument = STR_ARG;
else if (arg1 == "ENU") dm.argument = ENUM_ARG;
else if (arg1 == "COL") dm.argument = COLOR_ARG;
else if (arg1 == "SPA") dm.argument = SPACER_ARG;
}else{
//must be a LOG_ action
}
if (msgAddress.length() >= 9) {
std::string paramName = msgAddress.substr(9, msgAddress.length() - 9);
dm.paramName = paramName;
}else{
//must be a LOG_ action
}
return dm;
}
std::string ofxRemoteUI::getMyIP(std::string userChosenInteface, std::string & subnetMask){
//from https://github.com/jvcleave/LocalAddressGrabber/blob/master/src/LocalAddressGrabber.h
//and http://stackoverflow.com/questions/17288908/get-network-interface-name-from-ipv4-address
std::string output = RUI_LOCAL_IP_ADDRESS;
#if defined(__APPLE__) || defined(__linux__)
struct ifaddrs *myaddrs;
struct ifaddrs *ifa;
struct sockaddr_in *s4;
int status;
char buf[64];
status = getifaddrs(&myaddrs);
if (status != 0){
RLOG_ERROR << "getifaddrs failed! errno: " << errno;
}else{
for (ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next){
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET){
s4 = (struct sockaddr_in *)(ifa->ifa_addr);
if (inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, sizeof(buf)) == NULL){
RLOG_ERROR <<ifa->ifa_name << ": inet_ntop failed!";
}
void * tmpAddrPtr = &((struct sockaddr_in *)ifa->ifa_netmask)->sin_addr;
char SnAddressBuffer[INET_ADDRSTRLEN];
if(inet_ntop(AF_INET, tmpAddrPtr, SnAddressBuffer, INET_ADDRSTRLEN) == NULL){
RLOG_ERROR <<ifa->ifa_name << ": inet_ntop for subnet failed!";
}
if(inet_ntop(ifa->ifa_addr->sa_family, (void *)&(s4->sin_addr), buf, sizeof(buf)) == NULL){
RLOG_ERROR <<ifa->ifa_name << ": inet_ntop for address failed!";
}else{
std::string interface = std::string(ifa->ifa_name);
if(verbose_) RLOG_VERBOSE << "found interface: " << interface ;
if( interface.length() > 2 || interface == userSuppliedNetInterface ){
if (userSuppliedNetInterface.length() > 0){
if (interface == userSuppliedNetInterface){
output = std::string(buf);
subnetMask = std::string(SnAddressBuffer);
RLOG_VERBOSE << "using user chosen interface: " << interface;
break;
}
}else{
if ((interface[0] == 'e' && interface[1] == 'n') || (interface[0] == 'e' && interface[1] == 't')){
if(strlen(buf) > 2){
bool is169 = buf[0] == '1' && buf[1] == '6' && buf[2] == '9';
if(!is169){ //avoid 169.x.x.x addresses
output = std::string(buf);
subnetMask = std::string(SnAddressBuffer);
RLOG_NOTICE << "Using interface: " << interface << " IP: " << output << " SubnetMask: " << subnetMask;
break;
}
}
}
}
}
}
}
}
freeifaddrs(myaddrs);
}
#endif
#ifdef _WIN32
ULONG buflen = sizeof(IP_ADAPTER_INFO);
IP_ADAPTER_INFO *pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen);
if (GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen);
}
if (GetAdaptersInfo(pAdapterInfo, &buflen) == NO_ERROR) {
//FIXME: this is crappy, we get the first non 0.0.0.0 interface (no idea which order they come in)
for (IP_ADAPTER_INFO *pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) {
//printf("%s (%s)\n", pAdapter->IpAddressList.IpAddress.String, pAdapter->Description);
std::string ip = pAdapter->IpAddressList.IpAddress.String;
if (ip != "0.0.0.0"){
output = ip;
subnetMask = pAdapter->IpAddressList.IpMask.String;
break;
}
}
}
if (pAdapterInfo) free(pAdapterInfo);
#endif
if (userSuppliedNetInterface.length() > 0){
if (output == RUI_LOCAL_IP_ADDRESS){
RLOG_ERROR << "could not find the user supplied net interface: " << userSuppliedNetInterface;
RLOG_ERROR << "automatic advertising will not work! ";
}
}
return output;
}
#ifdef _WIN32
void GetHostName(std::string& host_name){
WSAData wsa_data;
int ret_code;
char buf[MAX_PATH];
WSAStartup(MAKEWORD(1, 1), &wsa_data);
ret_code = gethostname(buf, MAX_PATH);
if (ret_code == SOCKET_ERROR)
host_name = RUI_LOCAL_IP_ADDRESS;
else
host_name = buf;
WSACleanup();
}
#endif
void ofxRemoteUI::updateParamFromDecodedMessage(const ofxOscMessage & m, DecodedMessage dm){
std::string paramName = dm.paramName;
RemoteUIParam original;
bool newParam = true;
auto it = params.find(paramName);
if ( it != params.end() ){ //found the param, we already had it
original = params[paramName];
newParam = false;
}
RemoteUIParam p = original;
size_t arg = 0;
switch (dm.argument) {
case FLT_ARG:
p.type = REMOTEUI_PARAM_FLOAT;
p.floatVal = m.getArgAsFloat(arg); arg++;
if(m.getNumArgs() > 1){
p.minFloat = m.getArgAsFloat(arg); arg++;
p.maxFloat = m.getArgAsFloat(arg); arg++;
}
if (p.floatValAddr){
*p.floatValAddr = p.floatVal;
}break;
case INT_ARG:
p.type = REMOTEUI_PARAM_INT;
p.intVal = m.getArgAsInt32(arg); arg++;
if(m.getNumArgs() > 1){
p.minInt = m.getArgAsInt32(arg); arg++;
p.maxInt = m.getArgAsInt32(arg); arg++;
}
if (p.intValAddr){
*p.intValAddr = p.intVal;
}break;
case COLOR_ARG:
p.type = REMOTEUI_PARAM_COLOR;
if(m.getNumArgs() == 1){ //hex rgba encoded in one single int - vezér style
#ifdef OF_AVAILABLE
std::uint32_t rgba = m.getArgAsRgbaColor(arg); arg++;
#else
std::uint32_t rgba = m.getArgAsInt32(arg); arg++;
#endif
p.redVal = (rgba & 0xFF000000) >> 24;
p.greenVal = (rgba & 0x00FF0000) >> 16;
p.blueVal = (rgba & 0x0000FF00) >> 8;
p.alphaVal = (rgba & 0x000000FF);
}else{ //legacy ofxRemoteUI
p.redVal = (int)m.getArgAsInt32(arg); arg++;
p.greenVal = (int)m.getArgAsInt32(arg); arg++;
p.blueVal = (int)m.getArgAsInt32(arg); arg++;
p.alphaVal = (int)m.getArgAsInt32(arg); arg++;
}
if (p.redValAddr){
*p.redValAddr = p.redVal;
*(p.redValAddr+1) = p.greenVal;
*(p.redValAddr+2) = p.blueVal;
*(p.redValAddr+3) = p.alphaVal;
}break;
case ENUM_ARG:{
p.type = REMOTEUI_PARAM_ENUM;
p.intVal = m.getArgAsInt32(arg); arg++;
if (p.intValAddr){
*p.intValAddr = p.intVal;
}
if(m.getNumArgs() > 1){ //for standard RUI client
p.minInt = m.getArgAsInt32(arg); arg++;
p.maxInt = m.getArgAsInt32(arg); arg++;
int n = p.maxInt - p.minInt + 1;
int i = 0;
p.enumList.clear();
for (i = 0; i < n; i++) {
p.enumList.emplace_back( m.getArgAsString(arg + i) );
}
arg = arg + i;
}else{ //for basic enum suppport, where only the enum int value is sent (ie vezer)
arg ++; //only one param was used
}
}break;
case BOL_ARG:
p.type = REMOTEUI_PARAM_BOOL;
p.boolVal = m.getArgAsInt32(arg) == 0 ? false : true; arg++;
if (p.boolValAddr){
*p.boolValAddr = p.boolVal;
}break;
case STR_ARG:
p.type = REMOTEUI_PARAM_STRING;
p.stringVal = m.getArgAsString(arg); arg++;
if (p.stringValAddr){
*p.stringValAddr = p.stringVal;
}break;
case SPACER_ARG:
p.type = REMOTEUI_PARAM_SPACER;
p.stringVal = m.getArgAsString(arg); arg++;
break;
case NULL_ARG: RLOG_ERROR << "updateParamFromDecodedMessage NULL type!"; break;
default: RLOG_ERROR << "updateParamFromDecodedMessage unknown type!"; break;
}
if(m.getNumArgs() > arg){ //if msg contains bg color, parse it
p.r = m.getArgAsInt32(arg); arg++;
p.g = m.getArgAsInt32(arg); arg++;
p.b = m.getArgAsInt32(arg); arg++;
p.a = m.getArgAsInt32(arg); arg++;
p.group = m.getArgAsString(arg); arg++;
if(m.getNumArgs() > arg){ //if it provides a description, read it
p.description = m.getArgAsString(arg); arg++;
}
}
if ( !p.isEqualTo(original) || newParam ){ // if the udpdate changed the param, keep track of it
if(std::find(paramsChangedSinceLastCheck.begin(), paramsChangedSinceLastCheck.end(), paramName) == paramsChangedSinceLastCheck.end()){
paramsChangedSinceLastCheck.emplace_back(paramName);
}
}
//here we update our param db
//params[paramName] = p;
if(newParam)
addParamToDB(p, paramName);
else
params[paramName] = p;
}
vector<std::string> ofxRemoteUI::getAllParamNamesList(){
vector<std::string>paramsList;
//get list of params in add order
dataMutex.lock();
for( auto ii = orderedKeys.begin(); ii != orderedKeys.end(); ++ii ){
const std::string & paramName = (*ii).second;
paramsList.emplace_back(paramName);
}
dataMutex.unlock();
return paramsList;
}
vector<std::string> ofxRemoteUI::scanForUpdatedParamsAndSync(){
vector<std::string>paramsPendingUpdate;
dataMutex.lock();
for( auto ii = params.begin(); ii != params.end(); ++ii ){
RemoteUIParam p = (*ii).second;
if ( hasParamChanged(p) ){
paramsPendingUpdate.emplace_back( (*ii).first );
syncParamToPointer((*ii).first);
}
}
dataMutex.unlock();
return paramsPendingUpdate;
}
void ofxRemoteUI::sendUpdateForParamsInList(vector<std::string>list){
dataMutex.lock();
for(size_t i = 0; i < list.size(); i++){
std::string name = list[i];
auto it = params.find(name);
if(it!=params.end()){
const RemoteUIParam & p = params[list[i]];
//cout << "ofxRemoteUIServer: sending updated param " + list[i]; p.print();
sendParam(list[i], p);
}else{
RLOG_ERROR << "param not found?!";
}
}
dataMutex.unlock();
}
void ofxRemoteUI::syncAllParamsToPointers(){
dataMutex.lock();
for( auto ii = params.begin(); ii != params.end(); ++ii ){
syncParamToPointer( (*ii).first );
}
dataMutex.unlock();
}
void ofxRemoteUI::syncAllPointersToParams(){
dataMutex.lock();
for( auto ii = params.begin(); ii != params.end(); ++ii ){
syncPointerToParam( (*ii).first );
}
dataMutex.unlock();
}
void ofxRemoteUI::syncPointerToParam(const std::string & paramName){
RemoteUIParam &p = params[paramName];
switch (p.type) {
case REMOTEUI_PARAM_FLOAT:
if (p.floatValAddr){
*p.floatValAddr = p.floatVal;
}break;
case REMOTEUI_PARAM_ENUM:
case REMOTEUI_PARAM_INT:
if (p.intValAddr){
*p.intValAddr = p.intVal;
}break;
case REMOTEUI_PARAM_COLOR:
if (p.redValAddr){
*p.redValAddr = p.redVal ;
*(p.redValAddr+1) = p.greenVal;
*(p.redValAddr+2) = p.blueVal;
*(p.redValAddr+3) = p.alphaVal;
}break;
case REMOTEUI_PARAM_BOOL:
if (p.boolValAddr){
*p.boolValAddr = p.boolVal;
}break;
case REMOTEUI_PARAM_SPACER:
case REMOTEUI_PARAM_STRING:
if (p.stringValAddr){
*p.stringValAddr = p.stringVal;
}break;
default: break;
}
}
void ofxRemoteUI::syncParamToPointer(const std::string & paramName){
RemoteUIParam & p = params[paramName];
switch (p.type) {
case REMOTEUI_PARAM_FLOAT:
if (p.floatValAddr){
p.floatVal = *p.floatValAddr;
}break;
case REMOTEUI_PARAM_ENUM:
case REMOTEUI_PARAM_INT:
if (p.intValAddr){
p.intVal = *p.intValAddr;
}break;
case REMOTEUI_PARAM_COLOR:
if (p.redValAddr){
p.redVal = *p.redValAddr;
p.greenVal = *(p.redValAddr+1);
p.blueVal = *(p.redValAddr+2);
p.alphaVal = *(p.redValAddr+3);
}break;
case REMOTEUI_PARAM_BOOL:
if (p.boolValAddr){
p.boolVal = *p.boolValAddr;
}break;
case REMOTEUI_PARAM_SPACER:
case REMOTEUI_PARAM_STRING:
if (p.stringValAddr){
p.stringVal = *p.stringValAddr;
}break;
default: break;
}
}
bool ofxRemoteUI::hasParamChanged(const RemoteUIParam & p){
switch (p.type) {
case REMOTEUI_PARAM_FLOAT:
if (p.floatValAddr){
if (*p.floatValAddr != p.floatVal) return true; else return false;
}
return false;
case REMOTEUI_PARAM_ENUM:
case REMOTEUI_PARAM_INT:
if (p.intValAddr){
if (*p.intValAddr != p.intVal) return true; else return false;
}
return false;
case REMOTEUI_PARAM_COLOR:
if (p.redValAddr){
if (*p.redValAddr != p.redVal || *(p.redValAddr+1) != p.greenVal || *(p.redValAddr+2) != p.blueVal || *(p.redValAddr+3) != p.alphaVal ) return true;
else return false;
}
return false;
case REMOTEUI_PARAM_BOOL:
if (p.boolValAddr){
if (*p.boolValAddr != p.boolVal) return true; else return false;
}
return false;
case REMOTEUI_PARAM_STRING:
if (p.stringValAddr){
if (*p.stringValAddr != p.stringVal) return true; else return false;
}
return false;
case REMOTEUI_PARAM_SPACER: return false;
default: break;
}
RLOG_ERROR << "hasParamChanged >> something went wrong, unknown param type";
return false;
}
std::string ofxRemoteUI::stringForParamType(RemoteUIParamType t){
switch (t) {
case REMOTEUI_PARAM_FLOAT: return "FLT";
case REMOTEUI_PARAM_INT: return "INT";
case REMOTEUI_PARAM_COLOR: return "COL";
case REMOTEUI_PARAM_ENUM: return "ENU";
case REMOTEUI_PARAM_BOOL: return "BOL";
case REMOTEUI_PARAM_STRING: return "STR";
case REMOTEUI_PARAM_SPACER: return "SPA";
default: break;
}
RLOG_ERROR << "stringForParamType >> UNKNOWN TYPE!";
return "ERR";
}
bool ofxRemoteUI::paramExistsForName(const std::string & paramName){
dataMutex.lock();
auto it = params.find(paramName);
dataMutex.unlock();
return it != params.end();
}
RemoteUIParam ofxRemoteUI::getParamForName(const std::string & paramName){
RemoteUIParam p;
dataMutex.lock();
auto it = params.find(paramName);
if ( it != params.end() ){ // found!
p = params[paramName];
}else{
RLOG_ERROR << "getParamForName >> param " + paramName + " not found!";
}
dataMutex.unlock();
return p;
}
RemoteUIParam& ofxRemoteUI::getParamRefForName(const std::string & paramName){
auto it = params.find(paramName);
if ( it != params.end() ){ // found!
return params[paramName];
}else{
RLOG_ERROR << "getParamForName >> param " + paramName + " not found!";
}
return nullParam;
}
std::string ofxRemoteUI::getValuesAsString(const vector<std::string> & paramList){
std::stringstream out;
auto it = orderedKeys.begin();
while( it != orderedKeys.end() ){
std::string pname = it->second;
if(paramList.size() == 0 || find(paramList.begin(), paramList.end(), pname) != paramList.end()){
RemoteUIParam param = params[it->second];
if(param.type != REMOTEUI_PARAM_SPACER){
out << UriEncode(it->second) << "=";
}
switch (param.type) {
case REMOTEUI_PARAM_FLOAT: out << param.floatVal << endl; break;
case REMOTEUI_PARAM_INT: out << param.intVal << endl; break;
case REMOTEUI_PARAM_COLOR: out << (int)param.redVal << " " << (int)param.greenVal << " " << (int)param.blueVal << " " << (int)param.alphaVal << " " << endl; break;
case REMOTEUI_PARAM_ENUM: out << param.intVal << endl; break;
case REMOTEUI_PARAM_BOOL: out << (param.boolVal?"1":"0") << endl; break;
case REMOTEUI_PARAM_STRING: out << UriEncode(param.stringVal) << endl; break;
case REMOTEUI_PARAM_SPACER: break;
default: break;
}
}
++it;
}
return out.str();
}
void ofxRemoteUI::setValuesFromString( const std::string & values ){
stringstream in(values);
std::string name, value;
vector<std::string>changedParam;
while( !in.eof() ){
getline( in, name, '=' );
getline( in, value, '\n' );
dataMutex.lock();
if( params.find( name ) != params.end() ){
RemoteUIParam param = params[name];
RemoteUIParam original = params[name];
changedParam.emplace_back(name);
stringstream valstr( UriDecode(value) );
switch (param.type) {
case REMOTEUI_PARAM_FLOAT: valstr >> param.floatVal; break;
case REMOTEUI_PARAM_INT: valstr >> param.intVal; break;
case REMOTEUI_PARAM_COLOR: {
std::istringstream ss(UriDecode(value));
std::string token;
std::getline(ss, token, ' '); param.redVal = atoi(token.c_str());
std::getline(ss, token, ' '); param.greenVal = atoi(token.c_str());
std::getline(ss, token, ' '); param.blueVal = atoi(token.c_str());
std::getline(ss, token, ' '); param.alphaVal = atoi(token.c_str());
}
case REMOTEUI_PARAM_ENUM: valstr >> param.intVal; break;
case REMOTEUI_PARAM_BOOL: valstr >> param.boolVal; break;
case REMOTEUI_PARAM_STRING: param.stringVal = valstr.str(); break;
case REMOTEUI_PARAM_SPACER: break;
default: break;
}
if ( !param.isEqualTo(original) ){ // if the udpdate changed the param, keep track of it
params[name] = param;
syncPointerToParam(name);
if(std::find(paramsChangedSinceLastCheck.begin(), paramsChangedSinceLastCheck.end(), name) == paramsChangedSinceLastCheck.end()){
paramsChangedSinceLastCheck.emplace_back(name);
}
}
dataMutex.unlock();
}else{
if(name.size()){
RLOG_NOTICE << "unknown param name; ignoring (" << name << ")";
}
}
}
vector<std::string>::iterator it = changedParam.begin();
while( it != changedParam.end() ){
dataMutex.lock();
if ( params.find( *it ) != params.end()){
RemoteUIParam param = params[*it];
sendUntrackedParamUpdate(param, *it);
RLOG_VERBOSE << "sending update for " << *it ;
ScreenNotifArg arg;
arg.paramName = *it;
arg.p = param;
arg.bgColor = (param.type == REMOTEUI_PARAM_COLOR) ? param.getColor() : ofColor(0,0,0,0);
#ifdef OF_AVAILABLE
ofNotifyEvent(eventShowParamUpdateNotification, arg, this);
#endif
}
dataMutex.unlock();
it++;
}
}
void ofxRemoteUI::sendParam(std::string paramName, const RemoteUIParam & p){
ofxOscMessage m;
//if(verbose_){ ofLogVerbose("sending >> %s ", paramName.c_str()); p.print(); }
m.setAddress("/SEND " + stringForParamType(p.type) + " " + paramName);
switch (p.type) {
case REMOTEUI_PARAM_FLOAT: m.addFloatArg(p.floatVal); m.addFloatArg(p.minFloat); m.addFloatArg(p.maxFloat); break;
case REMOTEUI_PARAM_INT: m.addIntArg(p.intVal); m.addIntArg(p.minInt); m.addIntArg(p.maxInt); break;
case REMOTEUI_PARAM_COLOR: m.addIntArg(p.redVal); m.addIntArg(p.greenVal); m.addIntArg(p.blueVal); m.addIntArg(p.alphaVal); break;
case REMOTEUI_PARAM_BOOL: m.addIntArg(p.boolVal ? 1 : 0); break;
case REMOTEUI_PARAM_STRING: m.addStringArg(p.stringVal); break;
case REMOTEUI_PARAM_ENUM:{
m.addIntArg(p.intVal); m.addIntArg(p.minInt); m.addIntArg(p.maxInt);
for (size_t i = 0; i < p.enumList.size(); i++) {
m.addStringArg(p.enumList[i]);
}
}break;
case REMOTEUI_PARAM_SPACER: m.addStringArg(p.stringVal); break;
default: break;
}
m.addIntArg(p.r); m.addIntArg(p.g); m.addIntArg(p.b); m.addIntArg(p.a); // set bg color!
m.addStringArg(p.group);
m.addStringArg(p.description);
try{
sendMessage(m);
if(verbose_) RLOG_VERBOSE << "sendParam(" << paramName << ")";
paramsSentOverOsc.insert(paramName);
}catch(std::exception & e){
RLOG_ERROR << "exception sendParam " << paramName;
}
}
//if used by server, confirmation == YES
//else, NO
void ofxRemoteUI::sendREQU(bool confirmation){
if(verbose_) RLOG_VERBOSE << "sendREQU()";
ofxOscMessage m;
m.setAddress("/REQU");
if (confirmation) m.addStringArg("OK");
sendMessage(m);
}
void ofxRemoteUI::sendRESX(bool confirm){
if(verbose_) RLOG_VERBOSE << "sendRESX()";
ofxOscMessage m;
m.setAddress("/RESX");
if (confirm) m.addStringArg("OK");
sendMessage(m);
}
void ofxRemoteUI::sendRESD(bool confirm){
if(verbose_) RLOG_VERBOSE << "sendRESD()";
ofxOscMessage m;
m.setAddress("/RESD");
if (confirm) m.addStringArg("OK");
sendMessage(m);
}
void ofxRemoteUI::sendSAVE(bool confirm){
if(verbose_) RLOG_VERBOSE << "sendSAVE()";
ofxOscMessage m;
m.setAddress("/SAVE");
if (confirm) m.addStringArg("OK");
sendMessage(m);
}
void ofxRemoteUI::sendTEST(){
//if(verbose_) RLOG_VERBOSE << "sendTEST()";
waitingForReply = true;
timeSinceLastReply = 0.0f;
ofxOscMessage m;
m.setAddress("/TEST");
sendMessage(m);
}
//on client call, presetNames should be empty vector (request ing the list)
//on server call, presetNames should have all the presetNames
void ofxRemoteUI::sendPREL( vector<std::string> presetNames_ ){
if(verbose_) RLOG_VERBOSE << "sendPREL()";
ofxOscMessage m;
m.setAddress("/PREL");
if (presetNames_.size() == 0){ // if we are the client requesting a preset list, delete our current list
presetNames.clear();
m.addStringArg("OK");
}
for(size_t i = 0; i < presetNames_.size(); i++){
m.addStringArg(presetNames_[i]);
}
sendMessage(m);
}
//on client call, presetName should be the new preset name
//on server call, presetName should be empty string (so it will send "OK"
void ofxRemoteUI::sendSAVP(std::string presetName, bool confirm){
if(verbose_) RLOG_VERBOSE << "sendSAVP()";
ofxOscMessage m;
m.setAddress("/SAVP");
m.addStringArg(presetName);
if (confirm){
m.addStringArg("OK");
}
sendMessage(m);
}
//on client call, presetName should be the new preset name
//on server call, presetName should be empty string (so it will send "OK"
void ofxRemoteUI::sendSETP(std::string presetName, bool confirm){
if(verbose_) RLOG_VERBOSE << "sendSETP()";
ofxOscMessage m;
m.setAddress("/SETP");
m.addStringArg(presetName);
if (confirm){
m.addStringArg("OK");
}
sendMessage(m);
}
void ofxRemoteUI::sendMISP(vector<std::string> missingParamsInPreset){
if (missingParamsInPreset.size() == 0) return; //do nothing if no params are missing
if(verbose_) RLOG_VERBOSE << "sendMISP()";
ofxOscMessage m;
m.setAddress("/MISP");
for(size_t i = 0; i < missingParamsInPreset.size(); i++){
m.addStringArg(missingParamsInPreset[i]);
}
sendMessage(m);
}
void ofxRemoteUI::sendREMp(const string & paramName){
if(verbose_) RLOG_VERBOSE << "sendREMp() " << paramName ;
if(readyToSend){
ofxOscMessage m;
m.setAddress("/REMp");
m.addStringArg(paramName);
try{
sendMessage(m);
}catch(std::exception & e){
RLOG_ERROR << "Exception sendREMp " << e.what() ;
}
}
}
void ofxRemoteUI::sendDELP(std::string presetName, bool confirm){
if(verbose_) RLOG_VERBOSE << "sendDELP()";
ofxOscMessage m;
m.setAddress("/DELP");
m.addStringArg(presetName);
if (confirm){
m.addStringArg("OK");
}
sendMessage(m);
}
void ofxRemoteUI::sendHELLO(){
ofxOscMessage m;
m.setAddress("/HELO");
sendMessage(m);
}
void ofxRemoteUI::sendCIAO(){
ofxOscMessage m;
m.setAddress("/CIAO");
sendMessage(m);
}
//on client call, presetName should be the new preset name
//on server call, presetName should be empty string (so it will send "OK"
void ofxRemoteUI::sendSETp(std::string presetName, std::string group, bool confirm){
if(verbose_) RLOG_VERBOSE << "sendSETp()";
ofxOscMessage m;
m.setAddress("/SETp");
m.addStringArg(presetName);
m.addStringArg(group);
if (confirm){
m.addStringArg("OK");
}
sendMessage(m);
}
//on client call, presetName should be the new preset name
//on server call, presetName should be empty string (so it will send "OK"
void ofxRemoteUI::sendSAVp(std::string presetName, std::string group, bool confirm){
if(verbose_) RLOG_VERBOSE << "sendSAVp()";
ofxOscMessage m;
m.setAddress("/SAVp");
m.addStringArg(presetName);
m.addStringArg(group);
if (confirm){
m.addStringArg("OK");
}
sendMessage(m);
}
//on client call, presetName should be the new preset name
//on server call, presetName should be empty string (so it will send "OK"
void ofxRemoteUI::sendDELp(std::string presetName, std::string group, bool confirm){
if(verbose_) RLOG_VERBOSE << "sendDELp()";
ofxOscMessage m;
m.setAddress("/DELp");
m.addStringArg(presetName);
m.addStringArg(group);
if (confirm){
m.addStringArg("OK");
}
sendMessage(m);
}
const char *get_filename_ext(const char *filename) {
const char *dot = strrchr(filename, '.');
if(!dot || dot == filename) return "";
return dot + 1;
}
| 29.050813 | 167 | 0.669489 | bensnell |
716d6ff89efec8bad608f89174518f0b59c56ae0 | 2,783 | cpp | C++ | src/Components/ConcaveCollider.cpp | charlieSewell/YOKAI | 4fb39975e58e9a49bc984bc6e844721a7ad9462e | [
"MIT"
] | null | null | null | src/Components/ConcaveCollider.cpp | charlieSewell/YOKAI | 4fb39975e58e9a49bc984bc6e844721a7ad9462e | [
"MIT"
] | null | null | null | src/Components/ConcaveCollider.cpp | charlieSewell/YOKAI | 4fb39975e58e9a49bc984bc6e844721a7ad9462e | [
"MIT"
] | null | null | null | #include "ConcaveCollider.hpp"
ConcaveCollider::ConcaveCollider(GameObject* parent) : Component(parent){}
void ConcaveCollider::Start()
{
if(m_parent->GetComponent<Transform>() == nullptr)
{
m_parent->AddComponent<Transform>();
}
modelID = m_parent->GetComponent<DrawableEntity>()->GetModelID();
m_colliderID = PhysicsSystem::getInstance().AddConcaveShape(3,m_parent->GetComponent<Transform>().get(),m_parent->GetComponent<DrawableEntity>()->GetModelID());
}
void ConcaveCollider::Update(float deltaTime)
{
}
void ConcaveCollider::setMass(double m) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetMass(m);
}
double ConcaveCollider::getMass() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetMass();
}
double ConcaveCollider::getInverseMass() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetInverseMass();
}
void ConcaveCollider::setCentreOfMass(glm::dvec3 com) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetCentreOfMass(com);
}
glm::dvec3 ConcaveCollider::getCentreOfMass() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetCentreOfMass();
}
void ConcaveCollider::setInertiaTensor(glm::dmat3x3 it) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetInertiaTensor(it);
}
glm::dmat3x3 ConcaveCollider::getInertiaTensor() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetInertiaTensor();
}
glm::dmat3x3 ConcaveCollider::getInverseInertiaTensor() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetInverseInertiaTensor();
}
void ConcaveCollider::setLinearVelocity(glm::dvec3 lv) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetLinearVelocity(lv);
}
glm::dvec3 ConcaveCollider::getLinearVelocity() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetLinearVelocity();
}
void ConcaveCollider::setAngularVelocity(glm::dvec3 av) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetAngularVelocity(av);
}
glm::dvec3 ConcaveCollider::getAngularVelocity() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetAngularVelocity();
}
void ConcaveCollider::setIsStaticObject(bool s) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetIsStaticObject(s);
}
bool ConcaveCollider::getIsStaticObject() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetIsStaticObject();
}
void ConcaveCollider::setGravityAffected(bool g) {
PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->SetGravityAffected(g);
}
bool ConcaveCollider::getGravityAffected() {
return PhysicsSystem::getInstance().GetPhysicsBody(m_colliderID)->GetGravityAffected();
} | 33.939024 | 161 | 0.775782 | charlieSewell |
716f342aa6b588f4e376ac4f8618ba577645342c | 1,928 | cpp | C++ | C++/Timer.cpp | juliafeingold/My-Cpp-programs | cbc7095082da25ce2a4f66d711d77af8d794206c | [
"Apache-2.0"
] | null | null | null | C++/Timer.cpp | juliafeingold/My-Cpp-programs | cbc7095082da25ce2a4f66d711d77af8d794206c | [
"Apache-2.0"
] | null | null | null | C++/Timer.cpp | juliafeingold/My-Cpp-programs | cbc7095082da25ce2a4f66d711d77af8d794206c | [
"Apache-2.0"
] | null | null | null |
#include <iostream>
using namespace std;
class Timer
{
protected:
int setting;
int current;
public:
Timer(int s){
setting = s;
current = s;
}
virtual void OneTick(){
current--;
}
virtual bool Done() const{
return (current == 0);
}
virtual void Reset(){
current = setting;
}
virtual void Go()
{
while (this->Done() == false)
{
cout << current << "*";
this->OneTick();
}
cout << "ding!\n";
}
};
class UpwardCounter : public Timer
{
public:
UpwardCounter(int s) : Timer(s){
current = 0;
}
virtual void OneTick(){
current++;
}
virtual bool Done() const{
return (current >= setting);
}
virtual void Reset()
{
current = 0;
}
};
class MultCounter : public UpwardCounter
{
protected:
int mult;
public:
MultCounter(int s, int m) : UpwardCounter(s){
mult = m;
current = 1;
}
virtual void OneTick()
{
current = current * mult;
}
virtual void Reset()
{
current = 1;
}
};
class ExpoCounter : public MultCounter
{
public:
ExpoCounter(int s, int m = 1) : MultCounter(s, m)
{
current = 1;
}
void OneTick()
{
mult++;
current = mult * mult;
}
void Reset()
{
mult = 1;
current = 1;
}
};
int main()
{
cout << "Part 1" << endl;
Timer timerA(4);
timerA.Go();
cout << endl << endl;
cout << "Part 2" << endl;
UpwardCounter upB(4);
upB.Go();
cout << endl << endl;
cout << "Part 3" << endl;
MultCounter multC(8, 2);
multC.Go();
cout << endl << endl;
cout << "Part 4" << endl;
MultCounter multD(20, 3);
multD.Go();
cout << endl << endl;
cout << "Part 5" << endl;
timerA.Reset();
timerA.Go();
cout << endl << endl;
cout << "Part 6" << endl;
upB.Reset();
upB.Go();
cout << endl << endl;
cout << "Part 7" << endl;
multD.Reset();
multD.Go();
cout << endl << endl;
cout << "Part 8" << endl;
ExpoCounter ecE(100);
ecE.Go();
cout << endl << endl;
return 0;
}
| 14.176471 | 53 | 0.560685 | juliafeingold |
716fcb49daa264f7a86e37db02e53c3b1ac79a24 | 670 | cpp | C++ | src/hatchetfish_stopwatch.cpp | microwerx/hatchetfish | 923b951fc0ef578773fe88edaad9754d8a43ff77 | [
"MIT"
] | null | null | null | src/hatchetfish_stopwatch.cpp | microwerx/hatchetfish | 923b951fc0ef578773fe88edaad9754d8a43ff77 | [
"MIT"
] | null | null | null | src/hatchetfish_stopwatch.cpp | microwerx/hatchetfish | 923b951fc0ef578773fe88edaad9754d8a43ff77 | [
"MIT"
] | null | null | null | #include <hatchetfish_stopwatch.hpp>
namespace Hf {
StopWatch::StopWatch() {
start_timepoint = std::chrono::system_clock::now();
}
StopWatch::~StopWatch() {}
void StopWatch::Start() {
start_timepoint = std::chrono::system_clock::now();
}
void StopWatch::Stop() {
end_timepoint = std::chrono::system_clock::now();
}
double StopWatch::GetSecondsElapsed() {
auto diff = end_timepoint - start_timepoint;
return std::chrono::duration<double>(diff).count();
}
double StopWatch::GetMillisecondsElapsed() {
auto diff = end_timepoint - start_timepoint;
return std::chrono::duration<double, std::milli>(diff).count();
}
}
| 23.928571 | 66 | 0.676119 | microwerx |
7172b98808cb8022c7da883aeb8c5bd3eadaa54b | 739 | cpp | C++ | atcoder/abc/abc162/b.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc162/b.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc162/b.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
ll n,ans=0;
cin>>n;
ans=(n+1)*n/2;
ll m3=n-(n%3);
ll m5=n-(n%5);
ll m15=n-(n%15);
ll kou3=(m3-0)/3;
ll sum3=kou3*(3+m3)/2;
ll kou5=(m5-0)/5;
ll sum5=kou5*(5+m5)/2;
ll kou15=(m15-0)/15;
ll sum15=kou15*(15+m15)/2;
ans=ans-sum3-sum5+sum15;
//cout<<ans<<" "<<sum3<<" "<<sum5<<" "<<sum15<<endl;
cout<<ans<<endl;
return 0;
} | 18.02439 | 58 | 0.516915 | yu3mars |
71794cdb6a0874ede23cb71158bf445c76abbe89 | 1,476 | cpp | C++ | audio/linux/AudioEngine-linux.cpp | yangosoft/cocos2d-x-arm-opengles | af33a880b3f375ea31f0eacf4ffab769424ceba6 | [
"MIT"
] | 1 | 2020-12-26T19:47:41.000Z | 2020-12-26T19:47:41.000Z | audio/linux/AudioEngine-linux.cpp | yangosoft/cocos2d-x-arm-opengles | af33a880b3f375ea31f0eacf4ffab769424ceba6 | [
"MIT"
] | 1 | 2018-05-09T08:39:17.000Z | 2018-06-13T05:44:43.000Z | audio/linux/AudioEngine-linux.cpp | yangosoft/cocos2d-x-arm-opengles | af33a880b3f375ea31f0eacf4ffab769424ceba6 | [
"MIT"
] | null | null | null | /**
* @author cesarpachon
*/
#include <cstring>
#include "audio/linux/AudioEngine-linux.h"
#include "cocos2d.h"
using namespace cocos2d;
using namespace cocos2d::experimental;
AudioEngineImpl * g_AudioEngineImpl = nullptr;
typedef int FMOD_RESULT;
AudioEngineImpl::AudioEngineImpl(){
};
AudioEngineImpl::~AudioEngineImpl(){
};
bool AudioEngineImpl::init(){
return true;
};
int AudioEngineImpl::play2d(const std::string &fileFullPath ,bool loop ,float volume){
return 0;
};
void AudioEngineImpl::setVolume(int audioID,float volume){
};
void AudioEngineImpl::setLoop(int audioID, bool loop){
};
bool AudioEngineImpl::pause(int audioID){
return true;
};
bool AudioEngineImpl::resume(int audioID){
return true;
};
bool AudioEngineImpl::stop(int audioID){
return true;
};
void AudioEngineImpl::stopAll(){
};
float AudioEngineImpl::getDuration(int audioID){
return 0.0f;
};
float AudioEngineImpl::getCurrentTime(int audioID){
return 0;
};
bool AudioEngineImpl::setCurrentTime(int audioID, float time){
return true;
};
void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void (int, const std::string &)> &callback){
};
void AudioEngineImpl::uncache(const std::string& path){
};
void AudioEngineImpl::uncacheAll(){
};
int AudioEngineImpl::preload(const std::string& filePath, std::function<void(bool isSuccess)> callback){
return 0;
};
void AudioEngineImpl::update(float dt){
};
| 15.216495 | 117 | 0.72019 | yangosoft |
717a9cc799efd9644639ab0d1289a8b34e6f68e8 | 332 | cpp | C++ | code/uva/Q494.cpp | as535364/Judge-WriteupCode | e3e439a8c01d473e84422558593f7c992d0e9f8d | [
"MIT"
] | null | null | null | code/uva/Q494.cpp | as535364/Judge-WriteupCode | e3e439a8c01d473e84422558593f7c992d0e9f8d | [
"MIT"
] | null | null | null | code/uva/Q494.cpp | as535364/Judge-WriteupCode | e3e439a8c01d473e84422558593f7c992d0e9f8d | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
int main() {
string s;
while(getline (cin,s) ){
bool flag = 0;
int ans = 0;
for(int i=0;i<s.size();i++){
if( ('A'<=s[i]&&s[i]<='Z')||('a'<=s[i]&&s[i]<='z') )
flag = 1;
else if(flag==1){
ans++;
flag = 0;
}
}
cout<<ans<<'\n';
}
return 0;
}
| 15.809524 | 55 | 0.478916 | as535364 |
717e672f38fe33083e75f97b54301e9deae62407 | 1,057 | cpp | C++ | src/engine/Log.cpp | KrokodileGlue/blueshock | 0e082556015562ec8fd847b9fb2f0ec62bdd9bd9 | [
"MIT"
] | null | null | null | src/engine/Log.cpp | KrokodileGlue/blueshock | 0e082556015562ec8fd847b9fb2f0ec62bdd9bd9 | [
"MIT"
] | 1 | 2019-06-09T14:16:34.000Z | 2019-06-18T20:10:42.000Z | src/engine/Log.cpp | KrokodileGlue/blueshock | 0e082556015562ec8fd847b9fb2f0ec62bdd9bd9 | [
"MIT"
] | null | null | null | #include "Log.h"
#include <algorithm>
#include <fstream>
#include <chrono>
#include <ctime>
std::ostringstream oss;
std::ostringstream null_stream;
LogLevel max_log_level = LogLevel::DEBUG3;
std::ostringstream& log(LogLevel level)
{
if (level > max_log_level) {
null_stream.str(""), null_stream.clear();
return null_stream;
}
oss << std::endl;
std::chrono::time_point<std::chrono::system_clock> time;
time = std::chrono::system_clock::now();
std::time_t end_time = std::chrono::system_clock::to_time_t(time);
std::string time_str = std::ctime(&end_time);
time_str.erase(std::remove(time_str.begin(), time_str.end(), '\n'), time_str.end());
oss << time_str;
switch (level) {
case LogLevel::ERROR: oss << " [ERROR] "; break;
case LogLevel::WARNING: oss << " [WARNING] "; break;
case LogLevel::INFO: oss << " [INFO] "; break;
case LogLevel::DEBUG1:
case LogLevel::DEBUG2:
case LogLevel::DEBUG3: oss << " [DEBUG] "; break;
}
return oss;
}
void dump_log()
{
std::ofstream out("blueshock.log");
out << oss.str();
out.close();
}
| 22.020833 | 85 | 0.676443 | KrokodileGlue |
7180d4551c55f2a4edf3579c055c57094047cc56 | 34,226 | cpp | C++ | external/GTEngine/Source/Imagics/GteMarchingCubesTable.cpp | yushuiqiang/geometry3cpp | 2727986b89da2d40ffbd0dddb6947183c8bf68b0 | [
"BSL-1.0"
] | 1 | 2021-02-18T10:25:42.000Z | 2021-02-18T10:25:42.000Z | external/GTEngine/Source/Imagics/GteMarchingCubesTable.cpp | yushuiqiang/geometry3cpp | 2727986b89da2d40ffbd0dddb6947183c8bf68b0 | [
"BSL-1.0"
] | null | null | null | external/GTEngine/Source/Imagics/GteMarchingCubesTable.cpp | yushuiqiang/geometry3cpp | 2727986b89da2d40ffbd0dddb6947183c8bf68b0 | [
"BSL-1.0"
] | null | null | null | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.0 (2016/06/19)
#include <GTEnginePCH.h>
#include <Imagics/GteMarchingCubesTable.h>
namespace gte
{
int const gMarchingCubesTable[256][41] =
{
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 3, 1, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 3, 1, 1, 3, 1, 5, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 4, 2, 0, 4, 0, 2, 1, 3, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 2, 3, 0, 0, 0, 0, 0, 0, 0, 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0, 0, 0, 0 },
{ 3, 1, 0, 1, 0, 4, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
}
| 125.369963 | 134 | 0.315754 | yushuiqiang |
7184fc1cd21606c535d6a2867dd72c3ebf651762 | 229 | hpp | C++ | src/lib/utils/null_streambuf.hpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | 2 | 2019-01-22T19:44:32.000Z | 2019-01-22T19:52:33.000Z | src/lib/utils/null_streambuf.hpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | 69 | 2019-05-24T10:01:32.000Z | 2019-12-13T19:09:05.000Z | src/lib/utils/null_streambuf.hpp | nilsthamm/hyrise | 75a701f281bb7dc1636832012c43005ec3c66384 | [
"MIT"
] | null | null | null | #pragma once
#include <iosfwd>
namespace opossum {
// Create no-op stream that just swallows everything streamed into it
// See https://stackoverflow.com/a/11826666
std::ostream& get_null_streambuf();
} // namespace opossum
| 19.083333 | 69 | 0.751092 | nilsthamm |
71852aa19c76eef464ec2e50994909b5d2afb0ff | 6,257 | cpp | C++ | WildMagic4/LibFoundation/ComputationalGeometry/Wm4Query.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 23 | 2015-08-13T07:36:00.000Z | 2022-01-24T19:00:04.000Z | WildMagic4/LibFoundation/ComputationalGeometry/Wm4Query.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | null | null | null | WildMagic4/LibFoundation/ComputationalGeometry/Wm4Query.cpp | rms80/libgeometry | e60ec7d34968573a9cda3f3bf56d2d4717385dc9 | [
"BSL-1.0"
] | 6 | 2015-07-06T21:37:31.000Z | 2020-07-01T04:07:50.000Z | // Geometric Tools, LLC
// Copyright (c) 1998-2010
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 4.10.0 (2009/11/18)
#include "Wm4FoundationPCH.h"
#include "Wm4Query.h"
using namespace Wm4;
//----------------------------------------------------------------------------
Query::Query ()
{
}
//----------------------------------------------------------------------------
Query::~Query ()
{
}
//----------------------------------------------------------------------------
bool Query::Sort (int& iV0, int& iV1)
{
int j0, j1;
bool bPositive;
if (iV0 < iV1)
{
j0 = 0; j1 = 1; bPositive = true;
}
else
{
j0 = 1; j1 = 0; bPositive = false;
}
int aiValue[2] = { iV0, iV1 };
iV0 = aiValue[j0];
iV1 = aiValue[j1];
return bPositive;
}
//----------------------------------------------------------------------------
bool Query::Sort (int& iV0, int& iV1, int& iV2)
{
int j0, j1, j2;
bool bPositive;
if (iV0 < iV1)
{
if (iV2 < iV0)
{
j0 = 2; j1 = 0; j2 = 1; bPositive = true;
}
else if (iV2 < iV1)
{
j0 = 0; j1 = 2; j2 = 1; bPositive = false;
}
else
{
j0 = 0; j1 = 1; j2 = 2; bPositive = true;
}
}
else
{
if (iV2 < iV1)
{
j0 = 2; j1 = 1; j2 = 0; bPositive = false;
}
else if (iV2 < iV0)
{
j0 = 1; j1 = 2; j2 = 0; bPositive = true;
}
else
{
j0 = 1; j1 = 0; j2 = 2; bPositive = false;
}
}
int aiValue[3] = { iV0, iV1, iV2 };
iV0 = aiValue[j0];
iV1 = aiValue[j1];
iV2 = aiValue[j2];
return bPositive;
}
//----------------------------------------------------------------------------
bool Query::Sort (int& iV0, int& iV1, int& iV2, int& iV3)
{
int j0, j1, j2, j3;
bool bPositive;
if (iV0 < iV1)
{
if (iV2 < iV3)
{
if (iV1 < iV2)
{
j0 = 0; j1 = 1; j2 = 2; j3 = 3; bPositive = true;
}
else if (iV3 < iV0)
{
j0 = 2; j1 = 3; j2 = 0; j3 = 1; bPositive = true;
}
else if (iV2 < iV0)
{
if (iV3 < iV1)
{
j0 = 2; j1 = 0; j2 = 3; j3 = 1; bPositive = false;
}
else
{
j0 = 2; j1 = 0; j2 = 1; j3 = 3; bPositive = true;
}
}
else
{
if (iV3 < iV1)
{
j0 = 0; j1 = 2; j2 = 3; j3 = 1; bPositive = true;
}
else
{
j0 = 0; j1 = 2; j2 = 1; j3 = 3; bPositive = false;
}
}
}
else
{
if (iV1 < iV3)
{
j0 = 0; j1 = 1; j2 = 3; j3 = 2; bPositive = false;
}
else if (iV2 < iV0)
{
j0 = 3; j1 = 2; j2 = 0; j3 = 1; bPositive = false;
}
else if (iV3 < iV0)
{
if (iV2 < iV1)
{
j0 = 3; j1 = 0; j2 = 2; j3 = 1; bPositive = true;
}
else
{
j0 = 3; j1 = 0; j2 = 1; j3 = 2; bPositive = false;
}
}
else
{
if (iV2 < iV1)
{
j0 = 0; j1 = 3; j2 = 2; j3 = 1; bPositive = false;
}
else
{
j0 = 0; j1 = 3; j2 = 1; j3 = 2; bPositive = true;
}
}
}
}
else
{
if (iV2 < iV3)
{
if (iV0 < iV2)
{
j0 = 1; j1 = 0; j2 = 2; j3 = 3; bPositive = false;
}
else if (iV3 < iV1)
{
j0 = 2; j1 = 3; j2 = 1; j3 = 0; bPositive = false;
}
else if (iV2 < iV1)
{
if (iV3 < iV0)
{
j0 = 2; j1 = 1; j2 = 3; j3 = 0; bPositive = true;
}
else
{
j0 = 2; j1 = 1; j2 = 0; j3 = 3; bPositive = false;
}
}
else
{
if (iV3 < iV0)
{
j0 = 1; j1 = 2; j2 = 3; j3 = 0; bPositive = false;
}
else
{
j0 = 1; j1 = 2; j2 = 0; j3 = 3; bPositive = true;
}
}
}
else
{
if (iV0 < iV3)
{
j0 = 1; j1 = 0; j2 = 3; j3 = 2; bPositive = true;
}
else if (iV2 < iV1)
{
j0 = 3; j1 = 2; j2 = 1; j3 = 0; bPositive = true;
}
else if (iV3 < iV1)
{
if (iV2 < iV0)
{
j0 = 3; j1 = 1; j2 = 2; j3 = 0; bPositive = false;
}
else
{
j0 = 3; j1 = 1; j2 = 0; j3 = 2; bPositive = true;
}
}
else
{
if (iV2 < iV0)
{
j0 = 1; j1 = 3; j2 = 2; j3 = 0; bPositive = true;
}
else
{
j0 = 1; j1 = 3; j2 = 0; j3 = 2; bPositive = false;
}
}
}
}
int aiValue[4] = { iV0, iV1, iV2, iV3 };
iV0 = aiValue[j0];
iV1 = aiValue[j1];
iV2 = aiValue[j2];
iV3 = aiValue[j3];
return bPositive;
}
//----------------------------------------------------------------------------
| 26.400844 | 79 | 0.282564 | rms80 |
718d9f01288ac2f7d4dbbb76e6f7c3fad456603b | 7,808 | cpp | C++ | dlc/src/v20210125/model/TableInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | dlc/src/v20210125/model/TableInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | dlc/src/v20210125/model/TableInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/dlc/v20210125/model/TableInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Dlc::V20210125::Model;
using namespace std;
TableInfo::TableInfo() :
m_tableBaseInfoHasBeenSet(false),
m_dataFormatHasBeenSet(false),
m_columnsHasBeenSet(false),
m_partitionsHasBeenSet(false),
m_locationHasBeenSet(false)
{
}
CoreInternalOutcome TableInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("TableBaseInfo") && !value["TableBaseInfo"].IsNull())
{
if (!value["TableBaseInfo"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `TableInfo.TableBaseInfo` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_tableBaseInfo.Deserialize(value["TableBaseInfo"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_tableBaseInfoHasBeenSet = true;
}
if (value.HasMember("DataFormat") && !value["DataFormat"].IsNull())
{
if (!value["DataFormat"].IsObject())
{
return CoreInternalOutcome(Core::Error("response `TableInfo.DataFormat` is not object type").SetRequestId(requestId));
}
CoreInternalOutcome outcome = m_dataFormat.Deserialize(value["DataFormat"]);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_dataFormatHasBeenSet = true;
}
if (value.HasMember("Columns") && !value["Columns"].IsNull())
{
if (!value["Columns"].IsArray())
return CoreInternalOutcome(Core::Error("response `TableInfo.Columns` is not array type"));
const rapidjson::Value &tmpValue = value["Columns"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Column item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_columns.push_back(item);
}
m_columnsHasBeenSet = true;
}
if (value.HasMember("Partitions") && !value["Partitions"].IsNull())
{
if (!value["Partitions"].IsArray())
return CoreInternalOutcome(Core::Error("response `TableInfo.Partitions` is not array type"));
const rapidjson::Value &tmpValue = value["Partitions"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
Partition item;
CoreInternalOutcome outcome = item.Deserialize(*itr);
if (!outcome.IsSuccess())
{
outcome.GetError().SetRequestId(requestId);
return outcome;
}
m_partitions.push_back(item);
}
m_partitionsHasBeenSet = true;
}
if (value.HasMember("Location") && !value["Location"].IsNull())
{
if (!value["Location"].IsString())
{
return CoreInternalOutcome(Core::Error("response `TableInfo.Location` IsString=false incorrectly").SetRequestId(requestId));
}
m_location = string(value["Location"].GetString());
m_locationHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void TableInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_tableBaseInfoHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "TableBaseInfo";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_tableBaseInfo.ToJsonObject(value[key.c_str()], allocator);
}
if (m_dataFormatHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DataFormat";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
m_dataFormat.ToJsonObject(value[key.c_str()], allocator);
}
if (m_columnsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Columns";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_columns.begin(); itr != m_columns.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_partitionsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Partitions";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
int i=0;
for (auto itr = m_partitions.begin(); itr != m_partitions.end(); ++itr, ++i)
{
value[key.c_str()].PushBack(rapidjson::Value(rapidjson::kObjectType).Move(), allocator);
(*itr).ToJsonObject(value[key.c_str()][i], allocator);
}
}
if (m_locationHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Location";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_location.c_str(), allocator).Move(), allocator);
}
}
TableBaseInfo TableInfo::GetTableBaseInfo() const
{
return m_tableBaseInfo;
}
void TableInfo::SetTableBaseInfo(const TableBaseInfo& _tableBaseInfo)
{
m_tableBaseInfo = _tableBaseInfo;
m_tableBaseInfoHasBeenSet = true;
}
bool TableInfo::TableBaseInfoHasBeenSet() const
{
return m_tableBaseInfoHasBeenSet;
}
DataFormat TableInfo::GetDataFormat() const
{
return m_dataFormat;
}
void TableInfo::SetDataFormat(const DataFormat& _dataFormat)
{
m_dataFormat = _dataFormat;
m_dataFormatHasBeenSet = true;
}
bool TableInfo::DataFormatHasBeenSet() const
{
return m_dataFormatHasBeenSet;
}
vector<Column> TableInfo::GetColumns() const
{
return m_columns;
}
void TableInfo::SetColumns(const vector<Column>& _columns)
{
m_columns = _columns;
m_columnsHasBeenSet = true;
}
bool TableInfo::ColumnsHasBeenSet() const
{
return m_columnsHasBeenSet;
}
vector<Partition> TableInfo::GetPartitions() const
{
return m_partitions;
}
void TableInfo::SetPartitions(const vector<Partition>& _partitions)
{
m_partitions = _partitions;
m_partitionsHasBeenSet = true;
}
bool TableInfo::PartitionsHasBeenSet() const
{
return m_partitionsHasBeenSet;
}
string TableInfo::GetLocation() const
{
return m_location;
}
void TableInfo::SetLocation(const string& _location)
{
m_location = _location;
m_locationHasBeenSet = true;
}
bool TableInfo::LocationHasBeenSet() const
{
return m_locationHasBeenSet;
}
| 29.243446 | 136 | 0.653304 | suluner |
718f2915857eb78572ee3087ff8964cb0a6cb89e | 3,848 | cpp | C++ | PressureEngineCore/Src/Graphics/Skybox/SkyboxRenderer.cpp | Playturbo/PressureEngine | 6b023165fcaecb267e13cf5532ea26a8da3f1450 | [
"MIT"
] | 1 | 2017-09-13T13:29:27.000Z | 2017-09-13T13:29:27.000Z | PressureEngineCore/Src/Graphics/Skybox/SkyboxRenderer.cpp | Playturbo/PressureEngine | 6b023165fcaecb267e13cf5532ea26a8da3f1450 | [
"MIT"
] | null | null | null | PressureEngineCore/Src/Graphics/Skybox/SkyboxRenderer.cpp | Playturbo/PressureEngine | 6b023165fcaecb267e13cf5532ea26a8da3f1450 | [
"MIT"
] | 1 | 2019-01-18T07:16:59.000Z | 2019-01-18T07:16:59.000Z | #include "SkyboxRenderer.h"
#include "../Textures/TextureManager.h"
namespace Pressure {
const std::vector<float> SkyboxRenderer::VERTICES = {
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE,
-PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE,
PRESSURE_SKYBOX_SIZE, -PRESSURE_SKYBOX_SIZE, PRESSURE_SKYBOX_SIZE
};
SkyboxRenderer::SkyboxRenderer(Loader& loader, GLFWwindow* window)
: m_Window(window), m_Cube(loader.loadToVao(VERTICES, 3)) {
m_Texture = loader.loadCubeMap(PRESSURE_SKYBOX_FILE);
updateProjectionMatrix();
}
void SkyboxRenderer::updateProjectionMatrix() {
m_Shader.start();
m_Shader.loadProjectionMatrix(Matrix4f().createProjectionMatrix(m_Window));
m_Shader.stop();
}
void SkyboxRenderer::render(Camera& camera) {
m_Shader.start();
m_Shader.loadViewMatrix(camera);
m_Cube.getVertexArray().bind();
glEnableVertexAttribArray(0);
glActiveTexture(GL_TEXTURE0);
TextureManager::Inst()->BindTexture(m_Texture, GL_TEXTURE_CUBE_MAP);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glDrawArrays(GL_TRIANGLES, 0, m_Cube.getVertexCount());
glDisableVertexAttribArray(0);
m_Cube.getVertexArray().unbind();
m_Shader.stop();
}
} | 48.1 | 77 | 0.836798 | Playturbo |
719f720be5fbe75c0f3c5fe4a2b09b9b8d09eaac | 20,394 | cpp | C++ | src/funcs_cpp/BACKUP/BKU_lib_integrals_electron.cpp | Jussmith01/HFSCFCISProgram | 957d92229905c06fb97fba4ca3c2765ae8f700bb | [
"MIT"
] | null | null | null | src/funcs_cpp/BACKUP/BKU_lib_integrals_electron.cpp | Jussmith01/HFSCFCISProgram | 957d92229905c06fb97fba4ca3c2765ae8f700bb | [
"MIT"
] | null | null | null | src/funcs_cpp/BACKUP/BKU_lib_integrals_electron.cpp | Jussmith01/HFSCFCISProgram | 957d92229905c06fb97fba4ca3c2765ae8f700bb | [
"MIT"
] | null | null | null | #define _USE_MATH_DEFINES
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <string.h>
#include <string>
#include <cmath>
#include <math.h>
#include <fstream>
#include <time.h>
#include <iostream>
#include "../utils_cpp/lib_includes.h"
#include "../classes/classes.h"
#include "../scf_main/scf_classes.h"
#include "func_classes.h"
#include "lib_integrals.h"
using namespace std;
//________________________________________________________________________//
// ************************************************************* //
// Calculate P0 portion of the Electron Integrals
//
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/27/2014 ----
----Modified By: ----
*/
double J0_func(int axI,int axJ,double an1,double an2)
{
double rtnval;
rtnval = pow(-1,axI + axJ) * fact(axI) * fact(axJ) / (double)(pow(an1 + an2,axI + axJ));
return rtnval;
}
//________________________________________________________________________//
// ************************************************************* //
// Calculate J1 portion of the Electron Integrals
//
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/27/2014 ----
----Modified By: ----
*/
double J1_func(int i1,int i2,int o1,int o2,int r1,int aA,int aB,int aC,int aD,double an1,double an2,double an3,double an4,double Axyz,double Bxyz)
{
double rtnval;
rtnval = (pow(-1, o2 + r1) * fact(o1 + o2) / (double)(pow(4,i1 + i2 + r1) * fact(i1) * fact(i2) * fact(o1) * fact(o2) * fact(r1))) * ((pow(an1,o2 - i1 - r1) * pow(an2,o1 - i2 - r1) * pow(an1 + an2,2 * (i1 + i2) + r1) * pow(Axyz - Bxyz,o1 + o2 - 2 * r1)) / (double)(fact(aA - 2 * i1 - o1) * fact(aB - 2 * i2 - o2) * fact(o1 + o2 - 2 * r1))) * ((fact(aC) * fact(aD)) / (double)(pow(an3 + an4,aC + aD)));
return rtnval;
}
//________________________________________________________________________//
// ************************************************************* //
// Calculate J2 portion of the Electron Integrals
//
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/27/2014 ----
----Modified By: ----
*/
double J2_func(int i3,int i4,int o3,int o4,int r2,int aC,int aD,double an3,double an4,double Cxyz,double Dxyz)
{
double rtnval;
rtnval = ((pow(-1,o3 + r2) * fact(o3 + o4)) / (double)(pow(4,i3 + i4 + r2) * fact(i3) * fact(i4) * fact(o3) * fact(o4) * fact(r2))) * ((pow(an3,o4 - i3 - r2) * pow(an4,o3 - i4 - r2) * pow(an3 + an4,2 * (i3 + i4) + r2) * pow(Cxyz - Dxyz,o3 + o4 - 2 * r2)) / (double)(fact(aC - 2 * i3 - o3) * fact(aD - 2 * i4 - o4) * fact(o3 + o4 - 2 * r2)));
//rtnval = 1;
return rtnval;
}
//________________________________________________________________________//
// ************************************************************* //
// Calculate J3 portion of the Electron Integrals
//
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/27/2014 ----
----Modified By: ----
*/
double J3_func(int u,int mu,double n,double Pxyz,double Qxyz)
{
double rtnval;
rtnval = ((pow(-1,u) * fact(mu) * pow(n,mu - u) * pow(Pxyz - Qxyz,mu - 2 * u)) / (double)(pow(4,u) * fact(u) * fact(mu - 2 * u)));
//rtnval = 1;
return rtnval;
}
//________________________________________________________________________//
// ************************************************************* //
// Calc_sum_J Terms
//
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/27/2014 ----
----Modified By: ----
*/
double calc_sum_J(int test,int axA,int ayA,int azA,int axB,int ayB,int azB,int axC,int ayC,int azC,int axD,int ayD,int azD,double Ax,double Ay,double Az,double Bx,double By,double Bz,double Cx,double Cy,double Cz,double Dx,double Dy,double Dz,double an1,double an2,double an3,double an4)
{
double tol = 1.0E-13;
double rtnval = 0;
double pos = 0;
double neg = 0;
double Px = (an1 * Ax + an2 * Bx) / (double)(an1 + an2);
double Py = (an1 * Ay + an2 * By) / (double)(an1 + an2);
double Pz = (an1 * Az + an2 * Bz) / (double)(an1 + an2);
double Qx = (an3 * Cx + an4 * Dx) / (double)(an3 + an4);
double Qy = (an3 * Cy + an4 * Dy) / (double)(an3 + an4);
double Qz = (an3 * Cz + an4 * Dz) / (double)(an3 + an4);
double PmQ = (Px - Qx) * (Px - Qx) + (Py - Qy) * (Py - Qy) + (Pz - Qz) * (Pz - Qz);
//double PmQ = ((an1 * pow(pow(Ax,2.0) + pow(Ay,2.0) + pow(Az,2.0),0.5) - (an2 * pow(pow(Bx,2.0) + pow(By,2.0) + pow(Bz,2.0),0.5)) / (double)(an1 + an2))) - ((an3 * pow(pow(Cx,2.0) + pow(Cy,2.0) + pow(Cz,2.0),0.5) - (an4 * pow(pow(Dx,2.0) + pow(Dy,2.0) + pow(Dz,2.0),0.5)) / (double)(an3 + an4)));
//cout << "CmP: " << CmP << " an: " << an << " bm:" << bm << "\n";
//cout << "Cx: " << Cx << " Cy: " << Cy << " Cz: " << Cz << " Px: " << Px << " Py: " << Py << " Pz: " << Pz << "\n";
cout << "axA: " << axA << " ayA: " << ayA << " azA: " << azA << " | " ;
cout << " axB: " << axB << " ayB: " << ayB << " azB: " << azB << " | " ;
cout << " axC: " << axC << " ayC: " << ayC << " azC: " << azC << " | " ;
cout << " axD: " << axD << " ayD: " << ayD << " azD: " << azD << " | " << " PmQ: " << PmQ << "\n";
double nFACT = ((an1 + an2) * (an3 + an4)) / (double)((an1 + an2) + (an3 + an4));
//Indicies for X calculations
//double J0x = J0_func(axA,axB,an1,an2) * J0_func(axC,axD,an3,an4);
//double J0y = J0_func(ayA,ayB,an1,an2) * J0_func(ayC,ayD,an3,an4);
//double J0z = J0_func(azA,azB,an1,an2) * J0_func(azC,azD,an3,an4);
double J0x = J0_func(axA,axB,an1,an2);
double J0y = J0_func(ayA,ayB,an1,an2);
double J0z = J0_func(azA,azB,an1,an2);
for (int ix1 = 0; ix1 <= floor(axA / (double)2.0); ++ix1) {
for (int ix2 = 0; ix2 <= floor(axB / (double)2.0); ++ix2) {
for (int ox1 = 0; ox1 <= axA - 2.0 * ix1; ++ox1) {
for (int ox2 = 0; ox2 <= axB - 2.0 * ix2; ++ox2) {
for (int rx1 = 0; rx1 <= floor((ox1 + ox2) / (double)2.0); ++rx1) {
double J1x = J1_func(ix1,ix2,ox2,ox2,rx1,axA,axB,axC,axD,an1,an2,an3,an4,Ax,Bx);
for (int ix3 = 0; ix3 <= floor(axC / (double)2.0); ++ix3) {
for (int ix4 = 0; ix4 <= floor(axD / (double)2.0); ++ix4) {
for (int ox3 = 0; ox3 <= axC - 2.0 * ix3; ++ox3) {
for (int ox4 = 0; ox4 <= axD - 2.0 * ix4; ++ox4) {
for (int rx2 = 0; rx2 <= floor((ox3 + ox4) / (double)2.0); ++rx2) {
double J2x = J2_func(ix3,ix4,ox3,ox4,rx2,axC,axD,an3,an4,Cx,Dx);
int mux = axA + axB + axC + axD - 2.0 * (ix1 + ix2 + ix3 + ix4) - (ox1 + ox2 + ox3 + ox4);
for (int ux = 0; ux <= floor(mux / (double)2.0); ++ux) {
double J3x = J3_func(ux,mux,nFACT,Px,Qx);
//Indicies for Y calculations
//double J0y = J0_func(ayA,ayB,an1,an2);
for (int iy1 = 0; iy1 <= floor(ayA / (double)2.0); ++iy1) {
for (int iy2 = 0; iy2 <= floor(ayB / (double)2.0); ++iy2) {
for (int oy1 = 0; oy1 <= ayA - 2.0 * iy1; ++oy1) {
for (int oy2 = 0; oy2 <= ayB - 2.0 * iy2; ++oy2) {
for (int ry1 = 0; ry1 <= floor((oy1 + oy2) / (double)2.0); ++ry1) {
double J1y = J1_func(iy1,iy2,oy2,oy2,ry1,ayA,ayB,ayC,ayD,an1,an2,an3,an4,Ay,By);
for (int iy3 = 0; iy3 <= floor(ayC / (double)2.0); ++iy3) {
for (int iy4 = 0; iy4 <= floor(ayD / (double)2.0); ++iy4) {
for (int oy3 = 0; oy3 <= ayC - 2.0 * iy3; ++oy3) {
for (int oy4 = 0; oy4 <= ayD - 2.0 * iy4; ++oy4) {
for (int ry2 = 0; ry2 <= floor((oy3 + oy4) / (double)2.0); ++ry2) {
double J2y = J2_func(iy3,iy4,oy3,oy4,ry2,ayC,ayD,an3,an4,Cy,Dy);
int muy = ayA + ayB + ayC + ayD - 2.0 * (iy1 + iy2 + iy3 + iy4) - (oy1 + oy2 + oy3 + oy4);
for (int uy = 0; uy <= floor(muy / (double)2.0); ++uy) {
double J3y = J3_func(uy,muy,nFACT,Py,Qy);
//Indicies for Z calculations
//double J0z = J0_func(azA,azB,an1,an2);
for (int iz1 = 0; iz1 <= floor(azA / (double)2.0); ++iz1) {
for (int iz2 = 0; iz2 <= floor(azB / (double)2.0); ++iz2) {
for (int oz1 = 0; oz1 <= azA - 2.0 * iz1; ++oz1) {
for (int oz2 = 0; oz2 <= azB - 2.0 * iz2; ++oz2) {
for (int rz1 = 0; rz1 <= floor((oz1 + oz2) / (double)2.0); ++rz1) {
double J1z = J1_func(iz1,iz2,oz2,oz2,rz1,azA,azB,azC,azD,an1,an2,an3,an4,Az,Bz);
for (int iz3 = 0; iz3 <= floor(azC / (double)2.0); ++iz3) {
for (int iz4 = 0; iz4 <= floor(azD / (double)2.0); ++iz4) {
for (int oz3 = 0; oz3 <= azC - 2.0 * iz3; ++oz3) {
for (int oz4 = 0; oz4 <= azD - 2.0 * iz4; ++oz4) {
for (int rz2 = 0; rz2 <= floor((oz3 + oz4) / (double)2.0); ++rz2) {
double J2z = J2_func(iz3,iz4,oz3,oz4,rz2,azC,azD,an3,an4,Cz,Dz);
int muz = azA + azB + azC + azD - 2.0 * (iz1 + iz2 + iz3 + iz4) - (oz1 + oz2 + oz3 + oz4);
for (int uz = 0; uz <= floor(muz / (double)2.0); ++uz) {
double J3z = J3_func(uz,muz,nFACT,Pz,Qz);
double nu = mux + muy + muz - (ux + uy + uz);
//Putting it all together
double val = J3x * J2x * J1x * J0x * J3y * J2y * J1y * J0y * J3z * J2z * J1z * J0z * 2.0 * Fnu(nu,PmQ * nFACT);
if (val > 0 && val > tol)
{pos += val;}
else if (val < 0 && abs(val) > tol)
{neg += abs(val);}
cout.setf( std::ios::fixed, std::ios::floatfield );
cout << " J3x: " << J3x << " J2x: " << J2x << " J1x: " << J1x << " J0x: " << J0x << " J3y: " << J3y << " J2y: " << J2y << " J1y: " << J1y << " J0y: " << J0y << " J3z: " << J3z << " J2z: " << J2z << " J1z: " << J1z << " J0z: " << J0z << " Fnu: " << Fnu(nu,PmQ * nFACT) << "\n";
}}}}}}}}}}}
}}}}}}}}}}}
}}}}}}}}}}}
rtnval = pos - neg;
cout << " RTNVAL: " << rtnval << "\n";
return rtnval;
}
//________________________________________________________________________//
// ************************************************************* //
// Calculate the Nuclear Attraction Integrals
// Function that calculates the kinetic contribution to the fock
// matrix.
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/27/2014 ----
----Modified By: ----
Math functions nCk(), fact(), d_fact()
*/
double calculate_electron_repulsion(int basisA,int basisB, int basisC,int basisD,MemHandler *data_mem,scf_data *scf,STOnG_handler *STO,int assu,int test)
{
double rtnval = 0;
int N = STO->N;
//Orbital Index
int basis_A = data_mem->orb_idx[basisA]; //orbital type 1,2,3,4,5 ...
int basis_B = data_mem->orb_idx[basisB];
int basis_C = data_mem->orb_idx[basisC];
int basis_D = data_mem->orb_idx[basisD];
//Atmoic Index
int atomic_data_A = data_mem->atom_idx[basisA]; //Gives index of the atom in question
int atomic_data_B = data_mem->atom_idx[basisB];
int atomic_data_C = data_mem->atom_idx[basisC];
int atomic_data_D = data_mem->atom_idx[basisD];
//Atomic Number
int Anum = data_mem->atom_data[atomic_data_A].atomic_num;
int Bnum = data_mem->atom_data[atomic_data_B].atomic_num;
int Cnum = data_mem->atom_data[atomic_data_C].atomic_num;
int Dnum = data_mem->atom_data[atomic_data_D].atomic_num;
//A Position
double Ax = data_mem->atom_data[atomic_data_A].pos_xyz[0];
double Ay = data_mem->atom_data[atomic_data_A].pos_xyz[1];
double Az = data_mem->atom_data[atomic_data_A].pos_xyz[2];
//B Position
double Bx = data_mem->atom_data[atomic_data_B].pos_xyz[0];
double By = data_mem->atom_data[atomic_data_B].pos_xyz[1];
double Bz = data_mem->atom_data[atomic_data_B].pos_xyz[2];
//C Position
double Cx = data_mem->atom_data[atomic_data_C].pos_xyz[0];
double Cy = data_mem->atom_data[atomic_data_C].pos_xyz[1];
double Cz = data_mem->atom_data[atomic_data_C].pos_xyz[2];
//D Position
double Dx = data_mem->atom_data[atomic_data_D].pos_xyz[0];
double Dy = data_mem->atom_data[atomic_data_D].pos_xyz[1];
double Dz = data_mem->atom_data[atomic_data_D].pos_xyz[2];
//|A-B|^2
double AmB = (Ax - Bx) * (Ax - Bx) + (Ay - By) * (Ay - By) + (Az - Bz) * (Az - Bz);
//|C-D|^2
double CmD = (Cx - Dx) * (Cx - Dx) + (Cy - Dy) * (Cy - Dy) + (Cz - Dz) * (Cz - Dz);
//Used for indexing the constants array and obtaining the correct constants
int basis_idx_A = STO[Anum].rtn_bas_idx(basis_A);
int basis_idx_B = STO[Bnum].rtn_bas_idx(basis_B);
int basis_idx_C = STO[Bnum].rtn_bas_idx(basis_C);
int basis_idx_D = STO[Bnum].rtn_bas_idx(basis_D);
//The following sets the angular numbers for the given orbital
int axA,ayA,azA;
int axB,ayB,azB;
int axC,ayC,azC;
int axD,ayD,azD;
switch (basis_A)
{
case 1:{axA=0;ayA=0;azA=0;break;}
case 2:{axA=0;ayA=0;azA=0;break;}
case 3:{axA=1;ayA=0;azA=0;break;}
case 4:{axA=0;ayA=1;azA=0;break;}
case 5:{axA=0;ayA=0;azA=1;break;}
}
switch (basis_B)
{
case 1:{axB=0;ayB=0;azB=0;break;}
case 2:{axB=0;ayB=0;azB=0;break;}
case 3:{axB=1;ayB=0;azB=0;break;}
case 4:{axB=0;ayB=1;azB=0;break;}
case 5:{axB=0;ayB=0;azB=1;break;}
}
switch (basis_C)
{
case 1:{axC=0;ayC=0;azC=0;break;}
case 2:{axC=0;ayC=0;azC=0;break;}
case 3:{axC=1;ayC=0;azC=0;break;}
case 4:{axC=0;ayC=1;azC=0;break;}
case 5:{axC=0;ayC=0;azC=1;break;}
}
switch (basis_D)
{
case 1:{axD=0;ayD=0;azD=0;break;}
case 2:{axD=0;ayD=0;azD=0;break;}
case 3:{axD=1;ayD=0;azD=0;break;}
case 4:{axD=0;ayD=1;azD=0;break;}
case 5:{axD=0;ayD=0;azD=1;break;}
}
//This statement decides if the basis functions are orthogonal P functions, if they are set rtnval to 0.
if ((basis_A >= 3 && basis_B >= 3 && basis_A != basis_B) || (basis_C >= 3 && basis_D >= 3 && basis_C != basis_D) && assu == 0)
{
rtnval = 0.00;
//The following else statement calculates the rest of the integrals which are not orthogonal P functions.
} else {
for (int n1 = 0; n1 < N ;++n1) {
for (int n2 = 0; n2 < N ;++n2) {
for (int n3 = 0; n3 < N ;++n3) {
for (int n4 = 0; n4 < N ;++n4) {
//Load primitive gaussian exponent constant
double an1 = STO[Anum - 1].a[n1 + (N * basis_idx_A - N)];
double an2 = STO[Bnum - 1].a[n2 + (N * basis_idx_B - N)];
double an3 = STO[Cnum - 1].a[n3 + (N * basis_idx_C - N)];
double an4 = STO[Dnum - 1].a[n4 + (N * basis_idx_D - N)];
//Load primitive gaussian contraction coefficient
double dn1 = STO[Anum - 1].d[n1 + (N * basis_idx_A - N)];
double dn2 = STO[Bnum - 1].d[n2 + (N * basis_idx_B - N)];
double dn3 = STO[Cnum - 1].d[n3 + (N * basis_idx_C - N)];
double dn4 = STO[Dnum - 1].d[n4 + (N * basis_idx_D - N)];
//Define GammaP and GammaQ
double gammaP = an1 + an2;
double gammaQ = an3 + an4;
//Define constant factor
double NRI_fact = pow(M_PI,5 / (double)2) / (double)(gammaP * gammaQ * sqrt(gammaP + gammaQ));
cout << " n1: " << n1 << " n2: " << n2 << " n3: " << n3 << " n4: " << n4 << "\n";
double Ifact = calc_sum_J(test,axA,ayA,azA,axB,ayB,azB,axC,ayC,azC,axD,ayD,azD,Ax,Ay,Az,Bx,By,Bz,Cx,Cy,Cz,Dx,Dy,Dz,an1,an2,an3,an4);
rtnval += norm(axA,ayA,azA,an1) * norm(axB,ayB,azB,an2) * norm(axC,ayC,azC,an3) * norm(axD,ayD,azD,an4) * dn1 * dn2 * dn3 * dn4 * NRI_fact * Ifact * E_factor(an1,an2,AmB) * E_factor(an3,an4,CmD);
//cout << "NORMA: " << norm(axA,ayA,azA,an1) << " NORMB: " << norm(axB,ayB,azB,an2) << " NORMC: " << norm(axC,ayC,azC,an3) << " NORMD: " << norm(axD,ayD,azD,an4) << " dn1: " << dn1 << " dn2: " << dn2 << " dn3: " << dn3 << " dn4: " << dn4 << " NRI_fact: " << NRI_fact << " IFACT: " << Ifact << " E_factor1: " << E_factor(an1,an2,AmB) << " E_factor2: " << E_factor(an3,an4,CmD) << "\n";
}}}}
}
return rtnval;
}
//________________________________________________________________________//
// ************************************************************* //
// Electron Repulsion Main Function
// Create initial index and calculate the integrals for all
// degenerate electron repulsion integrals.
// ************************************************************* //
/* ----Author: Justin Smith ----
----Date Modified: 10/22/2014 ----
----Modified By: ----
*/
extern void electron_repulsion_main(MemHandler *data_mem,scf_data *scf,dataOutput *optfile,STOnG_handler *STO)
{
//Set some variables
timer int_timer;
optfile->ofile << "\nBeginning Electron Repulsion Calculations...\n";
int_timer.set_timer();
//**************************************
//Start Nuclear Attraction Computations
//**************************************
int count = 0;
scf->num_deg = 0;
int tot1 = scf->orbitals * (scf->orbitals + 1) / 2;
int total_calcs = tot1 * (tot1 + 1) / 2;
int check = 0;
int strider;
for (int i = 0; i < scf->orbitals; ++i) {
for (int j = i; j < scf->orbitals; ++j) {
for (int k = i; k < scf->orbitals; ++k) {
for (int l = k; l < scf->orbitals; ++l) {
if ((long int)scf->FEI.produce_unique_ident(i,j,k,l) == (long int)scf->FEI.produce_ident(i,j,k,l))
{
//int testval = scf->FEI.produce_ident(i,j,k,l);
//ofstream myfile;
//myfile.open ("edata.bin", ios::app);
//myfile << "TEST: " << i << "-" << j << "|" << k << "-" << l << "\n";
//myfile.close();
//scf->ERI_idx[scf->num_deg] = uint_val;
double ERIij;
//ERIij = calculate_electron_repulsion(i,j,k,l,data_mem,scf,STO,1,0);
ERIij = 0.0;
//scf->ERI[scf->num_deg] = ERIij;
scf->FEI.set_val(ERIij,i,j,k,l);
//if (abs(ERIij - ERIij2) > 1.0E-10)
//{
//cout << i << "," << j << "|" << k << "," << l << " = " << ERIij << " = " << ERIij2 << "\n";
//}
//cout << scf->FEI.get_val(i,j,k,l) << "\n";
double perc = (scf->num_deg / (double)total_calcs) * 100;
if (perc >= check)
{
//cout << perc << "\%\n";
check += 10;
}
++scf->num_deg;
}
++count;
}}}}
cout << "|---------------------------------FIRST: \n\n";
double Ifact1 = calculate_electron_repulsion(2,5,5,5,data_mem,scf,STO,1,0);
cout << "|---------------------------------SECOND: \n\n";
double Ifact2 = calculate_electron_repulsion(5,2,5,5,data_mem,scf,STO,1,0);
cout.setf( std::ios::fixed, std::ios::floatfield );
cout << "IFACT1: " << Ifact1 << " IFACT2: " << "" << Ifact2 << "\n";
/*cout.setf( std::ios::fixed, std::ios::floatfield );
for (int n = 0;n < scf->num_deg;++n)
{cout << scf->ERI_idx[n] << " = " << scf->ERI[n] << " | ";if (n % 6 == 0) {cout << "\n";}}
*/
//cout << "\n";
cout << " count: " << count << "\n";
cout << "FINISHED ARRAY: CALC_SIZE(" << scf->FEI.num_val << ")\n";
//************************************
//End Nuclear Attraction Computations
//************************************
//Some ending functions
int_timer.end_timer();
string message = "Electron Repulsion Calculationi Clock Time: ";
int_timer.print_clock_time(message,optfile->ofile);
optfile->ofile << "\n";
}
| 43.484009 | 409 | 0.500539 | Jussmith01 |
71a8e84d1bee23bd95dc69a14bc2afb34cdc7ffb | 4,306 | cpp | C++ | quad.cpp | mihalyvaghy/whiteboard | 252d938157ff29740c2a9ba68904df9a0c8d28f0 | [
"MIT"
] | null | null | null | quad.cpp | mihalyvaghy/whiteboard | 252d938157ff29740c2a9ba68904df9a0c8d28f0 | [
"MIT"
] | null | null | null | quad.cpp | mihalyvaghy/whiteboard | 252d938157ff29740c2a9ba68904df9a0c8d28f0 | [
"MIT"
] | null | null | null | #include <string>
#include "quad.hpp"
double QuadTree::Node::diffThreshold = 45.0;
std::map<char, Color> QuadTree::Node::colorMap = QuadTree::Node::initializeColorMap();
std::map<char, Color> QuadTree::Node::initializeColorMap() {
std::map<char, Color> res;
res['k'] = Color::BLACK;
res['b'] = Color::BLUE;
res['g'] = Color::GREEN;
res['r'] = Color::RED;
res['w'] = Color::WHITE;
return res;
}
QuadTree::Node::Node() : nw(nullptr), ne(nullptr), sw(nullptr), se(nullptr) {}
QuadTree::Node::Node(cv::Mat image) : Node() {
cv::Scalar mean, dev;
cv::meanStdDev(image, mean, dev);
int r = image.rows / 2, c = image.cols / 2;
double min, max;
cv::minMaxLoc(image, &min, &max);
if (r != 0 && c != 0 && (max - min) > diffThreshold) {
nw = new Node(image(cv::Range(0, r), cv::Range(0, c)));
ne = new Node(image(cv::Range(0, r), cv::Range(c, image.cols)));
sw = new Node(image(cv::Range(r, image.rows), cv::Range(0, c)));
se = new Node(image(cv::Range(r, image.rows), cv::Range(c, image.cols)));
} else
color = scalar2Color(mean);
}
QuadTree::Node::Node(std::ifstream& file) : Node() {
char tmp;
file >> tmp;
if (tmp == '|') {
nw = new Node(file);
ne = new Node(file);
sw = new Node(file);
se = new Node(file);
} else
setColor(tmp);
}
void QuadTree::Node::setColor(char _color) {
color = QuadTree::Node::colorMap[_color];
}
Color QuadTree::Node::scalar2Color(cv::Scalar s) {
std::vector<int> v;
v.push_back(cv::norm(s - cv::Scalar(0, 0, 0), cv::NORM_INF));
cv::Scalar c;
for (int i = 0; i < 3; i++) {
c = cv::Scalar(0, 0, 0);
c[i] = 255;
v.push_back(cv::norm(s - c, cv::NORM_INF));
}
v.push_back(cv::norm(s - cv::Scalar(255, 255, 255), cv::NORM_INF));
return static_cast<Color>(std::distance(v.begin(), std::min_element(v.begin(), v.end())));
}
cv::Scalar QuadTree::Node::color2Scalar(Color c) {
cv::Scalar s;
switch (c) {
case Color::BLACK:
s = cv::Scalar(0, 0, 0);
break;
case Color::BLUE:
s = cv::Scalar(255, 0, 0);
break;
case Color::GREEN:
s = cv::Scalar(0, 255, 0);
break;
case Color::RED:
s = cv::Scalar(0, 0, 255);
break;
case Color::WHITE:
s = cv::Scalar(255, 255, 255);
break;
default:
s = cv::Scalar(255, 255, 255);
break;
}
return s;
}
char QuadTree::Node::color2String(Color c) {
char s;
switch(c) {
case Color::BLACK:
s = 'k';
break;
case Color::BLUE:
s = 'b';
break;
case Color::GREEN:
s = 'g';
break;
case Color::RED:
s = 'r';
break;
case Color::WHITE:
s = 'w';
break;
}
return s;
}
void QuadTree::Node::destroy() {
if (nw != nullptr) {
nw->destroy();
ne->destroy();
sw->destroy();
se->destroy();
}
delete this;
(void*)0;
}
void QuadTree::Node::print(std::ofstream& file) {
if (nw != nullptr) {
file << "|";
nw->print(file);
ne->print(file);
sw->print(file);
se->print(file);
} else
file << color2String(color);
}
QuadTree::QuadTree(std::string filename) {
std::ifstream file(filename + std::string(".qd"));
file >> size_x >> size_y;
root = new Node(file);
file.close();
}
QuadTree::QuadTree(cv::Mat image) {
size_x = image.cols;
size_y = image.rows;
root = new Node(image);
}
void QuadTree::print(std::string filename) {
std::ofstream file(filename + std::string(".qd"));
file << size_x << " " << size_y;
root->print(file);
file.close();
}
QuadTree::~QuadTree() {
root->destroy();
}
cv::Mat QuadTree::Node::compose(int x, int y, bool grid) {
cv::Mat image(y, x, CV_8UC3);
if (nw != nullptr) {
int r = image.rows / 2, c = image.cols / 2;
nw->compose(c, r, grid).copyTo(image(cv::Range(0, r), cv::Range(0, c)));
ne->compose(image.cols - c, r, grid).copyTo(image(cv::Range(0, r), cv::Range(c, image.cols)));
sw->compose(c, image.rows - r, grid).copyTo(image(cv::Range(r, image.rows), cv::Range(0, c)));
se->compose(image.cols - c, image.rows - r, grid).copyTo(image(cv::Range(r, image.rows), cv::Range(c, image.cols)));
if (grid) {
cv::line(image, cv::Point(0, r), cv::Point(image.cols, r), cv::Scalar(255, 0, 0), 1, cv::LINE_AA);
cv::line(image, cv::Point(c, 0), cv::Point(c, image.rows), cv::Scalar(255, 0, 0), 1, cv::LINE_AA);
}
} else
image = color2Scalar(color);
return image;
}
cv::Mat QuadTree::getImage(bool grid) {
return root->compose(size_x, size_y, grid);
}
| 24.327684 | 118 | 0.602183 | mihalyvaghy |
71a975ed8787b8ddd826d80a98ed774f88982031 | 1,074 | cpp | C++ | solutions/c++/problems/[0265_Hard] Paint House II.cpp | RageBill/leetcode | a11d411f4e38b5c3f05ca506a193f50b25294497 | [
"MIT"
] | 6 | 2021-02-20T14:00:22.000Z | 2022-03-31T15:26:44.000Z | solutions/c++/problems/[0265_Hard] Paint House II.cpp | RageBill/leetcode | a11d411f4e38b5c3f05ca506a193f50b25294497 | [
"MIT"
] | null | null | null | solutions/c++/problems/[0265_Hard] Paint House II.cpp | RageBill/leetcode | a11d411f4e38b5c3f05ca506a193f50b25294497 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> getCurrCost(vector<int> prev, vector<int> curr) {
int n = prev.size();
int min = 999;
int min2 = 1000;
for (int num: prev) {
if (num < min) {
min2 = min;
min = num;
} else if (num < min2) {
min2 = num;
}
}
vector<int> ans = vector<int>(n, 0);
for (int i = 0; i < n; i++) {
ans[i] = prev[i] == min ? min2 + curr[i] : min + curr[i];
}
return ans;
}
int minCostII(vector<vector<int>> &costs) {
int n = costs.size();
vector<vector<int>> ans = vector<vector<int>>(n, vector<int>{});
// base case
ans[0] = costs[0];
for (int i = 1; i < n; i++) {
auto prev = ans[i - 1];
auto curr = costs[i];
ans[i] = getCurrCost(prev, curr);
}
vector<int> last = ans.back();
return *min_element(last.begin(), last.end());
}
}; | 27.538462 | 72 | 0.443203 | RageBill |
71ac1784b47660a2bd641055f45236018d8dda94 | 7,291 | cpp | C++ | BeaconCompilerBackend.cpp | beacon1096/Project-Guider | 3dcb16da2e091878e340a33230e66ddd4b4c2be1 | [
"Apache-2.0"
] | null | null | null | BeaconCompilerBackend.cpp | beacon1096/Project-Guider | 3dcb16da2e091878e340a33230e66ddd4b4c2be1 | [
"Apache-2.0"
] | null | null | null | BeaconCompilerBackend.cpp | beacon1096/Project-Guider | 3dcb16da2e091878e340a33230e66ddd4b4c2be1 | [
"Apache-2.0"
] | null | null | null | #include "BeaconCompilerBackend.h"
BeaconCompilerBackend::BeaconCompilerBackend(QObject *parent) : QObject(parent)
{
QSettings settings;
if(!settings.value("gccPath").toString().isEmpty()){
gcc.setProgram(settings.value("gccPath").toString());
gpp.setProgram(settings.value("gppPath").toString());
}
else if(BeaconPlatformInfo::isLinux || BeaconPlatformInfo::isMacos){
gcc.setProgram("/usr/bin/gcc");
gpp.setProgram("/usr/bin/g++");
settings.setValue("gccPath","/usr/bin/gcc");
settings.setValue("gppPath","/usr/bin/g++");
if(BeaconPlatformInfo::isMacos){
QMessageBox::warning(NULL, "Clang | GCC", tr("Please be noticed that macOS automatically links Clang to GCC.\nIf you wish to use GCC, please install it yourself and change the settings."), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
}
}
else{
gcc.setProgram("C:/MinGW/bin/gcc.exe");
gpp.setProgram("C:/MinGW/bin/g++.exe");
settings.setValue("gccPath","C:/MinGW/bin/gcc.exe");
settings.setValue("gppPath","C:/MinGW/bin/g++.exe");
}
connect(&gcc,SIGNAL(programExited(int,QProcess::ExitStatus)),this,SLOT(compileEnded(int,QProcess::ExitStatus)));
connect(&gpp,SIGNAL(programExited(int,QProcess::ExitStatus)),this,SLOT(compileEnded(int,QProcess::ExitStatus)));
connect(&gcc,SIGNAL(programLogUpdated(QString)),this,SLOT(_compileInfoUpdated(QString)));
connect(&gpp,SIGNAL(programLogUpdated(QString)),this,SLOT(_compileInfoUpdated(QString)));
}
void BeaconCompilerBackend::_compileInfoUpdated(QString Content){
qDebug() << "[BeaconCompilerBackend]_cIU:" << Content;
emit compileInfoUpdated(Content);
}
int BeaconCompilerBackend::compilerValidation(){
QString cCodeName=QDir::tempPath()+QDir::separator()+QCoreApplication::applicationName()+"_XXXXXX."+"c";
QString cppCodeName=QDir::tempPath()+QDir::separator()+QCoreApplication::applicationName()+"_XXXXXX."+"cpp";
QFile c(gcc.programPath),cpp(gpp.programPath);
if(!c.exists() || !cpp.exists())return -1;
QTemporaryFile ct(cCodeName);
if(ct.open()){
BeaconFileIO::saveFileContent(ct.fileName(),BeaconFileIO::readFileContent(":/Resources/Code/test.c"));
QStringList arg;
arg.append(ct.fileName());
gcc.program.setArguments(arg);
gcc.startProgram();
gcc.program.waitForFinished();
QString result=gcc.logOut;
qDebug() << "gcc test result:" << result;
qDebug() << "RT result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus;
if(lastCompileResult!=0)return -2;
if(!result.isEmpty())return -2;
}
QTemporaryFile cppt(cppCodeName);
if(cppt.open()){
BeaconFileIO::saveFileContent(cppt.fileName(),BeaconFileIO::readFileContent(":/Resources/Code/test.cpp"));
QStringList arg;
arg.append(cppt.fileName());
gpp.program.setArguments(arg);
gpp.startProgram();
gpp.program.waitForFinished();
QString result=gpp.logOut;
qDebug() << "g++ test result:" << result;
qDebug() << "RT result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus;
if(lastCompileResult!=0)return -2;
if(!result.isEmpty())return -2;
}
return 0;
}
bool BeaconCompilerBackend::configureCompilerPath(int lastError){
BeaconCompilerSetupInterface bcsi(lastError);
bcsi.exec();
return !compilerValidation();
}
void BeaconCompilerBackend::compileEnded(int result,QProcess::ExitStatus status){
lastCompileResult = result;
lastCompileStatus = status;
}
void BeaconCompilerBackend::compileStart(QString filePath,QString executable,QTextBrowser* target){
QString suffix=filePath.split(".").last();
if(suffix=="c"){
QStringList arg;
arg.append(filePath);
arg.append("-o");
arg.append(executable);
arg.append("-Wall");
gcc.clearLog();
gcc.setArguments(arg);
qDebug() << "executing gcc " << arg;
gcc.startProgram();
gcc.program.waitForFinished();
qDebug() << "result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus;
qDebug() << "logs:" << gcc.logOut;
latestCompileLog=gcc.logOut;
}
else if(suffix=="cpp"){
QStringList arg;
arg.append(filePath);
arg.append("-o");
arg.append(executable);
arg.append("-Wall");
gpp.clearLog();
gpp.setArguments(arg);
qDebug() << "executing g++ " << arg;
qDebug() << "compile command:[" << gpp.program.program() << " " << arg;
gpp.startProgram();
gpp.program.waitForFinished();
qDebug() << "result:(1)" << lastCompileResult << ",(2)" << lastCompileStatus;
qDebug() << "logs:" << gpp.logOut;
latestCompileLog=gpp.logOut;
}
}
BeaconCompilerSetupInterface::BeaconCompilerSetupInterface(int errorCode,QObject *parent) : QDialog(){
information = new QLabel;
QSettings settings;
if(errorCode==-1)information->setText(QString(tr("Could not find compiler in default Location.").append("\n").append(tr("Please specify where it is."))));
if(errorCode==-2)information->setText(QString(tr("Your compiler is unable to compile a simple test program.")).append("\n").append(tr("Please specify a working one.")));
gccHL = new QHBoxLayout;gppHL = new QHBoxLayout;
total = new QVBoxLayout;
gcc = new QLabel("GCC:");
gpp = new QLabel("G++:");
gccL = new QLineEdit();
gppL = new QLineEdit();
gccS = new QToolButton();
gppS = new QToolButton();
gccS->setText("...");
gppS->setText("...");
confirm = new QPushButton("OK");
gccL->setText(settings.value("gccPath").toString());
gppL->setText(settings.value("gppPath").toString());
connect(gccS,SIGNAL(clicked()),this,SLOT(gccSClicked()));
connect(gppS,SIGNAL(clicked()),this,SLOT(gppSClicked()));
connect(confirm,SIGNAL(clicked()),this,SLOT(confirmClicked()));
total->addWidget(information);
gccHL->addWidget(gcc);gccHL->addWidget(gccL);gccHL->addWidget(gccS);
gppHL->addWidget(gpp);gppHL->addWidget(gppL);gppHL->addWidget(gppS);
total->addLayout(gccHL);total->addLayout(gppHL);total->addWidget(confirm);
this->setLayout(total);
}
void BeaconCompilerSetupInterface::gppSClicked(){
QString path;
if(BeaconPlatformInfo::isWindows)
path = QFileDialog::getOpenFileName(this,tr("Select G++ Path"),"C:/","g++.exe");
else
path = QFileDialog::getOpenFileName(this,tr("Select G++ Path"),"/","");
gppL->setText(path);
}
void BeaconCompilerSetupInterface::gccSClicked(){
QString path;
if(BeaconPlatformInfo::isWindows)
path = QFileDialog::getOpenFileName(this,tr("Select GCC Path"),"C:/","gcc.exe");
else
path = QFileDialog::getOpenFileName(this,tr("Select GCC Path"),"/","");
gccL->setText(path);
QString gppPath=path;
gppPath.replace(gppPath.lastIndexOf("gcc"),3,"g++");
QFile gppTest(gppPath);
if(gppTest.exists())
gppL->setText(gppPath);
}
void BeaconCompilerSetupInterface::confirmClicked(){
QSettings settings;
settings.setValue("gccPath",this->gccL->text());
settings.setValue("gppPath",this->gppL->text());
this->close();
}
| 43.921687 | 255 | 0.654368 | beacon1096 |
71b84c3a2426d6a1ffa72dbf69768504bf6bacf9 | 214 | cpp | C++ | SourceCode/main.cpp | Remsya/M2Process | b2ad03ed91cc32305a114de187ac6dbc463baae7 | [
"MIT"
] | null | null | null | SourceCode/main.cpp | Remsya/M2Process | b2ad03ed91cc32305a114de187ac6dbc463baae7 | [
"MIT"
] | null | null | null | SourceCode/main.cpp | Remsya/M2Process | b2ad03ed91cc32305a114de187ac6dbc463baae7 | [
"MIT"
] | null | null | null | //
// main.cpp
// CauchyProcess, 1-dimension only
//
// Created by Rémi Carnec on 13/05/2020.
// Copyright © 2020 Rémi Carnec. All rights reserved.
//
int main(int argc, const char * argv[]){
return 0;
}
| 16.461538 | 54 | 0.640187 | Remsya |
71bc1fa5fd7927bc8e6cc6d9877f27f0c54aaae1 | 516 | hpp | C++ | source/Graphics/GLCheck.hpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | source/Graphics/GLCheck.hpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | source/Graphics/GLCheck.hpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | //File adapted from SFML source code, https://github.com/LaurentGomila/SFML
#ifndef GLCHECK_HPP
#define GLCHECK_HPP
#include <string>
namespace pcke
{
#ifdef PCKE_DEBUG
// In debug mode, perform a test on every OpenGL call
#define glCheck(x) x; pcke::glCheckError(__FILE__, __LINE__);
#else
// Else, we don't add any overhead
#define glCheck(call) (call)
#endif
void glCheckError(const char* file, unsigned int line);
} // namespace pcke
#endif //GLCHECK_HPP
| 19.846154 | 75 | 0.676357 | Dante12129 |
71ce8ea516e381387939e641d93df8d5fe46cc76 | 422 | cpp | C++ | src/admin/migrate.cpp | victorvw/eos-wps | e115197eb78b6f6a851f253f68784324383fae14 | [
"MIT"
] | 4 | 2020-03-26T11:12:07.000Z | 2020-04-19T02:07:31.000Z | src/admin/migrate.cpp | victorvw/eos-wps | e115197eb78b6f6a851f253f68784324383fae14 | [
"MIT"
] | 13 | 2019-12-12T21:33:49.000Z | 2019-12-22T17:23:54.000Z | src/admin/migrate.cpp | victorvw/eos-wps | e115197eb78b6f6a851f253f68784324383fae14 | [
"MIT"
] | 4 | 2019-11-11T14:13:25.000Z | 2020-03-15T17:44:38.000Z | void wps::migrate( const name type )
{
require_auth( get_self() );
if (type == "del.comment"_n) {
for ( auto row : _proposals ) {
comments_table _comments( get_self(), row.proposal_name.value );
auto comment_itr = _comments.begin();
while ( comment_itr != _comments.end() ) {
comment_itr = _comments.erase( comment_itr );
}
}
}
} | 30.142857 | 76 | 0.545024 | victorvw |
71d211f8f05affbfcb9d38d47caad40b91c5ae15 | 16,601 | hpp | C++ | SDK/ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Dino_Character_BP_DivingFlyer_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.OnDiveCrash
struct ADino_Character_BP_DivingFlyer_C_OnDiveCrash_Params
{
class AActor* HitActor; // (Parm, ZeroConstructor, IsPlainOldData)
class USceneComponent* HitComp; // (Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult HitResult; // (Parm)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPForceTurretFastTargeting
struct ADino_Character_BP_DivingFlyer_C_BPForceTurretFastTargeting_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReturnDivingFlyerToZeroPitchRotation
struct ADino_Character_BP_DivingFlyer_C_ReturnDivingFlyerToZeroPitchRotation_Params
{
float DeltaTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReduceDiverStamina
struct ADino_Character_BP_DivingFlyer_C_ReduceDiverStamina_Params
{
float cost; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_OnStartLandingNotify
struct ADino_Character_BP_DivingFlyer_C_BP_OnStartLandingNotify_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Diving Velocity Mult Ratio
struct ADino_Character_BP_DivingFlyer_C_Get_Diving_Velocity_Mult_Ratio_Params
{
float Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity Max
struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_Max_Params
{
float MaxVelocity; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity Ratio
struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_Ratio_Params
{
float Ratio; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Has Diving Momentum
struct ADino_Character_BP_DivingFlyer_C_Has_Diving_Momentum_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.UpdateDivingFX
struct ADino_Character_BP_DivingFlyer_C_UpdateDivingFX_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ResetDivingVars
struct ADino_Character_BP_DivingFlyer_C_ResetDivingVars_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Is Diver Moving Forward
struct ADino_Character_BP_DivingFlyer_C_Is_Diver_Moving_Forward_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.GetDefaultMaxFlySpeed
struct ADino_Character_BP_DivingFlyer_C_GetDefaultMaxFlySpeed_Params
{
float MaxFlySpeed; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Diving Required VelocityToStart
struct ADino_Character_BP_DivingFlyer_C_Get_Diving_Required_VelocityToStart_Params
{
float _float; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.HasEnoughStaminaToDive
struct ADino_Character_BP_DivingFlyer_C_HasEnoughStaminaToDive_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_OnSetRunning
struct ADino_Character_BP_DivingFlyer_C_BP_OnSetRunning_Params
{
bool* bNewIsRunning; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_GetCustomModifier_RotationRate
struct ADino_Character_BP_DivingFlyer_C_BP_GetCustomModifier_RotationRate_Params
{
float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BP_GetCustomModifier_MaxSpeed
struct ADino_Character_BP_DivingFlyer_C_BP_GetCustomModifier_MaxSpeed_Params
{
float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPNotifyClearRider
struct ADino_Character_BP_DivingFlyer_C_BPNotifyClearRider_Params
{
class AShooterCharacter** RiderClearing; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.IsDiving
struct ADino_Character_BP_DivingFlyer_C_IsDiving_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Has Diving Momentum_Pure
struct ADino_Character_BP_DivingFlyer_C_Has_Diving_Momentum_Pure_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPOnMovementModeChangedNotify
struct ADino_Character_BP_DivingFlyer_C_BPOnMovementModeChangedNotify_Params
{
TEnumAsByte<EMovementMode>* PrevMovementMode; // (Parm, ZeroConstructor, IsPlainOldData)
unsigned char* PreviousCustomMode; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity Ratio_Pure
struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_Ratio_Pure_Params
{
float Ratio; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Flyer Dive Velocity MaxPure
struct ADino_Character_BP_DivingFlyer_C_Get_Flyer_Dive_Velocity_MaxPure_Params
{
float MaxVelocity; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.CanFlyerDive
struct ADino_Character_BP_DivingFlyer_C_CanFlyerDive_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.AllowDiving
struct ADino_Character_BP_DivingFlyer_C_AllowDiving_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Diving_Tick
struct ADino_Character_BP_DivingFlyer_C_Diving_Tick_Params
{
float DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Diving_Stop
struct ADino_Character_BP_DivingFlyer_C_Diving_Stop_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Diving_Start
struct ADino_Character_BP_DivingFlyer_C_Diving_Start_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Set Is Diving
struct ADino_Character_BP_DivingFlyer_C_Set_Is_Diving_Params
{
bool newDiving; // (Parm, ZeroConstructor, IsPlainOldData)
bool forceSet; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.OnRep_bIsDiving
struct ADino_Character_BP_DivingFlyer_C_OnRep_bIsDiving_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Interp Diver Mesh
struct ADino_Character_BP_DivingFlyer_C_Interp_Diver_Mesh_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get Diving Velocity Mult Ratio_Pure
struct ADino_Character_BP_DivingFlyer_C_Get_Diving_Velocity_Mult_Ratio_Pure_Params
{
float Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPNotifySetRider
struct ADino_Character_BP_DivingFlyer_C_BPNotifySetRider_Params
{
class AShooterCharacter** RiderSetting; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPTimerNonDedicated
struct ADino_Character_BP_DivingFlyer_C_BPTimerNonDedicated_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Get DefaultDivingFlyer
struct ADino_Character_BP_DivingFlyer_C_Get_DefaultDivingFlyer_Params
{
class ADino_Character_BP_DivingFlyer_C* Default; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.BPModifyFOV
struct ADino_Character_BP_DivingFlyer_C_BPModifyFOV_Params
{
float* FOVIn; // (Parm, ZeroConstructor, IsPlainOldData)
float ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReceiveHit
struct ADino_Character_BP_DivingFlyer_C_ReceiveHit_Params
{
class UPrimitiveComponent** MyComp; // (Parm, ZeroConstructor, IsPlainOldData)
class AActor** Other; // (Parm, ZeroConstructor, IsPlainOldData)
class UPrimitiveComponent** OtherComp; // (Parm, ZeroConstructor, IsPlainOldData)
bool* bSelfMoved; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector* HitLocation; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector* HitNormal; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector* NormalImpulse; // (Parm, ZeroConstructor, IsPlainOldData)
struct FHitResult Hit; // (Parm, OutParm, ReferenceParm)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.HasLocallyCarriedPlayer
struct ADino_Character_BP_DivingFlyer_C_HasLocallyCarriedPlayer_Params
{
bool bLocallyCarried; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.DebugDiveVals
struct ADino_Character_BP_DivingFlyer_C_DebugDiveVals_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.GetCurrentAcceleration
struct ADino_Character_BP_DivingFlyer_C_GetCurrentAcceleration_Params
{
struct FVector ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.UserConstructionScript
struct ADino_Character_BP_DivingFlyer_C_UserConstructionScript_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.AbortDive
struct ADino_Character_BP_DivingFlyer_C_AbortDive_Params
{
bool bPlayAbortAnim; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.DiveBomb
struct ADino_Character_BP_DivingFlyer_C_DiveBomb_Params
{
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.OwningClientDiveBombCameraShake
struct ADino_Character_BP_DivingFlyer_C_OwningClientDiveBombCameraShake_Params
{
float Intensity; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Multi_LandFromDive
struct ADino_Character_BP_DivingFlyer_C_Multi_LandFromDive_Params
{
struct FRotator MeshRotation; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.Server_SetIsDiving
struct ADino_Character_BP_DivingFlyer_C_Server_SetIsDiving_Params
{
bool newDiving; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ReceiveTick
struct ADino_Character_BP_DivingFlyer_C_ReceiveTick_Params
{
float* DeltaSeconds; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Dino_Character_BP_DivingFlyer.Dino_Character_BP_DivingFlyer_C.ExecuteUbergraph_Dino_Character_BP_DivingFlyer
struct ADino_Character_BP_DivingFlyer_C_ExecuteUbergraph_Dino_Character_BP_DivingFlyer_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 52.369085 | 173 | 0.630805 | 2bite |
71d9e0440a273165a085872bb963684a3c3363db | 1,496 | cpp | C++ | core/net/ntp.cpp | JartC0ding/horizon | 2b9a75b45ac768a8da0f7a98f164a37690dc583f | [
"MIT"
] | 4 | 2022-01-06T09:19:46.000Z | 2022-03-27T18:08:36.000Z | core/net/ntp.cpp | JartC0ding/horizon | 2b9a75b45ac768a8da0f7a98f164a37690dc583f | [
"MIT"
] | null | null | null | core/net/ntp.cpp | JartC0ding/horizon | 2b9a75b45ac768a8da0f7a98f164a37690dc583f | [
"MIT"
] | 1 | 2022-03-22T19:10:05.000Z | 2022-03-22T19:10:05.000Z | #include <net/ntp.h>
#include <utils/abort.h>
#include <utils/log.h>
#include <utils/string.h>
#include <timer/timer.h>
#include <utils/unix_time.h>
using namespace net;
network_time_protocol::network_time_protocol(udp_socket* socket) {
this->socket = socket;
}
void network_time_protocol::on_udp_message(udp_socket *socket, uint8_t* data, size_t size) {
debugf("ntp: got packet of size %d\n", size);
last_packet = *(ntp_packet_t*) data;
received_packet = true;
}
driver::clock_device::clock_result_t network_time_protocol::time() {
debugf("ntp: sending request\n");
ntp_packet_t packet;
memset(&packet, 0, sizeof(ntp_packet_t));
memset(&last_packet, 0, sizeof(ntp_packet_t));
received_packet = false;
*((char*) &packet) = 0x1b;
__asm__ __volatile__("sti"); // make sure interrupts are enabled
this->socket->send((uint8_t*) &packet, sizeof(ntp_packet_t));
debugf("ntp: waiting for response\n");
int timeout = 1000;
while(timeout--) {
timer::global_timer->sleep(10);
if(received_packet) {
debugf("ntp: got response\n");
break;
}
}
if(!received_packet) {
abortf("ntp: no response\n");
}
int unix_time = (__builtin_bswap32(last_packet.txTm_s) - 2208988800);
debugf("ntp: unix time: %d\n", unix_time);
driver::clock_device::clock_result_t result;
memset(&result, 0, sizeof(driver::clock_device::clock_result_t));
from_unix_time(unix_time, &result.year, &result.month, &result.day, &result.hours, &result.minutes, &result.seconds);
return result;
} | 25.793103 | 118 | 0.720588 | JartC0ding |
71e387d3770567a10d0f161f181cf185497fa96b | 6,358 | cpp | C++ | template_mp/src/utils/RCBot2/bot_accessclient.cpp | moeabm/VS2013 | dd29099567b286acac7bb542a06f085df78ea480 | [
"Unlicense"
] | null | null | null | template_mp/src/utils/RCBot2/bot_accessclient.cpp | moeabm/VS2013 | dd29099567b286acac7bb542a06f085df78ea480 | [
"Unlicense"
] | null | null | null | template_mp/src/utils/RCBot2/bot_accessclient.cpp | moeabm/VS2013 | dd29099567b286acac7bb542a06f085df78ea480 | [
"Unlicense"
] | null | null | null | /*
* This file is part of RCBot.
*
* RCBot by Paul Murphy adapted from Botman's HPB Bot 2 template.
*
* RCBot is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* RCBot is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with RCBot; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* In addition, as a special exception, the author gives permission to
* link the code of this program with the Half-Life Game Engine ("HL
* Engine") and Modified Game Libraries ("MODs") developed by Valve,
* L.L.C ("Valve"). You must obey the GNU General Public License in all
* respects for all of the code used other than the HL Engine and MODs
* from Valve. If you modify this file, you may extend this exception
* to your version of the file, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
*/
#include "bot.h"
#include "bot_strings.h"
#include "bot_accessclient.h"
#include "bot_globals.h"
#include <vector>
using namespace std;
///////////
vector<CAccessClient*> CAccessClients :: m_Clients;
///////////
CAccessClient :: CAccessClient( char *szSteamId, int iAccessLevel )
{
m_iAccessLevel = iAccessLevel;
m_szSteamId = CStrings::getString(szSteamId);
}
bool CAccessClient :: forBot ()
{
return isForSteamId("BOT");
}
bool CAccessClient :: isForSteamId ( const char *szSteamId )
{
return FStrEq(m_szSteamId,szSteamId);
}
void CAccessClient :: save ( FILE *fp )
{
fprintf(fp,"\"%s\":%d\n",m_szSteamId,m_iAccessLevel);
}
void CAccessClient :: giveAccessToClient ( CClient *pClient )
{
// notify player
if ( !forBot() )
CBotGlobals::botMessage(pClient->getPlayer(),0,"%s authenticated for bot commands",pClient->getName());
// notify server
CBotGlobals::botMessage(NULL,0,"%s authenticated for bot commands",pClient->getName());
pClient->setAccessLevel(m_iAccessLevel);
}
//////////////
void CAccessClients :: showUsers ( edict_t *pEntity )
{
CAccessClient *pPlayer;
CClient *pClient;
CBotGlobals::botMessage(pEntity,0,"showing users...");
if ( m_Clients.empty() )
CBotGlobals::botMessage(NULL,0,"showUsers() : No users to show");
for ( unsigned int i = 0; i < m_Clients.size(); i ++ )
{
pPlayer = m_Clients[i];
pClient = CClients::findClientBySteamID(pPlayer->getSteamID());
if ( pClient )
CBotGlobals::botMessage(pEntity,0,"[ID: %s]/[AL: %d] (currently playing as : %s)\n",pPlayer->getSteamID(),pPlayer->getAccessLevel(),pClient->getName());
else
CBotGlobals::botMessage(pEntity,0,"[ID: %s]/[AL: %d]\n",pPlayer->getSteamID(),pPlayer->getAccessLevel());
}
}
void CAccessClients :: createFile ()
{
char filename[1024];
CBotGlobals::buildFileName(filename,BOT_ACCESS_CLIENT_FILE,BOT_CONFIG_FOLDER,BOT_CONFIG_EXTENSION);
FILE *fp = CBotGlobals::openFile(filename,"w");
CBotGlobals::botMessage(NULL,0,"Making an accessclients.ini file for you... Edit it in %s",filename);
if ( fp )
{
fprintf(fp,"# format is ");
fprintf(fp,"# \"<STEAM ID>\" <access level>\n");
fprintf(fp,"# see http://rcbot.bots-united.com/accesslev.htm for access\n");
fprintf(fp,"# levels\n");
fprintf(fp,"#\n");
fprintf(fp,"# example:\n");
fprintf(fp,"#\n");
fprintf(fp,"# \"STEAM_0:123456789\" 63\n");
fprintf(fp,"# don't put one of '#' these before a line you want to be read \n");
fprintf(fp,"# by the bot!\n");
fprintf(fp,"# \n");
fclose(fp);
}
else
CBotGlobals::botMessage(NULL,0,"Error! Couldn't create config file %s",filename);
}
void CAccessClients :: freeMemory ()
{
for ( unsigned int i = 0; i < m_Clients.size(); i ++ )
{
delete m_Clients[i];
m_Clients[i] = NULL;
}
m_Clients.clear();
}
void CAccessClients :: load ()
{
char filename[1024];
CBotGlobals::buildFileName(filename,BOT_ACCESS_CLIENT_FILE,BOT_CONFIG_FOLDER,BOT_CONFIG_EXTENSION);
FILE *fp = CBotGlobals::openFile(filename,"r");
if ( fp )
{
char buffer[256];
char szSteamId[32];
int iAccess;
int i;
int len;
int n;
int iLine = 0;
while ( fgets(buffer,255,fp) != NULL )
{
iLine++;
buffer[255] = 0;
if ( buffer[0] == 0 )
continue;
if ( buffer[0] == '\n' )
continue;
if ( buffer[0] == '#' )
continue;
len = strlen(buffer);
i = 0;
while (( i < len ) && ((buffer[i] == '\"') || (buffer[i] == ' ')))
i++;
n = 0;
// parse Steam ID
while ( (n<31) && (i < len) && (buffer[i] != '\"') )
szSteamId[n++] = buffer[i++];
szSteamId[n] = 0;
i++;
while (( i < len ) && (buffer[i] == ' '))
i++;
if ( i == len )
{
CBotGlobals::botMessage(NULL,0,"line %d invalid in access client config, missing access level",iLine);
continue; // invalid
}
iAccess = atoi(&buffer[i]);
// invalid
if ( (szSteamId[0] == 0) || (szSteamId[0] == ' ' ) )
{
CBotGlobals::botMessage(NULL,0,"line %d invalid in access client config, steam id invalid",iLine);
continue;
}
if ( iAccess == 0 )
{
CBotGlobals::botMessage(NULL,0,"line %d invalid in access client config, access level can't be 0",iLine);
continue;
}
m_Clients.push_back(new CAccessClient(szSteamId,iAccess));
}
fclose(fp);
}
else
CAccessClients :: createFile();
}
void CAccessClients :: save ()
{
char filename[1024];
CBotGlobals::buildFileName(filename,BOT_ACCESS_CLIENT_FILE,BOT_CONFIG_FOLDER,BOT_CONFIG_EXTENSION);
FILE *fp = CBotGlobals::openFile(filename,"w");
if ( fp )
{
for ( unsigned int i = 0; i < m_Clients.size(); i ++ )
{
m_Clients[i]->save(fp);
}
fclose(fp);
}
}
void CAccessClients :: checkClientAccess ( CClient *pClient )
{
for ( unsigned int i = 0; i < m_Clients.size(); i ++ )
{
CAccessClient *pAC = m_Clients[i];
if ( pAC->isForSteamId(pClient->getSteamID()) )
pAC->giveAccessToClient(pClient);
}
}
| 25.031496 | 155 | 0.651777 | moeabm |
71e4828fe3a91bf35c9f4748b2daa081a9dfb241 | 6,718 | cpp | C++ | lighthub/modules/in_ccs811_hdc1080.cpp | anklimov/lighthub | 99e9c1a27aca52bf38efec000547720fb8f82860 | [
"Apache-2.0"
] | 83 | 2017-11-05T14:05:16.000Z | 2022-02-21T16:34:53.000Z | lighthub/modules/in_ccs811_hdc1080.cpp | anklimov/lighthub | 99e9c1a27aca52bf38efec000547720fb8f82860 | [
"Apache-2.0"
] | 27 | 2018-03-12T21:49:33.000Z | 2022-01-20T19:06:05.000Z | lighthub/modules/in_ccs811_hdc1080.cpp | anklimov/lighthub | 99e9c1a27aca52bf38efec000547720fb8f82860 | [
"Apache-2.0"
] | 20 | 2017-11-20T08:27:17.000Z | 2022-03-28T02:26:17.000Z | #include "modules/in_ccs811_hdc1080.h"
#include "Arduino.h"
#include "options.h"
#include "Streaming.h"
#include "item.h"
#include "main.h"
#if defined(M5STACK)
#include <M5Stack.h>
#endif
#ifndef CSSHDC_DISABLE
static ClosedCube_HDC1080 hdc1080;
static CCS811 ccs811(CCS811_ADDR);
long ccs811Baseline;
static bool HDC1080ready = false;
static bool CCS811ready = false;
int in_ccs811::Setup()
{
if (CCS811ready) {debugSerial<<F("ccs811 is already initialized")<<endl; return 0;}
#ifdef WAK_PIN
pinMode(WAK_PIN,OUTPUT);
digitalWrite(WAK_PIN,LOW);
#endif
Serial.println("CCS811 Init");
Wire.begin(); //Inialize I2C Harware
Wire.setClock(4000);
//It is recommended to check return status on .begin(), but it is not
//required.
CCS811Core::status returnCode = ccs811.begin();
//CCS811Core::CC811_Status_e returnCode = ccs811.beginWithStatus();
if (returnCode != CCS811Core::SENSOR_SUCCESS)
//if (returnCode != CCS811Core::CCS811_Stat_SUCCESS)
{
Serial.print("CCS811 Init error ");
//Serial.println(ccs811.statusString(returnCode));
printDriverError(returnCode);
return 0;
}
//ccs811.setBaseline(62000);
CCS811ready = true;
//returnCode = ccs811.setDriveMode(1);
//printDriverError(returnCode);
/*
delay(2000);Poll();
delay(2000);Poll();
delay(2000);Poll();
delay(2000); */
return 1;
}
int in_hdc1080::Setup()
{
if (HDC1080ready) {debugSerial<<F("hdc1080 is already initialized")<<endl; return 0;}
Serial.println("HDC1080 Init ");
Wire.begin(); //Inialize I2C Harware
// Default settings:
// - Heater off
// - 14 bit Temperature and Humidity Measurement Resolutions
hdc1080.begin(0x40);
Serial.print("Manufacturer ID=0x");
Serial.println(hdc1080.readManufacturerId(), HEX); // 0x5449 ID of Texas Instruments
Serial.print("Device ID=0x");
Serial.println(hdc1080.readDeviceId(), HEX); // 0x1050 ID of the device
printSerialNumber();
HDC1080ready = true;
return 1;
}
void i2cReset(){
Wire.endTransmission(true);
#if defined (SCL_RESET)
SCL_LOW();
delay(300);
SCL_HIGH();
#endif
}
int in_hdc1080::Poll(short cause)
{
float h,t;
int reg;
if (cause!=POLLING_SLOW) return 0;
if (!HDC1080ready) {debugSerial<<F("HDC1080 not initialized")<<endl; return 0;}
Serial.print("HDC Status=");
Serial.println(reg=hdc1080.readRegister().rawData,HEX);
if (reg!=0xff)
{
Serial.print(" T=");
Serial.print(t=hdc1080.readTemperature());
Serial.print("C, RH=");
Serial.print(h=hdc1080.readHumidity());
Serial.println("%");
#ifdef M5STACK
M5.Lcd.print(" T=");
//Returns calculated CO2 reading
M5.Lcd.print(t=hdc1080.readTemperature());
M5.Lcd.print("C, RH=");
//Returns calculated TVOC reading
M5.Lcd.print(h=hdc1080.readHumidity());
M5.Lcd.print("%\n");
#endif
// New tyle unified activities
aJsonObject *actT = aJson.getObjectItem(in->inputObj, "temp");
aJsonObject *actH = aJson.getObjectItem(in->inputObj, "hum");
executeCommand(actT,-1,itemCmd(t));
executeCommand(actH,-1,itemCmd(h));
publish(t,"/T");
publish(h,"/H");
if (CCS811ready) ccs811.setEnvironmentalData(h,t);
}
else //ESP I2C glitch
{
Serial.println("I2C Reset");
i2cReset();
}
return INTERVAL_SLOW_POLLING;
}
int in_ccs811::Poll(short cause)
{
if (!CCS811ready) {debugSerial<<F("ccs811 not initialized")<<endl; return 0;}
#ifdef WAK_PIN
digitalWrite(WAK_PIN,LOW);
#endif
delay(1);
//Check to see if data is ready with .dataAvailable()
if (ccs811.dataAvailable())
//if (1)
{
//If so, have the sensor read and calculate the results.
//Get them later
CCS811Core::status returnCode = ccs811.readAlgorithmResults();
printDriverError(returnCode);
float co2,tvoc;
Serial.print(" CO2[");
//Returns calculated CO2 reading
Serial.print(co2 = ccs811.getCO2());
Serial.print("] tVOC[");
//Returns calculated TVOC reading
Serial.print(tvoc = ccs811.getTVOC());
Serial.print("] baseline[");
Serial.print(ccs811Baseline = ccs811.getBaseline());
#ifdef M5STACK
M5.Lcd.print(" CO2[");
//Returns calculated CO2 reading
M5.Lcd.print(co2 = ccs811.getCO2());
M5.Lcd.print("] tVOC[");
//Returns calculated TVOC reading
M5.Lcd.print(tvoc = ccs811.getTVOC());
M5.Lcd.print("]\n");
#endif
if (co2<10000.) //Spontaneous calculation error suppress
{
// New tyle unified activities
aJsonObject *actCO2 = aJson.getObjectItem(in->inputObj, "co2");
aJsonObject *actTVOC = aJson.getObjectItem(in->inputObj, "tvoc");
executeCommand(actCO2,-1,itemCmd(co2));
executeCommand(actTVOC,-1,itemCmd(tvoc));
publish(co2,"/CO2");
publish(tvoc,"/TVOC");
publish(ccs811Baseline,"/base");}
Serial.println("]");
printSensorError();
#ifdef WAK_PIN
digitalWrite(WAK_PIN,HIGH); //Relax some time
#endif
} else {debugSerial<<F("ccs811: data not available")<<endl; return 0;}
return 1;
}
void in_hdc1080::printSerialNumber() {
Serial.print("Device Serial Number=");
HDC1080_SerialNumber sernum = hdc1080.readSerialNumber();
char format[16];
sprintf(format, "%02X-%04X-%04X", sernum.serialFirst, sernum.serialMid, sernum.serialLast);
Serial.println(format);
}
//printDriverError decodes the CCS811Core::status type and prints the
//type of error to the serial terminal.
//
//Save the return value of any function of type CCS811Core::status, then pass
//to this function to see what the output was.
void in_ccs811::printDriverError( CCS811Core::status errorCode )
{
switch ( errorCode )
{
case CCS811Core::SENSOR_SUCCESS:
Serial.print("SUCCESS");
break;
case CCS811Core::SENSOR_ID_ERROR:
Serial.print("ID_ERROR");
break;
case CCS811Core::SENSOR_I2C_ERROR:
Serial.print("I2C_ERROR");
break;
case CCS811Core::SENSOR_INTERNAL_ERROR:
Serial.print("INTERNAL_ERROR");
break;
case CCS811Core::SENSOR_GENERIC_ERROR:
Serial.print("GENERIC_ERROR");
break;
default:
Serial.print("Unspecified error.");
}
}
//printSensorError gets, clears, then prints the errors
//saved within the error register.
void in_ccs811::printSensorError()
{
uint8_t error = ccs811.getErrorRegister();
if ( error == 0xFF ) //comm error
{
Serial.println("Failed to get ERROR_ID register.");
}
else
{
//Serial.print("");
if (error & 1 << 5) Serial.print("Error: HeaterSupply");
if (error & 1 << 4) Serial.print("Error: HeaterFault");
if (error & 1 << 3) Serial.print("Error: MaxResistance");
if (error & 1 << 2) Serial.print("Error: MeasModeInvalid");
if (error & 1 << 1) Serial.print("Error: ReadRegInvalid");
if (error & 1 << 0) Serial.print("Error: MsgInvalid");
Serial.println();
}
}
#endif
| 26.448819 | 91 | 0.686365 | anklimov |
71e90916fb1a1ee401320c25368a423298bb280a | 5,873 | cpp | C++ | src/display/VRDisplayNode.cpp | elainejiang8/MinVR | d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7 | [
"BSD-3-Clause"
] | null | null | null | src/display/VRDisplayNode.cpp | elainejiang8/MinVR | d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7 | [
"BSD-3-Clause"
] | null | null | null | src/display/VRDisplayNode.cpp | elainejiang8/MinVR | d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright Regents of the University of Minnesota, 2016. This software is released under the following license: http://opensource.org/licenses/
* Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu).
*
* Code author(s):
* Dan Orban (dtorban)
*/
#include "VRDisplayNode.h"
#include <main/VRFactory.h>
namespace MinVR {
VRDisplayNode::VRDisplayNode(const std::string &name) : _name(name) {
}
VRDisplayNode::~VRDisplayNode() {
clearChildren(true);
}
void VRDisplayNode::render(VRDataIndex *renderState,
VRRenderHandler *renderHandler) {
if (_children.size() > 0) {
for (vector<VRDisplayNode*>::iterator it = _children.begin();
it != _children.end(); it++) {
(*it)->render(renderState, renderHandler);
}
} else {
renderHandler->onVRRenderScene(renderState, this);
}
}
void VRDisplayNode::waitForRenderToComplete(VRDataIndex *renderState) {
for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) {
(*it)->waitForRenderToComplete(renderState);
}
}
void VRDisplayNode::displayFinishedRendering(VRDataIndex *renderState) {
for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) {
(*it)->displayFinishedRendering(renderState);
}
}
const std::vector<VRDisplayNode*>& VRDisplayNode::getChildren() const {
return _children;
}
void VRDisplayNode::addChild(VRDisplayNode* child) {
_children.push_back(child);
}
void VRDisplayNode::clearChildren(bool destroyChildren) {
if (destroyChildren) {
for (vector<VRDisplayNode*>::iterator it = _children.begin(); it != _children.end(); it++) {
delete (*it);
}
}
_children.clear();
}
void VRDisplayNode::createChildren(VRMainInterface *vrMain,
VRDataIndex *config,
const std::string &nameSpace) {
std::string validatedNameSpace = config->validateNameSpace(nameSpace);
std::list<std::string> names =
config->selectByAttribute("displaynodeType", "*", validatedNameSpace, true);
for (std::list<std::string>::const_iterator it = names.begin();
it != names.end(); ++it) {
// We only want to do this for direct children. The grandchildren
// and their progeny will be addressed in turn.
if (VRDataIndex::isChild(nameSpace, *it) == 1) {
VRDisplayNode *child =
vrMain->getFactory()->create<VRDisplayNode>(vrMain, config, *it);
if (child != NULL) {
addChild(child);
}
}
}
}
/// Returns a list of the values added to the render state by this
/// node, and its children nodes.
std::map<std::string,std::string> VRDisplayNode::getValuesAdded() {
std::map<std::string,std::string> out;
// Stick the node name with the values added.
if (_valuesAdded.size() > 0) {
for (std::list<std::string>::iterator it = _valuesAdded.begin();
it != _valuesAdded.end(); it++) {
out[*it] = _name + "(" + getType() + ")";
}
}
// Look through all the children nodes, and append their values to
// the list, with the current node name on the front.
if (_children.size() > 0) {
for (vector<VRDisplayNode*>::iterator it = _children.begin();
it != _children.end(); it++) {
std::map<std::string,std::string> childOut = (*it)->getValuesAdded();
if (childOut.size() > 0) {
for (std::map<std::string,std::string>::iterator jt = childOut.begin();
jt != childOut.end(); jt++) {
out[jt->first] = jt->second;
}
}
}
}
return out;
}
void VRDisplayNode::auditValues(std::list<std::string> valuesSupplied) {
// First check to see if all of the values needed appear in the
// input list.
bool found;
if ((_valuesNeeded.size() > 0) && (valuesSupplied.size() > 0)) {
for (std::list<std::string>::iterator it = _valuesNeeded.begin();
it != _valuesNeeded.end(); it++) {
found = false;
for (std::list<std::string>::iterator jt = valuesSupplied.begin();
jt != valuesSupplied.end(); jt++) {
found = found || ((*it).compare(*jt) == 0);
}
// If we haven't found this needed value, throw an error.
if (!found)
throw std::runtime_error("Needed " + (*it) + " but didn't get it, in " +
getName() + ":" + getType());
}
}
// Then add the valuesAdded to the input list and pass along to the
// children nodes.
valuesSupplied.insert(valuesSupplied.end(),
_valuesAdded.begin(), _valuesAdded.end());
if (_children.size() > 0) {
for (std::vector<VRDisplayNode*>::iterator it = _children.begin();
it != _children.end(); it++) {
(*it)->auditValues(valuesSupplied);
}
}
}
std::string VRDisplayNode::printNode(const std::string &prefix) const {
std::string name;
if (_name.size() > 48) {
name = _name.substr(0,15) + "..." +
_name.substr(_name.size() - 33, std::string::npos);
} else {
name = _name;
}
std::string out = prefix + "<displayNode:" + name + ">";
out += "\n" + prefix + " Values Added";
for (std::list<std::string>::const_iterator it = _valuesAdded.begin();
it != _valuesAdded.end(); it++) {
out += "\n" + prefix + " " + *it;
}
if (_valuesAdded.empty()) out += "\n" + prefix + " <none>";
out += "\n" + prefix + " Values Needed";
for (std::list<std::string>::const_iterator it = _valuesNeeded.begin();
it != _valuesNeeded.end(); it++) {
out += "\n" + prefix + " " + *it;
}
if (_valuesNeeded.empty()) out += "\n" + prefix + " <none>";
for (std::vector<VRDisplayNode*>::const_iterator it = _children.begin();
it != _children.end(); it++) {
out += "\n" + (*it)->printNode(prefix + "| ");
}
return out;
}
} /* namespace MinVR */
| 30.273196 | 146 | 0.612294 | elainejiang8 |
71eae2207b9960d1915ef7957da7c589d508f102 | 1,882 | cpp | C++ | problems/codejam/2021/2/matrygons/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/codejam/2021/2/matrygons/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/codejam/2021/2/matrygons/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
// *****
vector<int> primes, lp, nxt;
auto get_divisors(const unordered_map<int, int>& factors) {
vector<int> divs = {1};
for (const auto& [p, e] : factors) {
int D = divs.size();
divs.resize(D * (e + 1));
for (int n = 1; n <= e; n++) {
for (int d = 0; d < D; d++) {
divs[d + n * D] = divs[d + (n - 1) * D] * p;
}
}
}
if (!divs.empty() && divs[0] == 1) {
divs.erase(begin(divs));
}
return divs;
}
auto least_prime_sieve(int N) {
lp.assign(N + 1, 0), nxt.assign(N + 1, 0);
nxt[1] = 1;
for (int P = 0, n = 2; n <= N; n++) {
if (lp[n] == 0) {
lp[n] = n, primes.push_back(n), P++;
}
for (int i = 0; i < P && primes[i] <= lp[n] && n * primes[i] <= N; ++i) {
lp[n * primes[i]] = primes[i], nxt[n * primes[i]] = n;
}
}
return lp;
}
auto factor_primes(int n) {
unordered_map<int, int> primes;
while (n > 1) {
primes[lp[n]]++, n = nxt[n];
}
return primes;
}
constexpr int MAXN = 1'000'000;
int dp3[MAXN + 1];
int dp2[MAXN + 1];
void setup_dp() {
dp2[2] = 1;
dp2[3] = dp3[3] = 1;
for (int n = 4; n <= MAXN; n++) {
auto divs = get_divisors(factor_primes(n));
dp2[n] = dp3[n] = 1;
for (auto d : divs) {
if (d > 2) {
dp3[n] = max(dp3[n], 1 + dp2[n / d - 1]);
}
dp2[n] = max(dp2[n], 1 + dp2[n / d - 1]);
}
}
}
auto solve() {
int N;
cin >> N;
return dp3[N];
}
// *****
int main() {
least_prime_sieve(2'000'000);
setup_dp();
unsigned T;
cin >> T >> ws;
for (unsigned t = 1; t <= T; ++t) {
auto solution = solve();
cout << "Case #" << t << ": " << solution << '\n';
}
return 0;
}
| 21.386364 | 81 | 0.425611 | brunodccarvalho |
71ec616984ec83f8c0d5bc35f4c489b5450206c5 | 690 | hpp | C++ | include/strf/fps.hpp | AnttiVainio/STRF | 8c397a1efad0e35f76de0242c4fb82f48b48e824 | [
"MIT"
] | null | null | null | include/strf/fps.hpp | AnttiVainio/STRF | 8c397a1efad0e35f76de0242c4fb82f48b48e824 | [
"MIT"
] | null | null | null | include/strf/fps.hpp | AnttiVainio/STRF | 8c397a1efad0e35f76de0242c4fb82f48b48e824 | [
"MIT"
] | null | null | null | /** fps.hpp **/
#ifndef STRF_FPS_HPP
#define STRF_FPS_HPP
#include <strf/global.hpp>
#include <deque>
namespace strf {
#ifndef STRF_INIT_HPP
DLL_EXPORT void DLL_CALL set_fps_draw_size(cfloat value = 40.0);
#endif
class DLL_EXPORT fps {
private:
fps(const fps &fps); //Copy constructor
fps &operator=(const fps &fps); //Assign operator
cdouble delay;
double time;
double timestamp;
uchar undrawn_count;
uchar drew_previous_frame;
std::deque<double> real_delays;
std::deque<double> delays;
std::deque<double> sleeps;
public:
fps(cdouble new_fps);
void draw() const;
void wait();
void reset();
bool draw_frame() const;
};
}
#endif
| 17.692308 | 65 | 0.688406 | AnttiVainio |
71ecf89145d9edcafadc572248fecacead660f35 | 1,049 | hpp | C++ | include/SDPVer.hpp | Cyberunner23/libSDP | 0c4cffc951980c618c6f0e04bb8c3b184f246226 | [
"Apache-2.0"
] | 3 | 2015-03-07T09:51:56.000Z | 2017-05-13T20:17:15.000Z | include/SDPVer.hpp | Cyberunner23/libSDP | 0c4cffc951980c618c6f0e04bb8c3b184f246226 | [
"Apache-2.0"
] | null | null | null | include/SDPVer.hpp | Cyberunner23/libSDP | 0c4cffc951980c618c6f0e04bb8c3b184f246226 | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2015 Alex Frappier Lachapelle
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef SDPVER_HPP
#define SDPVER_HPP
#include "Utils/Typedefs.hpp"
namespace libSDP{
using namespace libSDP::Utils;
class SDPVer{
public:
//Vars
struct SDPLibVerStruct{
uint8 major=0;
uint8 minor=2;
uint8 patch=0;
} SDPLibVer;
struct SDPSpecRevStruct{
uint8 major=1;
uint8 minor=0;
} SDPSpecRev;
};
}
#endif // SDPVER_HPP
| 21.854167 | 75 | 0.666349 | Cyberunner23 |
71ecfa1dd87de1a6f3903e8a1189a73efa335ea3 | 4,231 | hh | C++ | src/patient/patient.hh | Apperta-IXN-for-the-NHS/GOSH-FHIRworks2020-datamaskgen | b8c075b01640f99730fcd39ad87c3009a510fa01 | [
"Apache-2.0"
] | 2 | 2020-03-10T04:35:17.000Z | 2020-03-30T12:26:51.000Z | src/patient/patient.hh | Apperta-IXN-for-the-NHS/GOSH-FHIRworks2020-datamaskgen | b8c075b01640f99730fcd39ad87c3009a510fa01 | [
"Apache-2.0"
] | 4 | 2020-03-09T01:11:30.000Z | 2020-03-10T03:12:43.000Z | src/patient/patient.hh | Apperta-IXN-for-the-NHS/GOSH-FHIRworks2020-datamaskgen | b8c075b01640f99730fcd39ad87c3009a510fa01 | [
"Apache-2.0"
] | 1 | 2020-05-29T14:38:49.000Z | 2020-05-29T14:38:49.000Z | //
// Created by Patrick Wu on 02/03/2020.
//
#ifndef GOSH_FHIRWORKS2020_DATAMASKGEN_PATIENT_HH
#define GOSH_FHIRWORKS2020_DATAMASKGEN_PATIENT_HH
#include <string>
#include <ctime>
#include <vector>
#include <sstream>
#include "name.hh"
#include "address.hh"
#include "language.hh"
#include "telecom.hh"
#include "identifier.hh"
#include "gender.hh"
#include "marital_status.hh"
using namespace std;
class patient {
public:
static string generate_current_timestamp () {
time_t now;
time(&now);
char buf[sizeof "YYYY-MM-DDThh:mm:ssZ"];
strftime(buf, sizeof buf, "%FT%TZ", gmtime(&now));
return buf;
}
bool operator == (const patient& p1) const {
return uuid == p1.uuid;
}
string uuid;
name name;
gender gender;
tm birthday;
string extensions;
vector<address> addresses;
marital_status marital_status;
vector<language> communication_languages;
vector<telecom> telecoms;
vector<identifier> identifiers;
bool multiple_birth = false;
int multiple_birth_count = 1;
patient (string id, string pre, string gn, string fn, string gen,
bool mul_birth, int mul_birth_count, string bday) : uuid(std::move(id)),
name(std::move(pre), std::move(gn), std::move(fn)), multiple_birth(mul_birth),
multiple_birth_count(mul_birth_count) {
if (gen == "male") gender = MALE;
else if (gen == "female") gender = FEMALE;
else gender = OTHER;
strptime(bday.c_str(), "%Y-%m-%d", &birthday);
}
patient (class name n, enum gender g, tm bday, vector<address> addrs, class marital_status m_status,
vector<language> c_langs, vector<telecom> ts, vector<identifier> is, string exs, string uid,
bool m_birth, int m_birth_count)
: uuid(std::move(uid)), name(std::move(n)), gender(std::move(g)), birthday(std::move(bday)),
addresses(std::move(addrs)), marital_status(std::move(m_status)),
communication_languages(std::move(c_langs)), telecoms(std::move(ts)),
identifiers(std::move(is)), extensions(exs), multiple_birth(m_birth),
multiple_birth_count(m_birth_count) { }
string jsonify () {
stringstream ss;
ss << R"({"fullUrl":"","resource":{"resourceType":"Patient","id":")" << uuid << "\",";
ss << R"("meta":{"versionId":"4","lastUpdated":")" << generate_current_timestamp() << "\"},";
ss << R"("text":{"status":"generated","div":""},)";
ss << R"("extension":)" << extensions << ",";
ss << "\"identifier\":[";
for (size_t i = 0; i < identifiers.size() - 1; i++) ss << identifiers[i].jsonify() << ","; ss << identifiers.back().jsonify() << "],";
ss << name.jsonify() << ",";
ss << "\"telecom\":[";
for (size_t i = 0; i < telecoms.size() - 1; i++) ss << telecoms[i].jsonify() << ","; ss << telecoms.back().jsonify() << "],";
ss << "\"gender\":\"";
switch (gender) {
case MALE:
ss << "male";
break;
case FEMALE:
ss << "female";
break;
default:
ss << "other";
break;
} ss << "\",";
ss << "\"birthDate\":\"" << birthday.tm_year + 1900 << "-" << birthday.tm_mon << "-" << birthday.tm_mday << "\",";
ss << "\"address\":[";
for (size_t i = 0; i < addresses.size() - 1; i++) ss << addresses[i].jsonify() << ","; ss << addresses.back().jsonify() << "],";
ss << marital_status.jsonify() << ",";
if (!multiple_birth) ss << "\"multipleBirthBoolean\":" << multiple_birth << ",";
else ss << "\"multipleBirthInteger\":" << multiple_birth_count << ",";
ss << "\"communication\":[";
for (size_t i = 0; i < communication_languages.size() - 1; i++) ss << communication_languages[i].jsonify() << ","; ss << communication_languages.back().jsonify() << "]";
ss << "}}";
return ss.str();
}
};
namespace std {
template<>
struct hash<patient> {
size_t operator() (const patient& p) const {
return std::hash<string>()(p.uuid);
}
};
}
#endif
| 35.855932 | 177 | 0.559679 | Apperta-IXN-for-the-NHS |
71ee75f97a2554d9a1cb1c7024b7d96104074b96 | 5,839 | cpp | C++ | src/input.cpp | adhithyaarun/Plane-Game-3D | aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21 | [
"MIT"
] | null | null | null | src/input.cpp | adhithyaarun/Plane-Game-3D | aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21 | [
"MIT"
] | null | null | null | src/input.cpp | adhithyaarun/Plane-Game-3D | aa9c2ec75baa662f3d75d27bd5a5301a4fb99f21 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "main.h"
bool cannon_keyboard_input = true;
bool drag_pan = false, old_cki;
double drag_oldx = -1, drag_oldy = -1;
int current_view = 0;
double x_initial = -1.0;
double y_initial = -1.0;
float radius = 15.0;
float theta = 60.0 * M_PI / 180.0;
float phi = 60.0 * M_PI / 180.0;
float cur_angle_theta = 0.0;
float cur_angle_phi = 0.0;
using namespace std;
/* Executed when a regular key is pressed/released/held-down */
/* Prefered for Keyboard events */
void keyboard(GLFWwindow *window, int key, int scancode, int action, int mods) {
// Function is called first on GLFW_PRESS.
if (action == GLFW_RELEASE) {
// switch (key) {
// case GLFW_KEY_C:
// rectangle_rot_status = !rectangle_rot_status;
// break;
// case GLFW_KEY_P:
// triangle_rot_status = !triangle_rot_status;
// break;
// case GLFW_KEY_X:
//// do something ..
// break;
// default:
// break;
// }
} else if (action == GLFW_PRESS) {
switch (key) {
case GLFW_KEY_ESCAPE:
quit(window);
break;
default:
break;
}
}
}
/* Executed for character input (like in text boxes) */
void keyboardChar(GLFWwindow *window, unsigned int key) {
switch (key) {
case 'Q':
case 'q':
// quit(window);
break;
case 'R':
case 'r':
if(current_view == 4)
{
x_initial = -1.0;
y_initial = -1.0;
radius = 15.0;
theta = 60.0 * M_PI / 180.0;
phi = 60.0 * M_PI / 180.0;
cur_angle_theta = 0.0;
cur_angle_phi = 0.0;
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
default:
break;
}
}
/* Executed when a mouse button is pressed/released */
void mouseButton(GLFWwindow *window, int button, int action, int mods) {
switch (button) {
case GLFW_MOUSE_BUTTON_LEFT:
if(action == GLFW_PRESS)
{
if(current_view == 4)
{
glfwGetCursorPos(window, &x_initial, &y_initial);
}
else
{
fire_missile();
}
// Do something
return;
}
else if(action == GLFW_RELEASE)
{
if(current_view == 4)
{
x_initial = -1.0;
y_initial = -1.0;
theta = fmod(theta + cur_angle_theta, 360.0);
cur_angle_theta = 0.0;
phi = fmod(phi + cur_angle_phi, 360.0);
cur_angle_phi = 0.0;
}
// Do something
}
break;
case GLFW_MOUSE_BUTTON_RIGHT:
if(action == GLFW_PRESS)
{
drop_bomb();
}
else if(action == GLFW_RELEASE)
{
// Do something
}
break;
case GLFW_MOUSE_BUTTON_MIDDLE:
if(action == GLFW_PRESS)
{
current_view = (current_view + 1) % 5;
if(current_view == 4)
{
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
else
{
x_initial = -1.0;
y_initial = -1.0;
}
}
else if(action == GLFW_RELEASE)
{
// Do something
}
default:
break;
}
}
void scroll_callback(GLFWwindow *window, double xoffset, double yoffset)
{
if(current_view == 4 && x_initial < 0.0 && y_initial < 0.0)
{
if(yoffset > 0 && radius > 7.0)
{
radius -= 1.0;
}
else if(yoffset < 0 && radius < 25.0)
{
radius += 1.0;
}
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
}
void track_cursor(GLFWwindow *window, int width, int height)
{
double x_final, y_final;
glfwGetCursorPos(window, &x_final, &y_final);
float dx = (x_final - x_initial);
float dy = (y_final - y_initial);
float angle_plane = 0.0;
float angle_vertical = 0.0;
if(x_initial >= 0.0 && y_initial >= 0.0)
{
cur_angle_theta = atan(((abs(dx) / 10.0) / (2 * M_PI * radius)) * 2 * M_PI) * dx / abs(dx);
cur_angle_phi = atan(((abs(dy) / 10.0) / (2 * M_PI * radius)) * 2 * M_PI) * dy / abs(dy) * (-1);
angle_plane = fmod(theta + cur_angle_theta, 360.0);
angle_vertical = fmod(phi + cur_angle_phi, 360.0);
view_options[4].eye.x = plane_pos.x + radius * cos(angle_plane) * sin(angle_vertical);
view_options[4].eye.y = plane_pos.y + radius * cos(angle_vertical);
view_options[4].eye.z = plane_pos.z + radius * sin(angle_plane) * sin(angle_vertical);
}
else
{
view_options[4].eye.x = plane_pos.x + radius * sin(phi) * cos(theta);
view_options[4].eye.y = plane_pos.y + radius * cos(phi);
view_options[4].eye.z = plane_pos.z + radius * sin(phi) * sin(theta);
}
} | 28.34466 | 104 | 0.520466 | adhithyaarun |
71f4f5f29690ea96f7894af73f012517a50d9a85 | 618 | hpp | C++ | src/main_finding_players.hpp | MlsDmitry/RakNet-samples | 05873aecb5c8dac0c0f822845c764bd5f8dc6a6d | [
"MIT"
] | null | null | null | src/main_finding_players.hpp | MlsDmitry/RakNet-samples | 05873aecb5c8dac0c0f822845c764bd5f8dc6a6d | [
"MIT"
] | null | null | null | src/main_finding_players.hpp | MlsDmitry/RakNet-samples | 05873aecb5c8dac0c0f822845c764bd5f8dc6a6d | [
"MIT"
] | null | null | null | #pragma once
#include "RakPeerInterface.h"
#include "RakNetTypes.h"
#include "RakNetDefines.h"
#include "RakNetStatistics.h"
#include "BitStream.h"
#include "StringCompressor.h"
#include "GetTime.h"
#include "MessageIdentifiers.h"
#include "NetworkIDManager.h"
#include "RakSleep.h"
// std::mutex mtx;
// RakNet::RakPeerInterface *current_active_client;
void send_ping(RakNet::RakPeerInterface *client, unsigned int ms_delay);
void listen_pong(RakNet::RakPeerInterface *peer, int peer_type);
void connect_players(RakNet::RakPeerInterface *server);
void send_data(RakNet::RakPeerInterface * server);
int main(); | 23.769231 | 72 | 0.779935 | MlsDmitry |
71f57908aac86476880e84d5d9092902524641f9 | 222 | hpp | C++ | reflex/test/implementation/members/Get.hpp | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 10 | 2018-03-26T07:41:44.000Z | 2021-11-06T08:33:24.000Z | reflex/test/implementation/members/Get.hpp | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | null | null | null | reflex/test/implementation/members/Get.hpp | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 1 | 2020-11-17T03:17:00.000Z | 2020-11-17T03:17:00.000Z | // Tests for Get
template <typename U>
struct St {
struct A {
int a;
static int s;
};
typedef A T;
};
#ifndef __GCCXML__
template <typename U>
int St<U>::A::s = 43;
#endif
template class St<int>;
| 11.1 | 23 | 0.594595 | paulwratt |
71f8202f267e4ebfd95289c46523925636024e83 | 976 | cc | C++ | src/hlib/libcpp/conv.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/conv.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null | src/hlib/libcpp/conv.cc | hascal/llvm | f9893068ec2cff12889d2a8c3f935bccda8769e3 | [
"MIT"
] | null | null | null |
int to_int(string s){
return std::stoi(s);
}
int to_int(float s){
return (int)s;
}
int to_int(bool s){
return (int)s;
}
int to_int(int s){
return s;
}
int to_int(char s){
return (int)s-48; // ASCII chars starts with 48
}
string to_string(int s){
string res = std::to_string(s);
return res;
}
string to_string(char s){
string res = { s };
return res;
}
string to_string(char* s){
string res = s;
return res;
}
string to_string(string s){
return s;
}
string to_string(float s){
return std::to_string(s);
}
string to_string(bool s){
if(s == true)
return "true";
return "false";
}
float to_float(int s){
return (float)s;
}
float to_float(string s){
return std::stof(s);
}
float to_float(float s){
return s;
}
float to_float(bool s){
if(s == true)
return 1.0;
return 0.0;
}
char to_char(int s){
return (char)(s+48);
}
char to_char(char c){
return c;
}
char* c_str(std::string s){
char* res = const_cast<char*>(s.c_str());
return res;
} | 12.2 | 48 | 0.643443 | hascal |
71fb19f6b6f42cb73cd54f5f176f7b060237af0f | 3,097 | cpp | C++ | dal gita/src/Prostopadloscian.cpp | Szymon253191/Zadanie_Dron_Podwodny | c5c88f2c67bd90eb6c216dc068b1bf60483cd766 | [
"MIT"
] | null | null | null | dal gita/src/Prostopadloscian.cpp | Szymon253191/Zadanie_Dron_Podwodny | c5c88f2c67bd90eb6c216dc068b1bf60483cd766 | [
"MIT"
] | null | null | null | dal gita/src/Prostopadloscian.cpp | Szymon253191/Zadanie_Dron_Podwodny | c5c88f2c67bd90eb6c216dc068b1bf60483cd766 | [
"MIT"
] | null | null | null | #include "Prostopadloscian.hh"
Prostopadloscian::Prostopadloscian()
{
dl_bokow = Wektor<double,3> W;
}
Prostopadloscian::Prostopadloscian(double A,double B, double H,drawNS::Draw3DAPI *api)
{
dl_bokow[0] = A;
dl_bokow[1] = B;
dl_bokow[2] = H;
(*this).gplt = api;
}
void Prostopadloscian::ustal_wierzcholki()
{
Wektor <double,3> Ana2((*this).dl_bokow[0]/2,0,0);
Wektor <double,3> Bna2(0,(*this).dl_bokow[1]/2,0);
Wektor <double,3> Hna2(0,0,(*this).dl_bokow[2]/2);
(*this).wierzcholki[0] = (*this).srodek + (*this).orientacja * ((Ana2+Bna2+Hna2)*(-1));
(*this).wierzcholki[1] = (*this).srodek + (*this).orientacja * (Ana2-Bna2-Hna2);
(*this).wierzcholki[2] = (*this).srodek + (*this).orientacja * (Ana2+Bna2-Hna2);
(*this).wierzcholki[3] = (*this).srodek + (*this).orientacja * (Bna2-Ana2-Hna2);
(*this).wierzcholki[4] = (*this).srodek + (*this).orientacja * (Hna2-Bna2-Ana2);
(*this).wierzcholki[5] = (*this).srodek + (*this).orientacja * (Ana2-Bna2+Hna2);
(*this).wierzcholki[6] = (*this).srodek + (*this).orientacja * (Ana2+Bna2+Hna2);
(*this).wierzcholki[7] = (*this).srodek + (*this).orientacja * (Bna2-Ana2+Hna2);
}
void Prostopadloscian::rysuj()
{
(*this).ustal_wierzcholki();
(*this).id = gplt.draw_polyhedron(vector<vector<Point3D>>
{
{
{
drawNS::Point3D((*this).wierzcholki[0][0],(*this).wierzcholki[0][1],(*this).wierzcholki[0][2]),
drawNS::Point3D((*this).wierzcholki[1][0],(*this).wierzcholki[1][1],(*this).wierzcholki[1][2]),
drawNS::Point3D((*this).wierzcholki[2][0],(*this).wierzcholki[2][1],(*this).wierzcholki[2][2])
},
{
drawNS::Point3D((*this).wierzcholki[3][0],(*this).wierzcholki[3][1],(*this).wierzcholki[3][2]),
drawNS::Point3D((*this).wierzcholki[4][0],(*this).wierzcholki[4][1],(*this).wierzcholki[4][2]),
drawNS::Point3D((*this).wierzcholki[5][0],(*this).wierzcholki[5][1],(*this).wierzcholki[5][2])
},
{
drawNS::Point3D((*this).wierzcholki[6][0],(*this).wierzcholki[6][1],(*this).wierzcholki[6][2]),
drawNS::Point3D((*this).wierzcholki[7][0],(*this).wierzcholki[7][1],(*this).wierzcholki[7][2]),
drawNS::Point3D((*this).wierzcholki[8][0],(*this).wierzcholki[8][1],(*this).wierzcholki[8][2])
}
}
},"black")
}
void Prostopadloscian::wymaz()
{
(*this).gplt->erase_shape((*this).id);
}
void Prostopadloscian::jazda(double odl)
{
Wektor <double,3> jazda(0,odl,0);
(*this).gplt.erase_shape((*this).id);
(*this).srodek = (*this).srodek + (*this).orientacja * jazda;
(*this).rysuj();
}
void Prostopadloscian::obrot(double kat)
{
MacierzObr nowa_orientacja('Z',kat);
(*this).gplt.erase_shape((*this).id);
(*this).orientacja = (*this).orientacja * nowa_orientacja;
(*this).rysuj();
}
void Prostopadloscian::gora_dol(double odl)
{
(*this).gplt.erase_shape((*this).id);
(*this).srodek[2] += odl;
(*this).rysuj();
} | 38.234568 | 111 | 0.587665 | Szymon253191 |
9f98b748adce7385c99149eecc6cdfc737fa0f0e | 5,773 | cpp | C++ | game_vision/src/main.cpp | SHEUN1/gameVision | 089f2fa1144e37a141dbb2e05d36c3131b92af0a | [
"MIT"
] | 20 | 2017-08-20T07:32:03.000Z | 2022-02-26T16:33:36.000Z | game_vision/src/main.cpp | SHEUN1/gameVision | 089f2fa1144e37a141dbb2e05d36c3131b92af0a | [
"MIT"
] | null | null | null | game_vision/src/main.cpp | SHEUN1/gameVision | 089f2fa1144e37a141dbb2e05d36c3131b92af0a | [
"MIT"
] | 2 | 2018-07-03T06:47:39.000Z | 2020-03-12T16:52:17.000Z | //============================================================================
// Name : main.cpp
// Author : Olu Adebari
// Description : Process the captured video game frame, analyse and then send data over to Python caller program
//============================================================================
#include <iostream>
#include <vector>
#include <chrono>
#include <future>
#include <memory>
#include <string>
#include <opencv2/opencv.hpp>
#include "SeperateObjects.h"
#include "SendDataToPython.h"
#include "OCR.h"
#include "RegionOfInterest.h"
#include "BinaryImage.h"
#include "FeatureExtraction.h"
#include "RecordProcessedImage.h"
#include "ConvertToBinaryImage.h"
#include <boost/python.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
boost::python::dict processImageFrame()
{
auto save_current_frame_with_bounded_boxes = true;
auto save_current_frame = true;
auto save_binary_image_of_current_frame = true;
auto save_regions_of_interest_from_current_frame_binary_image = true;
auto save_regions_of_interest_from_current_frame_binary_image_features_points = true;
static uint32_t starting_frame_number = 1;
uint32_t Number_of_frames_to_record = 1000;
auto image_processing_start_time = std::chrono::high_resolution_clock::now();
//read current video_game frame
cv::Mat img = cv::imread("../game_vision/current_game_frame/current_game_frame.jpg");
//get words in frame
OCR capture_words_in_image;
auto words_and_coordinates = std::async(std::launch::async,std::bind(&OCR::GetWordsAndLocations, capture_words_in_image,std::ref(img)));
//convert to grayscale
cv::Mat gray = cv::Mat::zeros(img.size(), img.type());
cv::cvtColor(img, gray, cv::COLOR_RGB2GRAY);
//smooth image
blur(gray, gray, cv::Size(3,3));
cv::Mat image_with_bounded_boxes_drawn_on = img.clone();
//create binary images
std::vector< std::shared_ptr<BinaryImage> > binary_images;
binary_images.emplace_back(std::make_shared<BinaryImage> (1, ConvertToBinaryImage().convertToBinary(gray,img)));
binary_images.emplace_back(std::make_shared<BinaryImage> (2, ConvertToBinaryImage().convertToBinaryInverse(gray,img)));
//extract regions of interest within an image
SeperateObjects seperate_regions_of_interest (gray,image_with_bounded_boxes_drawn_on);
auto get_binary_image_1_ROI_objects = std::async(std::launch::async,std::bind(&SeperateObjects::BoundBox, &seperate_regions_of_interest,binary_images[0] ,save_regions_of_interest_from_current_frame_binary_image));
auto get_binary_image_2_ROI_objects = std::async(std::launch::async,std::bind(&SeperateObjects::BoundBox, &seperate_regions_of_interest,binary_images[1] ,save_regions_of_interest_from_current_frame_binary_image));
get_binary_image_1_ROI_objects.wait();
get_binary_image_2_ROI_objects.wait();
//extract feature points for each region of interest
using surf_OCL = cv::xfeatures2d::SURF;
FeatureExtraction <surf_OCL> features_of_objects;
auto get_feature_points_for_binary_1_ROI_objects = std::async(std::launch::async,std::bind(&FeatureExtraction <surf_OCL>::extractFeaturePoints,
&features_of_objects,binary_images[0],save_regions_of_interest_from_current_frame_binary_image_features_points));
auto get_feature_points_for_binary_2_ROI_objects = std::async(std::launch::async,std::bind(&FeatureExtraction <surf_OCL>::extractFeaturePoints,
&features_of_objects,binary_images[1], save_regions_of_interest_from_current_frame_binary_image_features_points));
get_feature_points_for_binary_1_ROI_objects.wait();
get_feature_points_for_binary_2_ROI_objects.wait();
//Optional code: record frames with bounded boxes drawn on into their own directories.
std::string current_frame_file_name = "Image"+std::to_string(starting_frame_number)+".jpg";
RecordProcessedImage saveProcessedImages;
if (starting_frame_number >= Number_of_frames_to_record){
starting_frame_number = 1;
}
if(save_current_frame_with_bounded_boxes){
auto recordBoundBoxAsync = std::async(std::launch::async,std::bind(&RecordProcessedImage::saveImage, saveProcessedImages,std::ref(image_with_bounded_boxes_drawn_on),"../game_vision/cloudbank_images/Frame/bounded_boxes/",current_frame_file_name ));
}
if (save_current_frame){
auto recordCurrentFrameAsync = std::async(std::launch::async,std::bind(&RecordProcessedImage::saveImage, saveProcessedImages,std::ref(img),"../game_vision/cloudbank_images/Frame/Unprocessed/",current_frame_file_name));
}
if (save_binary_image_of_current_frame){
for (auto const & binary_image : binary_images){
auto recordCurrentFrameAsync = std::async(std::launch::async,std::bind(&RecordProcessedImage::saveImage, saveProcessedImages,binary_image->getBinaryImage(),"../game_vision/cloudbank_images/Frame/Binary/binaryImage_ID_"+std::to_string(binary_image->getID()),current_frame_file_name));
}
}
++starting_frame_number;
auto image_processing_end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(image_processing_end_time - image_processing_start_time ).count();
std::cout<< "this program took about " << duration<< " milliseconds to process the image" << std::endl;
words_and_coordinates.wait();
//send extracted image frame in python form into calling python process
SendDataToPython python_features_of_objects;
boost::python::dict send_to_python_Object_info= python_features_of_objects.SendObjectInformationToDict(binary_images, words_and_coordinates.get());
return send_to_python_Object_info;
}
int main()
{
Py_Initialize();
processImageFrame();
return 0;
}
BOOST_PYTHON_MODULE(opencv)
{
def("ProcessGameFrame", processImageFrame);
}
| 40.370629 | 286 | 0.778971 | SHEUN1 |
9f9fd055d24b87d0050cf7e7b729e23a7930dd62 | 2,455 | cc | C++ | course/test/src/CellMap_TEST.cc | LucasJSch/terrarium_simulator | 93dbd4a340d38ec54de6dc4876feceeb1f4a0094 | [
"Apache-2.0"
] | null | null | null | course/test/src/CellMap_TEST.cc | LucasJSch/terrarium_simulator | 93dbd4a340d38ec54de6dc4876feceeb1f4a0094 | [
"Apache-2.0"
] | 1 | 2020-11-12T15:40:37.000Z | 2020-11-12T15:40:37.000Z | course/test/src/CellMap_TEST.cc | LucasJSch/terrarium_simulator | 93dbd4a340d38ec54de6dc4876feceeb1f4a0094 | [
"Apache-2.0"
] | null | null | null | #include "cellmap.h"
#include "ant.h"
#include "cell.h"
#include <cmath>
#include <sstream>
#include <string>
#include "gtest/gtest.h"
namespace ekumen {
namespace simulation {
namespace test {
namespace {
using insect_ptr = std::shared_ptr<Insect>;
GTEST_TEST(CellMapTest, ReturnsExceptionOnConstructorWithNonPositiveCols) {
ASSERT_THROW(CellMap map(0, 1), std::invalid_argument);
ASSERT_THROW(CellMap map(-1, 1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, CellMapConstructedCorrectlyWithPositiveArguments) {
ASSERT_NO_THROW(CellMap map(1,1));
}
GTEST_TEST(CellMapTest, ReturnsExceptionOnConstructorWithNonPositiveRows) {
ASSERT_THROW(CellMap map(1, 0), std::invalid_argument);
ASSERT_THROW(CellMap map(1, -1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, ReturnedCellsAreNotNullPointer) {
CellMap map(2,2);
EXPECT_TRUE(map.GetCell(0,0));
EXPECT_TRUE(map.GetCell(0,1));
EXPECT_TRUE(map.GetCell(1,0));
EXPECT_TRUE(map.GetCell(1,1));
}
GTEST_TEST(CellMapTest, GetCellsAndVerifyThatReferenceIsCorrect) {
CellMap map(1,2);
std::shared_ptr<Cell> cell1 = map.GetCell(0,0);
std::shared_ptr<Cell> cell2 = map.GetCell(0,1);
EXPECT_TRUE(map.GetCell(0,0)->IsFree());
insect_ptr ant1(new Ant());
ant1->SetCell(cell1);
EXPECT_FALSE(map.GetCell(0,0)->IsFree());
EXPECT_TRUE(map.GetCell(0,1)->IsFree());
insect_ptr ant2(new Ant());
ant2->SetCell(cell2);
EXPECT_FALSE(map.GetCell(0,1)->IsFree());
}
GTEST_TEST(CellMapTest, GetNegativeRowsThrowsException) {
CellMap map(1,1);
ASSERT_THROW(map.GetCell(-1,0), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetNegativeColsThrowsException) {
CellMap map(1,1);
ASSERT_THROW(map.GetCell(0,-1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetExceededRowIndexThrowsException) {
CellMap map(2,2);
ASSERT_THROW(map.GetCell(2,1), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetExceededColIndexThrowsException) {
CellMap map(2,2);
ASSERT_THROW(map.GetCell(1,2), std::invalid_argument);
}
GTEST_TEST(CellMapTest, GetRowsIsCorrect) {
CellMap map(7,3);
EXPECT_EQ(map.rows(), 7);
}
GTEST_TEST(CellMapTest, GetColsIsCorrect) {
CellMap map(7,3);
EXPECT_EQ(map.cols(), 3);
}
} // namespace
} // namespace test
} // namespace math
} // namespace ekumen
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.572917 | 75 | 0.716904 | LucasJSch |
9fb3cd137b0eef10c67b094162cdf360e302bb59 | 734 | cpp | C++ | leetcode/491. Increasing Subsequences/s3.cpp | zhuohuwu0603/leetcode_cpp_lzl124631x | 6a579328810ef4651de00fde0505934d3028d9c7 | [
"Fair"
] | 787 | 2017-05-12T05:19:57.000Z | 2022-03-30T12:19:52.000Z | leetcode/491. Increasing Subsequences/s3.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 8 | 2020-03-16T05:55:38.000Z | 2022-03-09T17:19:17.000Z | leetcode/491. Increasing Subsequences/s3.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 247 | 2017-04-30T15:07:50.000Z | 2022-03-30T09:58:57.000Z | // OJ: https://leetcode.com/problems/permutations-ii
// Author: github.com/lzl124631x
// Time: O(2^N)
// Space: O(N)
class Solution {
private:
vector<vector<int>> ans;
void dfs(vector<int> &nums, int start, vector<int> &seq) {
if (start == nums.size()) return;
unordered_set<int> visited;
for (int i = start; i < nums.size(); ++i) {
int n = nums[i];
if (visited.count(n) || (seq.size() && seq.back() > n)) continue;
visited.insert(n);
seq.push_back(n);
if (seq.size() > 1) ans.push_back(seq);
dfs(nums, i + 1, seq);
seq.pop_back();
}
}
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<int> seq;
dfs(nums, 0, seq);
return ans;
}
}; | 27.185185 | 71 | 0.581744 | zhuohuwu0603 |
9fb3de83b9f2ec610527cc45678c9ba4d9787ecf | 706 | cpp | C++ | TVTest_0.7.23_Src/Options.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | TVTest_0.7.23_Src/Options.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | TVTest_0.7.23_Src/Options.cpp | mark10als/TVTest_0.7.23_fix_Sources | 313c295ab67a39bb285303ad814ee4f5aa15d921 | [
"libpng-2.0"
] | null | null | null | #include "stdafx.h"
#include "TVTest.h"
#include "Options.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
COptionFrame *COptions::m_pFrame=NULL;
DWORD COptions::m_GeneralUpdateFlags=0;
COptions::COptions()
: m_UpdateFlags(0)
{
}
COptions::COptions(LPCTSTR pszSection)
: CSettingsBase(pszSection)
, m_UpdateFlags(0)
{
}
COptions::~COptions()
{
}
DWORD COptions::SetUpdateFlag(DWORD Flag)
{
m_UpdateFlags|=Flag;
return m_UpdateFlags;
}
DWORD COptions::SetGeneralUpdateFlag(DWORD Flag)
{
m_GeneralUpdateFlags|=Flag;
return m_GeneralUpdateFlags;
}
void COptions::SettingError()
{
if (m_pFrame!=NULL)
m_pFrame->OnSettingError(this);
}
| 12.836364 | 48 | 0.746459 | mark10als |
9fb59be37087068fc162869dc19b2c2d61e62b97 | 15,865 | cpp | C++ | src/Scene/COctree.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | 1 | 2018-01-06T04:44:36.000Z | 2018-01-06T04:44:36.000Z | src/Scene/COctree.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | src/Scene/COctree.cpp | przemyslaw-szymanski/vke | 1d8fb139e0e995e330db6b8873dfc49463ec312c | [
"MIT"
] | null | null | null | #include "Scene/COctree.h"
#include "Scene/CScene.h"
namespace VKE
{
namespace Scene
{
SOctreeNode::~SOctreeNode()
{
//m_vObjectAABBs.Destroy();
//m_vpObjectBits.Destroy();
}
//void SOctreeNode::CalcAABB( const COctree* pOctree, Math::CAABB* pOut ) const
//{
// static const Math::CVector4 aCenterVectors[ 9 ] =
// {
// Math::CVector4( -1.0f, 1.0f, 1.0f, 1.0f ),
// Math::CVector4( 1.0f, 1.0f, 1.0f, 1.0f ),
// Math::CVector4( -1.0f, 1.0f, -1.0f, 1.0f ),
// Math::CVector4( 1.0f, 1.0f, -1.0f, 1.0f ),
// Math::CVector4( -1.0f, -1.0f, 1.0f, 1.0f ),
// Math::CVector4( 1.0f, -1.0f, 1.0f, 1.0f ),
// Math::CVector4( -1.0f, -1.0f, -1.0f, 1.0f ),
// Math::CVector4( 1.0f, -1.0f, -1.0f, 1.0f ),
// Math::CVector4( 0.0f, 0.0f, 0.0f, 0.0f )
// };
// // Divide root size /2 this node level times
// const uint8_t level = m_handle.level;
// VKE_ASSERT( level > 0, "" );
// //if( level > 0 )
// {
// const OCTREE_NODE_POSITION_INDEX index = static_cast< const OCTREE_NODE_POSITION_INDEX >( m_handle.bit );
// Math::CVector4 vecExtents;
// vecExtents.x = static_cast<float>( static_cast< uint32_t >( pOctree->m_vecMaxSize.x ) >> level );
// vecExtents.y = static_cast<float>( static_cast< uint32_t >( pOctree->m_vecMaxSize.y ) >> level );
// vecExtents.z = static_cast<float>( static_cast< uint32_t >( pOctree->m_vecMaxSize.z ) >> level );
// vecExtents.w = 0;
// Math::CVector4 vecCenter;
// // vecCenter = direction * distance + position
// Math::CVector4::Mad( aCenterVectors[ index ], vecExtents, vecParentCenter, &vecCenter );
// // vecExtentSize = vecPercentSize * vecExtentSize + vecExtentSize
// Math::CVector4::Mad( pOctree->m_vecExtraSize, vecExtents, vecExtents, &vecExtents );
// *pOut = Math::CAABB( Math::CVector3( vecCenter ), Math::CVector3( vecExtents ) );
// }
// /*else
// {
// Math::CVector4 vecExtents;
// Math::CVector4::Mad( Info.vecExtraSize, Info.vecMaxSize, Info.vecMaxSize, &vecExtents );
// *pOut = Math::CAABB( Math::CVector3( Info.vecParentCenter ), Math::CVector3( vecExtents ) );
// }*/
//}
float CalcNodeSize(float rootSize, uint8_t level)
{
float ret = (float)((uint32_t)rootSize >> level);
return ret;
}
void CalcNodeCenter( const float rootSize, const Math::CVector4& vecParentCenter,
const SOctreeNode::UNodeHandle& Handle, Math::CVector3* pOut )
{
static const Math::CVector4 aCenterVectors[9] =
{
Math::CVector4( -1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, -1.0f, 1.0f ),
Math::CVector4( 0.0f, 0.0f, 0.0f, 0.0f )
};
const OCTREE_NODE_POSITION_INDEX index = static_cast< const OCTREE_NODE_POSITION_INDEX >( Handle.bit );
Math::CVector4 vecCenter;
const float size = CalcNodeSize( rootSize, Handle.level );
Math::CVector4 vecExtents( size );
// vecCenter = direction * distance + position
Math::CVector4::Mad( aCenterVectors[ index ], vecExtents, vecParentCenter, &vecCenter );
*pOut = Math::CVector3( vecCenter );
}
void SOctreeNode::CalcAABB( const COctree* pOctree, Math::CAABB* pOut ) const
{
if( m_handle.level > 0 )
{
float size = (float)((uint32_t)(pOctree->m_vecMaxSize.x) >> m_handle.level);
size += size * pOctree->m_vecExtraSize.x;
size *= 0.5f;
*pOut = Math::CAABB( m_vecCenter, Math::CVector3( size ) );
}
else
{
*pOut = pOctree->m_RootAABB;
}
}
uint32_t SOctreeNode::AddObject( const SObjectData& Data )
{
uint32_t ret = UNDEFINED_U32;
for( uint32_t i = 0; i < m_vObjData.GetCount(); ++i )
{
if( m_vObjData[ i ].Handle.handle == 0 )
{
ret = i;
m_vObjData[ i ] = Data;
break;
}
}
if( ret == UNDEFINED_U32 )
{
ret = m_vObjData.PushBack( Data );
}
return ret;
}
COctree::COctree( CScene* pScnee ) :
m_pScene( pScnee )
{
}
COctree::~COctree()
{
}
void COctree::_Destroy()
{
}
Result COctree::_Create( const SOctreeDesc& Desc )
{
Result ret = VKE_OK;
m_Desc = Desc;
m_Desc.maxDepth = Math::Min( Desc.maxDepth, VKE_CALC_MAX_VALUE_FOR_BITS( SOctreeNode::NODE_LEVEL_BIT_COUNT ) );
m_vecExtraSize = Math::CVector4( m_Desc.extraSizePercent );
m_vecMaxSize = Math::CVector4( m_Desc.vec3MaxSize );
m_vecMinSize = Math::CVector4( m_Desc.vec3MinSize );
// Create root node
m_vNodes.Reserve( 512 ); // 8 * 8 * 8
//m_vNodeInfos.Reserve( 512 );
SOctreeNode Root;
Root.m_parentNode = 0;
Root.m_handle.handle = 0;
Root.m_vecCenter = Desc.vec3Center;
m_RootAABB = Math::CAABB( Desc.vec3Center, Desc.vec3MaxSize );
m_vNodes.PushBack( Root );
return ret;
}
void COctree::Build()
{
}
void COctree::FrustumCull( const Math::CFrustum& Frustum )
{
_FrustumCull( Frustum, m_vNodes[0], m_RootAABB );
}
void COctree::_FrustumCull( const Math::CFrustum& Frustum, const SOctreeNode& Node, const Math::CAABB& NodeAABB )
{
if( Frustum.Intersects( NodeAABB ) )
{
_FrustumCullObjects( Frustum, Node );
Math::CAABB ChildAABB;
for( uint32_t i = 0; i < Node.m_vChildNodes.GetCount(); ++i )
{
const SOctreeNode& ChildNode = m_vNodes[ Node.m_vChildNodes[ i ] ];
ChildNode.CalcAABB( this, &ChildAABB );
_FrustumCull( Frustum, ChildNode, ChildAABB );
}
}
}
void COctree::_FrustumCullObjects( const Math::CFrustum& Frustum, const SOctreeNode& Node )
{
const uint32_t count = Node.m_vObjData.GetCount();
for( uint32_t i = 0; i < count; ++i )
{
const auto& Curr = Node.m_vObjData[i];
const bool visible = Frustum.Intersects( Curr.AABB );
m_pScene->_SetObjectVisible( Curr.Handle, visible );
}
}
COctree::UObjectHandle COctree::AddObject( const Math::CAABB& AABB, const Scene::UObjectHandle& handle )
{
UObjectHandle hRet;
uint8_t level = 0;
SNodeData Data;
Data.AABB = AABB;
AABB.CalcMinMax( &Data.MinMax );
NodeHandle hNode = _CreateNode( &m_vNodes[0], m_RootAABB, Data, &level );
hRet.hNode = hNode.handle;
auto& Node = m_vNodes[ hNode.index ];
hRet.index = Node.m_vObjData.PushBack( { AABB, handle } );
return hRet;
}
COctree::UObjectHandle COctree::_AddObject( const NodeHandle& hNode, const Math::CAABB& AABB,
const Scene::UObjectHandle& handle )
{
auto& Node = m_vNodes[ hNode.index ];
UObjectHandle hRet;
hRet.hNode = hNode.handle;
hRet.index = Node.AddObject( { AABB, handle } );
return hRet;
}
COctree::UObjectHandle COctree::_UpdateObject( const handle_t& hGraph,
const Scene::UObjectHandle& hObj, const Math::CAABB& AABB )
{
UObjectHandle Handle;
Handle.handle = hGraph;
SOctreeNode::UNodeHandle hNode;
hNode.handle = Handle.hNode;
auto& CurrNode = m_vNodes[hNode.index];
// Check if new AABB fits into current node
auto hTmpNode = _CreateNodeForObject( AABB );
if( hTmpNode.handle != hNode.handle )
{
CurrNode.m_vObjData[ Handle.index ].Handle.handle = 0; // invalidate this object
Handle = _AddObject( hTmpNode, AABB, hObj );
}
return Handle;
}
bool InBounds( const Math::CVector4& V, const Math::CVector4& Bounds )
{
Math::CVector4 vec4Tmp1, vec4Tmp2, vec4NegBounds;
Math::CVector4::LessOrEquals( V, Bounds, &vec4Tmp1 );
Math::CVector4::Mul( Bounds, Math::CVector4::NEGATIVE_ONE, &vec4Tmp2 );
Math::CVector4::LessOrEquals( vec4Tmp2, V, &vec4Tmp2 );
Math::CVector4::And( vec4Tmp1, vec4Tmp2, &vec4Tmp1 );
const auto res = Math::CVector4::MoveMask( vec4Tmp1 ) & 0x7;
return ( res == 0x7 ) != 0;
}
OCTREE_NODE_POSITION_INDEX CalcChildIndex( const Math::CVector4& vecNodeCenter,
const Math::CVector4& vecObjectCenter )
{
OCTREE_NODE_POSITION_INDEX ret;
// objectAABB.center <= OctreeAABB.center
Math::CVector4 vecTmp1;
Math::CVector4::LessOrEquals( vecObjectCenter, vecNodeCenter, &vecTmp1 );
// Compare result is not a float value, make it 0-1 range
bool aResults[ 4 ];
vecTmp1.ConvertCompareToBools( aResults );
/*static const bool LEFT = 1;
static const bool RIGHT = 0;
static const bool TOP = 0;
static const bool BOTTOM = 1;
static const bool NEAR = 0;
static const bool FAR = 1;*/
static const OCTREE_NODE_POSITION_INDEX aRets[2][2][2] =
{
// RIGHT
{
{ OctreeNodePositionIndices::RIGHT_TOP_FAR, OctreeNodePositionIndices::RIGHT_TOP_NEAR }, // TOP
{ OctreeNodePositionIndices::RIGHT_BOTTOM_FAR, OctreeNodePositionIndices::RIGHT_BOTTOM_NEAR } // BOTTOM
},
// LEFT
{
{ OctreeNodePositionIndices::LEFT_TOP_FAR, OctreeNodePositionIndices::LEFT_TOP_NEAR }, // TOP
{ OctreeNodePositionIndices::LEFT_BOTTOM_FAR, OctreeNodePositionIndices::LEFT_BOTTOM_NEAR } // BOTTOM
}
};
ret = aRets[ aResults[0] ][ aResults[ 1 ] ][ aResults[ 2 ] ];
return ret;
}
COctree::NodeHandle COctree::_CreateNode( SOctreeNode* pCurrent, const Math::CAABB& CurrentAABB,
const SNodeData& Data, uint8_t* pCurrLevel )
{
NodeHandle ret = pCurrent->m_handle;
// Finish here
/*Math::CAABB CurrentAABB;
SOctreeNode::SCalcAABBInfo Info;
Info.vecExtraSize = m_vecExtraSize;
Info.vecMaxSize = m_vecMaxSize;
Info.vecParentCenter = Math::CVector4( m_vNodeInfos[ pCurrent->m_parentNode ].vecCenter );
pCurrent->CalcAABB( Info, &CurrentAABB );*/
if( *pCurrLevel < m_Desc.maxDepth &&
CurrentAABB.Extents > ( m_Desc.vec3MinSize ) )
{
// Check which child node should constains the AABB
SOctreeNode::UNodeMask NodeMask;
SOctreeNode::UPositionMask PosMask;
Math::CVector4 vecNodeCenter;
CurrentAABB.CalcCenter( &vecNodeCenter );
// Check children overlapping
const bool overlappingChildren = Data.AABB.Contains( vecNodeCenter ) != Math::IntersectResults::OUTSIDE;
if( !overlappingChildren )
{
Math::CVector4 vecObjCenter;
Data.AABB.CalcCenter( &vecObjCenter );
// Select child index
OCTREE_NODE_POSITION_INDEX childIdx = CalcChildIndex( vecNodeCenter, vecObjCenter );
// If this child doesn't exist
const bool childExists = VKE_GET_BIT( pCurrent->m_childNodeMask.mask, childIdx );
if( !childExists )
{
++( *pCurrLevel );
Math::CAABB ChildAABB;
const auto hNode = _CreateNewNode( pCurrent, CurrentAABB, childIdx, *pCurrLevel, &ChildAABB );
{
pCurrent->m_vChildNodes.PushBack( hNode.index );
pCurrent->m_childNodeMask.mask |= VKE_BIT( childIdx );
}
VKE_ASSERT( pCurrent->m_vChildNodes.GetCount() <= 8, "" );
SOctreeNode& ChildNode = m_vNodes[ hNode.index ];
ret = _CreateNode( &ChildNode, ChildAABB, Data, pCurrLevel );
}
}
}
return ret;
}
COctree::NodeHandle COctree::_CreateNodeForObject( const Math::CAABB& AABB )
{
uint8_t level = 0;
SNodeData Data;
Data.AABB = AABB;
AABB.CalcMinMax( &Data.MinMax );
return _CreateNode( &m_vNodes[ 0 ], m_RootAABB, Data, &level );
}
COctree::NodeHandle COctree::_CreateNewNode( const SOctreeNode* pParent,
const Math::CAABB& ParentAABB, OCTREE_NODE_POSITION_INDEX idx, uint8_t level, Math::CAABB* pOut )
{
static const Math::CVector4 aCenterVectors[8] =
{
Math::CVector4( -1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, 1.0f, -1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, 1.0f, 1.0f ),
Math::CVector4( -1.0f, -1.0f, -1.0f, 1.0f ),
Math::CVector4( 1.0f, -1.0f, -1.0f, 1.0f ),
};
static const Math::CVector4 HALF( 0.5f );
const Math::CVector4 EXTRA_SIZE( m_Desc.extraSizePercent );
NodeHandle hRet;
{
Threads::ScopedLock l( m_NodeSyncObject );
hRet.index = m_vNodes.PushBack( {} );
VKE_ASSERT( m_vNodes.GetCount() < VKE_CALC_MAX_VALUE_FOR_BITS( SOctreeNode::BUFFER_INDEX_BIT_COUNT ), "" );
}
SOctreeNode& Node = m_vNodes[ hRet.index ];
hRet.bit = idx;
hRet.level = level;
Node.m_handle = hRet;
Node.m_parentNode = pParent->m_handle.index;
CalcNodeCenter( m_vecMaxSize.x, Math::CVector4( pParent->m_vecCenter ), hRet, &Node.m_vecCenter );
Node.CalcAABB( this, pOut );
return hRet;
}
} // Scene
} // VKE
| 40.368957 | 123 | 0.515916 | przemyslaw-szymanski |
9fb8e9c3e7e26bc435816a07831bb06ad39a7486 | 3,187 | cpp | C++ | src/matching.cpp | gnardari/urquhart | ce92836bd3eeecca6e4b21c5efb13ff43953b800 | [
"MIT"
] | 2 | 2021-05-15T03:04:17.000Z | 2021-09-16T12:21:58.000Z | src/matching.cpp | gnardari/urquhart | ce92836bd3eeecca6e4b21c5efb13ff43953b800 | [
"MIT"
] | null | null | null | src/matching.cpp | gnardari/urquhart | ce92836bd3eeecca6e4b21c5efb13ff43953b800 | [
"MIT"
] | null | null | null | #include <matching.hpp>
namespace matching {
void polygonMatching(
urquhart::Observation& ref, std::vector<size_t> refIds,
urquhart::Observation& targ, std::vector<size_t> targIds, double thresh,
std::vector<std::pair<size_t, size_t>>& polygonMatches){
std::set<size_t> matched;
for(auto rIdx : refIds){
size_t bestMatch = 0;
size_t bestDist = 100000;
urquhart::Polygon rp = ref.H->get_vertex(rIdx);
for(auto tIdx : targIds){
urquhart::Polygon tp = targ.H->get_vertex(tIdx);
// if tIdx was not matched before and the difference of number of points is not larger than 3
if(matched.find(tIdx) == matched.end() &&
std::abs(int(rp.points.size() - tp.points.size())) <= 3){
double d = euclideanDistance(rp.descriptor, tp.descriptor);
if(d < bestDist){
bestDist = d;
bestMatch = tIdx;
}
}
}
if(bestDist < thresh){
matched.insert(bestMatch);
std::pair<size_t, size_t> m = std::make_pair(rIdx, bestMatch);
polygonMatches.push_back(m);
}
}
}
void linePointMatching(const urquhart::Polygon& A, const urquhart::Polygon& B,
std::vector<std::pair<PointT, PointT>>& pointMatches){
// chi works as a permutation matrix
std::vector<size_t> chi = {0,1,2};
std::vector<size_t> bestPermutation;
double bestDist = 1000000;
do {
std::vector<double> permutation = {B.edgeLengths[chi[0]],
B.edgeLengths[chi[1]], B.edgeLengths[chi[2]]};
double d = euclideanDistance(A.edgeLengths, permutation);
if(d < bestDist){
bestDist = d;
bestPermutation = chi;
}
} while (std::next_permutation(chi.begin(), chi.end()));
for(size_t i = 0; i < 3; ++i){
PointT pA = A.points[i];
PointT pB = B.points[bestPermutation[i]];
pointMatches.push_back(std::make_pair(pA, pB));
}
}
std::vector<std::pair<PointT, PointT>> hierarchyMatching(
urquhart::Observation& ref, urquhart::Observation& targ, double thresh){
std::vector<size_t> refIds = ref.H->get_children(0);
std::vector<size_t> targIds = targ.H->get_children(0);
std::vector<std::pair<size_t, size_t>> polygonMatches;
polygonMatching(ref, refIds, targ, targIds, thresh, polygonMatches);
std::vector<std::pair<size_t,size_t>> triangleMatches;
for(auto pMatch : polygonMatches){
refIds = ref.H->get_children(pMatch.first);
targIds = targ.H->get_children(pMatch.second);
// TODO: ADD CHECK IF % OF TRIANGLES THAT MACTHED IS LARGER THAN 1/2
polygonMatching(ref, refIds, targ, targIds, thresh, triangleMatches);
}
std::vector<std::pair<PointT,PointT>> pointMatches;
for(auto tMatch : triangleMatches){
urquhart::Polygon rT = ref.H->get_vertex(tMatch.first);
urquhart::Polygon tT = targ.H->get_vertex(tMatch.second);
linePointMatching(rT, tT, pointMatches);
}
return pointMatches;
}
} // matching | 37.940476 | 106 | 0.600565 | gnardari |
9fb99605718228a2f381abae032b9fe97bb084fc | 1,681 | hpp | C++ | engine/include/engine/rendering/ForwardRenderingSystem.hpp | sienkiewiczkm/framework | 9940403404aa5c67186fe09b0910de3a6c8e9762 | [
"MIT"
] | null | null | null | engine/include/engine/rendering/ForwardRenderingSystem.hpp | sienkiewiczkm/framework | 9940403404aa5c67186fe09b0910de3a6c8e9762 | [
"MIT"
] | 9 | 2016-12-09T13:02:18.000Z | 2019-09-13T09:29:18.000Z | engine/include/engine/rendering/ForwardRenderingSystem.hpp | sienkiewiczkm/framework | 9940403404aa5c67186fe09b0910de3a6c8e9762 | [
"MIT"
] | null | null | null | #pragma once
#include "entityx/entityx.h"
#include "fw/UniversalPhongEffect.hpp"
#include "fw/resources/Cubemap.hpp"
#include "fw/Mesh.hpp"
#include "fw/Vertices.hpp"
#include "fw/rendering/Framebuffer.hpp"
namespace ee
{
class ForwardRenderingSystem:
public entityx::System<ForwardRenderingSystem>
{
public:
ForwardRenderingSystem();
virtual ~ForwardRenderingSystem();
void setFramebuffer(std::shared_ptr<fw::IFramebuffer> framebuffer)
{
_framebuffer = framebuffer;
}
virtual void update(
entityx::EntityManager &entities,
entityx::EventManager& events,
entityx::TimeDelta
) override;
void setSkybox(std::shared_ptr<fw::Cubemap> cubemap) { _cubemap = cubemap; }
void setIrradianceMap(std::shared_ptr<fw::Cubemap> cubemap)
{
_irradianceMap = cubemap;
}
void setPrefilterMap(std::shared_ptr<fw::Cubemap> cubemap)
{
_prefilterMap = cubemap;
}
void setBrdfLut(std::shared_ptr<fw::Texture> texture)
{
_brdfLut = texture;
}
private:
std::shared_ptr<fw::Cubemap> _cubemap;
std::shared_ptr<fw::Cubemap> _irradianceMap;
std::shared_ptr<fw::Cubemap> _prefilterMap;
std::shared_ptr<fw::Texture> _brdfLut;
std::shared_ptr<fw::UniversalPhongEffect> _universalPhongEffect;
std::shared_ptr<fw::Mesh<fw::VertexNormalTexCoords>> _box;
std::shared_ptr<fw::Mesh<fw::VertexNormalTexCoords>> _skybox;
std::unique_ptr<fw::Mesh<fw::VertexNormalTexCoords>> _plane;
std::shared_ptr<fw::IFramebuffer> _framebuffer;
std::shared_ptr<fw::ShaderProgram> _skyboxShader;
GLint _skyboxViewLoc, _skyboxProjLoc, _skyboxLoc;
};
}
| 25.469697 | 80 | 0.703153 | sienkiewiczkm |
9fbbf1637bd30d8d8df212435ccbb1ad65d29c8f | 4,205 | hpp | C++ | include/simple/template_is_prime.hpp | kahido/template-metaprogramming-journey | ad214c14039e40f56e32e72fb83dcff01601b267 | [
"Unlicense"
] | null | null | null | include/simple/template_is_prime.hpp | kahido/template-metaprogramming-journey | ad214c14039e40f56e32e72fb83dcff01601b267 | [
"Unlicense"
] | null | null | null | include/simple/template_is_prime.hpp | kahido/template-metaprogramming-journey | ad214c14039e40f56e32e72fb83dcff01601b267 | [
"Unlicense"
] | null | null | null | /*
* @brief Template Metaprogramming 06
*
* Source: https://youtu.be/XNJlyCAr7tA
*
*/
#pragma once
// simple primality test
// this algorithm is inefficient
bool is_prime_loop(unsigned p)
{
bool ret = true;
if (p < 4)// p = 0, 1, 2, 3
{
ret = (p > 1);// p = 2 or 3, then we return true
} else {
// p = 4, 5 ,6, ...
unsigned half_p = p / 2;
// d = p/2, ..., 3, 2 (the least d is 2)
for (unsigned d = half_p; d > 1; --d) {
if (p % d == 0)// p is divisile by d
{
return false;// p is not prime
}
}
return true;// p is not divisible by 2, 3, ..., p/2
}
return ret;
}
bool _is_prime_recu(unsigned p, unsigned d)
{
bool ret = true;
if (d == 2) {// escape clause -> specialization
ret = (p % d != 0);// p is not divisible by d, then return true
} else {
/*
* Rule 1:
*
* if (true_condition)
* return true_expr;
* else
* return false_expr;
*
* return (true_condition ? true_expr : false_expr);
*
*
*/
// d is greater than 2
// if (p % d != 0)// p is not divisible by d
// {
// ret = _is_prime_recu(p, --d);
// } else {
// // p is divisible by d
// return false;
// }
// return (p%d != 0 ? _is_prime_recu(p, --d) : false);
/*
* Rule 2:
*
* if (true_condition)
* return true_expr;
* elss
* return false;
*
* return true_condition && true_expr;
*
*/
// recursive clause -> primary template
return (p % d != 0) && _is_prime_recu(p, --d);
}
return ret;
// return (d == 2 ? (p % d != 0) : (p % d != 0) && _is_prime_recu(p, --d));
}
bool is_prime_recursion(unsigned p)
{
bool ret = true;
if (p < 4)// excape clause -> specialization
// p = 0, 1, 2, 3
{
ret = (p > 1);// p = 2 or 3, then we return true
} else {
// recursive clause -> primary template
// p is 4, 5, 6, ...
return _is_prime_recu(p, p / 2);
}
return ret;
}
// primary template
// recursive clause of recursive function
template<unsigned p, unsigned d>
struct st_is_prime_recu
{
/*
* (p%d != 0) && _is_prime_recu(p, --d);
*
* p and d are template parameters.
* we cannot change template parameters
* so --d is incorerect, instead us d-1
*/
static const bool value = (p % d) && st_is_prime_recu<p, d - 1>::value;
};
// escape clause to specialization
template<unsigned p>
struct st_is_prime_recu<p, 2>
{
static const bool value = (p % 2 != 0);
};
// primary template
// when we translate recursive function
// to template class, recursive clause becomes primary template
template<unsigned p>
struct st_is_prime
{
static const bool value = st_is_prime_recu<p, p / 2>::value;
};
template<>
struct st_is_prime<3>
{
static const bool value = true;
};
template<>
struct st_is_prime<2>
{
static const bool value = true;
};
template<>
struct st_is_prime<1>
{
static const bool value = true;
};
template<>
struct st_is_prime<0>
{
static const bool value = false;
};
void test_is_prime(unsigned limit)
{
for (unsigned p = 1; p <= limit; ++p) {
std::cout << std::setw(3) << p << " is "
<< (is_prime_loop(p) ? "Yes, Prime" : "No") << std::endl;
}
}
void test_is_prime_recursion(unsigned limit)
{
for (unsigned p = 1; p <= limit; ++p) {
std::cout << std::setw(3) << p << " is "
<< (is_prime_recursion(p) ? "Yes, Prime" : "No") << std::endl;
}
}
[[maybe_unused]] constexpr unsigned magic_prime_t = 7;
void test_st_is_prime()
{
std::cout << std::setw(3) << 1 << " is "
<< (st_is_prime<1>::value ? "Yes, Prime" : "No") << std::endl;
std::cout << std::setw(3) << magic_prime_t << " is "
<< (st_is_prime<magic_prime_t>::value ? "Yes, Prime" : "No") << std::endl;
}
[[maybe_unused]] constexpr unsigned magic_prime = 25;
| 22.72973 | 88 | 0.51629 | kahido |
9fbefa6eb15cb74f1d464592a697063b1e3c6f65 | 1,599 | cpp | C++ | Native/Src/detail/ChannelFactory.cpp | chengwei45254/IPC | 86df124c5f2a0447d6ec56af7a506dc41bbf5546 | [
"MIT"
] | 167 | 2017-04-26T00:17:34.000Z | 2019-05-06T09:50:30.000Z | Native/Src/detail/ChannelFactory.cpp | chengwei45254/IPC | 86df124c5f2a0447d6ec56af7a506dc41bbf5546 | [
"MIT"
] | 22 | 2017-04-26T20:24:40.000Z | 2019-03-23T20:03:42.000Z | Native/Src/detail/ChannelFactory.cpp | chengwei45254/IPC | 86df124c5f2a0447d6ec56af7a506dc41bbf5546 | [
"MIT"
] | 42 | 2017-04-27T01:51:39.000Z | 2019-04-12T21:23:17.000Z | #include "stdafx.h"
#include "IPC/detail/ChannelFactory.h"
namespace IPC
{
namespace detail
{
std::shared_ptr<SharedMemory> ChannelFactory<void>::InstanceBase::GetMemory(
create_only_t, bool input, const char* name, const ChannelSettingsBase& settings)
{
return GetMemory(false, input, name, settings);
}
std::shared_ptr<SharedMemory> ChannelFactory<void>::InstanceBase::GetMemory(
open_only_t, bool input, const char* name, const ChannelSettingsBase& settings)
{
return GetMemory(true, input, name, settings);
}
std::shared_ptr<SharedMemory> ChannelFactory<void>::InstanceBase::GetMemory(
bool open, bool input, const char* name, const ChannelSettingsBase& settings)
{
const auto& config = settings.GetConfig();
const auto& channelConfig = input ? config.m_input : config.m_output;
if (config.m_shared)
{
if (auto memory = m_current.lock())
{
return memory;
}
}
auto memory = channelConfig.m_common
? channelConfig.m_common
: open
? settings.GetMemoryCache()->Open(name)
: settings.GetMemoryCache()->Create(name, channelConfig.m_size);
if (config.m_shared)
{
m_current = memory;
}
return memory;
}
} // detail
} // IPC
| 31.352941 | 94 | 0.537211 | chengwei45254 |
9fc125b0e726e5ae456466ee8cd318a8ab4fad2f | 1,763 | cpp | C++ | math_pazzle/1.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | math_pazzle/1.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null | math_pazzle/1.cpp | taku-xhift/labo | 89dc28fdb602c7992c6f31920714225f83a11218 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <sstream>
#include <bitset>
// #include <maniplator>
bool IsReversible(const std::string& str) {
std::size_t count = str.length()/2;
if (count == 0) {
return true;
}
auto begin = str.cbegin();
auto rbegin = str.crbegin();
for (std::size_t i = 0; i < count; ++i) {
char beginVal = *begin;
char rbeginVal = *rbegin;
if (beginVal != rbeginVal) {
return false;
}
++begin;
++rbegin;
}
return true;
}
bool IsKaibun(int i) {
// std::cout << i << ":\n";
std::stringstream ss;
ss << i;
auto str = ss.str();
std::cout << "\t" << str << std::endl;
bool isReversible = IsReversible(str);
if (isReversible == false) {
return false;
}
ss.clear();
ss.str("");
// 2進数のチェック
std::bitset<32> binary(i);
bool isFirst = true;
for (int i = binary.size() -1; i >= 0; --i) {
int val = binary[i];
if (binary[i] == 0) {
if (isFirst == true) {
continue;
}
} else {
isFirst = false;
}
ss << binary[i];
}
str = ss.str();
std::cout << "\t" << str << std::endl;
const bool isBinaryReversible = IsReversible(ss.str());
if (isBinaryReversible == false) {
return false;
}
ss.clear();
ss.str("");
ss << std::oct << i;
const bool isOctReversible = IsReversible(ss.str());
str = ss.str();
std::cout << "\t" << str << "\n";
return isOctReversible;
}
int main() {
// const bool nine = IsKaibun(9);
// std::cout << "nine => " << nine << std::endl;
// const bool ninty = IsKaibun(90);
// std::cout << "ninty => " << ninty << std::endl;
int i = 11;
for (; ; ++i) {
const bool isKaibun = IsKaibun(i);
if (isKaibun == true) {
break;
}
}
// int i = 121;
// const bool isKaibun = IsKaibun(i);
std::cout << "the minimum => " << i << "\n";
}
| 16.951923 | 56 | 0.559841 | taku-xhift |
9fc2753bed0ed37270c307c5ecca0c4bd43cd435 | 407 | hh | C++ | octo/types/OctoString.hh | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null | octo/types/OctoString.hh | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null | octo/types/OctoString.hh | KevinTheBarbarian/octo | 98047dbe7fd7ba5bf6a5f6c1b1a5a8d03fdf8f5f | [
"MIT"
] | null | null | null |
#ifndef __OCTO_STRING_HH__
#define __OCTO_STRING_HH__
#include "OctoObject.hh"
namespace types {
class OctoString : public OctoObject {
public:
virtual void assign(const char* data, size_t size) = 0;
// Compare to a null terminated string.
virtual bool equalTo(const char* data) const = 0;
virtual void toCppString(std::string& str) const = 0;
};
}
#endif
| 19.380952 | 63 | 0.665848 | KevinTheBarbarian |
9fd30f542f14d939964a19a9b22a5dde0219cdf3 | 10,427 | cpp | C++ | src/WeatherData.cpp | FMeinicke/Weather-App | 8168c07592938539c1c00f8fd15e1297c32d2f0d | [
"MIT"
] | 10 | 2020-03-12T12:45:50.000Z | 2020-06-28T06:10:04.000Z | src/WeatherData.cpp | FMeinicke/Weather-App | 8168c07592938539c1c00f8fd15e1297c32d2f0d | [
"MIT"
] | null | null | null | src/WeatherData.cpp | FMeinicke/Weather-App | 8168c07592938539c1c00f8fd15e1297c32d2f0d | [
"MIT"
] | 2 | 2021-08-24T12:37:33.000Z | 2021-09-05T14:59:58.000Z | /**
** This file is part of the "Mobile Weather" project.
** Copyright (c) 2020 Florian Meinicke <florian.meinicke@t-online.de>.
**
** Permission is hereby granted, free of charge, to any person obtaining a copy
** of this software and associated documentation files (the "Software"), to deal
** in the Software without restriction, including without limitation the rights
** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
** copies of the Software, and to permit persons to whom the Software is
** furnished to do so, subject to the following conditions:
**
** The above copyright notice and this permission notice shall be included in all
** copies or substantial portions of the Software.
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
** SOFTWARE.
**/
//============================================================================
/// \file WeatherData.cpp
/// \author Florian Meinicke <florian.meinicke@t-online.de>
/// \date 18/02/2020
/// \brief Implementation of the CWeatherData class.
//============================================================================
//============================================================================
// INCLUDES
//============================================================================
#include "WeatherData.h"
static constexpr auto MILES_TO_KM_FACTOR = 1.609344;
//=============================================================================
CWeatherData::CWeatherData(QObject* parent) : QObject(parent)
{}
//=============================================================================
CWeatherData::CWeatherData(const CWeatherData& rhs)
: m_WeatherStateName{rhs.m_WeatherStateName},
m_WeatherStateAbbreviation{rhs.m_WeatherStateAbbreviation},
m_TheTemp{rhs.m_TheTemp},
m_MinTemp{rhs.m_MinTemp},
m_MaxTemp{rhs.m_MaxTemp}
{}
//=============================================================================
CWeatherData::CWeatherData(CWeatherData&& rhs) noexcept
: m_WeatherStateName{rhs.m_WeatherStateName},
m_WeatherStateAbbreviation{rhs.m_WeatherStateAbbreviation},
m_TheTemp{rhs.m_TheTemp},
m_MinTemp{rhs.m_MinTemp},
m_MaxTemp{rhs.m_MaxTemp}
{}
//=============================================================================
CWeatherData& CWeatherData::operator=(const CWeatherData& rhs)
{
m_WeatherStateName = rhs.m_WeatherStateName;
m_WeatherStateAbbreviation = rhs.m_WeatherStateAbbreviation;
m_TheTemp = rhs.m_TheTemp;
m_MinTemp = rhs.m_MinTemp;
m_MaxTemp = rhs.m_MaxTemp;
return *this;
}
//=============================================================================
CWeatherData& CWeatherData::operator=(CWeatherData&& rhs) noexcept
{
m_WeatherStateName = rhs.m_WeatherStateName;
m_WeatherStateAbbreviation = rhs.m_WeatherStateAbbreviation;
m_TheTemp = rhs.m_TheTemp;
m_MinTemp = rhs.m_MinTemp;
m_MaxTemp = rhs.m_MaxTemp;
return *this;
}
//=============================================================================
QDate CWeatherData::date() const
{
return m_Date;
}
//=============================================================================
void CWeatherData::setDate(const QDate& day)
{
m_Date = day;
emit dateChanged();
}
//=============================================================================
QString CWeatherData::weatherStateName() const
{
return m_WeatherStateName;
}
//=============================================================================
void CWeatherData::setWeatherStateName(const QString& weatherStateName)
{
m_WeatherStateName = weatherStateName;
emit weatherStateNameChanged();
}
//=============================================================================
QString CWeatherData::weatherStateAbbreviation() const
{
return m_WeatherStateAbbreviation;
}
//=============================================================================
void CWeatherData::setWeatherStateAbbreviation(
const QString& weatherStateAbbreviation)
{
m_WeatherStateAbbreviation = weatherStateAbbreviation;
emit weatherStateAbbreviationChanged();
}
//=============================================================================
qreal CWeatherData::theTemp() const
{
return m_TheTemp;
}
//=============================================================================
void CWeatherData::setTheTemp(const qreal& temp)
{
m_TheTemp = temp;
emit theTempChanged();
}
//=============================================================================
qreal CWeatherData::minTemp() const
{
return m_MinTemp;
}
//=============================================================================
void CWeatherData::setMinTemp(const qreal& temp)
{
m_MinTemp = temp;
emit minTempChanged();
}
//=============================================================================
qreal CWeatherData::maxTemp() const
{
return m_MaxTemp;
}
//=============================================================================
void CWeatherData::setMaxTemp(const qreal& temp)
{
m_MaxTemp = temp;
emit maxTempChanged();
}
//=============================================================================
qreal CWeatherData::windSpeed() const
{
return m_WindSpeed;
}
//=============================================================================
void CWeatherData::setWindSpeed(const qreal& speed)
{
m_WindSpeed = speed;
emit windSpeedChanged();
}
//=============================================================================
void CWeatherData::setWindSpeedInMph(const qreal& speed)
{
setWindSpeed(speed * MILES_TO_KM_FACTOR);
}
//=============================================================================
qreal CWeatherData::windDirection() const
{
return m_WindDirection;
}
//=============================================================================
void CWeatherData::setWindDirection(const qreal& dir)
{
m_WindDirection = dir;
emit windDirectionChanged();
}
//=============================================================================
QString CWeatherData::windDirCompass() const
{
return m_WindDirCompass;
}
//=============================================================================
void CWeatherData::setWindDirCompass(const QString& compass)
{
m_WindDirCompass = compass;
emit windDirCompassChanged();
}
//=============================================================================
qreal CWeatherData::airPressure() const
{
return m_AirPressure;
}
//=============================================================================
void CWeatherData::setAirPressure(const qreal& pressure)
{
m_AirPressure = pressure;
emit airPressureChanged();
}
//=============================================================================
qreal CWeatherData::humidity() const
{
return m_Humidity;
}
//=============================================================================
void CWeatherData::setHumidity(const qreal& humidity)
{
m_Humidity = humidity;
emit humidityChanged();
}
//=============================================================================
qreal CWeatherData::visibility() const
{
return m_Visibility;
}
//=============================================================================
void CWeatherData::setVisibility(const qreal& visibility)
{
m_Visibility = visibility;
emit visibilityChanged();
}
//=============================================================================
void CWeatherData::setVisibilityInMiles(const qreal& visibility)
{
setVisibility(visibility * MILES_TO_KM_FACTOR);
}
//=============================================================================
int CWeatherData::confidence() const
{
return m_Confidence;
}
//=============================================================================
void CWeatherData::setConfidence(int confidence)
{
m_Confidence = confidence;
emit confidenceChanged();
}
//=============================================================================
QDateTime CWeatherData::sunriseTime() const
{
return m_SunriseTime;
}
//=============================================================================
void CWeatherData::setSunriseTime(const QDateTime& time)
{
m_SunriseTime = time;
static auto OffsetFromUTC = QDateTime::currentDateTime().offsetFromUtc();
// Convert the time from UTC to the same time in the local timezone
// by changing the UTC offset to the current timezone's offset.
// This means, if the time 07:00 UTC-7 is given and we are currently in the
// UTC+1 timezone, the time would be displayed as 15:00 UTC+1. To prevent
// that we change the UTC offset from UTC-7 to UTC+1 (i.e. the given time
// would now be 07:00 UTC+1; the actual value of the time is not affected).
// Now the time will be displayed correctly as 07:00.
// Without this the sunrise time for e.g. Los Angeles would be displayed as
// 15:00 (if we are in the UTC+1 timezone) when it is actually 07:00 in the
// local timezone (i.e. UTC-7).
m_SunriseTime.setOffsetFromUtc(OffsetFromUTC);
emit sunriseTimeChanged();
}
//=============================================================================
QDateTime CWeatherData::sunsetTime() const
{
return m_SunsetTime;
}
//=============================================================================
void CWeatherData::setSunsetTime(const QDateTime& time)
{
m_SunsetTime = time;
static auto OffsetFromUTC = QDateTime::currentDateTime().offsetFromUtc();
// see above for an explanation
m_SunsetTime.setOffsetFromUtc(OffsetFromUTC);
emit sunsetTimeChanged();
}
| 34.299342 | 83 | 0.482018 | FMeinicke |
9fdef1ca39b0c61b56e5e893bbf52a6927962a12 | 267 | cc | C++ | find_first_of/find_first_of_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | find_first_of/find_first_of_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | find_first_of/find_first_of_main.cc | ULL-ESIT-IB-2020-2021/ib-practica09-funciones-LZ01014 | c3351a8e1e62d01dad072c21f57654c102efc114 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <cstring>
#include "find_first_of.h"
int main(int argc, char *argv[]){
std::string word =argv[1];
std::string character_to_find = argv[2];
std::cout << PositionOfCharacter(word, character_to_find) << std::endl;
} | 24.272727 | 73 | 0.70412 | ULL-ESIT-IB-2020-2021 |
9fe74f0633e78896deed5dd2fcaad8450039d33a | 311 | cpp | C++ | 283.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 8 | 2018-10-31T11:00:19.000Z | 2020-07-31T05:25:06.000Z | 283.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | null | null | null | 283.cpp | zfang399/LeetCode-Problems | 4cb25718a3d1361569f5ee6fde7b4a9a4fde2186 | [
"MIT"
] | 2 | 2018-05-31T11:29:22.000Z | 2019-09-11T06:34:40.000Z | class Solution {
public:
void moveZeroes(vector<int>& nums) {
int now = 0;
for(int i = 0; i < nums.size(); i++){
if(nums[i]){
nums[now] = nums[i];
now++;
}
}
for(int i = now; i < nums.size(); i++) nums[i] = 0;
}
};
| 22.214286 | 59 | 0.382637 | zfang399 |
9fefee80d0f02d86c8d2a971b451ae3feb5d166f | 458 | cpp | C++ | Dynamic Programing/21min_operations.cpp | waytoashutosh/CPP_Algo_Implementation | b7f8d859eeff06740dd8b343951308d8937ea6fb | [
"MIT"
] | null | null | null | Dynamic Programing/21min_operations.cpp | waytoashutosh/CPP_Algo_Implementation | b7f8d859eeff06740dd8b343951308d8937ea6fb | [
"MIT"
] | null | null | null | Dynamic Programing/21min_operations.cpp | waytoashutosh/CPP_Algo_Implementation | b7f8d859eeff06740dd8b343951308d8937ea6fb | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
unsigned long long int n;
unsigned long long int solve(unsigned long long int i)
{
if(i>=n)
{
return 0;
}
unsigned long long int x=0,y=0;
if(i+1<=n)
x = 1+solve(i+1);
if((unsigned long long int)(i*2)<=n)
y = 1+solve(i*2);
return min(x,y);
}
int main() {
int t;
cin>>t;
while(t--)
{
cin>>n;
cout<<1+solve(1)<<"\n";
}
return 0;
} | 13.470588 | 54 | 0.50655 | waytoashutosh |
9ff5cfc1bc1a8e25d4d66f43c60fb532d0188333 | 1,589 | cpp | C++ | Examenes/Febrero2016/UnidadCuriosaDeMonitorizacion.cpp | manumonforte/AdvancedAlgorithm | fe82ef552147a041e7ad717f85999eb677f5340a | [
"MIT"
] | 4 | 2019-01-30T21:35:40.000Z | 2019-06-25T03:19:44.000Z | Examenes/Febrero2016/UnidadCuriosaDeMonitorizacion.cpp | manumonforte/AdvancedAlgorithm | fe82ef552147a041e7ad717f85999eb677f5340a | [
"MIT"
] | null | null | null | Examenes/Febrero2016/UnidadCuriosaDeMonitorizacion.cpp | manumonforte/AdvancedAlgorithm | fe82ef552147a041e7ad717f85999eb677f5340a | [
"MIT"
] | 3 | 2019-06-06T17:01:28.000Z | 2021-06-27T10:55:34.000Z | //Manuel Monforte
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "PriorityQueue.h"
/*
Coste de la solucion--> Aplicamos PriorityQueue
-->Se aplican operaciones top y pop que tiene complejidad logN
-->Se aplican K veces cada una de ella
-->Total: O(2K*logN)
*/
struct tUsuario{
int id;
int periodo;
int tiempo;
tUsuario(){};
tUsuario(int pk, int ped) : id(pk), periodo(ped),tiempo(ped){};
};
bool operator < (const tUsuario & a, const tUsuario & b){
return a.tiempo < b.tiempo || ( a.tiempo == b.tiempo && a.id < b.id) ;
}
// Resuelve un caso de prueba, leyendo de la entrada la
// configuración, y escribiendo la respuesta
bool resuelveCaso() {
// leer los datos de la entrada
int N, K,id,periodo;
std::string registro;
std::cin >> N;
if (N== 0)
return false;
PriorityQueue<tUsuario> UCM;
for (int i = 0; i < N; i++){
std::cin >> registro >> id >> periodo;
UCM.push({ id, periodo });
}
std::cin >> K;
for (int i = 0; i < K; i++){
tUsuario aux = UCM.top();
UCM.pop();
std::cout << aux.id << "\n";
aux.tiempo += aux.periodo;
UCM.push(aux);
}
return true;
}
int main() {
// Para la entrada por fichero.
// Comentar para acepta el reto
#ifndef DOMJUDGE
std::ifstream in("datos.txt");
auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save old buf and redirect std::cin to casos.txt
#endif
while (resuelveCaso())
;
// Para restablecer entrada. Comentar para acepta el reto
#ifndef DOMJUDGE // para dejar todo como estaba al principio
std::cin.rdbuf(cinbuf);
system("PAUSE");
#endif
return 0;
} | 20.113924 | 92 | 0.651353 | manumonforte |
9ff8346f48ef2d620986d0cf1fe99a9efcf36bb7 | 1,492 | cpp | C++ | 15. Maximum Sub Array - GFG/15.-maximum-sub-array.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | 1 | 2022-02-27T09:01:07.000Z | 2022-02-27T09:01:07.000Z | 15. Maximum Sub Array - GFG/15.-maximum-sub-array.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | 15. Maximum Sub Array - GFG/15.-maximum-sub-array.cpp | champmaniac/LeetCode | 65810e0123e0ceaefb76d0a223436d1525dac0d4 | [
"MIT"
] | null | null | null | // { Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function template for C++
class Solution{
public:
bool checkPositive(int arr[], int n){
for(int i=0;i<n;i++){
if(arr[i]>0) return (true);
}
return (false);
}
vector<int> findSubarray(int a[], int n) {
// code here
if(!checkPositive(a,n)){
return (vector<int>{-1});
}
int i=0,j=0;
long long int max_sum=0;
long long int cur_sum=0;
int start=0,end=0;
while(j<n){
if(a[j]>=0){
cur_sum+=a[j];
if(cur_sum>=max_sum){
start =i;
end=j;
max_sum=cur_sum;
}
j++;
}
else{
cur_sum=0;
i=j+1;
j++;
}
}
vector<int> ans;
for(int i=start;i<=end;i++)
{
ans.push_back(a[i]);
}
if(!ans.size()) ans.push_back(-1);
return (ans);
}
};
// { Driver Code Starts.
void printAns(vector<int> &ans) {
for (auto &x : ans) {
cout << x << " ";
}
cout << "\n";
}
int main() {
int t;
cin >> t;
while (t--) {
int n, i;
cin >> n;
int a[n];
for (i = 0; i < n; i++) {
cin >> a[i];
}
Solution ob;
auto ans = ob.findSubarray(a, n);
printAns(ans);
}
return 0;
}
// } Driver Code Ends | 19.128205 | 43 | 0.419571 | champmaniac |
9ffd4514974b80bf43987e06a64668aca487fc26 | 2,440 | cpp | C++ | cpc/exercise2-17_allowance.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | cpc/exercise2-17_allowance.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | cpc/exercise2-17_allowance.cpp | aoibird/pc | b72c0b10117f95d45e2e7423614343b5936b260a | [
"MIT"
] | null | null | null | // POJ 3040
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
typedef pair<int,int> PII;
const int INF = 2000000000;
const int MAXN = 20+10;
PII D[MAXN];
int N, C;
void print_d()
{
for (int i = 0; i < N; i++) printf("(%d,%d)%c", D[i].first, D[i].second,
i==N-1?'\n':' ');
}
bool cmp(const PII &a, const PII &b)
{
return a.first > b.first || (a.first==b.first && a.second > b.second);
}
int take(int amount)
{
map<int,int> m;
for (int i = 0; i < N; i++) {// descent
if (D[i].second > 0 && amount / D[i].first > 0) {
int c = (amount / D[i].first < D[i].second) ?
amount / D[i].first : D[i].second;
// printf("(%d * %d)", D[i].first, c);
m[i] += c;
D[i].second -= c;
amount -= D[i].first * c;
}
}
for (int i = N-1; i >= 0; i--) {// ascent
if (amount <= 0) break;
if (D[i].second <= 0) continue;
if (amount < D[i].first || amount / D[i].first <= D[i].second) {
int c = (amount / D[i].first > 0
&& amount <= D[i].second * D[i].first) ?
amount / D[i].first : 1;
// printf("(%d %d)", D[i].first, c);
m[i] += c;
D[i].second -= c;
amount -= D[i].first * c;
}
}
if (amount > 0) return 0;
int mi = INF;
for (map<int,int>::iterator it = m.begin(); it != m.end(); it++) {
PII pair = *it; int index = pair.first; int cnt = pair.second;
if (cnt > 0) mi = min(mi, D[index].second / cnt);
}
for (map<int,int>::iterator it = m.begin(); it != m.end(); it++) {
PII pair = *it; int index = pair.first; int cnt = pair.second;
D[index].second -= (mi * cnt);
}
// print_d();
return mi+1;
}
void solve()
{
sort(D, D+N, cmp);
int cnt = 0, c = 0;
while ((c = take(C)) != 0) {
cnt += c;
}
// printf("\n");
printf("%d\n", cnt);
}
int main()
{
while (scanf("%d%d", &N, &C) == 2) {
if (N == 0 && C == 0) break;
memset(D, 0, sizeof(D));
for (int i = 0; i < N; i++) {
int v, b; scanf("%d%d", &v, &b);
D[i] = PII(v, b);
}
solve();
}
}
| 25.154639 | 76 | 0.445492 | aoibird |
b004658140899e7ae44fd85eefc013fb862fe3d9 | 1,673 | cpp | C++ | src/CipherTable.cpp | fcifuentesq/bg-mixnet | dea0e6ff1ad321f0e919298cbdc3fe9a666fae43 | [
"Apache-2.0"
] | 7 | 2018-03-25T23:45:36.000Z | 2020-02-13T13:55:41.000Z | src/CipherTable.cpp | fcifuentesq/bg-mixnet | dea0e6ff1ad321f0e919298cbdc3fe9a666fae43 | [
"Apache-2.0"
] | 1 | 2022-01-21T00:44:07.000Z | 2022-01-21T00:44:07.000Z | src/CipherTable.cpp | fcifuentesq/bg-mixnet | dea0e6ff1ad321f0e919298cbdc3fe9a666fae43 | [
"Apache-2.0"
] | 4 | 2018-03-27T19:36:00.000Z | 2022-01-10T22:24:06.000Z | #include "CipherTable.h"
#include "Functions.h"
CipherTable::CipherTable() : m_(0), n_(0), owner_(true) {}
CipherTable::CipherTable(string& ciphers, long m, ElGammal* elgammal) : m_(m), owner_(true) {
Functions::parse_ciphers(ciphers, m, C_, elgammal);
if (m == 0) {
n_ = 0;
} else {
n_ = C_.at(0)->size();
}
}
CipherTable::CipherTable(vector<vector<Cipher_elg>* >* ciphers, long m): m_(m), owner_(false) {
C_ = *ciphers;
if (m == 0) {
n_ = 0;
} else {
n_ = C_.at(0)->size();
}
}
CipherTable::CipherTable(vector<vector<Cipher_elg>* >* ciphers, long m, const bool owner):
m_(m), owner_(owner){
C_ = *ciphers;
if (m == 0) {
n_ = 0;
} else {
n_ = C_.at(0)->size();
}
}
CipherTable::~CipherTable() {
if (owner_) {
for (unsigned int i = 0; i < C_.size(); i++) {
delete C_.at(i);
}
for (unsigned int i = 0; i < elements_.size(); i++) {
delete elements_.at(i);
}
}
}
vector<vector<Cipher_elg>* >* CipherTable::getCMatrix() {
return &C_;
}
vector<vector<Mod_p>* >* CipherTable::getElementsMatrix() {
return &elements_;
}
string CipherTable::getCipher(int i, int j) {
stringstream cipher_str;
cipher_str << C_.at(i)->at(j);
return cipher_str.str();
}
Cipher_elg& CipherTable::get_elg_cipher(int i, int j) {
return C_.at(i)->at(j);
}
string CipherTable::getElement(int i, int j) {
stringstream cipher_str;
cipher_str << elements_.at(i)->at(j);
return cipher_str.str();
}
string CipherTable::encode_all_ciphers() {
return Functions::ciphers_to_str(&C_);
}
int CipherTable::rows() {
return m_;
}
int CipherTable::cols() {
return n_;
}
void CipherTable::set_dimensions(int m, int n) {
m_ = m;
n_ = n;
}
| 18.797753 | 95 | 0.632397 | fcifuentesq |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.