hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k โ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 โ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 โ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k โ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 โ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 โ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k โ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 โ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 โ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
858d1219e9e1be331ca432ebb6a99d65c36bf1a1 | 2,023 | cpp | C++ | android/app/src/cpp/src/base/tools/Timer.cpp | FlameSalamander/react-native-xmrig | 6a6e3b301bd78b88459989f334d759f65e434082 | [
"MIT"
] | 28 | 2021-05-11T03:28:57.000Z | 2022-03-09T14:34:57.000Z | android/app/src/cpp/src/base/tools/Timer.cpp | FlameSalamander/react-native-xmrig | 6a6e3b301bd78b88459989f334d759f65e434082 | [
"MIT"
] | 10 | 2021-05-16T19:50:31.000Z | 2022-01-30T03:56:45.000Z | android/app/src/cpp/src/base/tools/Timer.cpp | FlameSalamander/react-native-xmrig | 6a6e3b301bd78b88459989f334d759f65e434082 | [
"MIT"
] | 12 | 2021-07-19T22:14:58.000Z | 2022-02-08T02:24:05.000Z | /* XMRig
* Copyright 2018-2020 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2020 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/tools/Timer.h"
#include "base/kernel/interfaces/ITimerListener.h"
#include "base/tools/Handle.h"
xmrig::Timer::Timer(ITimerListener *listener) :
m_listener(listener)
{
init();
}
xmrig::Timer::Timer(ITimerListener *listener, uint64_t timeout, uint64_t repeat) :
m_listener(listener)
{
init();
start(timeout, repeat);
}
xmrig::Timer::~Timer()
{
Handle::close(m_timer);
}
uint64_t xmrig::Timer::repeat() const
{
return uv_timer_get_repeat(m_timer);
}
void xmrig::Timer::setRepeat(uint64_t repeat)
{
uv_timer_set_repeat(m_timer, repeat);
}
void xmrig::Timer::singleShot(uint64_t timeout, int id)
{
m_id = id;
stop();
start(timeout, 0);
}
void xmrig::Timer::start(uint64_t timeout, uint64_t repeat)
{
uv_timer_start(m_timer, onTimer, timeout, repeat);
}
void xmrig::Timer::stop()
{
setRepeat(0);
uv_timer_stop(m_timer);
}
void xmrig::Timer::init()
{
m_timer = new uv_timer_t;
m_timer->data = this;
uv_timer_init(uv_default_loop(), m_timer);
}
void xmrig::Timer::onTimer(uv_timer_t *handle)
{
const auto timer = static_cast<Timer *>(handle->data);
timer->m_listener->onTimer(timer);
}
| 21.521277 | 82 | 0.695502 |
858d21f8b3654fc3784454fa510505c5cdb008ed | 527 | cc | C++ | ui/display/chromeos/ozone/display_configurator_ozone.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | ui/display/chromeos/ozone/display_configurator_ozone.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | ui/display/chromeos/ozone/display_configurator_ozone.cc | domenic/mojo | 53dda76fed90a47c35ed6e06baf833a0d44495b8 | [
"BSD-3-Clause"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/display/chromeos/display_configurator.h"
#include "ui/display/types/native_display_delegate.h"
#include "ui/ozone/public/ozone_platform.h"
namespace ui {
scoped_ptr<NativeDisplayDelegate>
DisplayConfigurator::CreatePlatformNativeDisplayDelegate() {
return ui::OzonePlatform::GetInstance()->CreateNativeDisplayDelegate();
}
} // namespace ui
| 29.277778 | 73 | 0.789374 |
859144fe3502ca1d0a582301f21ac43a1abcc4b9 | 4,268 | hpp | C++ | include/codegen/include/System/DateTimeResult.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/System/DateTimeResult.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/System/DateTimeResult.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: System.ParseFlags
#include "System/ParseFlags.hpp"
// Including type: System.TimeSpan
#include "System/TimeSpan.hpp"
// Including type: System.DateTime
#include "System/DateTime.hpp"
// Including type: System.ParseFailureKind
#include "System/ParseFailureKind.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::Globalization
namespace System::Globalization {
// Forward declaring type: Calendar
class Calendar;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Autogenerated type: System.DateTimeResult
struct DateTimeResult : public System::ValueType {
public:
// System.Int32 Year
// Offset: 0x0
int Year;
// System.Int32 Month
// Offset: 0x4
int Month;
// System.Int32 Day
// Offset: 0x8
int Day;
// System.Int32 Hour
// Offset: 0xC
int Hour;
// System.Int32 Minute
// Offset: 0x10
int Minute;
// System.Int32 Second
// Offset: 0x14
int Second;
// System.Double fraction
// Offset: 0x18
double fraction;
// System.Int32 era
// Offset: 0x20
int era;
// System.ParseFlags flags
// Offset: 0x24
System::ParseFlags flags;
// System.TimeSpan timeZoneOffset
// Offset: 0x28
System::TimeSpan timeZoneOffset;
// System.Globalization.Calendar calendar
// Offset: 0x30
System::Globalization::Calendar* calendar;
// System.DateTime parsedDate
// Offset: 0x38
System::DateTime parsedDate;
// System.ParseFailureKind failure
// Offset: 0x40
System::ParseFailureKind failure;
// System.String failureMessageID
// Offset: 0x48
::Il2CppString* failureMessageID;
// System.Object failureMessageFormatArgument
// Offset: 0x50
::Il2CppObject* failureMessageFormatArgument;
// System.String failureArgumentName
// Offset: 0x58
::Il2CppString* failureArgumentName;
// Creating value type constructor for type: DateTimeResult
DateTimeResult(int Year_ = {}, int Month_ = {}, int Day_ = {}, int Hour_ = {}, int Minute_ = {}, int Second_ = {}, double fraction_ = {}, int era_ = {}, System::ParseFlags flags_ = {}, System::TimeSpan timeZoneOffset_ = {}, System::Globalization::Calendar* calendar_ = {}, System::DateTime parsedDate_ = {}, System::ParseFailureKind failure_ = {}, ::Il2CppString* failureMessageID_ = {}, ::Il2CppObject* failureMessageFormatArgument_ = {}, ::Il2CppString* failureArgumentName_ = {}) : Year{Year_}, Month{Month_}, Day{Day_}, Hour{Hour_}, Minute{Minute_}, Second{Second_}, fraction{fraction_}, era{era_}, flags{flags_}, timeZoneOffset{timeZoneOffset_}, calendar{calendar_}, parsedDate{parsedDate_}, failure{failure_}, failureMessageID{failureMessageID_}, failureMessageFormatArgument{failureMessageFormatArgument_}, failureArgumentName{failureArgumentName_} {}
// System.Void Init()
// Offset: 0xA2CEB0
void Init();
// System.Void SetDate(System.Int32 year, System.Int32 month, System.Int32 day)
// Offset: 0xA2CED0
void SetDate(int year, int month, int day);
// System.Void SetFailure(System.ParseFailureKind failure, System.String failureMessageID, System.Object failureMessageFormatArgument)
// Offset: 0xA2CEDC
void SetFailure(System::ParseFailureKind failure, ::Il2CppString* failureMessageID, ::Il2CppObject* failureMessageFormatArgument);
// System.Void SetFailure(System.ParseFailureKind failure, System.String failureMessageID, System.Object failureMessageFormatArgument, System.String failureArgumentName)
// Offset: 0xA2CF18
void SetFailure(System::ParseFailureKind failure, ::Il2CppString* failureMessageID, ::Il2CppObject* failureMessageFormatArgument, ::Il2CppString* failureArgumentName);
}; // System.DateTimeResult
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(System::DateTimeResult, "System", "DateTimeResult");
#pragma pack(pop)
| 43.55102 | 862 | 0.714855 |
85930680ecaf000349ed02a841828353c188a384 | 10,830 | cc | C++ | Third-party/Sokol/src/d3d11/imgui-d3d11.cc | VLiance/Demos | fa8435c2fa0f46e1324a71501fdf646326936148 | [
"Unlicense"
] | null | null | null | Third-party/Sokol/src/d3d11/imgui-d3d11.cc | VLiance/Demos | fa8435c2fa0f46e1324a71501fdf646326936148 | [
"Unlicense"
] | null | null | null | Third-party/Sokol/src/d3d11/imgui-d3d11.cc | VLiance/Demos | fa8435c2fa0f46e1324a71501fdf646326936148 | [
"Unlicense"
] | null | null | null | //------------------------------------------------------------------------------
// imgui-d3d11.cc
// Dear ImGui integration sample with D3D11 backend.
//------------------------------------------------------------------------------
#include "d3d11entry.h"
#define SOKOL_IMPL
#define SOKOL_D3D11
#define SOKOL_D3D11_SHADER_COMPILER
#define SOKOL_LOG(s) OutputDebugStringA(s)
#include "sokol_gfx.h"
#include "sokol_time.h"
#include "imgui.h"
const int Width = 1024;
const int Height = 768;
const int MaxVertices = (1<<16);
const int MaxIndices = MaxVertices * 3;
uint64_t last_time = 0;
bool show_test_window = true;
bool show_another_window = false;
sg_draw_state draw_state = { };
sg_pass_action pass_action = { };
ImDrawVert vertices[MaxVertices];
uint16_t indices[MaxIndices];
typedef struct {
ImVec2 disp_size;
} vs_params_t;
void imgui_draw_cb(ImDrawData*);
int WINAPI WinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) {
// setup d3d11 app wrapper, sokol_gfx, sokol_time
d3d11_init(Width, Height, 1, L"Sokol Dear ImGui D3D11");
sg_desc desc = { };
desc.d3d11_device = d3d11_device();
desc.d3d11_device_context = d3d11_device_context();
desc.d3d11_render_target_view_cb = d3d11_render_target_view;
desc.d3d11_depth_stencil_view_cb = d3d11_depth_stencil_view;
sg_setup(&desc);
stm_setup();
// input forwarding
d3d11_mouse_pos([] (float x, float y) { ImGui::GetIO().MousePos = ImVec2(x, y); });
d3d11_mouse_btn_down([] (int btn) { ImGui::GetIO().MouseDown[btn] = true; });
d3d11_mouse_btn_up([] (int btn) { ImGui::GetIO().MouseDown[btn] = false; });
d3d11_mouse_wheel([](float v) { ImGui::GetIO().MouseWheel = v; });
d3d11_char([] (wchar_t c) { ImGui::GetIO().AddInputCharacter(c); });
d3d11_key_down([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = true; });
d3d11_key_up([] (int key) { if (key < 512) ImGui::GetIO().KeysDown[key] = false; });
// setup Dear Imgui
ImGui::CreateContext();
ImGui::StyleColorsDark();
ImGuiIO& io = ImGui::GetIO();
io.IniFilename = nullptr;
io.RenderDrawListsFn = imgui_draw_cb;
io.Fonts->AddFontDefault();
io.KeyMap[ImGuiKey_Tab] = VK_TAB;
io.KeyMap[ImGuiKey_LeftArrow] = VK_LEFT;
io.KeyMap[ImGuiKey_RightArrow] = VK_RIGHT;
io.KeyMap[ImGuiKey_UpArrow] = VK_UP;
io.KeyMap[ImGuiKey_DownArrow] = VK_DOWN;
io.KeyMap[ImGuiKey_Home] = VK_HOME;
io.KeyMap[ImGuiKey_End] = VK_END;
io.KeyMap[ImGuiKey_Delete] = VK_DELETE;
io.KeyMap[ImGuiKey_Backspace] = VK_BACK;
io.KeyMap[ImGuiKey_Enter] = VK_RETURN;
io.KeyMap[ImGuiKey_Escape] = VK_ESCAPE;
io.KeyMap[ImGuiKey_A] = 'A';
io.KeyMap[ImGuiKey_C] = 'C';
io.KeyMap[ImGuiKey_V] = 'V';
io.KeyMap[ImGuiKey_X] = 'X';
io.KeyMap[ImGuiKey_Y] = 'Y';
io.KeyMap[ImGuiKey_Z] = 'Z';
// dynamic vertex- and index-buffers for imgui-generated geometry
sg_buffer_desc vbuf_desc = { };
vbuf_desc.usage = SG_USAGE_STREAM;
vbuf_desc.size = sizeof(vertices);
draw_state.vertex_buffers[0] = sg_make_buffer(&vbuf_desc);
sg_buffer_desc ibuf_desc = { };
ibuf_desc.type = SG_BUFFERTYPE_INDEXBUFFER;
ibuf_desc.usage = SG_USAGE_STREAM;
ibuf_desc.size = sizeof(indices);
draw_state.index_buffer = sg_make_buffer(&ibuf_desc);
// font texture for imgui's default font
unsigned char* font_pixels;
int font_width, font_height;
io.Fonts->GetTexDataAsRGBA32(&font_pixels, &font_width, &font_height);
sg_image_desc img_desc = { };
img_desc.width = font_width;
img_desc.height = font_height;
img_desc.pixel_format = SG_PIXELFORMAT_RGBA8;
img_desc.wrap_u = SG_WRAP_CLAMP_TO_EDGE;
img_desc.wrap_v = SG_WRAP_CLAMP_TO_EDGE;
img_desc.content.subimage[0][0].ptr = font_pixels;
img_desc.content.subimage[0][0].size = font_width * font_height * 4;
draw_state.fs_images[0] = sg_make_image(&img_desc);
// shader object for imgui rendering
sg_shader_desc shd_desc = { };
auto& ub = shd_desc.vs.uniform_blocks[0];
ub.size = sizeof(vs_params_t);
shd_desc.vs.source =
"cbuffer params {\n"
" float2 disp_size;\n"
"};\n"
"struct vs_in {\n"
" float2 pos: POSITION;\n"
" float2 uv: TEXCOORD0;\n"
" float4 color: COLOR0;\n"
"};\n"
"struct vs_out {\n"
" float2 uv: TEXCOORD0;\n"
" float4 color: COLOR0;\n"
" float4 pos: SV_Position;\n"
"};\n"
"vs_out main(vs_in inp) {\n"
" vs_out outp;\n"
" outp.pos = float4(((inp.pos/disp_size)-0.5)*float2(2.0,-2.0), 0.5, 1.0);\n"
" outp.uv = inp.uv;\n"
" outp.color = inp.color;\n"
" return outp;\n"
"}\n";
shd_desc.fs.images[0].type = SG_IMAGETYPE_2D;
shd_desc.fs.source =
"Texture2D<float4> tex: register(t0);\n"
"sampler smp: register(s0);\n"
"float4 main(float2 uv: TEXCOORD0, float4 color: COLOR0): SV_Target0 {\n"
" return tex.Sample(smp, uv) * color;\n"
"}\n";
sg_shader shd = sg_make_shader(&shd_desc);
// pipeline object for imgui rendering
sg_pipeline_desc pip_desc = { };
pip_desc.layout.buffers[0].stride = sizeof(ImDrawVert);
auto& attrs = pip_desc.layout.attrs;
attrs[0].sem_name="POSITION"; attrs[0].offset=offsetof(ImDrawVert, pos); attrs[0].format=SG_VERTEXFORMAT_FLOAT2;
attrs[1].sem_name="TEXCOORD"; attrs[1].offset=offsetof(ImDrawVert, uv); attrs[1].format=SG_VERTEXFORMAT_FLOAT2;
attrs[2].sem_name="COLOR"; attrs[2].offset=offsetof(ImDrawVert, col); attrs[2].format=SG_VERTEXFORMAT_UBYTE4N;
pip_desc.shader = shd;
pip_desc.index_type = SG_INDEXTYPE_UINT16;
pip_desc.blend.enabled = true;
pip_desc.blend.src_factor_rgb = SG_BLENDFACTOR_SRC_ALPHA;
pip_desc.blend.dst_factor_rgb = SG_BLENDFACTOR_ONE_MINUS_SRC_ALPHA;
pip_desc.blend.color_write_mask = SG_COLORMASK_RGB;
draw_state.pipeline = sg_make_pipeline(&pip_desc);
// initial clear color
pass_action.colors[0].action = SG_ACTION_CLEAR;
pass_action.colors[0].val[0] = 0.0f;
pass_action.colors[0].val[1] = 0.5f;
pass_action.colors[0].val[2] = 0.7f;
pass_action.colors[0].val[3] = 1.0f;
// draw loop
while (d3d11_process_events()) {
const int cur_width = d3d11_width();
const int cur_height = d3d11_height();
// this is standard ImGui demo code
ImGuiIO& io = ImGui::GetIO();
io.DisplaySize = ImVec2(float(cur_width), float(cur_height));
io.DeltaTime = (float) stm_sec(stm_laptime(&last_time));
ImGui::NewFrame();
// 1. Show a simple window
// Tip: if we don't call ImGui::Begin()/ImGui::End() the widgets appears in a window automatically called "Debug"
static float f = 0.0f;
ImGui::Text("Hello, world!");
ImGui::SliderFloat("float", &f, 0.0f, 1.0f);
ImGui::ColorEdit3("clear color", &pass_action.colors[0].val[0]);
if (ImGui::Button("Test Window")) show_test_window ^= 1;
if (ImGui::Button("Another Window")) show_another_window ^= 1;
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
// 2. Show another simple window, this time using an explicit Begin/End pair
if (show_another_window) {
ImGui::SetNextWindowSize(ImVec2(200,100), ImGuiSetCond_FirstUseEver);
ImGui::Begin("Another Window", &show_another_window);
ImGui::Text("Hello");
ImGui::End();
}
// 3. Show the ImGui test window. Most of the sample code is in ImGui::ShowTestWindow()
if (show_test_window) {
ImGui::SetNextWindowPos(ImVec2(460, 20), ImGuiSetCond_FirstUseEver);
ImGui::ShowTestWindow();
}
// the sokol_gfx draw pass
sg_begin_default_pass(&pass_action, cur_width, cur_height);
ImGui::Render();
sg_end_pass();
sg_commit();
d3d11_present();
}
ImGui::DestroyContext();
sg_shutdown();
d3d11_shutdown();
}
// imgui draw callback
void imgui_draw_cb(ImDrawData* draw_data) {
assert(draw_data);
if (draw_data->CmdListsCount == 0) {
return;
}
// copy vertices and indices
int num_vertices = 0;
int num_indices = 0;
int num_cmdlists = 0;
for (num_cmdlists = 0; num_cmdlists < draw_data->CmdListsCount; num_cmdlists++) {
const ImDrawList* cl = draw_data->CmdLists[num_cmdlists];
const int cl_num_vertices = cl->VtxBuffer.size();
const int cl_num_indices = cl->IdxBuffer.size();
// overflow check
if ((num_vertices + cl_num_vertices) > MaxVertices) {
break;
}
if ((num_indices + cl_num_indices) > MaxIndices) {
break;
}
// copy vertices
memcpy(&vertices[num_vertices], &cl->VtxBuffer.front(), cl_num_vertices*sizeof(ImDrawVert));
// copy indices, need to 'rebase' indices to start of global vertex buffer
const ImDrawIdx* src_index_ptr = &cl->IdxBuffer.front();
const uint16_t base_vertex_index = num_vertices;
for (int i = 0; i < cl_num_indices; i++) {
indices[num_indices++] = src_index_ptr[i] + base_vertex_index;
}
num_vertices += cl_num_vertices;
}
// update vertex and index buffers
const int vertex_data_size = num_vertices * sizeof(ImDrawVert);
const int index_data_size = num_indices * sizeof(uint16_t);
sg_update_buffer(draw_state.vertex_buffers[0], vertices, vertex_data_size);
sg_update_buffer(draw_state.index_buffer, indices, index_data_size);
// render the command list
vs_params_t vs_params;
vs_params.disp_size = ImGui::GetIO().DisplaySize;
sg_apply_draw_state(&draw_state);
sg_apply_uniform_block(SG_SHADERSTAGE_VS, 0, &vs_params, sizeof(vs_params));
int base_element = 0;
for (int cl_index=0; cl_index<num_cmdlists; cl_index++) {
const ImDrawList* cmd_list = draw_data->CmdLists[cl_index];
for (const ImDrawCmd& pcmd : cmd_list->CmdBuffer) {
if (pcmd.UserCallback) {
pcmd.UserCallback(cmd_list, &pcmd);
}
else {
const int sx = (int) pcmd.ClipRect.x;
const int sy = (int) pcmd.ClipRect.y;
const int sw = (int) (pcmd.ClipRect.z - pcmd.ClipRect.x);
const int sh = (int) (pcmd.ClipRect.w - pcmd.ClipRect.y);
sg_apply_scissor_rect(sx, sy, sw, sh, true);
sg_draw(base_element, pcmd.ElemCount, 1);
}
base_element += pcmd.ElemCount;
}
}
}
| 39.525547 | 130 | 0.637027 |
8594dcfafda4d2bda1e07bb9eb18ee8bd8228b10 | 2,771 | cpp | C++ | engine/RenderPipelineManager.cpp | shanysheng/orange3d | 9ee081a98e14fdeb3aaafd6bbb49fe027d4cd3c0 | [
"BSD-2-Clause"
] | 11 | 2017-06-06T17:22:30.000Z | 2022-03-23T11:56:49.000Z | engine/RenderPipelineManager.cpp | shanysheng/orange3d | 9ee081a98e14fdeb3aaafd6bbb49fe027d4cd3c0 | [
"BSD-2-Clause"
] | null | null | null | engine/RenderPipelineManager.cpp | shanysheng/orange3d | 9ee081a98e14fdeb3aaafd6bbb49fe027d4cd3c0 | [
"BSD-2-Clause"
] | 5 | 2018-02-07T02:48:59.000Z | 2021-08-23T05:16:59.000Z | #include "RenderPipelineManager.h"
namespace pipeline{
CRenderPipelineManager::CRenderPipelineManager():m_pRenderingEngine(NULL)
{
}
CRenderPipelineManager::~CRenderPipelineManager()
{
ClearRenderPipeline();
ClearPrototypes();
}
IRenderPipeline*CRenderPipelineManager::Give( const std::string& Name, const std::string& PrototypeName )
{
std::unordered_map< std::string, IRenderPipeline *>::iterator pos;
pos = m_RenderPipelines.find(Name);
if (pos!=m_RenderPipelines.end())
{
return pos->second;
}
pos = m_Prototypes.find(PrototypeName);
if (pos!=m_Prototypes.end())
{
IRenderPipeline* pRenderPipeline = pos->second->Clone();
pRenderPipeline->SetContext(this->m_pRenderingEngine);
m_RenderPipelines.insert(std::make_pair(Name, pRenderPipeline));
return pRenderPipeline;
}
return NULL;
}
void CRenderPipelineManager::Register(const std::string& PrototypeName, IRenderPipeline * pPrototype )
{
std::unordered_map< std::string, IRenderPipeline *>::iterator pos;
pos = m_Prototypes.find(PrototypeName);
if (pos!=m_Prototypes.end())
{
if (pos->second)
delete pos->second;
pos->second = pPrototype;
return ;
}
m_Prototypes.insert(std::make_pair(PrototypeName, pPrototype));
}
IRenderPipeline * CRenderPipelineManager::operator [](const std::string& Name)
{
std::unordered_map< std::string, IRenderPipeline *>::iterator pos;
pos = m_RenderPipelines.find(Name);
if(pos == m_RenderPipelines.end())
return NULL;
return pos->second;
}
void CRenderPipelineManager::ClearPrototypes()
{
std::unordered_map< std::string, IRenderPipeline *>::iterator pos;
pos = m_Prototypes.begin();
while (pos!=m_Prototypes.end())
{
if (pos->second)
delete pos->second;
++pos;
}
m_Prototypes.clear();
}
void CRenderPipelineManager::ClearRenderPipeline()
{
std::unordered_map< std::string, IRenderPipeline *>::iterator pos;
pos = m_RenderPipelines.begin();
while (pos!=m_RenderPipelines.end())
{
if (pos->second)
delete pos->second;
++pos;
}
m_RenderPipelines.clear();
}
CRenderModuleManager& CRenderPipelineManager::GetRenderModuleManager()
{
return m_RenderModuleMgr;
}
}
| 27.71 | 109 | 0.568748 |
859d147d58d8cc6943a7c3f9494e518edaee6312 | 369 | cpp | C++ | Algorithms/1759.Count_Number_of_Homogenous_Substrings.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/1759.Count_Number_of_Homogenous_Substrings.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/1759.Count_Number_of_Homogenous_Substrings.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
const int MOD = (int) 1e9 + 7;
int countHomogenous(string s) {
long long ans = 0;
int n = s.length();
for( int i = 0 , j = 0 ; i < n ; i = j ) {
while(j < n && s[i] == s[j])
j++;
long long k = j-i;
ans += k*(k+1)/2;
}
return ans % MOD;
}
}; | 24.6 | 50 | 0.382114 |
859ed42fd82392c56c62d3d4b1c29d87fb390c43 | 24,351 | cpp | C++ | ugene/src/plugins_3rdparty/primer3/src/Primer3Task.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins_3rdparty/primer3/src/Primer3Task.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins_3rdparty/primer3/src/Primer3Task.cpp | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | /**
* UGENE - Integrated Bioinformatics Tools.
* Copyright (C) 2008-2012 UniPro <ugene@unipro.ru>
* http://ugene.unipro.ru
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#include <cstdlib>
#include <U2Core/AppContext.h>
#include <U2Core/Counter.h>
#include <U2Core/SequenceWalkerTask.h>
#include <U2Core/CreateAnnotationTask.h>
#include "primer3_main.h"
#include "boulder_input.h"
#include "Primer3Task.h"
namespace U2 {
// Primer
Primer::Primer():
start(0),
length(0),
meltingTemperature(0),
gcContent(0),
selfAny(0),
selfEnd(0),
endStability(0)
{
}
Primer::Primer(const primer_rec &primerRec):
start(primerRec.start),
length(primerRec.length),
meltingTemperature(primerRec.temp),
gcContent(primerRec.gc_content),
selfAny(primerRec.self_any),
selfEnd(primerRec.self_end),
endStability(primerRec.end_stability)
{
}
int Primer::getStart()const
{
return start;
}
int Primer::getLength()const
{
return length;
}
double Primer::getMeltingTemperature()const
{
return meltingTemperature;
}
double Primer::getGcContent()const
{
return gcContent;
}
short Primer::getSelfAny()const
{
return selfAny;
}
short Primer::getSelfEnd()const
{
return selfEnd;
}
double Primer::getEndStabilyty()const
{
return endStability;
}
void Primer::setStart(int start)
{
this->start = start;
}
void Primer::setLength(int length)
{
this->length = length;
}
void Primer::setMeltingTemperature(double meltingTemperature)
{
this->meltingTemperature = meltingTemperature;
}
void Primer::setGcContent(double gcContent)
{
this->gcContent = gcContent;
}
void Primer::setSelfAny(short selfAny)
{
this->selfAny = selfAny;
}
void Primer::setSelfEnd(short selfEnd)
{
this->selfEnd = selfEnd;
}
void Primer::setEndStability(double endStability)
{
this->endStability = endStability;
}
// PrimerPair
PrimerPair::PrimerPair():
leftPrimer(NULL),
rightPrimer(NULL),
internalOligo(NULL),
complAny(0),
complEnd(0),
productSize(0),
quality(0),
complMeasure(0)
{
}
PrimerPair::PrimerPair(const primer_pair &primerPair, int offset):
leftPrimer((NULL == primerPair.left)? NULL:new Primer(*primerPair.left)),
rightPrimer((NULL == primerPair.right)? NULL:new Primer(*primerPair.right)),
internalOligo((NULL == primerPair.intl)? NULL:new Primer(*primerPair.intl)),
complAny(primerPair.compl_any),
complEnd(primerPair.compl_end),
productSize(primerPair.product_size),
quality(primerPair.pair_quality),
complMeasure(primerPair.compl_measure)
{
if(NULL != leftPrimer.get())
{
leftPrimer->setStart(leftPrimer->getStart() + offset);
}
if(NULL != rightPrimer.get())
{
rightPrimer->setStart(rightPrimer->getStart() + offset);
}
if(NULL != internalOligo.get())
{
internalOligo->setStart(internalOligo->getStart() + offset);
}
}
PrimerPair::PrimerPair(const PrimerPair &primerPair):
leftPrimer((NULL == primerPair.leftPrimer.get())? NULL:new Primer(*primerPair.leftPrimer)),
rightPrimer((NULL == primerPair.rightPrimer.get())? NULL:new Primer(*primerPair.rightPrimer)),
internalOligo((NULL == primerPair.internalOligo.get())? NULL:new Primer(*primerPair.internalOligo)),
complAny(primerPair.complAny),
complEnd(primerPair.complEnd),
productSize(primerPair.productSize),
quality(primerPair.quality),
complMeasure(primerPair.complMeasure)
{
}
const PrimerPair &PrimerPair::operator=(const PrimerPair &primerPair)
{
leftPrimer.reset((NULL == primerPair.leftPrimer.get())? NULL:new Primer(*primerPair.leftPrimer));
rightPrimer.reset((NULL == primerPair.rightPrimer.get())? NULL:new Primer(*primerPair.rightPrimer));
internalOligo.reset((NULL == primerPair.internalOligo.get())? NULL:new Primer(*primerPair.internalOligo));
complAny = primerPair.complAny;
complEnd = primerPair.complEnd;
productSize = primerPair.productSize;
quality = primerPair.quality;
complMeasure = primerPair.complMeasure;
return *this;
}
Primer *PrimerPair::getLeftPrimer()const
{
return leftPrimer.get();
}
Primer *PrimerPair::getRightPrimer()const
{
return rightPrimer.get();
}
Primer *PrimerPair::getInternalOligo()const
{
return internalOligo.get();
}
short PrimerPair::getComplAny()const
{
return complAny;
}
short PrimerPair::getComplEnd()const
{
return complEnd;
}
int PrimerPair::getProductSize()const
{
return productSize;
}
void PrimerPair::setLeftPrimer(Primer *leftPrimer)
{
this->leftPrimer.reset((NULL == leftPrimer)? NULL:new Primer(*leftPrimer));
}
void PrimerPair::setRightPrimer(Primer *rightPrimer)
{
this->rightPrimer.reset((NULL == rightPrimer)? NULL:new Primer(*rightPrimer));
}
void PrimerPair::setInternalOligo(Primer *internalOligo)
{
this->internalOligo.reset((NULL == internalOligo)? NULL:new Primer(*internalOligo));
}
void PrimerPair::setComplAny(short complAny)
{
this->complAny = complAny;
}
void PrimerPair::setComplEnd(short complEnd)
{
this->complEnd = complEnd;
}
void PrimerPair::setProductSize(int productSize)
{
this->productSize = productSize;
}
bool PrimerPair::operator<(const PrimerPair &pair)const
{
if(quality < pair.quality)
{
return true;
}
if(quality > pair.quality)
{
return false;
}
if (complMeasure < pair.complMeasure)
{
return true;
}
if (complMeasure > pair.complMeasure)
{
return false;
}
if(leftPrimer->getStart() > pair.leftPrimer->getStart())
{
return true;
}
if(leftPrimer->getStart() < pair.leftPrimer->getStart())
{
return false;
}
if(rightPrimer->getStart() < pair.rightPrimer->getStart())
{
return true;
}
if(rightPrimer->getStart() > pair.rightPrimer->getStart())
{
return false;
}
if(leftPrimer->getLength() < pair.leftPrimer->getLength())
{
return true;
}
if(leftPrimer->getLength() > pair.leftPrimer->getLength())
{
return false;
}
if(rightPrimer->getLength() < pair.rightPrimer->getLength())
{
return true;
}
if(rightPrimer->getLength() > pair.rightPrimer->getLength())
{
return false;
}
return false;
}
// Primer3Task
namespace
{
bool clipRegion(QPair<int, int> ®ion, const QPair<int, int> &clippingRegion)
{
int start = region.first;
int end = region.first + region.second;
start = qMax(start, clippingRegion.first);
end = qMin(end, clippingRegion.first + clippingRegion.second);
if(start > end)
{
return false;
}
region.first = start;
region.second = end - start;
return true;
}
}
Primer3Task::Primer3Task(const Primer3TaskSettings &settingsArg):
Task(tr("Pick primers task"), TaskFlag_ReportingIsEnabled),
settings(settingsArg)
{
GCOUNTER( cvar, tvar, "Primer3Task" );
{
QPair<int, int> region = settings.getIncludedRegion();
region.first -= settings.getFirstBaseIndex();
settings.setIncludedRegion(region);
}
offset = settings.getIncludedRegion().first;
settings.setSequence(settings.getSequence().mid(
settings.getIncludedRegion().first, settings.getIncludedRegion().second));
settings.setSequenceQuality(settings.getSequenceQuality().mid(
settings.getIncludedRegion().first, settings.getIncludedRegion().second));
settings.setIncludedRegion(qMakePair(0, settings.getIncludedRegion().second));
if(!PR_START_CODON_POS_IS_NULL(settings.getSeqArgs()))
{
int startCodonPosition = PR_DEFAULT_START_CODON_POS;
if(settings.getIntProperty("PRIMER_START_CODON_POSITION", &startCodonPosition))
{
settings.setIntProperty("PRIMER_START_CODON_POSITION",
startCodonPosition - settings.getFirstBaseIndex());
}
}
{
QList<QPair<int, int> > regionList;
QPair<int, int> region;
foreach(region, settings.getTarget())
{
region.first -= settings.getFirstBaseIndex();
region.first -= offset;
if(clipRegion(region, settings.getIncludedRegion()))
{
regionList.append(region);
}
}
settings.setTarget(regionList);
}
{
QList<QPair<int, int> > regionList;
QPair<int, int> region;
foreach(region, settings.getExcludedRegion())
{
region.first -= settings.getFirstBaseIndex();
region.first -= offset;
if(clipRegion(region, settings.getIncludedRegion()))
{
regionList.append(region);
}
}
settings.setExcludedRegion(regionList);
}
{
QList<QPair<int, int> > regionList;
QPair<int, int> region;
foreach(region, settings.getInternalOligoExcludedRegion())
{
region.first -= settings.getFirstBaseIndex();
region.first -= offset;
if(clipRegion(region, settings.getIncludedRegion()))
{
regionList.append(region);
}
}
settings.setInternalOligoExcludedRegion(regionList);
}
}
void Primer3Task::run()
{
if(!settings.getRepeatLibrary().isEmpty())
{
read_seq_lib(&settings.getPrimerArgs()->repeat_lib, settings.getRepeatLibrary().constData(), "mispriming library");
if(NULL != settings.getPrimerArgs()->repeat_lib.error.data)
{
pr_append_new_chunk(&settings.getPrimerArgs()->glob_err, settings.getPrimerArgs()->repeat_lib.error.data);
pr_append_new_chunk(&settings.getSeqArgs()->error, settings.getPrimerArgs()->repeat_lib.error.data);
return;
}
}
if(!settings.getMishybLibrary().isEmpty())
{
read_seq_lib(&settings.getPrimerArgs()->io_mishyb_library, settings.getMishybLibrary().constData(), "internal oligo mishyb library");
if(NULL != settings.getPrimerArgs()->io_mishyb_library.error.data)
{
pr_append_new_chunk(&settings.getPrimerArgs()->glob_err, settings.getPrimerArgs()->io_mishyb_library.error.data);
pr_append_new_chunk(&settings.getSeqArgs()->error, settings.getPrimerArgs()->io_mishyb_library.error.data);
return;
}
}
primers_t primers = runPrimer3(settings.getPrimerArgs(), settings.getSeqArgs(), &stateInfo.cancelFlag, &stateInfo.progress);
bestPairs.clear();
for(int index = 0;index < primers.best_pairs.num_pairs;index++)
{
bestPairs.append(PrimerPair(primers.best_pairs.pairs[index], offset));
}
if(primers.best_pairs.num_pairs > 0)
{
std::free(primers.best_pairs.pairs);
primers.best_pairs.pairs = NULL;
}
if(NULL != primers.left)
{
std::free(primers.left);
primers.left = NULL;
}
if(NULL != primers.right)
{
std::free(primers.right);
primers.right = NULL;
}
if(NULL != primers.intl)
{
std::free(primers.intl);
primers.intl = NULL;
}
}
Task::ReportResult Primer3Task::report()
{
if(!settings.getError().isEmpty())
{
stateInfo.setError(settings.getError());
}
return Task::ReportResult_Finished;
}
void Primer3Task::sumStat(Primer3TaskSettings *st) {
st->getSeqArgs()->left_expl.considered += settings.getSeqArgs()->left_expl.considered;
st->getSeqArgs()->left_expl.ns += settings.getSeqArgs()->left_expl.ns;
st->getSeqArgs()->left_expl.target += settings.getSeqArgs()->left_expl.target;
st->getSeqArgs()->left_expl.excluded += settings.getSeqArgs()->left_expl.excluded;
st->getSeqArgs()->left_expl.gc += settings.getSeqArgs()->left_expl.gc;
st->getSeqArgs()->left_expl.gc_clamp += settings.getSeqArgs()->left_expl.gc_clamp;
st->getSeqArgs()->left_expl.temp_min += settings.getSeqArgs()->left_expl.temp_min;
st->getSeqArgs()->left_expl.temp_max += settings.getSeqArgs()->left_expl.temp_max;
st->getSeqArgs()->left_expl.compl_any += settings.getSeqArgs()->left_expl.compl_any;
st->getSeqArgs()->left_expl.compl_end += settings.getSeqArgs()->left_expl.compl_end;
st->getSeqArgs()->left_expl.poly_x += settings.getSeqArgs()->left_expl.poly_x;
st->getSeqArgs()->left_expl.stability += settings.getSeqArgs()->left_expl.stability;
st->getSeqArgs()->left_expl.ok += settings.getSeqArgs()->left_expl.ok;
st->getSeqArgs()->right_expl.considered += settings.getSeqArgs()->right_expl.considered;
st->getSeqArgs()->right_expl.ns += settings.getSeqArgs()->right_expl.ns;
st->getSeqArgs()->right_expl.target += settings.getSeqArgs()->right_expl.target;
st->getSeqArgs()->right_expl.excluded += settings.getSeqArgs()->right_expl.excluded;
st->getSeqArgs()->right_expl.gc += settings.getSeqArgs()->right_expl.gc;
st->getSeqArgs()->right_expl.gc_clamp += settings.getSeqArgs()->right_expl.gc_clamp;
st->getSeqArgs()->right_expl.temp_min += settings.getSeqArgs()->right_expl.temp_min;
st->getSeqArgs()->right_expl.temp_max += settings.getSeqArgs()->right_expl.temp_max;
st->getSeqArgs()->right_expl.compl_any += settings.getSeqArgs()->right_expl.compl_any;
st->getSeqArgs()->right_expl.compl_end += settings.getSeqArgs()->right_expl.compl_end;
st->getSeqArgs()->right_expl.poly_x += settings.getSeqArgs()->right_expl.poly_x;
st->getSeqArgs()->right_expl.stability += settings.getSeqArgs()->right_expl.stability;
st->getSeqArgs()->right_expl.ok += settings.getSeqArgs()->right_expl.ok;
st->getSeqArgs()->pair_expl.considered += settings.getSeqArgs()->pair_expl.considered;
st->getSeqArgs()->pair_expl.product += settings.getSeqArgs()->pair_expl.product;
st->getSeqArgs()->pair_expl.compl_end += settings.getSeqArgs()->pair_expl.compl_end;
st->getSeqArgs()->pair_expl.ok += settings.getSeqArgs()->pair_expl.ok;
}
QList<PrimerPair> Primer3Task::getBestPairs()const
{
return bestPairs;
}
// Primer3SWTask
Primer3SWTask::Primer3SWTask(const Primer3TaskSettings &settingsArg):
Task("Pick primers SW task", TaskFlags_NR_FOSCOE),
settings(settingsArg)
{
setMaxParallelSubtasks(MAX_PARALLEL_SUBTASKS_AUTO);
}
void Primer3SWTask::prepare()
{
if((settings.getIncludedRegion().first < settings.getFirstBaseIndex()) ||
(settings.getIncludedRegion().second <= 0) ||
(settings.getIncludedRegion().first + settings.getIncludedRegion().second >
settings.getSequence().size() + settings.getFirstBaseIndex()))
{
setError("invalid included region");
return;
}
QVector<U2Region> regions = SequenceWalkerTask::splitRange(
U2Region(settings.getIncludedRegion().first, settings.getIncludedRegion().second),
CHUNK_SIZE, 0, CHUNK_SIZE/2, false);
foreach(U2Region region, regions)
{
Primer3TaskSettings regionSettings = settings;
regionSettings.setIncludedRegion(qMakePair((int)region.startPos, (int)region.length));
Primer3Task *task = new Primer3Task(regionSettings);
regionTasks.append(task);
addSubTask(task);
}
}
Task::ReportResult Primer3SWTask::report()
{
foreach(Primer3Task *task, regionTasks)
{
bestPairs.append(task->getBestPairs());
}
if(regionTasks.size() > 1)
{
qStableSort(bestPairs);
int pairsCount = 0;
if(!settings.getIntProperty("PRIMER_NUM_RETURN", &pairsCount))
{
setError("can't get PRIMER_NUM_RETURN property");
return Task::ReportResult_Finished;
}
bestPairs = bestPairs.mid(0, pairsCount);
}
return Task::ReportResult_Finished;
}
QList<PrimerPair> Primer3SWTask::getBestPairs()const
{
return bestPairs;
}
//////////////////////////////////////////////////////////////////////////
////Primer3ToAnnotationsTask
Primer3ToAnnotationsTask::Primer3ToAnnotationsTask( const Primer3TaskSettings &settings, U2SequenceObject* so_,
AnnotationTableObject * aobj_, const QString & groupName_, const QString & annName_ ) :
Task(tr("Search primers to annotations"), /*TaskFlags_NR_FOSCOE*/TaskFlags(TaskFlag_NoRun) | TaskFlag_ReportingIsSupported | TaskFlag_ReportingIsEnabled | TaskFlag_FailOnSubtaskError),
settings(settings), seqObj(so_), aobj(aobj_),
groupName(groupName_), annName(annName_), searchTask(NULL), findExonsTask(NULL)
{
}
void Primer3ToAnnotationsTask::prepare()
{
if (settings.getSpanIntronExonBoundarySettings().enabled) {
findExonsTask = new FindExonRegionsTask(seqObj,settings.getSpanIntronExonBoundarySettings().mRnaSeqId);
addSubTask(findExonsTask);
} else {
searchTask = new Primer3SWTask(settings);
addSubTask(searchTask);
}
}
QList<Task *> Primer3ToAnnotationsTask::onSubTaskFinished(Task *subTask)
{
QList<Task*> res;
if (isCanceled() || hasError()) {
return res;
}
if (!subTask->isFinished()) {
return res;
}
if (subTask == findExonsTask) {
QList<U2Region> regions = findExonsTask->getRegions();
if (regions.isEmpty()) {
setError(tr("No exons are found in the sequence. Please, make sure corresponding RNA sequence id (%1) is selected correctly."));
return res;
}
// TODO: think how to include other regions
const U2Region& firstRegion = regions.first();
int intronStart = firstRegion.endPos() - settings.getSpanIntronExonBoundarySettings().minLeftOverlap;
int intronEnd = firstRegion.endPos() + settings.getSpanIntronExonBoundarySettings().minRightOverlap;
if (regions.size() > 1 || settings.getSpanIntronExonBoundarySettings().spanIntron) {
const U2Region& secondRegion = regions.at(1);
intronEnd = secondRegion.startPos + settings.getSpanIntronExonBoundarySettings().minRightOverlap;
}
QList<QPair<int,int> > targets = settings.getTarget();
targets.append(QPair<int,int>(intronStart,intronEnd));
settings.setTarget(targets);
searchTask = new Primer3SWTask(settings);
res.append(searchTask);
}
return res;
}
QString Primer3ToAnnotationsTask::generateReport() const {
QString res;
if (hasError() || isCanceled()) {
return res;
}
foreach(Primer3Task *t, searchTask->regionTasks) {
t->sumStat(&searchTask->settings);
}
oligo_stats leftStats = searchTask->settings.getSeqArgs()->left_expl;
oligo_stats rightStats = searchTask->settings.getSeqArgs()->right_expl;
pair_stats pairStats = searchTask->settings.getSeqArgs()->pair_expl;
if(!leftStats.considered) {
leftStats.considered = leftStats.ns + leftStats.target + leftStats.excluded + leftStats.gc + leftStats.gc_clamp + leftStats.temp_min
+ leftStats.temp_max + leftStats.compl_any + leftStats.compl_end + leftStats.poly_x + leftStats.stability + leftStats.ok;
}
if(!rightStats.considered) {
rightStats.considered = rightStats.ns + rightStats.target + rightStats.excluded + rightStats.gc + rightStats.gc_clamp + rightStats.temp_min
+ rightStats.temp_max + rightStats.compl_any + rightStats.compl_end + rightStats.poly_x + rightStats.stability + rightStats.ok;
}
res+="<table cellspacing='7'>";
res += "<tr><th>Statistics</th></tr>\n";
res += QString("<tr><th></th> <th>con</th> <th>too</th> <th>in</th> <th>in</th> <th></th> <th>no</th> <th>tm</th> <th>tm</th> <th>high</th> <th>high</th> <th></th> <th>high</th> <th></th></tr>");
res += QString("<tr><th></th> <th>sid</th> <th>many</th> <th>tar</th> <th>excl</th> <th>bag</th> <th>GC</th> <th>too</th> <th>too</th> <th>any</th> <th>3'</th> <th>poly</th> <th>end</th> <th></th></tr>");
res += QString("<tr><th></th> <th>ered</th> <th>Ns</th> <th>get</th> <th>reg</th> <th>GC%</th> <th>clamp</th> <th>low</th> <th>high</th> <th>compl</th> <th>compl</th> <th>X</th> <th>stab</th> <th>ok</th></tr>");
res += QString("<tr><th>Left</th><th> %1 </th><th> %2 </th><th> %3 </th><th> %4 </th><th> %5 </th><th> %6 </th><th> %7 </th><th> %8 </th><th> %9 </th><th> %10 </th><th> %11 </th><th> %12 </th><th> %13 </th></tr>")
.arg(leftStats.considered).arg(leftStats.ns).arg(leftStats.target).arg(leftStats.excluded).arg(leftStats.gc).arg(leftStats.gc_clamp).arg(leftStats.temp_min).arg(leftStats.temp_max)
.arg(leftStats.compl_any).arg(leftStats.compl_end).arg(leftStats.poly_x).arg(leftStats.stability).arg(leftStats.ok);
res += QString("<tr><th>Right</th><th> %1 </th><th> %2 </th><th> %3 </th><th> %4 </th><th> %5 </th><th> %6 </th><th> %7 </th><th> %8 </th><th> %9 </th><th> %10 </th><th> %11 </th><th> %12 </th><th> %13 </th></tr>")
.arg(rightStats.considered).arg(rightStats.ns).arg(rightStats.target).arg(rightStats.excluded).arg(rightStats.gc).arg(rightStats.gc_clamp).arg(rightStats.temp_min).arg(rightStats.temp_max)
.arg(rightStats.compl_any).arg(rightStats.compl_end).arg(rightStats.poly_x).arg(rightStats.stability).arg(rightStats.ok);
res+="</table>";
res += "<br>Pair stats:<br>";
res += QString("considered %1, unacceptable product size %2, high end compl %3, ok %4.")
.arg(pairStats.considered).arg(pairStats.product).arg(pairStats.compl_end).arg(pairStats.ok);
return res;
}
Task::ReportResult Primer3ToAnnotationsTask::report()
{
if (hasError() || isCanceled()) {
return ReportResult_Finished;
}
assert( searchTask );
QList<PrimerPair> bestPairs = searchTask->getBestPairs();
int index = 0;
foreach(PrimerPair pair, bestPairs)
{
QList<SharedAnnotationData> annotations;
if(NULL != pair.getLeftPrimer())
{
annotations.append(oligoToAnnotation("primer", *pair.getLeftPrimer(), pair.getProductSize(), U2Strand::Direct));
}
if(NULL != pair.getInternalOligo())
{
annotations.append(oligoToAnnotation("internalOligo", *pair.getInternalOligo(), pair.getProductSize(), U2Strand::Direct));
}
if(NULL != pair.getRightPrimer())
{
annotations.append(oligoToAnnotation("primer", *pair.getRightPrimer(), pair.getProductSize(), U2Strand::Complementary));
}
AppContext::getTaskScheduler()->registerTopLevelTask(
new CreateAnnotationsTask(aobj, groupName + "/pair " + QString::number(index + 1), annotations));
index++;
}
return ReportResult_Finished;
}
SharedAnnotationData Primer3ToAnnotationsTask::oligoToAnnotation(QString title, const Primer &primer, int productSize, U2Strand strand)
{
SharedAnnotationData annotationData(new AnnotationData());
annotationData->name = title;
int start = primer.getStart();
int length = primer.getLength();
if (strand == U2Strand::Complementary) {
start -= length - 1;
}
annotationData->setStrand(strand);
annotationData->location->regions << U2Region(start, length);
annotationData->qualifiers.append(U2Qualifier("tm", QString::number(primer.getMeltingTemperature())));
annotationData->qualifiers.append(U2Qualifier("gc%", QString::number(primer.getGcContent())));
annotationData->qualifiers.append(U2Qualifier("any", QString::number(0.01*primer.getSelfAny())));
annotationData->qualifiers.append(U2Qualifier("3'", QString::number(0.01*primer.getSelfEnd())));
annotationData->qualifiers.append(U2Qualifier("product_size", QString::number(productSize)));
return annotationData;
}
} // namespace
| 33.727147 | 219 | 0.66909 |
85a18b33b0e57de1af303a5730d694bb85701870 | 1,751 | cpp | C++ | tightvnc/win-system/DynamicLibrary.cpp | jjzhang166/qmlvncviewer2 | b888c416ab88b81fe802ab0559bb87361833a0b5 | [
"Apache-2.0"
] | 47 | 2016-08-17T03:18:32.000Z | 2022-01-14T01:33:15.000Z | tightvnc/win-system/DynamicLibrary.cpp | jjzhang166/qmlvncviewer2 | b888c416ab88b81fe802ab0559bb87361833a0b5 | [
"Apache-2.0"
] | 3 | 2018-06-29T06:13:28.000Z | 2020-11-26T02:31:49.000Z | tightvnc/win-system/DynamicLibrary.cpp | jjzhang166/qmlvncviewer2 | b888c416ab88b81fe802ab0559bb87361833a0b5 | [
"Apache-2.0"
] | 15 | 2016-08-17T07:03:55.000Z | 2021-08-02T14:42:02.000Z | // Copyright (C) 2009,2010,2011,2012 GlavSoft LLC.
// All rights reserved.
//
//-------------------------------------------------------------------------
// This file is part of the TightVNC software. Please visit our Web site:
//
// http://www.tightvnc.com/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, write to the Free Software Foundation, Inc.,
// 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//-------------------------------------------------------------------------
//
#include "DynamicLibrary.h"
#include <crtdbg.h>
DynamicLibrary::DynamicLibrary(const TCHAR *filename)
: m_module(0)
{
init(filename);
}
DynamicLibrary::DynamicLibrary()
: m_module(0)
{
}
DynamicLibrary::~DynamicLibrary()
{
if (m_module != 0) {
FreeLibrary(m_module);
}
}
void DynamicLibrary::init(const TCHAR *filename)
{
m_module = LoadLibrary(filename);
if (m_module == 0) {
StringStorage errMsg;
errMsg.format(_T("%s library not found"), filename);
throw Exception(errMsg.getString());
}
}
FARPROC DynamicLibrary::getProcAddress(const char *procName)
{
_ASSERT(m_module != 0);
return ::GetProcAddress(m_module, procName);
}
| 26.530303 | 75 | 0.649343 |
85a1fb49cef5a8ebf25d907f3fcac85c57a5e1f9 | 1,999 | cpp | C++ | BattleTank/Source/BattleTank/Private/TankPlayerController.cpp | kahuunao/UE_BattleTank | 35cbb516fa4102508e3404370473f64ec5f5d77e | [
"Unlicense"
] | null | null | null | BattleTank/Source/BattleTank/Private/TankPlayerController.cpp | kahuunao/UE_BattleTank | 35cbb516fa4102508e3404370473f64ec5f5d77e | [
"Unlicense"
] | null | null | null | BattleTank/Source/BattleTank/Private/TankPlayerController.cpp | kahuunao/UE_BattleTank | 35cbb516fa4102508e3404370473f64ec5f5d77e | [
"Unlicense"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "TankPlayerController.h"
#include "Runtime/Engine/Classes/Engine/World.h"
void ATankPlayerController::BeginPlay()
{
Super::BeginPlay();
ATank* MyTank = GetTank();
if (!MyTank)
{
UE_LOG(LogTemp, Warning, TEXT("No Tank pawn controlled by the player"));
}
}
void ATankPlayerController::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
AimTowardsCrosshair();
}
ATank* ATankPlayerController::GetTank() const
{
return Cast<ATank>(GetPawn());
}
void ATankPlayerController::AimTowardsCrosshair()
{
if (!GetTank())
{
return;
}
FVector aimingPosition;
if (GetSightRayHitLocation(aimingPosition))
{
GetTank()->AimedAt(aimingPosition);
}
}
bool ATankPlayerController::GetSightRayHitLocation(FVector &OutHitLocation) const
{
// Get crosshair screen location
int32 screenWidth;
int32 screenHeight;
GetViewportSize(screenWidth, screenHeight);
FVector2D crosshairLocation = FVector2D(screenWidth * CrosshairXLocation, screenHeight* CrosshairYLocation);
// Get crosshair world position
FVector worldDirection;
if (GetLookDirection(crosshairLocation, worldDirection))
{
return GetLookLocation(worldDirection, OutHitLocation);
}
OutHitLocation = FVector::ZeroVector;
return false;
}
bool ATankPlayerController::GetLookDirection(FVector2D &pScreenPosition, FVector &OutWorldDirection) const
{
FVector cameraWorldLocation;
return DeprojectScreenPositionToWorld(pScreenPosition.X, pScreenPosition.Y, cameraWorldLocation, OutWorldDirection);
}
bool ATankPlayerController::GetLookLocation(FVector &pLookDirection, FVector &OutHitLocation) const
{
FVector start = PlayerCameraManager->GetCameraLocation();
FVector end = start + pLookDirection * LineTraceRange;
FHitResult hit;
if (GetWorld()->LineTraceSingleByChannel(hit, start, end, ECollisionChannel::ECC_Visibility))
{
OutHitLocation = hit.Location;
return true;
}
OutHitLocation = FVector::ZeroVector;
return false;
}
| 24.378049 | 117 | 0.781891 |
85a2fec098af9df8d734c08883b097b3b97ed746 | 4,462 | cpp | C++ | src/BlockOccupationDetector.cpp | pvanassen/BlockOccupationDetector | d427b415592d4c8e79d326b18661718f838c9d4d | [
"Apache-2.0"
] | null | null | null | src/BlockOccupationDetector.cpp | pvanassen/BlockOccupationDetector | d427b415592d4c8e79d326b18661718f838c9d4d | [
"Apache-2.0"
] | null | null | null | src/BlockOccupationDetector.cpp | pvanassen/BlockOccupationDetector | d427b415592d4c8e79d326b18661718f838c9d4d | [
"Apache-2.0"
] | null | null | null |
#include "BlockOccupationDetector.h"
BlockOccupationDetector::BlockOccupationDetector(byte pinA, byte pinB, byte pinC, byte pinRead) {
selectPinArray[0] = pinA;
selectPinArray[1] = pinB;
selectPinArray[2] = pinC;
this->pinRead = pinRead;
pinMode(pinA, OUTPUT);
pinMode(pinB, OUTPUT);
pinMode(pinC, OUTPUT);
pinMode(pinRead, INPUT);
if (debugStream == NULL) {
#ifdef BLOCKOCCUPATIONDETECTOR_DEBUG
exit(0);
#endif
}
}
BlockOccupationDetector::BlockOccupationDetector(byte pinA, byte pinB, byte pinC, byte pinRead,
void (*blockOccupied)(byte), void (*blockReleased)(byte)):
BlockOccupationDetector(pinA, pinB, pinC, pinRead) {
this->blockOccupied = blockOccupied;
this->blockReleased = blockReleased;
}
BlockOccupationDetector::BlockOccupationDetector(byte pinA, byte pinB, byte pinC, byte pinRead, Stream *debugStream):
BlockOccupationDetector(pinA, pinB, pinC, pinRead){
this->debugStream = debugStream;
}
BlockOccupationDetector::BlockOccupationDetector(byte pinA, byte pinB, byte pinC, byte pinRead, Stream *debugStream,
void (*blockOccupied)(byte), void (*blockReleased)(byte)):
BlockOccupationDetector(pinA, pinB, pinC, pinRead, debugStream) {
this->blockOccupied = blockOccupied;
this->blockReleased = blockReleased;
}
void BlockOccupationDetector::addDetector(byte detectorEnablePin) {
if (detectors > 0) {
pinEnable = (byte*) realloc(pinEnable, (detectors + 1) * sizeof(byte));
lastState = (bool**) realloc(lastState, (detectors + 1) * sizeof(bool[8]));
lastStateChange = (unsigned long**) realloc(lastStateChange, (detectors + 1) * sizeof(long[8]));
blockStates = (bool**) realloc(blockStates, (detectors + 1) * sizeof(bool[8]));
}
else {
pinEnable = (byte*) malloc((detectors + 1) * sizeof(byte));
lastState = (bool**) malloc((detectors + 1) * sizeof(bool[8]));
lastStateChange = (unsigned long**) malloc((detectors + 1) * sizeof(long[8]));
blockStates = (bool**) malloc((detectors + 1) * sizeof(bool[8]));
}
pinEnable[detectors] = detectorEnablePin;
pinMode(detectorEnablePin, OUTPUT);
digitalWrite(detectorEnablePin, HIGH);
for (int i=0;i!=8;i++) {
lastState[detectors][i] = false;
lastStateChange[detectors][i] = 0;
blockStates[detectors][i] = false;
}
detectors++;
}
void BlockOccupationDetector::tick() {
now = millis();
if (block == 8) {
block = 0;
}
if (detector == detectors) {
detector = 0;
}
#ifdef BLOCKOCCUPATIONDETECTOR_DEBUG
debugStream->print("Checking block: ");
debugStream->print(block);
debugStream->print(", detector: ");
debugStream->println(detector);
#endif
for (int pin=0; pin<3; pin++) {
digitalWrite(selectPinArray[pin], block & (1<<pin) ? HIGH : LOW);
}
digitalWrite(pinEnable[detector], LOW);
lastBlock.changed = false;
int value = 0;
for (int sample=0;sample!=samples;sample++) {
value += analogRead(this->pinRead);
}
#ifdef BLOCKOCCUPATIONDETECTOR_DEBUG
debugStream->print("Value from analog read: ");
debugStream->println(value);
#endif
bool occupied = (value / samples) < 150;
if (lastState[detector][block] != occupied) {
lastStateChange[detector][block] = now;
lastState[detector][block] = occupied;
}
else if ((now - lastStateChange[detector][block]) > debounceDelay) {
if (blockStates[detector][block] != occupied) {
blockStates[detector][block] = occupied;
int absoluteBlock = (detector * 8) + block;
lastBlock.changed = true;
lastBlock.absoluteBlock = absoluteBlock;
lastBlock.occupied = occupied;
if (blockOccupied != NULL && blockReleased != NULL) {
if (occupied) {
blockOccupied(absoluteBlock);
} else {
blockReleased(absoluteBlock);
}
}
}
}
digitalWrite(pinEnable[detector], HIGH);
}
byte BlockOccupationDetector::firstAvailableSensor() {
return (detectors * 8);
}
bool* BlockOccupationDetector::getLastKnownStates() {
return (bool*)lastState;
} | 34.061069 | 117 | 0.613402 |
85a8a6b10f2ae79f6d883c916966b6b98a62618d | 1,506 | hpp | C++ | include/dish2/record/global_records_finalize.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 29 | 2019-02-04T02:39:52.000Z | 2022-01-28T10:06:26.000Z | include/dish2/record/global_records_finalize.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 95 | 2020-02-22T19:48:14.000Z | 2021-09-14T19:17:53.000Z | include/dish2/record/global_records_finalize.hpp | mmore500/dishtiny | 9fcb52c4e56c74a4e17f7d577143ed40c158c92e | [
"MIT"
] | 6 | 2019-11-19T10:13:09.000Z | 2021-03-25T17:35:32.000Z | #pragma once
#ifndef DISH2_RECORD_GLOBAL_RECORDS_FINALIZE_HPP_INCLUDE
#define DISH2_RECORD_GLOBAL_RECORDS_FINALIZE_HPP_INCLUDE
#include <cstdlib>
#include "../../../third-party/conduit/include/uitsl/debug/err_verify.hpp"
#include "../../../third-party/conduit/include/uitsl/debug/list_cwd.hpp"
#include "../../../third-party/conduit/include/uitsl/mpi/audited_routines.hpp"
#include "../../../third-party/conduit/include/uitsl/mpi/comm_utils.hpp"
#include "finalize/finalize_artifacts.hpp"
#include "finalize/finalize_benchmarks.hpp"
#include "finalize/finalize_data.hpp"
#include "finalize/finalize_drawings.hpp"
#include "finalize/finalize_videos.hpp"
#include "finalize/finalize_zips.hpp"
#include "finalize/try_animate_frames.hpp"
#include "finalize/try_create_montage.hpp"
namespace dish2 {
void global_records_finalize() {
UITSL_Barrier( MPI_COMM_WORLD );
if ( uitsl::is_root() ) {
if ( dish2::cfg.ANIMATE_FRAMES() ) try_animate_frames();
if (
dish2::cfg.ALL_DRAWINGS_WRITE()
|| dish2::cfg.SELECTED_DRAWINGS().size()
) finalize_drawings();
finalize_artifacts();
finalize_benchmarks();
finalize_data();
finalize_videos();
finalize_zips();
#ifndef __EMSCRIPTEN__
// hash all files, excluding source directory
uitsl::err_verify( std::system( "tree --du -h" ) );
#else
uitsl::list_cwd();
#endif // #ifndef __EMSCRIPTEN__
}
}
} // namespace dish2
#endif // #ifndef DISH2_RECORD_GLOBAL_RECORDS_FINALIZE_HPP_INCLUDE
| 28.415094 | 78 | 0.731076 |
85a95df74baa0d5171c000bcde253f924c623d5d | 4,791 | hpp | C++ | contrib/autoboost/autoboost/mpl/aux_/logical_op.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 87 | 2015-01-18T00:43:06.000Z | 2022-02-11T17:40:50.000Z | contrib/autoboost/autoboost/mpl/aux_/logical_op.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 274 | 2015-01-03T04:50:49.000Z | 2021-03-08T09:01:09.000Z | contrib/autoboost/autoboost/mpl/aux_/logical_op.hpp | CaseyCarter/autowiring | 48e95a71308318c8ffb7ed1348e034fd9110f70c | [
"Apache-2.0"
] | 15 | 2015-09-30T20:58:43.000Z | 2020-12-19T21:24:56.000Z |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION!
#if !defined(AUTOBOOST_MPL_PREPROCESSING_MODE)
# include <autoboost/mpl/bool.hpp>
# include <autoboost/mpl/aux_/nested_type_wknd.hpp>
# include <autoboost/mpl/aux_/na_spec.hpp>
# include <autoboost/mpl/aux_/lambda_support.hpp>
#endif
#include <autoboost/mpl/limits/arity.hpp>
#include <autoboost/mpl/aux_/preprocessor/params.hpp>
#include <autoboost/mpl/aux_/preprocessor/ext_params.hpp>
#include <autoboost/mpl/aux_/preprocessor/def_params_tail.hpp>
#include <autoboost/mpl/aux_/preprocessor/enum.hpp>
#include <autoboost/mpl/aux_/preprocessor/sub.hpp>
#include <autoboost/mpl/aux_/config/ctps.hpp>
#include <autoboost/mpl/aux_/config/workaround.hpp>
#include <autoboost/preprocessor/dec.hpp>
#include <autoboost/preprocessor/inc.hpp>
#include <autoboost/preprocessor/cat.hpp>
namespace autoboost { namespace mpl {
# define AUX778076_PARAMS(param, sub) \
AUTOBOOST_MPL_PP_PARAMS( \
AUTOBOOST_MPL_PP_SUB(AUTOBOOST_MPL_LIMIT_METAFUNCTION_ARITY, sub) \
, param \
) \
/**/
# define AUX778076_SHIFTED_PARAMS(param, sub) \
AUTOBOOST_MPL_PP_EXT_PARAMS( \
2, AUTOBOOST_MPL_PP_SUB(AUTOBOOST_PP_INC(AUTOBOOST_MPL_LIMIT_METAFUNCTION_ARITY), sub) \
, param \
) \
/**/
# define AUX778076_SPEC_PARAMS(param) \
AUTOBOOST_MPL_PP_ENUM( \
AUTOBOOST_PP_DEC(AUTOBOOST_MPL_LIMIT_METAFUNCTION_ARITY) \
, param \
) \
/**/
namespace aux {
#if !defined(AUTOBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
template< bool C_, AUX778076_PARAMS(typename T, 1) >
struct AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)
: AUTOBOOST_PP_CAT(AUX778076_OP_VALUE1,_)
{
};
template< AUX778076_PARAMS(typename T, 1) >
struct AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)< AUX778076_OP_VALUE2,AUX778076_PARAMS(T, 1) >
: AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<
AUTOBOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
, AUX778076_SHIFTED_PARAMS(T, 1)
, AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_)
>
{
};
template<>
struct AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<
AUX778076_OP_VALUE2
, AUX778076_SPEC_PARAMS(AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_))
>
: AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_)
{
};
#else
template< bool C_ > struct AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)
{
template< AUX778076_PARAMS(typename T, 1) > struct result_
: AUTOBOOST_PP_CAT(AUX778076_OP_VALUE1,_)
{
};
};
template<> struct AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<AUX778076_OP_VALUE2>
{
template< AUX778076_PARAMS(typename T, 1) > struct result_
: AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<
AUTOBOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
>::template result_< AUX778076_SHIFTED_PARAMS(T,1),AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_) >
{
};
#if AUTOBOOST_WORKAROUND(AUTOBOOST_MSVC, == 1300)
template<> struct result_<AUX778076_SPEC_PARAMS(AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_))>
: AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_)
{
};
};
#else
};
template<>
struct AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<AUX778076_OP_VALUE2>
::result_< AUX778076_SPEC_PARAMS(AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_)) >
: AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_)
{
};
#endif // AUTOBOOST_MSVC == 1300
#endif // AUTOBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION
} // namespace aux
template<
typename AUTOBOOST_MPL_AUX_NA_PARAM(T1)
, typename AUTOBOOST_MPL_AUX_NA_PARAM(T2)
AUTOBOOST_MPL_PP_DEF_PARAMS_TAIL(2, typename T, AUTOBOOST_PP_CAT(AUX778076_OP_VALUE2,_))
>
struct AUX778076_OP_NAME
#if !defined(AUTOBOOST_NO_TEMPLATE_PARTIAL_SPECIALIZATION)
: aux::AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<
AUTOBOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
, AUX778076_SHIFTED_PARAMS(T,0)
>
#else
: aux::AUTOBOOST_PP_CAT(AUX778076_OP_NAME,impl)<
AUTOBOOST_MPL_AUX_NESTED_TYPE_WKND(T1)::value
>::template result_< AUX778076_SHIFTED_PARAMS(T,0) >
#endif
{
AUTOBOOST_MPL_AUX_LAMBDA_SUPPORT(
AUTOBOOST_MPL_LIMIT_METAFUNCTION_ARITY
, AUX778076_OP_NAME
, (AUX778076_PARAMS(T, 0))
)
};
AUTOBOOST_MPL_AUX_NA_SPEC2(
2
, AUTOBOOST_MPL_LIMIT_METAFUNCTION_ARITY
, AUX778076_OP_NAME
)
}}
#undef AUX778076_SPEC_PARAMS
#undef AUX778076_SHIFTED_PARAMS
#undef AUX778076_PARAMS
#undef AUX778076_OP_NAME
#undef AUX778076_OP_VALUE1
#undef AUX778076_OP_VALUE2
| 28.861446 | 104 | 0.736798 |
85a9c3645576374a0825d30068d3a73f82dd6ac9 | 2,331 | hpp | C++ | Public/Expected/Details/BaseCopy.hpp | doctor-fate/expected | 1cfa9a1fe6700c49a4cc5c65301559a0b373a692 | [
"MIT"
] | 1 | 2021-07-10T09:54:18.000Z | 2021-07-10T09:54:18.000Z | Public/Expected/Details/BaseCopy.hpp | doctor-fate/expected | 1cfa9a1fe6700c49a4cc5c65301559a0b373a692 | [
"MIT"
] | null | null | null | Public/Expected/Details/BaseCopy.hpp | doctor-fate/expected | 1cfa9a1fe6700c49a4cc5c65301559a0b373a692 | [
"MIT"
] | null | null | null | #pragma once
#include "BaseDestructor.hpp"
namespace stdx::details {
enum class EConstructorSelector { Disabled, Trivial, NonTrivial };
template <typename T, typename E>
constexpr EConstructorSelector SelectCopyConstructor() noexcept {
if constexpr (VoidOrTriviallyCopyConstructible<T>() && TriviallyCopyConstructible<E>()) {
return EConstructorSelector::Trivial;
} else if constexpr (VoidOrCopyConstructible<T>() && CopyConstructible<E>()) {
return EConstructorSelector::NonTrivial;
} else {
return EConstructorSelector::Disabled;
}
}
template <typename T, typename E, EConstructorSelector = SelectCopyConstructor<T, E>()>
struct BaseCopyConstructor : BaseDestructor<T, E> {
using Super = BaseDestructor<T, E>;
using Super::Super;
BaseCopyConstructor() = default;
BaseCopyConstructor(const BaseCopyConstructor&) = delete;
BaseCopyConstructor(BaseCopyConstructor&&) = default;
BaseCopyConstructor& operator=(const BaseCopyConstructor&) = default;
BaseCopyConstructor& operator=(BaseCopyConstructor&&) = default;
};
template <typename T, typename E>
struct BaseCopyConstructor<T, E, EConstructorSelector::Trivial> : BaseDestructor<T, E> {
using Super = BaseDestructor<T, E>;
using Super::Super;
};
template <typename T, typename E>
struct BaseCopyConstructor<T, E, EConstructorSelector::NonTrivial> : BaseDestructor<T, E> {
using Super = BaseDestructor<T, E>;
using Super::Super;
BaseCopyConstructor() = default;
constexpr BaseCopyConstructor(const BaseCopyConstructor& Other) noexcept(
VoidOrNothrowCopyConstructible<T>() && NothrowCopyConstructible<E>()) {
if (Other.HasValue()) {
if constexpr (!IsVoid<T>()) {
Super::ConstructValue(*Other);
}
} else {
Super::ConstructUnexpected(Other.Error());
}
Super::bHasValue = Other.bHasValue;
}
BaseCopyConstructor(BaseCopyConstructor&&) = default;
BaseCopyConstructor& operator=(const BaseCopyConstructor&) = default;
BaseCopyConstructor& operator=(BaseCopyConstructor&&) = default;
};
}
| 34.791045 | 97 | 0.648649 |
85b0c4fb364783a7874cf6a4da39e9523835dede | 666 | cpp | C++ | server/memory.cpp | FaresMehanna/Monitor-And-Control-Server-Room | 29caea1501a5174c63ba87c47545c889b9cf2e51 | [
"MIT"
] | null | null | null | server/memory.cpp | FaresMehanna/Monitor-And-Control-Server-Room | 29caea1501a5174c63ba87c47545c889b9cf2e51 | [
"MIT"
] | null | null | null | server/memory.cpp | FaresMehanna/Monitor-And-Control-Server-Room | 29caea1501a5174c63ba87c47545c889b9cf2e51 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include "device.h"
#include "memory.h"
void acquire(DeviceData* device_data) {
printf("acquire.\n");
pthread_mutex_lock(&(device_data->itmes_mutex));
(device_data->memory_pointers)++;
pthread_mutex_unlock(&(device_data->itmes_mutex));
}
void release(DeviceData* device_data) {
printf("release.\n");
pthread_mutex_lock(&(device_data->itmes_mutex));
(device_data->memory_pointers)--;
if(0 == device_data->memory_pointers) {
close(device_data->sockfd);
delete(device_data);
printf("delete.\n");
}
pthread_mutex_unlock(&(device_data->itmes_mutex));
} | 26.64 | 54 | 0.71021 |
85b1838fdc34e86335c44941f09cd5104ecc0cf1 | 3,988 | cpp | C++ | src/loader/ImageIO.cpp | PearCoding/PearRay | 8654a7dcd55cc67859c7c057c7af64901bf97c35 | [
"MIT"
] | 19 | 2016-11-07T00:01:19.000Z | 2021-12-29T05:35:14.000Z | src/loader/ImageIO.cpp | PearCoding/PearRay | 8654a7dcd55cc67859c7c057c7af64901bf97c35 | [
"MIT"
] | 33 | 2016-07-06T21:58:05.000Z | 2020-08-01T18:18:24.000Z | src/loader/ImageIO.cpp | PearCoding/PearRay | 8654a7dcd55cc67859c7c057c7af64901bf97c35 | [
"MIT"
] | null | null | null | #include "ImageIO.h"
#include "Logger.h"
#include "config/Build.h"
#include <OpenImageIO/imageio.h>
namespace PR {
bool ImageIO::save(const std::filesystem::path& path, const float* data, size_t width, size_t height, size_t channels, const ImageSaveOptions& opts)
{
OIIO::ImageSpec spec(width, height, channels, OIIO::TypeFloat);
const std::string versionStr = Build::getVersionString();
spec.attribute("PixelAspectRatio", 1.0f);
spec.attribute("Software", "PearRay " + versionStr);
spec.attribute("IPTC:ProgramVersion", versionStr);
if (opts.Parametric) {
spec.attribute("oiio:ColorSpace", "PRParametric");
spec.attribute("oiio:Gamma", 1.0f);
spec.attribute("PR:Parametric", "true");
spec.attribute("oiio:RawColor", 1);
spec.attribute("compression", "piz");
spec.channelnames.clear();
spec.channelnames.push_back("coeff.A");
spec.channelnames.push_back("coeff.B");
spec.channelnames.push_back("coeff.C");
} else {
spec.attribute("compression", "pxr24");
}
if (channels > 3) {
spec.channelnames.resize(channels);
for (size_t i = 0; i < channels; ++i)
spec.channelnames[i] = "Value_" + std::to_string(i + 1);
}
auto out = OIIO::ImageOutput::create(path.string());
if (!out) {
PR_LOG(L_ERROR) << "[Output] Could not create output context for file " << path << ", error = " << OIIO::geterror() << std::endl;
return false;
}
if (!out->open(path.generic_string(), spec)) {
PR_LOG(L_ERROR) << "[Output] Could not open file " << path << ", error = " << out->geterror() << std::endl;
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageOutput::destroy(out);
#endif
return false;
}
if (!out->write_image(OIIO::TypeUnknown, data)) {
PR_LOG(L_ERROR) << "[Output] Could not write pixels to " << path << ", error = " << out->geterror() << std::endl;
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageOutput::destroy(out);
#endif
return false;
}
if (!out->close()) {
PR_LOG(L_ERROR) << "[Output] Could not close file " << path << ", error = " << out->geterror() << std::endl;
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageOutput::destroy(out);
#endif
return false;
}
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageOutput::destroy(out);
#endif
return true;
}
bool ImageIO::load(const std::filesystem::path& path, std::vector<float>& data, size_t& width, size_t& height, size_t& channels)
{
auto in = OIIO::ImageInput::open(path.string());
if (!in) {
PR_LOG(L_ERROR) << "[Input] Could not open file " << path << ", error = " << OIIO::geterror() << std::endl;
return false;
}
const OIIO::ImageSpec spec = in->spec();
width = std::max(0, spec.width);
height = std::max(0, spec.height);
channels = std::max(0, spec.nchannels);
if (width * height * channels == 0) {
PR_LOG(L_ERROR) << "[Input] Image file " << path << " has bad specifications" << std::endl;
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageInput::destroy(in);
#endif
return false;
}
const float gamma = spec.get_float_attribute("oiio:Gamma", 1.0f);
const bool isSRGB = spec.get_string_attribute("oiio:ColorSpace") == "sRGB";
data.resize(width * height * channels);
if (!in->read_image(OIIO::TypeFloat, data.data())) {
PR_LOG(L_ERROR) << "[Input] Could not read file " << path << ", error = " << in->geterror() << std::endl;
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageInput::destroy(in);
#endif
}
if (!in->close()) {
PR_LOG(L_ERROR) << "[Input] Could not close file " << path << ", error = " << in->geterror() << std::endl;
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageInput::destroy(in);
#endif
}
#if OIIO_PLUGIN_VERSION < 22
OIIO::ImageInput::destroy(in);
#endif
// Map to linear
if (isSRGB) {
const auto map = [](float u) {
if (u <= 0.04045f)
return u / 12.92f;
else
return std::pow((u + 0.055f) / 1.055f, 2.4f);
};
//PR_OPT_LOOP
for (float& v : data)
v = map(v);
} else if (gamma != 1.0f) {
const float invGamma = 1 / gamma;
//PR_OPT_LOOP
for (float& v : data)
v = std::pow(v, invGamma);
}
return true;
}
} // namespace PR | 28.690647 | 148 | 0.650201 |
85b9aed1dcde728eecce0366c3f190a1540c442b | 224 | cpp | C++ | various/COP3330/lect9/sample9.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | 14 | 2019-04-23T13:45:10.000Z | 2022-03-12T18:26:47.000Z | various/COP3330/lect9/sample9.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | null | null | null | various/COP3330/lect9/sample9.cpp | chgogos/oop | 3b0e6bbd29a76f863611e18d082913f080b1b571 | [
"MIT"
] | 9 | 2019-09-01T15:17:45.000Z | 2020-11-13T20:31:36.000Z | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
int MyInt = 4;
int &MyIntRef = MyInt;
int *MyIntPtr;
MyIntPtr = &MyIntRef;
cout << *MyIntPtr << "\n";
return 0;
}
/*
4
*/ | 10.666667 | 30 | 0.558036 |
85bc42eec3122deae4f4f2cb2c166a236d58a2a3 | 60,580 | cpp | C++ | corokafka/impl/corokafka_consumer_manager_impl.cpp | gridgentoo/corokafka | 23705484d7126771c012e04304499aa06dbc88c7 | [
"Apache-2.0"
] | null | null | null | corokafka/impl/corokafka_consumer_manager_impl.cpp | gridgentoo/corokafka | 23705484d7126771c012e04304499aa06dbc88c7 | [
"Apache-2.0"
] | null | null | null | corokafka/impl/corokafka_consumer_manager_impl.cpp | gridgentoo/corokafka | 23705484d7126771c012e04304499aa06dbc88c7 | [
"Apache-2.0"
] | null | null | null | /*
** Copyright 2019 Bloomberg Finance L.P.
**
** 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 <corokafka/impl/corokafka_consumer_manager_impl.h>
#include <cppkafka/macros.h>
#include <cmath>
#include <tuple>
using namespace std::placeholders;
namespace Bloomberg {
namespace corokafka {
//===========================================================================================
// class ConsumerManagerImpl
//===========================================================================================
ConsumerManagerImpl::ConsumerManagerImpl(quantum::Dispatcher& dispatcher,
const ConnectorConfiguration& connectorConfiguration,
const ConfigMap& configs) :
_dispatcher(dispatcher)
{
//Create a consumer for each topic and apply the appropriate configuration
for (const auto& entry : configs) {
// Process each configuration
auto it = _consumers.emplace(entry.first, ConsumerTopicEntry(nullptr,
connectorConfiguration,
entry.second,
dispatcher.getNumIoThreads(),
dispatcher.getCoroQueueIdRangeForAny()));
setup(entry.first, it.first->second);
}
}
ConsumerManagerImpl::ConsumerManagerImpl(quantum::Dispatcher& dispatcher,
const ConnectorConfiguration& connectorConfiguration,
ConfigMap&& configs) :
_dispatcher(dispatcher)
{
//Create a consumer for each topic and apply the appropriate configuration
for (auto&& entry : configs) {
// Process each configuration
auto it = _consumers.emplace(entry.first, ConsumerTopicEntry(nullptr,
connectorConfiguration,
std::move(entry.second),
dispatcher.getNumIoThreads(),
dispatcher.getCoroQueueIdRangeForAny()));
setup(entry.first, it.first->second);
}
}
ConsumerManagerImpl::~ConsumerManagerImpl()
{
shutdown();
}
void ConsumerManagerImpl::setup(const std::string& topic, ConsumerTopicEntry& topicEntry)
{
const Configuration::Options& rdKafkaOptions = topicEntry._configuration.getOptions(Configuration::OptionType::RdKafka);
const Configuration::Options& rdKafkaTopicOptions = topicEntry._configuration.getTopicOptions(Configuration::OptionType::RdKafka);
const Configuration::Options& internalOptions = topicEntry._configuration.getOptions(Configuration::OptionType::Internal);
//Validate config
const cppkafka::ConfigurationOption* brokerList =
Configuration::findOption("metadata.broker.list", rdKafkaOptions);
if (!brokerList) {
throw std::runtime_error(std::string("Consumer broker list not found. Please set 'metadata.broker.list' for topic ") + topic);
}
//Set the rdkafka configuration options
cppkafka::Configuration kafkaConfig(rdKafkaOptions);
kafkaConfig.set_default_topic_configuration(cppkafka::TopicConfiguration(rdKafkaTopicOptions));
const cppkafka::ConfigurationOption* autoThrottle =
Configuration::findOption("internal.consumer.auto.throttle", internalOptions);
if (autoThrottle) {
topicEntry._throttleControl.autoThrottle() = StringEqualCompare()(autoThrottle->get_value(), "true");
}
const cppkafka::ConfigurationOption* throttleMultiplier =
Configuration::findOption("internal.consumer.auto.throttle.multiplier", internalOptions);
if (throttleMultiplier) {
topicEntry._throttleControl.throttleMultiplier() = std::stol(throttleMultiplier->get_value());
}
//Set the global callbacks
if (topicEntry._configuration.getErrorCallback()) {
auto errorFunc = std::bind(errorCallback2, std::ref(topicEntry), _1, _2, _3);
kafkaConfig.set_error_callback(std::move(errorFunc));
}
if (topicEntry._configuration.getThrottleCallback() || topicEntry._throttleControl.autoThrottle()) {
auto throttleFunc = std::bind(throttleCallback, std::ref(topicEntry), _1, _2, _3, _4);
kafkaConfig.set_throttle_callback(std::move(throttleFunc));
}
if (topicEntry._configuration.getLogCallback()) {
auto logFunc = std::bind(logCallback, std::ref(topicEntry), _1, _2, _3, _4);
kafkaConfig.set_log_callback(std::move(logFunc));
}
if (topicEntry._configuration.getStatsCallback()) {
auto statsFunc = std::bind(statsCallback, std::ref(topicEntry), _1, _2);
kafkaConfig.set_stats_callback(std::move(statsFunc));
}
if (topicEntry._configuration.getOffsetCommitCallback()) {
auto offsetCommitFunc = std::bind(offsetCommitCallback, std::ref(topicEntry), _1, _2, _3);
kafkaConfig.set_offset_commit_callback(std::move(offsetCommitFunc));
}
if (topicEntry._configuration.getPreprocessorCallback()) {
topicEntry._preprocessorCallback = std::bind(preprocessorCallback, std::ref(topicEntry), _1);
}
const cppkafka::ConfigurationOption* autoPersist =
Configuration::findOption("internal.consumer.auto.offset.persist", internalOptions);
if (autoPersist) {
topicEntry._autoOffsetPersist = StringEqualCompare()(autoPersist->get_value(), "true");
}
const cppkafka::ConfigurationOption* persistStrategy =
Configuration::findOption("internal.consumer.offset.persist.strategy", internalOptions);
if (persistStrategy) {
if (StringEqualCompare()(persistStrategy->get_value(), "commit")) {
topicEntry._autoOffsetPersistStrategy = OffsetPersistStrategy::Commit;
}
else if (StringEqualCompare()(persistStrategy->get_value(), "store")) {
topicEntry._autoOffsetPersistStrategy = OffsetPersistStrategy::Store;
}
else {
throw std::runtime_error("Unknown internal.consumer.offset.persist.strategy value");
}
}
const cppkafka::ConfigurationOption* autoPersistOnException =
Configuration::findOption("internal.consumer.auto.offset.persist.on.exception", internalOptions);
if (autoPersistOnException) {
topicEntry._autoOffsetPersistOnException = StringEqualCompare()(autoPersist->get_value(), "true");
}
const cppkafka::ConfigurationOption* commitExec =
Configuration::findOption("internal.consumer.commit.exec", internalOptions);
if (commitExec) {
if (StringEqualCompare()(commitExec->get_value(), "sync")) {
topicEntry._autoCommitExec = ExecMode::Sync;
}
else if (StringEqualCompare()(commitExec->get_value(), "async")) {
topicEntry._autoCommitExec = ExecMode::Async;
}
else {
throw std::runtime_error("Unknown internal.consumer.commit.exec value");
}
}
// Set underlying rdkafka options
if (topicEntry._autoOffsetPersist) {
kafkaConfig.set("enable.auto.offset.store", false);
if (topicEntry._autoOffsetPersistStrategy == OffsetPersistStrategy::Commit) {
kafkaConfig.set("enable.auto.commit", false);
kafkaConfig.set("auto.commit.interval.ms", 0);
}
else {
kafkaConfig.set("enable.auto.commit", true);
}
}
bool roundRobinPolling = false; //default is batch
const cppkafka::ConfigurationOption* pollStrategy =
Configuration::findOption("internal.consumer.poll.strategy", internalOptions);
if (pollStrategy) {
if (StringEqualCompare()(pollStrategy->get_value(), "roundrobin")) {
roundRobinPolling = true;
}
else if (!StringEqualCompare()(pollStrategy->get_value(), "batch")) {
throw std::runtime_error("Unknown internal.consumer.poll.strategy");
}
}
//=======================================================================================
//DO NOT UPDATE ANY KAFKA CONFIG OPTIONS BELOW THIS POINT SINCE THE CONSUMER MAKES A COPY
//=======================================================================================
//Create a consumer
topicEntry._consumer.reset(new cppkafka::Consumer(kafkaConfig));
topicEntry._committer.reset(new cppkafka::BackoffCommitter(*topicEntry._consumer));
if (roundRobinPolling) {
topicEntry._roundRobin.reset(new cppkafka::RoundRobinPollStrategy(*topicEntry._consumer));
}
auto offsetCommitErrorFunc = std::bind(&offsetCommitErrorCallback, std::ref(topicEntry), _1);
topicEntry._committer->set_error_callback(offsetCommitErrorFunc);
//Set internal config options
const cppkafka::ConfigurationOption* pauseOnStart =
Configuration::findOption("internal.consumer.pause.on.start", internalOptions);
if (pauseOnStart) {
topicEntry._pauseOnStart = StringEqualCompare()(pauseOnStart->get_value(), "true");
}
const cppkafka::ConfigurationOption* skipUnknownHeaders =
Configuration::findOption("internal.consumer.skip.unknown.headers", internalOptions);
if (skipUnknownHeaders) {
topicEntry._skipUnknownHeaders = StringEqualCompare()(skipUnknownHeaders->get_value(), "true");
}
const cppkafka::ConfigurationOption* consumerTimeout =
Configuration::findOption("internal.consumer.timeout.ms", internalOptions);
if (consumerTimeout) {
topicEntry._consumer->set_timeout(std::chrono::milliseconds(std::stoll(consumerTimeout->get_value())));
}
const cppkafka::ConfigurationOption* pollTimeout =
Configuration::findOption("internal.consumer.poll.timeout.ms", internalOptions);
if (pollTimeout) {
topicEntry._pollTimeout = std::chrono::milliseconds(std::stoll(pollTimeout->get_value()));
}
const cppkafka::ConfigurationOption* logLevel =
Configuration::findOption("internal.consumer.log.level", internalOptions);
if (logLevel) {
cppkafka::LogLevel level = logLevelFromString(logLevel->get_value());
topicEntry._consumer->set_log_level(level);
topicEntry._logLevel = level;
}
const cppkafka::ConfigurationOption* numRetriesOption =
Configuration::findOption("internal.consumer.commit.num.retries", internalOptions);
if (numRetriesOption) {
topicEntry._committer->set_maximum_retries(std::stoll(numRetriesOption->get_value()));
}
const cppkafka::ConfigurationOption* backoffStrategyOption =
Configuration::findOption("internal.consumer.commit.backoff.strategy", internalOptions);
if (backoffStrategyOption) {
if (StringEqualCompare()(backoffStrategyOption->get_value(), "linear")) {
topicEntry._committer->set_backoff_policy(cppkafka::BackoffPerformer::BackoffPolicy::LINEAR);
}
else if (StringEqualCompare()(backoffStrategyOption->get_value(), "exponential")) {
topicEntry._committer->set_backoff_policy(cppkafka::BackoffPerformer::BackoffPolicy::EXPONENTIAL);
}
else {
throw std::runtime_error("Unknown internal.consumer.commit.backoff.strategy value");
}
}
const cppkafka::ConfigurationOption* backoffInterval =
Configuration::findOption("internal.consumer.commit.backoff.interval.ms", internalOptions);
if (backoffInterval) {
std::chrono::milliseconds interval(std::stoll(backoffInterval->get_value()));
topicEntry._committer->set_initial_backoff(interval);
topicEntry._committer->set_backoff_step(interval);
}
const cppkafka::ConfigurationOption* maxBackoff =
Configuration::findOption("internal.consumer.commit.max.backoff.ms", internalOptions);
if (maxBackoff) {
topicEntry._committer->set_maximum_backoff(std::chrono::milliseconds(std::stoll(maxBackoff->get_value())));
}
const cppkafka::ConfigurationOption* batchSize =
Configuration::findOption("internal.consumer.read.size", internalOptions);
if (batchSize) {
topicEntry._batchSize = std::stoll(batchSize->get_value());
}
const cppkafka::ConfigurationOption* threadRangeLow =
Configuration::findOption("internal.consumer.receive.callback.thread.range.low", internalOptions);
if (threadRangeLow) {
int value = std::stoi(threadRangeLow->get_value());
if (value < topicEntry._receiveCallbackThreadRange.first || value > topicEntry._receiveCallbackThreadRange.second) {
throw std::runtime_error("Invalid value for internal.consumer.receive.callback.thread.range.low");
}
topicEntry._receiveCallbackThreadRange.first = value;
}
const cppkafka::ConfigurationOption* threadRangeHigh =
Configuration::findOption("internal.consumer.receive.callback.thread.range.high", internalOptions);
if (threadRangeHigh) {
int value = std::stoi(threadRangeHigh->get_value());
if (value < topicEntry._receiveCallbackThreadRange.first || value > topicEntry._receiveCallbackThreadRange.second) {
throw std::runtime_error("Invalid value for internal.consumer.receive.callback.thread.range.high");
}
topicEntry._receiveCallbackThreadRange.second = value;
}
const cppkafka::ConfigurationOption* receiveCallbackExec =
Configuration::findOption("internal.consumer.receive.callback.exec", internalOptions);
if (receiveCallbackExec) {
if (StringEqualCompare()(receiveCallbackExec->get_value(), "sync")) {
topicEntry._receiveCallbackExec = ExecMode::Sync;
}
else if (StringEqualCompare()(receiveCallbackExec->get_value(), "async")) {
topicEntry._receiveCallbackExec = ExecMode::Async;
}
else {
throw std::runtime_error("Unknown internal.consumer.receive.callback.exec value");
}
}
const cppkafka::ConfigurationOption* receiveThread =
Configuration::findOption("internal.consumer.receive.invoke.thread", internalOptions);
if (receiveThread) {
if (StringEqualCompare()(receiveThread->get_value(), "io")) {
topicEntry._receiveOnIoThread = true;
}
else if (StringEqualCompare()(receiveThread->get_value(), "coro")) {
topicEntry._receiveOnIoThread = false;
topicEntry._receiveCallbackExec = ExecMode::Sync; //override user setting
}
else {
throw std::runtime_error("Unknown internal.consumer.receive.invoke.thread value");
}
}
const cppkafka::ConfigurationOption* batchPrefetch =
Configuration::findOption("internal.consumer.batch.prefetch", internalOptions);
if (batchPrefetch) {
topicEntry._batchPrefetch = StringEqualCompare()(batchPrefetch->get_value(), "true");
}
const cppkafka::ConfigurationOption* preprocessMessages =
Configuration::findOption("internal.consumer.preprocess.messages", internalOptions);
if (preprocessMessages) {
topicEntry._preprocess = StringEqualCompare()(preprocessMessages->get_value(), "true");
}
const cppkafka::ConfigurationOption* invokeThread =
Configuration::findOption("internal.consumer.preprocess.invoke.thread", internalOptions);
if (invokeThread) {
if (StringEqualCompare()(invokeThread->get_value(), "io")) {
topicEntry._preprocessOnIoThread = true;
}
else if (StringEqualCompare()(invokeThread->get_value(), "coro")) {
topicEntry._preprocessOnIoThread = false;
}
else {
throw std::runtime_error("Unknown internal.consumer.preprocess.invoke.thread value");
}
}
// Set the buffered producer callbacks
if (topicEntry._configuration.getRebalanceCallback() ||
((topicEntry._configuration.getPartitionStrategy() == PartitionStrategy::Dynamic) &&
!topicEntry._configuration.getInitialPartitionAssignment().empty())) {
auto assignmentFunc = std::bind(&ConsumerManagerImpl::assignmentCallback, std::ref(topicEntry), _1);
topicEntry._consumer->set_assignment_callback(std::move(assignmentFunc));
}
if (topicEntry._configuration.getRebalanceCallback()) {
auto revocationFunc = std::bind(&ConsumerManagerImpl::revocationCallback, std::ref(topicEntry), _1);
topicEntry._consumer->set_revocation_callback(std::move(revocationFunc));
auto rebalanceErrorFunc = std::bind(&ConsumerManagerImpl::rebalanceErrorCallback, std::ref(topicEntry), _1);
topicEntry._consumer->set_rebalance_error_callback(std::move(rebalanceErrorFunc));
}
if (topicEntry._pauseOnStart) {
topicEntry._consumer->pause(topic);
}
//subscribe or statically assign partitions to this consumer
if (topicEntry._configuration.getPartitionStrategy() == PartitionStrategy::Static) {
if ((topicEntry._configuration.getInitialPartitionAssignment().size() == 1) &&
(topicEntry._configuration.getInitialPartitionAssignment().front().get_partition() == RD_KAFKA_PARTITION_UA)) {
//assign all partitions belonging to this topic
cppkafka::TopicMetadata metadata = topicEntry._consumer->get_metadata(topicEntry._consumer->get_topic(topic));
cppkafka::TopicPartitionList partitions = cppkafka::convert(topic, metadata.get_partitions());
//set the specified offset on all partitions
for (auto& p : partitions) {
p.set_offset(topicEntry._configuration.getInitialPartitionAssignment().front().get_offset());
}
topicEntry._consumer->assign(partitions);
}
else {
topicEntry._consumer->assign(topicEntry._configuration.getInitialPartitionAssignment());
}
}
else {
topicEntry._consumer->subscribe({topic});
}
}
ConsumerMetadata ConsumerManagerImpl::getMetadata(const std::string& topic)
{
auto it = findConsumer(topic);
return makeMetadata(it->second);
}
void ConsumerManagerImpl::preprocess(bool enable, const std::string& topic)
{
if (topic.empty()) {
for (auto&& consumer : _consumers) {
consumer.second._preprocess = enable;
}
}
else {
auto it = findConsumer(topic);
it->second._preprocess = enable;
}
}
void ConsumerManagerImpl::pause(const std::string& topic)
{
if (topic.empty()) {
for (auto&& consumer : _consumers) {
consumer.second._consumer->pause();
consumer.second._isPaused = true;
}
}
else {
ConsumerTopicEntry& consumerTopicEntry = findConsumer(topic)->second;
consumerTopicEntry._consumer->pause();
consumerTopicEntry._isPaused = true;
}
}
void ConsumerManagerImpl::resume(const std::string& topic)
{
if (topic.empty()) {
for (auto&& consumer : _consumers) {
consumer.second._consumer->resume();
consumer.second._isPaused = false;
}
}
else {
auto it = _consumers.find(topic);
if (it == _consumers.end()) {
throw std::runtime_error("Invalid topic");
}
ConsumerTopicEntry& consumerTopicEntry = findConsumer(topic)->second;
consumerTopicEntry._consumer->resume();
consumerTopicEntry._isPaused = false;
}
}
void ConsumerManagerImpl::subscribe(const std::string& topic,
cppkafka::TopicPartitionList partitionList)
{
ConsumerTopicEntry& topicEntry = findConsumer(topic)->second;
if (topicEntry._isSubscribed) {
throw std::runtime_error("Already subscribed");
}
//subscribe or statically assign partitions to this consumer
topicEntry._isSubscribed = true;
topicEntry._setOffsetsOnStart = true;
if (!partitionList.empty()) {
//Overwrite the initial assignment
topicEntry._configuration.assignInitialPartitions(topicEntry._configuration.getPartitionStrategy(),
std::move(partitionList));
}
if (topicEntry._configuration.getPartitionStrategy() == PartitionStrategy::Static) {
cppkafka::TopicPartitionList partitions = topicEntry._configuration.getInitialPartitionAssignment();
for (auto& partition : partitions) {
partition.set_offset(RD_KAFKA_OFFSET_STORED);
}
topicEntry._consumer->assign(partitions);
}
else {
topicEntry._consumer->subscribe({topic});
}
}
void ConsumerManagerImpl::unsubscribe(const std::string& topic)
{
if (topic.empty()) {
for (auto&& consumer : _consumers) {
if (consumer.second._isSubscribed) {
if (consumer.second._configuration.getPartitionStrategy() == PartitionStrategy::Static) {
consumer.second._consumer->unassign();
}
else {
consumer.second._consumer->unsubscribe();
}
consumer.second._isSubscribed = false;
}
}
}
else {
ConsumerTopicEntry& consumerTopicEntry = findConsumer(topic)->second;
if (consumerTopicEntry._isSubscribed) {
if (consumerTopicEntry._configuration.getPartitionStrategy() == PartitionStrategy::Static) {
consumerTopicEntry._consumer->unassign();
}
else {
consumerTopicEntry._consumer->unsubscribe();
}
}
}
}
cppkafka::Error ConsumerManagerImpl::commit(const cppkafka::TopicPartition& topicPartition,
const void* opaque,
bool forceSync)
{
auto it = _consumers.find(topicPartition.get_topic());
if (it == _consumers.end()) {
return RD_KAFKA_RESP_ERR_UNKNOWN_TOPIC_OR_PART;
}
return commitImpl(it->second, cppkafka::TopicPartitionList{topicPartition}, opaque, forceSync);
}
cppkafka::Error ConsumerManagerImpl::commit(const cppkafka::TopicPartitionList& topicPartitions,
const void* opaque,
bool forceSync)
{
if (topicPartitions.empty()) {
return RD_KAFKA_RESP_ERR_INVALID_PARTITIONS;
}
auto it = _consumers.find(topicPartitions.at(0).get_topic());
if (it == _consumers.end()) {
return RD_KAFKA_RESP_ERR_UNKNOWN_TOPIC_OR_PART;
}
return commitImpl(it->second, topicPartitions, opaque, forceSync);
}
cppkafka::Error ConsumerManagerImpl::commitImpl(ConsumerTopicEntry& entry,
const cppkafka::TopicPartitionList& topicPartitions,
const void* opaque,
bool forceSync)
{
try {
const cppkafka::TopicPartition& headPartition = topicPartitions.at(0);
if (entry._committer->get_consumer().get_configuration().get_offset_commit_callback() && (opaque != nullptr)) {
entry._offsets.insert(headPartition, opaque);
}
if (entry._autoOffsetPersistStrategy == OffsetPersistStrategy::Commit || forceSync) {
if ((entry._autoCommitExec == ExecMode::Sync) || forceSync) {
if (headPartition.get_partition() == RD_KAFKA_PARTITION_UA) {
//commit the current assignment
entry._committer->commit();
}
else {
entry._committer->commit(topicPartitions);
}
}
else { // async
if (headPartition.get_partition() == RD_KAFKA_PARTITION_UA) {
//commit the current assignment
entry._committer->get_consumer().async_commit();
}
else {
entry._committer->get_consumer().async_commit(topicPartitions);
}
}
}
else { //OffsetPersistStrategy::Store
#if (RD_KAFKA_VERSION >= RD_KAFKA_STORE_OFFSETS_SUPPORT_VERSION)
entry._committer->get_consumer().store_offsets(topicPartitions);
#else
std::ostringstream oss;
oss << hex << "Current RdKafka version " << RD_KAFKA_VERSION
<< " does not support this functionality. Must be greater than "
<< RD_KAFKA_STORE_OFFSETS_SUPPORT_VERSION;
throw std::runtime_error(oss.str());
#endif
}
}
catch (const cppkafka::HandleException& ex) {
return ex.get_error();
}
catch (const cppkafka::ActionTerminatedException& ex) {
return RD_KAFKA_RESP_ERR__FAIL; //no more retries left
}
catch (...) {
return RD_KAFKA_RESP_ERR_UNKNOWN;
}
return {};
}
const ConsumerConfiguration& ConsumerManagerImpl::getConfiguration(const std::string& topic) const
{
auto it = findConsumer(topic);
return it->second._configuration;
}
std::vector<std::string> ConsumerManagerImpl::getTopics() const
{
std::vector<std::string> topics;
topics.reserve(_consumers.size());
for (const auto& entry : _consumers) {
topics.emplace_back(entry.first);
}
return topics;
}
void ConsumerManagerImpl::shutdown()
{
if (!_shutdownInitiated.test_and_set()) {
unsubscribe({});
}
}
void ConsumerManagerImpl::poll()
{
auto now = std::chrono::steady_clock::now();
for (auto&& entry : _consumers) {
if (!entry.second._isSubscribed) {
continue; //we are no longer subscribed here
}
// Adjust throttling if necessary
adjustThrottling(entry.second, now);
bool doPoll = !entry.second._pollFuture || (entry.second._pollFuture->waitFor(std::chrono::milliseconds(0)) == std::future_status::ready);
if (doPoll) {
// Round-robin
if (entry.second._roundRobin) {
entry.second._pollFuture =
_dispatcher.postFirst((int)quantum::IQueue::QueueId::Any, true, pollCoro, entry.second)->
then(processorCoro, entry.second)->
end();
}
else {
// Batch
entry.second._pollFuture =
_dispatcher.post((int)quantum::IQueue::QueueId::Any, true, pollBatchCoro, entry.second);
}
}
}
}
void ConsumerManagerImpl::errorCallback2(
ConsumerTopicEntry& topicEntry,
cppkafka::KafkaHandleBase& handle,
int error,
const std::string& reason)
{
errorCallback(topicEntry, handle, error, reason, nullptr);
}
void ConsumerManagerImpl::errorCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::KafkaHandleBase& handle,
int error,
const std::string& reason,
cppkafka::Message* message)
{
cppkafka::CallbackInvoker<Callbacks::ErrorCallback>
("error", topicEntry._configuration.getErrorCallback(), &handle)
(makeMetadata(topicEntry), cppkafka::Error((rd_kafka_resp_err_t)error), reason, message);
}
void ConsumerManagerImpl::throttleCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::KafkaHandleBase& handle,
const std::string& brokerName,
int32_t brokerId,
std::chrono::milliseconds throttleDuration)
{
if (!topicEntry._isPaused) {
//calculate throttle periods
cppkafka::Consumer& consumer = static_cast<cppkafka::Consumer&>(handle);
ThrottleControl::Status status = topicEntry._throttleControl.handleThrottleCallback(throttleDuration);
if (status._on) {
consumer.pause();
}
else if (status._off) {
consumer.resume();
}
}
cppkafka::CallbackInvoker<Callbacks::ThrottleCallback>
("throttle", topicEntry._configuration.getThrottleCallback(), &handle)
(makeMetadata(topicEntry), brokerName, brokerId, throttleDuration);
}
void ConsumerManagerImpl::logCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::KafkaHandleBase& handle,
int level,
const std::string& facility,
const std::string& message)
{
cppkafka::CallbackInvoker<Callbacks::LogCallback>
("log", topicEntry._configuration.getLogCallback(), &handle)
(makeMetadata(topicEntry), static_cast<cppkafka::LogLevel>(level), facility, message);
}
void ConsumerManagerImpl::statsCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::KafkaHandleBase& handle,
const std::string& json)
{
cppkafka::CallbackInvoker<Callbacks::StatsCallback>
("stats", topicEntry._configuration.getStatsCallback(), &handle)
(makeMetadata(topicEntry), json);
}
void ConsumerManagerImpl::offsetCommitCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::Consumer& consumer,
cppkafka::Error error,
const cppkafka::TopicPartitionList& topicPartitions)
{
// Check if we have opaque data
cppkafka::TopicPartitionList& partitions = const_cast<cppkafka::TopicPartitionList&>(topicPartitions);
std::vector<const void*> opaques;
if (!topicEntry._offsets.empty()) {
opaques.reserve(partitions.size());
}
for (auto& partition : partitions) {
//subtract one since rdkafka always gives us the next offset
partition.set_offset(partition.get_offset()-1);
//remove the opaque values and pass them back to the application
if (!topicEntry._offsets.empty()) {
opaques.push_back(topicEntry._offsets.remove(partition));
}
}
cppkafka::CallbackInvoker<Callbacks::OffsetCommitCallback>
("offset commit", topicEntry._configuration.getOffsetCommitCallback(), &consumer)
(makeMetadata(topicEntry), error, partitions, opaques);
}
bool ConsumerManagerImpl::offsetCommitErrorCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::Error error)
{
report(topicEntry, cppkafka::LogLevel::LogErr, error.get_error(), "Failed to commit offset.", nullptr);
return ((error.get_error() != RD_KAFKA_RESP_ERR_OFFSET_OUT_OF_RANGE) &&
(error.get_error() != RD_KAFKA_RESP_ERR_OFFSET_METADATA_TOO_LARGE) &&
(error.get_error() != RD_KAFKA_RESP_ERR_INVALID_COMMIT_OFFSET_SIZE));
}
bool ConsumerManagerImpl::preprocessorCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::TopicPartition hint)
{
// Check if we have opaque data
return cppkafka::CallbackInvoker<Callbacks::PreprocessorCallback>
("preprocessor", topicEntry._configuration.getPreprocessorCallback(), topicEntry._consumer.get())
(hint);
}
void ConsumerManagerImpl::assignmentCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::TopicPartitionList& topicPartitions)
{
// Clear any throttling we may have
topicEntry._isSubscribed = true;
topicEntry._throttleControl.reset();
PartitionStrategy strategy = topicEntry._configuration.getPartitionStrategy();
if ((strategy == PartitionStrategy::Dynamic) &&
!topicEntry._configuration.getInitialPartitionAssignment().empty() &&
topicEntry._setOffsetsOnStart) {
topicEntry._setOffsetsOnStart = false;
//perform first offset assignment based on user config
for (auto&& partition : topicPartitions) {
for (const auto& assigned : topicEntry._configuration.getInitialPartitionAssignment()) {
if (partition.get_partition() == assigned.get_partition()) {
//we have a match
partition.set_offset(assigned.get_offset());
break;
}
}
}
}
cppkafka::CallbackInvoker<Callbacks::RebalanceCallback>
("assignment", topicEntry._configuration.getRebalanceCallback(), topicEntry._consumer.get())
(makeMetadata(topicEntry), cppkafka::Error(RD_KAFKA_RESP_ERR__ASSIGN_PARTITIONS), topicPartitions);
}
void ConsumerManagerImpl::revocationCallback(
ConsumerTopicEntry& topicEntry,
const cppkafka::TopicPartitionList& topicPartitions)
{
topicEntry._isSubscribed = false;
cppkafka::CallbackInvoker<Callbacks::RebalanceCallback>
("revocation", topicEntry._configuration.getRebalanceCallback(), topicEntry._consumer.get())
(makeMetadata(topicEntry), cppkafka::Error(RD_KAFKA_RESP_ERR__REVOKE_PARTITIONS), const_cast<cppkafka::TopicPartitionList&>(topicPartitions));
}
void ConsumerManagerImpl::rebalanceErrorCallback(
ConsumerTopicEntry& topicEntry,
cppkafka::Error error)
{
cppkafka::TopicPartitionList partitions;
cppkafka::CallbackInvoker<Callbacks::RebalanceCallback>
("rebalance", topicEntry._configuration.getRebalanceCallback(), topicEntry._consumer.get())
(makeMetadata(topicEntry), error, partitions);
}
void ConsumerManagerImpl::adjustThrottling(ConsumerTopicEntry& topicEntry,
const std::chrono::steady_clock::time_point& now)
{
if (!topicEntry._isPaused && topicEntry._throttleControl.reduceThrottling(now)) {
// Resume only if this consumer is not paused explicitly by the user
topicEntry._consumer->resume();
}
}
void ConsumerManagerImpl::report(
ConsumerTopicEntry& topicEntry,
cppkafka::LogLevel level,
int error,
const std::string& reason,
const cppkafka::Message& message)
{
if (error) {
errorCallback(topicEntry, *topicEntry._consumer, error, reason, &const_cast<cppkafka::Message&>(message));
}
if (topicEntry._logLevel >= level) {
logCallback(topicEntry, *topicEntry._consumer, (int)level, "corokafka", reason);
}
}
void ConsumerManagerImpl::setConsumerBatchSize(size_t size)
{
_batchSize = size;
}
size_t ConsumerManagerImpl::getConsumerBatchSize() const
{
return _batchSize;
}
std::vector<cppkafka::Message> ConsumerManagerImpl::messageBatchReceiveTask(ConsumerTopicEntry& entry)
{
try {
if (entry._pollTimeout.count() == -1) {
return entry._consumer->poll_batch(entry._batchSize);
}
else {
return entry._consumer->poll_batch(entry._batchSize, entry._pollTimeout);
}
}
catch (const std::exception& ex) {
exceptionHandler(ex, entry);
throw ex;
}
}
int ConsumerManagerImpl::messageRoundRobinReceiveTask(quantum::ThreadPromise<MessageContainer>::Ptr promise,
ConsumerTopicEntry& entry)
{
try {
int batchSize = entry._batchSize;
std::chrono::milliseconds timeoutPerMessage(entry._pollTimeout.count()/entry._batchSize);
while (batchSize--) {
if (entry._pollTimeout.count() == -1) {
cppkafka::Message message = entry._roundRobin->poll();
if (message) {
promise->push(std::move(message));
}
}
else {
cppkafka::Message message = entry._roundRobin->poll(timeoutPerMessage);
if (message) {
promise->push(std::move(message));
}
}
}
}
catch (const std::exception& ex) {
exceptionHandler(ex, entry);
}
return promise->closeBuffer();
}
ConsumerManagerImpl::DeserializedMessage
ConsumerManagerImpl::deserializeMessage(ConsumerTopicEntry& entry,
const cppkafka::Message& kafkaMessage)
{
DeserializerError de;
if (kafkaMessage.get_error()) {
de._error = kafkaMessage.get_error();
de._source |= (uint8_t)DeserializerError::Source::Kafka;
return DeserializedMessage(boost::any(), boost::any(), HeaderPack{}, de);
}
const TypeErasedDeserializer& deserializer = entry._configuration.getTypeErasedDeserializer();
//Get the topic partition
cppkafka::TopicPartition toppar(kafkaMessage.get_topic(), kafkaMessage.get_partition(), kafkaMessage.get_offset());
//Deserialize the key
boost::any key = cppkafka::CallbackInvoker<Deserializer>("key_deserializer",
*deserializer._keyDeserializer,
entry._consumer.get())
(toppar, kafkaMessage.get_key());
if (key.empty()) {
// Decoding failed
de._error = RD_KAFKA_RESP_ERR__KEY_DESERIALIZATION;
de._source |= (uint8_t)DeserializerError::Source::Key;
report(entry, cppkafka::LogLevel::LogErr, RD_KAFKA_RESP_ERR__KEY_DESERIALIZATION, "Failed to deserialize key", kafkaMessage);
}
//Deserialize the headers if any
HeaderPack headers(deserializer._headerEntries.size());
int num = 0;
const cppkafka::HeaderList<cppkafka::Header<cppkafka::Buffer>>& kafkaHeaders = kafkaMessage.get_header_list();
for (auto it = kafkaHeaders.begin(); it != kafkaHeaders.end(); ++it) {
try {
const TypeErasedDeserializer::HeaderEntry& headerEntry = deserializer._headerDeserializers.at(it->get_name());
headers[headerEntry._pos].first = it->get_name();
headers[headerEntry._pos].second = cppkafka::CallbackInvoker<Deserializer>("header_deserializer",
*headerEntry._deserializer,
entry._consumer.get())
(toppar, it->get_value());
if (headers[headerEntry._pos].second.empty()) {
// Decoding failed
de._error = RD_KAFKA_RESP_ERR__VALUE_DESERIALIZATION;
de._source |= (uint8_t)DeserializerError::Source::Header;
de._headerNum = num;
std::ostringstream oss;
oss << "Failed to deserialize header: " << it->get_name();
report(entry, cppkafka::LogLevel::LogErr, RD_KAFKA_RESP_ERR__VALUE_DESERIALIZATION, oss.str(), kafkaMessage);
break;
}
}
catch (const std::exception& ex) {
if (entry._skipUnknownHeaders) {
report(entry, cppkafka::LogLevel::LogWarning, 0, ex.what(), kafkaMessage);
continue;
}
de._error = RD_KAFKA_RESP_ERR__NOT_IMPLEMENTED;
de._source |= (uint8_t)DeserializerError::Source::Header;
de._headerNum = num;
report(entry, cppkafka::LogLevel::LogErr, RD_KAFKA_RESP_ERR__NOT_IMPLEMENTED, ex.what(), kafkaMessage);
break;
}
++num;
}
//Deserialize the payload
boost::any payload = cppkafka::CallbackInvoker<Deserializer>("payload_deserializer",
*deserializer._payloadDeserializer,
entry._consumer.get())
(toppar, kafkaMessage.get_payload());
if (payload.empty()) {
// Decoding failed
de._error = RD_KAFKA_RESP_ERR__VALUE_DESERIALIZATION;
de._source |= (uint8_t)DeserializerError::Source::Payload;
report(entry, cppkafka::LogLevel::LogErr, RD_KAFKA_RESP_ERR__VALUE_DESERIALIZATION, "Failed to deserialize payload", kafkaMessage);
}
return DeserializedMessage(std::move(key), std::move(payload), std::move(headers), de);
}
ConsumerManagerImpl::DeserializedMessage
ConsumerManagerImpl::deserializeCoro(quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry,
const cppkafka::Message& kafkaMessage)
{
bool skip = false;
if (entry._preprocessorCallback && entry._preprocess) {
if (entry._preprocessOnIoThread) {
// Call the preprocessor callback
skip = ctx->template postAsyncIo(preprocessorTask, entry, kafkaMessage)->get(ctx);
}
else {
//run in this coroutine
skip = entry._preprocessorCallback(cppkafka::TopicPartition(kafkaMessage.get_topic(),
kafkaMessage.get_partition(),
kafkaMessage.get_offset()));
}
if (skip) {
//return immediately and skip de-serializing
DeserializedMessage dm;
std::get<3>(dm)._error = RD_KAFKA_RESP_ERR__BAD_MSG;
std::get<3>(dm)._source |= (uint8_t)DeserializerError::Source::Preprocessor;
return dm;
}
}
// Deserialize the message
return deserializeMessage(entry, kafkaMessage);
}
std::vector<bool> ConsumerManagerImpl::executePreprocessorCallbacks(
quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry,
const std::vector<cppkafka::Message>& messages)
{
// Preprocessor IO threads
const size_t callbackThreadRangeSize = entry._receiveCallbackThreadRange.second -
entry._receiveCallbackThreadRange.first + 1;
int numPerBatch = messages.size()/callbackThreadRangeSize;
int remainder = messages.size()%callbackThreadRangeSize;
std::vector<bool> skipMessages(messages.size(), false);
std::vector<quantum::CoroFuturePtr<int>> futures;
futures.reserve(callbackThreadRangeSize);
auto inputIt = messages.cbegin();
size_t batchIndex = 0;
// Run the preprocessor callbacks in batches
for (int i = 0; i < (int)callbackThreadRangeSize; ++i) {
//get the begin and end iterators for each batch
size_t batchSize = (i < remainder) ? numPerBatch + 1 : numPerBatch;
if (batchSize == 0) {
break; //nothing to do
}
int ioQueueId = i + entry._receiveCallbackThreadRange.first;
futures.emplace_back(ctx->postAsyncIo(ioQueueId, false,
[&entry, &skipMessages, batchIndex, batchSize, inputIt]() mutable ->int
{
for (size_t j = batchIndex; j < (batchIndex + batchSize) && entry._preprocess; ++j, ++inputIt) {
skipMessages[j] = entry._preprocessorCallback(cppkafka::TopicPartition(inputIt->get_topic(),
inputIt->get_partition(),
inputIt->get_offset()));
}
return 0;
}));
// Advance index and iterator
batchIndex += batchSize;
std::advance(inputIt, batchSize);
}
//Wait on preprocessor stage to finish
for (auto&& f : futures) {
f->wait(ctx);
}
return skipMessages;
}
std::vector<ConsumerManagerImpl::DeserializedMessage>
ConsumerManagerImpl::deserializeBatchCoro(quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry,
const std::vector<cppkafka::Message>& messages)
{
std::vector<bool> skipMessages;
if (entry._configuration.getPreprocessorCallback() && entry._preprocess) {
if (entry._preprocessOnIoThread) {
skipMessages = executePreprocessorCallbacks(ctx, entry, messages);
}
else {
skipMessages.resize(messages.size(), false);
}
}
// Reset values
size_t numCoros = entry._coroQueueIdRangeForAny.second - entry._coroQueueIdRangeForAny.first + 1;
int numPerBatch = messages.size()/numCoros;
int remainder = messages.size()%numCoros;
std::vector<DeserializedMessage> deserializedMessages(messages.size()); //pre-allocate default constructed messages
std::vector<quantum::CoroContextPtr<int>> futures;
futures.reserve(numCoros);
auto inputIt = messages.cbegin();
size_t batchIndex = 0;
// Post unto all the coroutine threads.
for (int i = entry._coroQueueIdRangeForAny.first; i <= entry._coroQueueIdRangeForAny.second; ++i) {
//get the begin and end iterators for each batch
size_t batchSize = (i < remainder) ? numPerBatch + 1 : numPerBatch;
if (batchSize == 0) {
break; //nothing to do
}
futures.emplace_back(ctx->post(i, false,
[&entry, &deserializedMessages, &skipMessages, inputIt, batchIndex, batchSize]
(quantum::CoroContextPtr<int>) mutable ->int
{
for (size_t j = batchIndex; j < (batchIndex + batchSize); ++j, ++inputIt) {
if (entry._configuration.getPreprocessorCallback() &&
entry._preprocess &&
!entry._preprocessOnIoThread) {
// Run the preprocessor on the coroutine thread
skipMessages[j] = entry._preprocessorCallback(cppkafka::TopicPartition(inputIt->get_topic(),
inputIt->get_partition(),
inputIt->get_offset()));
}
if (!skipMessages.empty() && skipMessages[j]) {
// Set error and mark source as preprocessor
std::get<3>(deserializedMessages[j])._error = RD_KAFKA_RESP_ERR__BAD_MSG;
std::get<3>(deserializedMessages[j])._source |= (uint8_t)DeserializerError::Source::Preprocessor;
}
else {
// Deserialize message
deserializedMessages[j] = deserializeMessage(entry, *inputIt);
}
}
return 0;
}));
// Advance index and iterator
batchIndex += batchSize;
std::advance(inputIt, batchSize);
}
//Wait on deserialize stage to finish
for (auto&& f : futures) {
f->wait(ctx);
}
return deserializedMessages;
}
int ConsumerManagerImpl::invokeReceiver(ConsumerTopicEntry& entry,
cppkafka::Message&& kafkaMessage,
DeserializedMessage&& deserializedMessage)
{
cppkafka::CallbackInvoker<Receiver>("receiver", entry._configuration.getTypeErasedReceiver(), entry._consumer.get())
(*entry._committer,
entry._offsets,
std::move(kafkaMessage), //kafka raw message
std::get<0>(std::move(deserializedMessage)), //key
std::get<1>(std::move(deserializedMessage)), //payload
std::get<2>(std::move(deserializedMessage)), //headers
std::get<3>(std::move(deserializedMessage)), //error
makeOffsetPersistSettings(entry));
return 0;
}
int ConsumerManagerImpl::receiverTask(ConsumerTopicEntry& entry,
cppkafka::Message&& kafkaMessage,
DeserializedMessage&& deserializedMessage)
{
return invokeReceiver(entry, std::move(kafkaMessage), std::move(deserializedMessage));
}
std::deque<ConsumerManagerImpl::MessageTuple>
ConsumerManagerImpl::pollCoro(quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry)
{
try {
using MessageTuple = std::tuple<cppkafka::Message, quantum::CoroContext<DeserializedMessage>::Ptr>;
std::deque<MessageTuple> messageQueue;
// Start the IO task to get messages in a round-robin way
quantum::CoroFuture<MessageContainer>::Ptr future = ctx->postAsyncIo(
(int)quantum::IQueue::QueueId::Any, true, messageRoundRobinReceiveTask, entry);
// Receive all messages from kafka and deserialize in parallel
bool isBufferClosed = false;
while (!isBufferClosed) {
cppkafka::Message message = future->pull(ctx, isBufferClosed);
if (!isBufferClosed) {
messageQueue.emplace_back(MessageTuple(std::move(message), nullptr));
MessageTuple& tuple = messageQueue.back();
if (!std::get<0>(tuple).get_error()) { // check if message has any errors
std::get<1>(tuple) = ctx->post(deserializeCoro, entry, std::get<0>(tuple));
}
}
}
// Pass the message queue to the processor coroutine
return messageQueue;
}
catch (const std::exception& ex) {
exceptionHandler(ex, entry);
throw ex;
}
}
void ConsumerManagerImpl::processMessageBatchOnIoThreads(quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry,
std::vector<cppkafka::Message>&& raw,
std::vector<DeserializedMessage>&& deserializedMessages)
{
const std::pair<int,int>& threadRange = entry._receiveCallbackThreadRange;
const int callbackThreadRangeSize = threadRange.second - threadRange.first + 1;
if (callbackThreadRangeSize > 1) {
// split the messages into io queues
std::vector<ReceivedBatch> partitions(callbackThreadRangeSize);
size_t rawIx = 0;
for (auto&& deserializedMessage : deserializedMessages) {
cppkafka::Message& rawMessage = raw[rawIx++];
if (rawIx > raw.size()) {
throw std::out_of_range("Invalid message index");
}
// Find out on which IO thread we should process this message
const int ioQueue = mapPartitionToQueue(rawMessage.get_partition(), threadRange);
partitions[ioQueue - threadRange.first]
.emplace_back(std::make_tuple(std::move(rawMessage), std::move(deserializedMessage)));
}
if (rawIx != raw.size()) {
throw std::runtime_error("Not all messages were processed");
}
// invoke batch jobs for the partitioned messages
std::vector<quantum::ICoroFuture<int>::Ptr> ioFutures;
ioFutures.reserve(partitions.size());
for (size_t queueIx = 0; queueIx < partitions.size(); ++queueIx) {
const int ioQueue = queueIx + threadRange.first;
quantum::ICoroFuture<int>::Ptr future =
ctx->postAsyncIo(ioQueue,
false,
receiverMultipleBatchesTask,
entry,
std::move(partitions[queueIx]));
if (entry._receiveCallbackExec == ExecMode::Sync) {
ioFutures.push_back(future);
}
}
// wait until all the batches are processed
for (auto c: ioFutures) {
c->get(ctx);
}
}
else {
// optimization: no need to spend time on message distribution for a single io queue
quantum::ICoroFuture<int>::Ptr future =
ctx->postAsyncIo(threadRange.first,
false,
receiverSingleBatchTask,
entry,
std::move(raw),
std::move(deserializedMessages));
if (entry._receiveCallbackExec == ExecMode::Sync) {
future->get(ctx);
}
}
}
int ConsumerManagerImpl::pollBatchCoro(quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry)
{
try{
// get the messages from the prefetched future, or
std::vector<cppkafka::Message> raw;
if (entry._batchPrefetch)
{
if (entry._messagePrefetchFuture) {
//get the pre-fetched batch
raw = entry._messagePrefetchFuture->get(ctx);
}
// start pre-fetching for the next batch
entry._messagePrefetchFuture = ctx->postAsyncIo
((int)quantum::IQueue::QueueId::Any, true, messageBatchReceiveTask, entry);
}
else {
raw = ctx->postAsyncIo((int)quantum::IQueue::QueueId::Any,
true,
messageBatchReceiveTask,
entry)->get(ctx);
}
std::vector<DeserializedMessage> deserializedMessages = ctx->post(deserializeBatchCoro, entry, raw)->get(ctx);
if (entry._receiveOnIoThread) {
processMessageBatchOnIoThreads(ctx, entry, std::move(raw), std::move(deserializedMessages));
}
else {
invokeSingleBatchReceiver(entry, std::move(raw), std::move(deserializedMessages));
}
return 0;
}
catch (const std::exception& ex) {
exceptionHandler(ex, entry);
return -1;
}
}
int ConsumerManagerImpl::receiverMultipleBatchesTask(ConsumerTopicEntry& entry,
ReceivedBatch&& messageBatch)
{
for (auto&& messageTuple : messageBatch) {
cppkafka::CallbackInvoker<Receiver>("receiver", entry._configuration.getTypeErasedReceiver(), entry._consumer.get())
(*entry._committer,
entry._offsets,
std::get<0>(std::move(messageTuple)), //kafka raw message
std::get<0>(std::get<1>(std::move(messageTuple))), //key
std::get<1>(std::get<1>(std::move(messageTuple))), //payload
std::get<2>(std::get<1>(std::move(messageTuple))), //headers
std::get<3>(std::get<1>(std::move(messageTuple))), //error
makeOffsetPersistSettings(entry));
}
return 0;
}
int ConsumerManagerImpl::invokeSingleBatchReceiver(ConsumerTopicEntry& entry,
std::vector<cppkafka::Message>&& rawMessages,
std::vector<DeserializedMessage>&& deserializedMessages)
{
size_t rawIx = 0;
for (auto&& deserializedMessage : deserializedMessages) {
cppkafka::Message& rawMessage = rawMessages[rawIx++];
if (rawIx > rawMessages.size()) {
throw std::out_of_range("Invalid message index");
}
cppkafka::CallbackInvoker<Receiver>("receiver", entry._configuration.getTypeErasedReceiver(), entry._consumer.get())
(*entry._committer,
entry._offsets,
std::move(rawMessage), //kafka raw message
std::get<0>(std::move(deserializedMessage)), //key
std::get<1>(std::move(deserializedMessage)), //payload
std::get<2>(std::move(deserializedMessage)), //headers
std::get<3>(std::move(deserializedMessage)), //error
makeOffsetPersistSettings(entry));
}
if (rawIx != rawMessages.size()) {
throw std::runtime_error("Not all messages were processed");
}
return 0;
}
int ConsumerManagerImpl::receiverSingleBatchTask(ConsumerTopicEntry& entry,
std::vector<cppkafka::Message>&& rawMessages,
std::vector<DeserializedMessage>&& deserializedMessages)
{
return invokeSingleBatchReceiver(entry, std::move(rawMessages), std::move(deserializedMessages));
}
bool ConsumerManagerImpl::preprocessorTask(ConsumerTopicEntry& entry,
const cppkafka::Message& kafkaMessage)
{
return entry._preprocessorCallback(cppkafka::TopicPartition(kafkaMessage.get_topic(),
kafkaMessage.get_partition(),
kafkaMessage.get_offset()));
}
int ConsumerManagerImpl::processorCoro(quantum::VoidContextPtr ctx,
ConsumerTopicEntry& entry)
{
//Get the polled messages from the previous stage (non-blocking)
std::deque<MessageTuple> messageQueue = ctx->getPrev<std::deque<MessageTuple>>();
// Enqueue all messages and wait for completion
for (auto& messageTuple : messageQueue) {
try {
auto &message = std::get<0>(messageTuple);
auto deserializedFuture = std::get<1>(messageTuple);
if (entry._receiveOnIoThread) {
// Find out on which IO thread we should process this message
int ioQueue = mapPartitionToQueue(message.get_partition(), entry._receiveCallbackThreadRange);
// Post and wait until delivered
quantum::ICoroFuture<int>::Ptr future =
ctx->postAsyncIo(ioQueue,
false,
receiverTask,
entry,
std::move(message),
deserializedFuture ? deserializedFuture->get(ctx) : DeserializedMessage());
if (entry._receiveCallbackExec == ExecMode::Sync) {
future->get(ctx);
}
}
else {
//call serially on this coroutine
invokeReceiver(entry,
std::move(message),
deserializedFuture ? deserializedFuture->get(ctx) : DeserializedMessage());
}
}
catch (const std::exception& ex) {
exceptionHandler(ex, entry);
}
}
return 0;
}
void ConsumerManagerImpl::exceptionHandler(const std::exception& ex,
const ConsumerTopicEntry& topicEntry)
{
handleException(ex, makeMetadata(topicEntry), topicEntry._configuration, topicEntry._logLevel);
}
ConsumerMetadata ConsumerManagerImpl::makeMetadata(const ConsumerTopicEntry& topicEntry)
{
return ConsumerMetadata(topicEntry._configuration.getTopic(),
topicEntry._consumer.get(),
topicEntry._configuration.getPartitionStrategy());
}
int ConsumerManagerImpl::mapPartitionToQueue(int partition,
const std::pair<int,int>& range)
{
return (partition % (range.second - range.first + 1)) + range.first;
}
OffsetPersistSettings ConsumerManagerImpl::makeOffsetPersistSettings(const ConsumerTopicEntry& topicEntry)
{
return {topicEntry._autoOffsetPersist,
topicEntry._autoOffsetPersistOnException,
topicEntry._autoOffsetPersistStrategy,
topicEntry._autoCommitExec};
}
ConsumerManagerImpl::Consumers::iterator
ConsumerManagerImpl::findConsumer(const std::string& topic)
{
auto it = _consumers.find(topic);
if (it == _consumers.end()) {
throw std::runtime_error("Invalid topic");
}
return it;
}
ConsumerManagerImpl::Consumers::const_iterator
ConsumerManagerImpl::findConsumer(const std::string& topic) const
{
auto it = _consumers.find(topic);
if (it == _consumers.end()) {
throw std::runtime_error("Invalid topic");
}
return it;
}
}
}
| 43.520115 | 154 | 0.611571 |
85beaa553c98c788002eef0f4d070a28bd621981 | 5,831 | cpp | C++ | pimc/particleContainer/particleContainer.cpp | lucaparisi91/qmc4 | f1ad1b105568500c9a8259e509dd3e01a933a050 | [
"MIT"
] | null | null | null | pimc/particleContainer/particleContainer.cpp | lucaparisi91/qmc4 | f1ad1b105568500c9a8259e509dd3e01a933a050 | [
"MIT"
] | null | null | null | pimc/particleContainer/particleContainer.cpp | lucaparisi91/qmc4 | f1ad1b105568500c9a8259e509dd3e01a933a050 | [
"MIT"
] | null | null | null |
#include "particleContainer.h"
#include <array>
#include <cmath>
#include <cassert>
#include <exception>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <memory.h>
#include "../pimcConfigurations.h"
namespace pimc
{
template<int d>
inline int indexFortranStorage(const int* im, const int* sizes)
{
return sizes[0]*( sizes[1]*im[2] + im[1] ) + im[0] ;
}
template<int d>
void indicesFromIndexFortranStorage(int* im, int cellIndex,const int* sizes)
{
im[0]=cellIndex%sizes[0];
cellIndex-=im[0];
cellIndex/=sizes[0];
im[1]=cellIndex%sizes[1];
cellIndex-=im[1];
cellIndex/=sizes[1];
im[2]=cellIndex;
}
auto wrap( int index, int N)
{
if (index < 0) {return index + N;};
if (index >= N) {return index - N ;}
return index;
};
auto nDisplacement( int index , int N )
{
if (index<0) return +1;
if (index>=N) return - 1;
return 0;
}
simpleCellNeighbourList::simpleCellNeighbourList(std::array<size_t,getDimensions()> nCells, std::array<Real,getDimensions()> lBox ) :
_nCells(nCells),
_lBox(lBox),
nParticles(0)
{
int nCellsTotal=1;
for(int d=0;d<getDimensions();d++)
{
nCellsTotal*=nCells[d];
_left[d]=-lBox[d]/2;
_right[d]=lBox[d]/2;
_delta[d]=_lBox[d]/_nCells[d];
_lBoxInverse[d]=1/_lBox[d];
}
cells.resize(nCellsTotal);
for ( size_t i=0;i<nCellsTotal;i++)
{
cells[i]=(new cell{});
}
for (int i=0;i<_nCells[0];i++)
for (int j=0;j<_nCells[1];j++)
for (int k=0;k<_nCells[2];k++)
{
auto & neighbours = getCell(i,j,k).neighbours();
auto & displacements = getCell(i,j,k).displacements();
getCell(i,j,k).setCellIndex({i,j,k});
int iNeigh=0;
for (int ii=i-1;ii<=i+1;ii++)
for (int jj=j-1;jj<=j+1;jj++)
for (int kk=k-1;kk<=k+1;kk++)
{
if ( (ii==i) and (jj==j) and (kk==k) )
{
continue;
}
int iii=wrap(ii,_nCells[0]);
int jjj=wrap(jj,_nCells[1]);
int kkk=wrap(kk,_nCells[2]);
neighbours[iNeigh]= & (getCell(iii,jjj,kkk) );
displacements(iNeigh,0)=nDisplacement(ii,_nCells[0])*_lBox[0];
displacements(iNeigh,1)=nDisplacement(jj,_nCells[1])*_lBox[1];
displacements(iNeigh,2)=nDisplacement(kk,_nCells[2])*_lBox[2];
iNeigh++;
}
}
}
simpleCellNeighbourList::~simpleCellNeighbourList()
{
for ( int i=0;i<cells.size();i++)
{
delete cells[i];
}
}
void simpleCellNeighbourList::setCapacity(size_t N)
{
cellIndexPerParticle.resize( N );
subIndexPerParticle.resize( N);
isParticleRemoved.resize(N,true);
for ( auto cell : cells)
{
//cell->setCapacity(N);
}
}
cell::cell( size_t nMaxParticles) : _nMaxParticles(nMaxParticles),
_displacements( std::pow(3,getDimensions() ) - 1 ,getDimensions() ),
_nParticles(0),
nBuffer(10),
_index{0,0,0} {
int nNeighbours=std::pow(3,getDimensions()) -1;
_displacements.setConstant(0);
_neighbours.resize( nNeighbours,nullptr);
};
void cell::setCapacity(size_t N)
{
_particleIndex.resize(N);
_nMaxParticles=N;
}
linkedCellParticles::linkedCellParticles( std::array<size_t,getDimensions()> nCells, std::array<Real,getDimensions() > lBox ) :
_nCells(nCells),
_lBox(lBox)
{}
void linkedCellParticles::setCapacity(size_t N,size_t M)
{
auto oldSize=particles.size();
particles.resize( M + 1);
for(int i=oldSize;i<M + 1;i++)
{
particles[i]=std::make_shared<linkedCell_t>(_nCells,_lBox);
};
for(int i=0;i<M + 1;i++)
{
particles[i]->setCapacity(N);
}
}
void linkedCellParticles::add( const Eigen::Tensor<Real,3> & data, const range_t & timeRange,const range_t & particleRange)
{
for (int t=timeRange[0]; t<=timeRange[1]+1;t++)
{
for(int i=particleRange[0];i<=particleRange[1];i++)
{
particles[t]->add(i, data(i,0,t),data(i,1,t),data(i,2,t));
}
}
}
void linkedCellParticles::add( const Eigen::Tensor<Real,3> & data, const mask_t & mask, const range_t & timeRange,const range_t & particleRange)
{
for (int t=timeRange[0]; t<=timeRange[1]+1;t++)
{
for(int i=particleRange[0];i<=particleRange[1];i++)
{
if ( mask(i,t) == 1 )
{
particles[t]->add(i, data(i,0,t),data(i,1,t),data(i,2,t));
}
}
}
}
void linkedCellParticles::update( const Eigen::Tensor<Real,3> & data, const range_t & timeRange,const range_t & particleRange)
{
remove(timeRange,particleRange);
add(data,timeRange,particleRange);
}
void linkedCellParticles::update( const Eigen::Tensor<Real,3> & data, const mask_t & mask, const range_t & timeRange,const range_t & particleRange)
{
remove(timeRange,particleRange);
add(data,mask,timeRange,particleRange);
}
void linkedCellParticles::remove( const range_t & timeRange,const range_t & particleRange)
{
for (int t=timeRange[0]; t<=timeRange[1]+1;t++)
{
for(int i=particleRange[0];i<=particleRange[1];i++)
{
particles[t]->remove(i);
}
}
}
}
| 24.295833 | 149 | 0.537644 |
85c14746d830a377c8fc64b56d5af9c8ae2a6ffa | 7,462 | cxx | C++ | Modules/Radiometry/Simulation/test/otbImageSimulationMethodKMeansClassif.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/Radiometry/Simulation/test/otbImageSimulationMethodKMeansClassif.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | Modules/Radiometry/Simulation/test/otbImageSimulationMethodKMeansClassif.cxx | qingswu/otb | ed903b6a5e51a27a3d04786e4ad1637cf6b2772e | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbVectorImage.h"
#include "otbImageFileWriter.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataToLabelMapWithAttributesFilter.h"
#include "otbSpatialisationFilter.h"
#include "otbImageSimulationMethod.h"
#include "otbAttributesMapLabelObject.h"
#include "otbImageFileReader.h"
#include "itkWeightedCentroidKdTreeGenerator.h"
#include "itkKdTreeBasedKmeansEstimator.h"
#include "otbKMeansImageClassificationFilter.h"
int otbImageSimulationMethodKMeansClassif(int itkNotUsed(argc), char* argv[])
{
const char* satRSRFilename = argv[1];
unsigned int nbBands = static_cast<unsigned int>(atoi(argv[2]));
const char* rootPath = argv[3];
unsigned int radius = atoi(argv[4]);
const char* outfilename = argv[5];
const char* outLabelfilename = argv[6];
const unsigned int nbClasses = 4;
double ConvergenceThreshold = 0.0001;
unsigned int NumberOfIterations = 1000;
typedef unsigned short LabelType;
const unsigned int Dimension = 2;
typedef otb::Image<LabelType, Dimension> LabelImageType;
typedef otb::VectorImage<double, Dimension> OutputImageType;
typedef otb::ImageFileWriter<OutputImageType> ImageWriterType;
typedef otb::ImageFileWriter<LabelImageType> LabelImageWriterType;
typedef otb::VectorData<double, Dimension> VectorDataType;
typedef otb::AttributesMapLabelObject<LabelType, Dimension, std::string> LabelObjectType;
typedef itk::LabelMap<LabelObjectType> LabelMapType;
typedef otb::SpatialisationFilter<LabelMapType> SpatialisationFilterType;
typedef otb::ProspectModel SimulationStep1Type;
typedef otb::SailModel SimulationStep2Type;
typedef otb::ProlateInterpolateImageFunction<LabelImageType> FTMType;
typedef otb::ImageSimulationMethod<VectorDataType, SpatialisationFilterType, SimulationStep1Type, SimulationStep2Type, FTMType, OutputImageType>
ImageSimulationMethodType;
typedef OutputImageType::PixelType SampleType;
typedef itk::Statistics::ListSample<SampleType> ListSampleType;
typedef itk::Statistics::WeightedCentroidKdTreeGenerator<ListSampleType> TreeGeneratorType;
typedef TreeGeneratorType::KdTreeType TreeType;
typedef itk::Statistics::KdTreeBasedKmeansEstimator<TreeType> EstimatorType;
typedef otb::KMeansImageClassificationFilter<OutputImageType, LabelImageType, nbClasses> ClassificationFilterType;
typedef itk::ImageRegionIterator<OutputImageType> ImageRegionIteratorType;
/** Instantiation of pointer objects*/
ImageWriterType::Pointer writer = ImageWriterType::New();
LabelImageWriterType::Pointer labelWriter = LabelImageWriterType::New();
ImageSimulationMethodType::Pointer imageSimulation = ImageSimulationMethodType::New();
SpatialisationFilterType::Pointer spatialisationFilter = SpatialisationFilterType::New();
ClassificationFilterType::Pointer classifier = ClassificationFilterType::New();
SpatialisationFilterType::SizeType objectSize;
objectSize[0] = 300;
objectSize[1] = 300;
SpatialisationFilterType::SizeType nbOjects;
nbOjects[0] = 2;
nbOjects[1] = 2;
std::vector<std::string> pathVector(nbClasses);
pathVector[0] = "JHU/becknic/rocks/sedimentary/powder/0_75/txt/greywa1f.txt";
pathVector[1] = "";
pathVector[2] = "JHU/becknic/water/txt/coarse.txt";
pathVector[3] = "JHU/becknic/soils/txt/0015c.txt";
std::vector<std::string> areaVector(nbClasses);
areaVector[0] = "sedimentaryRock";
areaVector[1] = "prosail";
areaVector[2] = "water";
areaVector[3] = "soils";
std::vector<LabelType> labels(nbClasses);
labels[0] = 1;
labels[1] = 2;
labels[2] = 3;
labels[3] = 4;
spatialisationFilter->SetObjectSize(objectSize);
spatialisationFilter->SetNumberOfObjects(nbOjects);
spatialisationFilter->SetPathVector(pathVector);
spatialisationFilter->SetAreaVector(areaVector);
spatialisationFilter->SetLabels(labels);
imageSimulation->SetSpatialisation(spatialisationFilter);
imageSimulation->SetNumberOfComponentsPerPixel(nbBands);
imageSimulation->SetSatRSRFilename(satRSRFilename);
imageSimulation->SetPathRoot(rootPath);
imageSimulation->SetRadius(radius);
// imageSimulation->SetMean();
// imageSimulation->SetVariance();
imageSimulation->UpdateData();
imageSimulation->GetOutputReflectanceImage()->Update();
// get all the pixel of the image for KMeans centroid estimation
OutputImageType::IndexType centroidIndex;
centroidIndex[0] = objectSize[0] / 2;
centroidIndex[1] = objectSize[1] / 2;
EstimatorType::ParametersType initialCentroids(nbBands * nbClasses);
ImageRegionIteratorType it(imageSimulation->GetOutputReflectanceImage(), imageSimulation->GetOutputReflectanceImage()->GetLargestPossibleRegion());
it.GoToBegin();
ListSampleType::Pointer listSample = ListSampleType::New();
listSample->SetMeasurementVectorSize(nbBands);
unsigned int x = 0;
unsigned int classIndex = 0;
while (!it.IsAtEnd())
{
if (it.GetIndex() == centroidIndex)
{
for (unsigned int j = 0; j < nbBands; ++j)
{
initialCentroids[j + classIndex * nbBands] = it.Get()[j];
}
classIndex++;
if (x < (nbOjects[0] - 1))
{
centroidIndex[0] += objectSize[0];
x++;
}
else
{
x = 0;
centroidIndex[0] = objectSize[0] / 2;
centroidIndex[1] += objectSize[1];
}
}
listSample->PushBack(it.Get());
++it;
}
TreeGeneratorType::Pointer treeGenerator = TreeGeneratorType::New();
treeGenerator->SetSample(listSample);
treeGenerator->SetBucketSize(100 / (10 * nbClasses));
treeGenerator->Update();
EstimatorType::Pointer estimator = EstimatorType::New();
estimator->SetKdTree(treeGenerator->GetOutput());
estimator->SetParameters(initialCentroids);
estimator->SetMaximumIteration(NumberOfIterations);
estimator->SetCentroidPositionChangesThreshold(ConvergenceThreshold);
estimator->StartOptimization();
classifier->SetCentroids(estimator->GetParameters());
classifier->SetInput(imageSimulation->GetOutputReflectanceImage());
// Write the result to an image file
writer->SetFileName(outfilename);
writer->SetInput(imageSimulation->GetOutputReflectanceImage());
writer->Update();
labelWriter->SetFileName(outLabelfilename);
// labelWriter->SetInput(imageSimulation->GetOutputLabelImage());
labelWriter->SetInput(classifier->GetOutput());
labelWriter->Update();
return EXIT_SUCCESS;
}
| 38.266667 | 155 | 0.719244 |
85c2389dec561ca7a80bd6c08f9934a6746ac57a | 7,736 | cpp | C++ | appsrc/DistributedConfigGenerator.cpp | slashdotted/PomaPure | c469efba9813b4b897129cff9699983c3f90b24b | [
"BSD-3-Clause"
] | 2 | 2017-12-11T01:07:45.000Z | 2021-08-21T20:57:04.000Z | appsrc/DistributedConfigGenerator.cpp | slashdotted/PomaPure | c469efba9813b4b897129cff9699983c3f90b24b | [
"BSD-3-Clause"
] | null | null | null | appsrc/DistributedConfigGenerator.cpp | slashdotted/PomaPure | c469efba9813b4b897129cff9699983c3f90b24b | [
"BSD-3-Clause"
] | 1 | 2017-08-29T17:53:20.000Z | 2017-08-29T17:53:20.000Z | /*
* Copyright (C)2015,2016,2017 Amos Brocco (amos.brocco@supsi.ch)
* Scuola Universitaria Professionale della
* Svizzera Italiana (SUPSI)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Scuola Universitaria Professionale della Svizzera
* Italiana (SUPSI) 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 <COPYRIGHT HOLDER> 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 <boost/property_tree/json_parser.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdlib>
#include "DistributedConfigGenerator.h"
#include <iostream>
namespace poma {
DistributedConfigGenerator::DistributedConfigGenerator(const std::string &p_source_mid,
const std::map<std::string, Module> &p_modules,
const std::vector<Link> &p_links,
unsigned int base_port)
: m_source_mid{p_source_mid}, m_modules{p_modules}, m_links{p_links}, m_base_port{base_port} {
}
void DistributedConfigGenerator::process()
{
for (auto &it : m_modules) {
auto v{m_modules.find(it.first)};
const Module &mod{v->second};
m_host_modules_map.insert(std::make_pair(mod.mhost, mod));
m_module_host_map.insert(std::make_pair(mod.mid, mod.mhost));
}
std::string source_host{m_module_host_map.find(m_source_mid)->second};
Link lnkprocessor;
lnkprocessor.fid = Module::source(source_host);
lnkprocessor.tid = m_source_mid;
m_host_link_map.insert(std::make_pair(source_host, lnkprocessor));
for (auto &lnk : m_links) {
if (lnk.fid == "" || m_module_host_map.count(lnk.fid) == 0) {
die("invalid link definition: invalid or no source specified: " + lnk.fid + ", to " + lnk.tid +
", channel " + lnk.channel);
}
if (lnk.tid == "" || m_module_host_map.count(lnk.tid) == 0) {
die("invalid link definition: invalid or no destination specified: " + lnk.tid + ", from " + lnk.fid +
", channel " + lnk.channel);
}
if (lnk.channel == "") {
die("invalid link definition: channel cannot be empty");
}
std::string fhost{m_module_host_map[lnk.fid]};
std::string thost{m_module_host_map[lnk.tid]};
if (fhost == thost) {
std::cout << fhost << "<->" << thost << std::endl;
m_host_link_map.insert(std::make_pair(fhost, lnk));
} else {
// Insert ZeroMQ bridge
Module sink;
sink.mid = Module::unique("__net_sink_");
sink.mtype = "ZeroMQSink";
sink.mhost = fhost;
sink.mparams["sinkaddress"] = Module::address(thost, m_base_port);
sink.mparams["#bandwidth"] = lnk.bandwidth;
Module source;
source.mid = Module::unique("__net_source");
source.mtype = "ZeroMQSource";
source.mhost = thost;
source.mparams["sourceaddress"] = Module::address("*", m_base_port);
source.mparams["#bandwidth"] = lnk.bandwidth;
++m_base_port;
m_host_modules_map.insert(std::make_pair(sink.mhost, sink));
m_host_modules_map.insert(std::make_pair(source.mhost, source));
m_module_host_map[sink.mid] = sink.mhost;
m_module_host_map[source.mid] = source.mhost;
Link lnksink;
lnksink.fid = lnk.fid;
lnksink.tid = sink.mid;
lnksink.channel = lnk.channel;
lnksink.debug = lnk.debug;
lnksink.bandwidth = lnk.bandwidth;
m_host_link_map.insert(std::make_pair(fhost, lnksink));
Link lnksource;
lnksource.fid = source.mid;
lnksource.tid = lnk.tid;
lnksource.channel = lnk.channel;
lnksource.debug = lnk.debug;
lnksource.bandwidth = lnk.bandwidth;
m_host_link_map.insert(std::make_pair(thost, lnksource));
Link lnkprocessor;
lnkprocessor.fid = Module::source(thost);
lnkprocessor.tid = source.mid;
m_host_link_map.insert(std::make_pair(thost, lnkprocessor));
}
}
// Each host must have a ParProcessor module as source
for (auto const &h: hosts()) {
Module source_pp;
source_pp.mid = Module::source(h);
source_pp.mhost = h;
source_pp.mtype = "ParProcessor";
m_host_modules_map.insert(std::make_pair(source_pp.mhost, source_pp));
m_module_host_map.insert(std::make_pair(source_pp.mid, source_pp.mhost));
}
}
void DistributedConfigGenerator::get_config(const std::string &host, std::string &p_source_mid,
std::map<std::string, Module> &p_modules,
std::vector<Link> &p_links) {
p_source_mid = Module::source(host);
auto iter = m_host_modules_map.equal_range(host);
for (auto it = iter.first; it != iter.second; ++it) {
const Module& module{it->second};
p_modules[module.mid] = module;
}
auto iter2 = m_host_link_map.equal_range(host);
for (auto it = iter2.first; it != iter2.second; ++it) {
p_links.push_back(it->second);
}
}
std::set<std::string> DistributedConfigGenerator::hosts() const {
std::set<std::string> hosts;
for(auto const& h: m_host_modules_map) {
hosts.insert(h.first);
}
return hosts;
}
std::set<std::string> DistributedConfigGenerator::modules(const std::string &host) const {
std::set<std::string> modules;
auto iter = m_host_modules_map.equal_range(host);
for (auto it = iter.first; it != iter.second; ++it) {
const Module& module{it->second};
modules.insert(module.mtype);
}
return modules;
}
} | 47.460123 | 118 | 0.586608 |
85c3a32ec8a115fac835f0e829db3cbda2aa6e23 | 35,918 | cpp | C++ | csl/cslbase/arith07.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | csl/cslbase/arith07.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | csl/cslbase/arith07.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | // arith07.cpp Copyright (C) 1990-2020 Codemist
//
// Arithmetic functions. negation plus a load of Common Lisp things
// for support of complex numbers.
//
//
/**************************************************************************
* Copyright (C) 2020, Codemist. A C Norman *
* *
* 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 relevant *
* copyright notice, this list of conditions and the following *
* disclaimer. *
* * Redistributions in binary form must reproduce the above *
* copyright notice, this list of conditions and the following *
* disclaimer in the documentation and/or other materials provided *
* with the distribution. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT *
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS *
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE *
* COPYRIGHT OWNERS 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. *
*************************************************************************/
// $Id: arith07.cpp 5387 2020-08-20 19:40:24Z arthurcnorman $
#include "headers.h"
LispObject copyb(LispObject a)
//
// copy a bignum.
//
{ LispObject b;
size_t len = bignum_length(a), i;
push(a);
b = get_basic_vector(TAG_NUMBERS, TYPE_BIGNUM, len);
pop(a);
len = (len-CELL)/4;
for (i=0; i<len; i++)
bignum_digits(b)[i] = vbignum_digits(a)[i];
return b;
}
LispObject negateb(LispObject a)
//
// Negate a bignum. Note that negating the 1-word bignum
// value of 0x08000000 will produce a fixnum as a result (for 32 bits),
// which might confuse the caller... in a similar way negating
// the value -0x40000000 will need to promote from a one-word
// bignum to a 2-word bignum. How messy just for negation!
// And on 64 bit systems the same effect applies but with larger values!
// In an analogous manner negating the positive number of the style
// 0x40000000 can lead to a negative result that uses one less digit.
// Well on a 64-bit machine it is a 2-word bignum that can end up
// negated to get a fixnum result.
//
{ LispObject b;
size_t len = bignum_length(a), i;
int32_t carry;
// There are two messy special cases here. The first is that there is a
// positive value (2^27 or 2^59) which has to be represented as a bignum,
// but when you negate it you get a fixnum.
// Then there will be negative values (the smallest being -2^31 or -2^62)
// that fit in a certain number of words of bignum, but their absolute
// value needs one more word...
// Note that on a 64-bit machine there ought never to be any one-word
// bignums because all the values representable with just one 31-bit digit
// can be handled as fixnums instead.
if (SIXTY_FOUR_BIT &&
len == CELL+8) // two-word bignum - do specially
{ if (bignum_digits(a)[0] == 0 &&
bignum_digits(a)[1] == (int32_t)0x10000000)
return MOST_NEGATIVE_FIXNUM;
else if (bignum_digits(a)[0] == 0 &&
(int32_t)bignum_digits(a)[1] == -(int32_t)(1<<30))
return make_three_word_bignum(0, 1<<30, 0);
uint32_t d0 = bignum_digits(a)[0];
int32_t d1 = (int32_t)~bignum_digits(a)[1];
if (d0 == 0) d1++;
else return make_two_word_bignum(d1, (-d0) & 0x7fffffff);
}
if (!SIXTY_FOUR_BIT &&
len == CELL+4) // one-word bignum - do specially
{ int32_t d0 = -(int32_t)bignum_digits(a)[0];
if (d0 == MOST_NEGATIVE_FIXVAL) return MOST_NEGATIVE_FIXNUM;
else if (d0 == 0x40000000) return make_two_word_bignum(0, d0);
else return make_one_word_bignum(d0);
}
push(a);
b = get_basic_vector(TAG_NUMBERS, TYPE_BIGNUM, len);
pop(a);
len = (len-CELL-4)/4;
carry = -1;
for (i=0; i<len; i++)
{
// The next couple of lines really caught me out wrt compiler optimisation
// before I put in all the casts. I used to have what was in effect
// carry = (signed_x ^ 0x7fffffff) + (int32_t)((uint32_t)carry>>31);
// ... ((uint32_t)carry >> 31);
// and a compiler seems to have observed that the masking leaves the left
// operand of the addition positive, and that the unsigned shift right
// leaves the right operand positive too. So based on an assumption that
// signed integer overflow will not happen it deduces that the sum will also
// be positive, and hence that on the next line (carry>>31) will be zero.
// For the assumption to fail there will have had to be integer overflow, and
// the C/C++ standards say that the consequence of that are undefined - a term
// that can include behaviour as per the optimised code here.
//
// To avoid that I am working on the basis that casts between int32_t and
// uint32_t will leave bit representations unchanged and that arithmetic uses
// twos complement for signed values. Then by casting to unsigned at times
// I can allow a carry to propagate into the top bit of a word without that
// counting as an overflow, and that should force the compiler to do the
// arithmetic in full.
//
// Having spotted this particular case I now worry about how many related
// ones there may be hiding in the code!
//
carry = ADD32(clear_top_bit(~bignum_digits(a)[i]),
top_bit(carry));
bignum_digits(b)[i] = clear_top_bit(carry);
}
// Handle the top digit separately since it is signed.
carry = ADD32(~bignum_digits(a)[i], top_bit(carry));
if (!signed_overflow(carry))
{
// If the most significant word ends up as -1 then I just might
// have 0x40000000 in the next word down and so I may need to shrink
// the number. Since I handled 1-word bignums specially I have at
// least two words to deal with here.
if (carry == -1 && (bignum_digits(b)[i-1] & 0x40000000) != 0)
{ bignum_digits(b)[i-1] |= ~0x7fffffff;
setnumhdr(b, numhdr(b) - pack_hdrlength(1));
if (SIXTY_FOUR_BIT)
{ if ((i & 1) != 0) bignum_digits(b)[i] = 0;
else *reinterpret_cast<Header *>(&bignum_digits(b)[i]) = make_bighdr(
2);
}
else
{ if ((i & 1) == 0) bignum_digits(b)[i] = 0;
else *reinterpret_cast<Header *>(&bignum_digits(b)[i]) = make_bighdr(
2);
}
}
else bignum_digits(b)[i] = carry; // no shrinking needed
return b;
}
// Here I have overflow: this can only happen when I negate a number
// that started off with 0xc0000000 in the most significant digit,
// and I have to pad a zero word onto the front.
bignum_digits(b)[i] = clear_top_bit(carry);
return lengthen_by_one_bit(b, carry);
}
//
// generic negation
//
LispObject negate(LispObject a)
{ switch (static_cast<int>(a) & TAG_BITS)
{ case TAG_FIXNUM:
if (!SIXTY_FOUR_BIT && is_sfloat(a))
return a ^ 0x80000000U;
if (SIXTY_FOUR_BIT && is_sfloat(a))
return a ^ UINT64_C(0x8000000000000000);
else return make_lisp_integer64(-int_of_fixnum(a));
case TAG_NUMBERS:
{ int32_t ha = type_of_header(numhdr(a));
switch (ha)
{ case TYPE_BIGNUM:
return negateb(a);
case TYPE_RATNUM:
{ LispObject n = numerator(a),
d = denominator(a);
push(d);
n = negate(n);
pop(d);
return make_ratio(n, d);
}
case TYPE_COMPLEX_NUM:
{ LispObject r = real_part(a),
i = imag_part(a);
push(i);
r = negate(r);
pop(i);
push(r);
i = negate(i);
pop(r);
return make_complex(r, i);
}
default:
return aerror1("bad arg for minus", a);
}
}
case TAG_BOXFLOAT:
switch (type_of_header(flthdr(a)))
{ case TYPE_SINGLE_FLOAT:
return make_boxfloat(-single_float_val(a),
TYPE_SINGLE_FLOAT);
case TYPE_DOUBLE_FLOAT:
return make_boxfloat(-double_float_val(a),
TYPE_DOUBLE_FLOAT);
#ifdef HAVE_SOFTFLOAT
case TYPE_LONG_FLOAT:
{ float128_t aa = long_float_val(a);
f128M_negate(&aa);
return make_boxfloat128(aa);
}
#endif // HAVE_SOFTFLOAT
}
default:
return aerror1("bad arg for minus", a);
}
}
/*****************************************************************************/
//** Transcendental functions etcetera. **
/*****************************************************************************/
//
// Much of the code here is extracted from the portable Fortran library
// used by Codemist with its Fortran compiler.
//
//
// The object of the following macro is to adjust the floating point
// variables concerned so that the more significant one can be squared
// with NO LOSS OF PRECISION. It is only used when there is no danger
// of over- or under-flow.
//
// This code is NOT PORTABLE but can be modified for use elsewhere
// It should, however, serve for IEEE and IBM FP formats.
//
typedef union _char_double
{ double d;
char c[8];
} char_double_union;
#ifdef LITTLEENDIAN
#define LOW_BITS_OFFSET 0
#else
#define LOW_BITS_OFFSET 4
#endif
// The code here explictly puns between a double and a row of char values
// so that it can force the bottom 32-bits of the represenattion of the
// double to be zero. The use of the char type here and then memset to clear
// it is intended to keep me safe from strict-aliasing concerns, and modern
// C compilers are liable to map the use of memset onto a simple store
// instruction.
#define _fp_normalize(high, low) \
{ char_double_union temp; /* access to representation */ \
temp.d = high; /* take original number */ \
std::memset(&temp.c[LOW_BITS_OFFSET], 0, 4); \
/* make low part of mantissa 0 */ \
low += (high - temp.d); /* add into low-order result */ \
high = temp.d; \
}
//
// A modern C system will provide a datatype "complex double" which
// will (I hope) provide direct implementations of some things I need
// here. However in the end I may prefer not to use it because for
// real floating point I am using crlibm that implements correctly
// rounded and hence consistent across all platforms values. If I use
// that as a basis for my complex code I will at least get bit-for-bit
// identical results everywhere even if I do not manage to achieve
// correctly rounded last-bit performance in all cases.
// log, sqrt and all the inverse trig functions here need careful review
// as to their treatment of -0.0 on branch-cuts!
//
double Cabs(Complex z)
{
//
// Obtain the absolute value of a complex number - note that the main
// agony here is in ensuring that neither overflow nor underflow can
// wreck the calculation. Given ideal arithmetic the sum could be carried
// through as just sqrt(x^2 + y^2).
//
double x = z.real, y = z.imag;
double scale;
int n1, n2;
if (x==0.0) return std::fabs(y);
else if (y==0.0) return std::fabs(x);
static_cast<void>(std::frexp(x, &n1));
static_cast<void>(std::frexp(y, &n2));
// The exact range of values returned by frexp does not matter here
if (n2>n1) n1 = n2;
// n1 is now the exponent of the larger (in absolute value) of x, y
scale = std::ldexp(1.0, n1); // can not be 0.0
x /= scale;
y /= scale;
// The above scaling operation introduces no rounding error (since the
// scale factor is exactly a power of 2). It reduces the larger of x, y
// to be somewhere near 1.0 so overflow in x*x+y*y is impossible. It is
// still possible that one of x*x and y*y will underflow (but not both)
// but this is harmless.
return scale * std::sqrt(x*x + y*y);
}
Complex Ccos(Complex z)
{ double x = z.real, y = z.imag;
//
// cos(x + iy) = cos(x)*cosh(y) - i sin(x)*sinh(y)
// For smallish y this can be used directly. For |y| > 50 I will
// compute sinh and cosh as just +/- exp(|y|)/2
//
double s = std::sin(x), c = std::cos(x);
double absy = std::fabs(y);
if (absy <= 50.0)
{ double sh = std::sinh(y), ch = std::cosh(y);
z.real = c*ch;
z.imag = - s*sh;
return z;
}
else
{ double w;
int n = _reduced_exp(absy, &w) - 1;
z.real = std::ldexp(c*w, n);
if (y < 0.0) z.imag = std::ldexp(s*w, n);
else z.imag = std::ldexp(-s*w, n);
return z;
}
}
static double reduced_power(double a, int n)
{
//
// Compute (1 + a)^n - 1 avoiding undue roundoff error.
// Assumes n >= 1 on entry and that a is small.
//
if (n == 1) return a;
{ double d = reduced_power(a, n/2);
d = (2.0 + d)*d;
if (n & 1) d += (1.0 + d)*a;
return d;
}
}
//
// The following value is included for documentation purposes - it
// give the largest args that can be given to exp() without leading to
// overflow on IEEE-arithmetic machines.
// #define _exp_arg_limit 709.78271289338397
// Note that in any case exp(50.0) will not overflow (it is only 5.2e21),
// so it can be evaluated the simple direct way.
//
int _reduced_exp(double x, double *r)
{
//
// (*r) = exp(x)/2^n; return n;
// where n will be selected so that *r gets set to a fairly small value
// (precise range of r unimportant provided it will be WELL away from
// chances of overflow, even when exp(x) would actually overflow). This
// function may only be called with argument x that is positive and
// large enough that n will end up satisfying n>=1. The coding here
// will ensure that if x>4.0, and in general the use of this function
// will only be for x > 50.
// For IBM hardware it would be good to be able to control the value
// of n mod 4, maybe, to help counter wobbling precision. This is not
// done here.
//
int n;
double f;
n = static_cast<int>(x / 7.625 + 0.5);
//
// 7.625 = 61/8 and is expected to have an exact floating point
// representation here, so f is computed without any rounding error.
// (do I need something like the (x - 0.5) - 0.5 trick here?)
//
f = std::exp(x - 7.625*static_cast<double>(n));
//
// the magic constant is ((exp(61/8) / 2048) - 1) and it arises because
// 61/88 is a decent rational approximation to log(2), hence exp(61/8)
// is almost 2^11. Thus I compute exp(x) as
// 2^(11*n) * (exp(61/8)/2^11)^n * exp(f)
// The first factor is exact, the second is (1+e)^n where e is small and
// n is an integer, so can be computer accurately, and the residue f at the
// end is small enough not to give over-bad trouble.
// The numeric constant given here was calculated with the REDUCE 3.3
// bigfloat package.
//
#define _e61q8 3.81086435594567676751e-4
*r = reduced_power(_e61q8, n)*f + f;
#undef _e61q8
return 11*n;
}
Complex Cexp(Complex z)
{ double x = z.real, y = z.imag;
//
// value is exp(x)*(cos(y) + i sin(y)) but have care with overflow
// Here (and throughout the complex library) there is an opportunity
// to save time by computing sin(y) and cos(y) together. Since this
// code is (to begin with) to sit on top of an arbitrary C library,
// perhaps with hardware support for the calculation of real-valued
// trig functions I am not going to try to realise this saving.
//
double s = std::sin(y), c = std::cos(y);
//
// if x > 50 I will use a cautious sceme which computes exp(x) with
// its (binary) exponent separated. Note that 50.0 is chosen as a
// number noticably smaller than _exp_arg_limit (exp(50) = 5.18e21),
// but is not a critical very special number.
//
if (x <= 50.0) // includes x < 0.0, of course
{ double w = std::exp(x);
z.real = w*c;
z.imag = w*s;
return z;
}
else
{ double w;
int n = _reduced_exp(x, &w);
z.real = std::ldexp(w*c, n);
z.imag = std::ldexp(w*s, n);
return z;
}
}
Complex Cln(Complex z)
{ double x = z.real, y = z.imag;
//
// if x and y are both very large then cabs(z) may be out of range
// even though log or if is OK. Thus it is necessary to perform an
// elaborate scaled calculation here, and not just
// z.real = log(cabs(z));
//
double scale, r;
int n1, n2;
if (x==0.0) r = std::log(std::fabs(y));
else if (y==0.0) r = std::log(std::fabs(x));
else
{ static_cast<void>(std::frexp(x, &n1));
static_cast<void>(std::frexp(y, &n2));
// The exact range of values returned by frexp does not matter here
if (n2>n1) n1 = n2;
scale = std::ldexp(1.0, n1);
x /= scale;
y /= scale;
r = std::log(scale) + 0.5*std::log(x*x + y*y);
}
z.real = r;
//
// The C standard is not very explicit about the behaviour of atan2(0.0, -n)
// while for Fortran it is necessary that this returns +pi not -pi. Hence
// with extreme caution I put a special test here.
//
if (y == 0.0)
if (x < 0.0) z.imag = _pi;
else z.imag = 0.0;
else z.imag = std::atan2(y, x);
return z;
}
//
// Complex raising to a power. This seems to be pretty nasty
// to get right, and the code includes extra high precision variants
// on atan() and log(). Further refinements wrt efficiency may be
// possible later on.
// This code has been partially tested, and seems to be uniformly
// better than using just a**b = exp(b*log(a)), but much more careful
// study is needed before it can possibly be claimed that it is
// right in the sense of not throwing away accuracy when it does not
// have to. I also need to make careful checks to verify that the
// correct (principal) value is computed.
//
//
// The next function is used after arithmetic has been done on extra-
// precision numbers so that the relationship between high and low parts
// is no longer known. Re-instate it.
//
#define _two_minus_25 2.98023223876953125e-8 // 2^(-25)
static double fp_add(double a, double b, double *lowres)
{
// Result is the high part of a+b, with the low part assigned to *lowres
double absa, absb;
if (a >= 0.0) absa = a;
else absa = -a;
if (b >= 0.0) absb = b;
else absb = -b;
if (absa < absb)
{ double t = a; a = b; b = t;
}
// Now a is the larger (in absolute value) of the two numbers
if (absb > absa * _two_minus_25)
{ double al = 0.0, bl = 0.0;
//
// If the exponent difference beweeen a and b is no more than 25 then
// I can add the top part (20 or 24 bits) of a to the top part of b
// without going beyond the 52 or 56 bits that a full mantissa can hold.
//
_fp_normalize(a, al);
_fp_normalize(b, bl);
a = a + b; // No rounding needed here
b = al + bl;
if (a == 0.0)
{ a = b;
b = 0.0;
}
}
//
// The above step leaves b small wrt the value in a (unless a+b led
// to substantial cancellation of leading digits), but leaves the high
// part a with bits everywhere. Force low part of a to zero.
//
{ double al = 0.0;
_fp_normalize(a, al);
b = b + al;
}
if (a >= 0.0) absa = a;
else absa = -a;
if (b >= 0.0) absb = b;
else absb = -b;
if (absb > absa * _two_minus_25)
//
// If on input a is close to -b, then a+b is close to zero. In this
// case the exponents of a abd b matched, and so earlier calculations
// have all been done exactly. Go around again to split residue into
// high and low parts.
//
{ double al = 0.0, bl = 0.0;
_fp_normalize(b, bl);
a = a + b;
_fp_normalize(a, al);
b = bl + al;
}
*lowres = b;
return a;
}
#undef _two_minus_25
static void extended_atan2(double b, double a, double *thetah,
double *thetal)
{ int octant;
double rh, rl, thh, thl;
//
// First reduce the argument to the first octant (i.e. a, b both +ve,
// and b <= a).
//
if (b < 0.0)
{ octant = 4;
a = -a;
b = -b;
}
else octant = 0;
if (a < 0.0)
{ double t = a;
octant += 2;
a = b;
b = -t;
}
if (b > a)
{ double t = a;
octant += 1;
a = b;
b = t;
}
{ static struct
{ double h;
double l;
} _atan[] =
{
//
// The table here gives atan(n/16) in 1.5-precision for n=0..16
// Note that all the magic numbers used in this file were calculated
// using the REDUCE bigfloat package, and all the 'exact' parts have
// a denominator of at worst 2^26 and so are expected to have lots
// of trailing zero bits in their floating point representation.
//
{ 0.0, 0.0 },
{ 0.06241881847381591796875, -0.84778585694947708870e-8 },
{ 0.124355018138885498046875, -2.35921240630155201508e-8 },
{ 0.185347974300384521484375, -2.43046897565983490387e-8 },
{ 0.2449786663055419921875, -0.31786778380154175187e-8 },
{ 0.302884876728057861328125, -0.83530864557675689054e-8 },
{ 0.358770668506622314453125, 0.17639499059427950639e-8 },
{ 0.412410438060760498046875, 0.35366268088529162896e-8 },
{ 0.4636476039886474609375, 0.50121586552767562314e-8 },
{ 0.512389481067657470703125, -2.07569197640365239794e-8 },
{ 0.558599293231964111328125, 2.21115983246433832164e-8 },
{ 0.602287352085113525390625, -0.59501493437085023057e-8 },
{ 0.643501102924346923828125, 0.58689374629746842287e-8 },
{ 0.6823165416717529296875, 1.32029951485689299817e-8 },
{ 0.71882998943328857421875, 1.01883359311982641515e-8 },
{ 0.75315129756927490234375, -1.66070805128190106297e-8 },
{ 0.785398185253143310546875, -2.18556950009312141541e-8 }
};
int k = static_cast<int>(16.0*(b/a + 0.03125)); // 0 to 16
double kd = static_cast<double>(k)/16.0;
double ah = a, al = 0.0,
bh = b, bl = 0.0,
ch, cl, q, q2;
_fp_normalize(ah, al);
_fp_normalize(bh, bl);
ch = bh - ah*kd; cl = bl - al*kd;
ah = ah + bh*kd; al = al + bl*kd;
bh = ch; bl = cl;
// Now |(a/b)| <= 1/32
ah = fp_add(ah, al, &al); // Re-normalise
bh = fp_add(bh, bl, &bl);
// Compute approximation to b/a
rh = (bh + bl)/(ah + al); rl = 0.0;
_fp_normalize(rh, rl);
bh -= ah*rh; bl -= al*rh;
rl = (bh + bl)/(ah + al); // Quotient now formed
//
// Now it is necessary to compute atan(q) to one-and-a-half precision.
// Since |q| < 1/32 I will leave just q as the high order word of
// the result and compute atan(q)-q as a single precision value. This
// gives about 16 bits accuracy beyond regular single precision work.
//
q = rh + rl;
q2 = q*q;
// The expansion the follows could be done better using a minimax poly
rl -= q*q2*(0.33333333333333333333 -
q2*(0.20000000000000000000 -
q2*(0.14285714285714285714 -
q2*(0.11111111111111111111 -
q2* 0.09090909090909090909))));
// OK - now (rh, rl) is atan(reduced b/a). Need to add on atan(kd)
rh += _atan[k].h;
rl += _atan[k].l;
}
//
// The following constants give high precision versions of pi and pi/2,
// and the high partwords (p2h and pih) have lots of low order zero bits
// in their binary representation. Expect (=require) that the arithmetic
// that computes thh is done without introduced rounding error.
//
#define _p2h 1.57079632580280303955078125
#define _p2l 9.92093579680540441639751e-10
#define _pih 3.14159265160560607910156250
#define _pil 1.984187159361080883279502e-9
switch (octant)
{ default:
case 0: thh = rh; thl = rl; break;
case 1: thh = _p2h - rh; thl = _p2l - rl; break;
case 2: thh = _p2h + rh; thl = _p2l + rl; break;
case 3: thh = _pih - rh; thl = _pil - rl; break;
case 4: thh = -_pih + rh; thl = -_pil + rl; break;
case 5: thh = -_p2h - rh; thl = -_p2l - rl; break;
case 6: thh = -_p2h + rh; thl = -_p2l + rl; break;
case 7: thh = -rh; thl = -rl; break;
}
#undef _p2h
#undef _p2l
#undef _pih
#undef _pil
*thetah = fp_add(thh, thl, thetal);
}
static void extended_log(int k, double a, double b,
double *logrh, double *logrl)
{
//
// If we had exact arithmetic this procedure could be:
// k*log(2) + 0.5*log(a^2 + b^2)
//
double al = 0.0, bl = 0.0, all = 0.0, bll = 0.0, c, ch, cl, cll;
double w, q, qh, ql, rh, rl;
int n;
//
// First (a^2 + b^2) is calculated, using extra precision.
// Because any rounding at this stage can lead to bad errors in
// the power that I eventually want to compute, I use 3-word
// arithmetic here, and with the version of _fp_normalize given
// above and IEEE or IBM370 arithmetic this part of the
// computation is exact.
//
_fp_normalize(a, al); _fp_normalize(al, all);
_fp_normalize(b, bl); _fp_normalize(bl, bll);
ch = a*a + b*b;
cl = 2.0*(a*al + b*bl);
cll = (al*al + bl*bl) +
all*(2.0*(a + al) + all) +
bll*(2.0*(b + bl) + bll);
_fp_normalize(ch, cl);
_fp_normalize(cl, cll);
c = ch + (cl + cll); // single precision approximation
//
// At this stage the scaling of the input value will mean that we
// have 0.25 <= c <= 2.0
//
// Now rewrite things as
// (2*k + n)*log(s) + 0.5*log((a^2 + b^2)/2^n))
// where s = sqrt(2)
// and where the arg to the log is in sqrt(0.5), sqrt(2)
//
#define _sqrt_half 0.70710678118654752440
#define _sqrt_two 1.41421356237309504880
k = 2*k;
while (c < _sqrt_half)
{ k -= 1;
ch *= 2.0;
cl *= 2.0;
cll *= 2.0;
c *= 2.0;
}
while (c > _sqrt_two)
{ k += 1;
ch *= 0.5;
cl *= 0.5;
cll *= 0.5;
c *= 0.5;
}
#undef _sqrt_half
#undef _sqrt_two
n = static_cast<int>(16.0/c + 0.5);
w = static_cast<double>(n) / 16.0;
ch *= w;
cl *= w;
cll *= w; // Now |c-1| < 0.04317
ch = (ch - 0.5) - 0.5;
ch = fp_add(ch, cl, &cl);
cl = cl + cll;
//
// (ch, cl) is now the reduced argument ready for calculating log(1+c),
// and now that the reduction is over I can drop back to the use of just
// two doubleprecision values to represent c.
//
c = ch + cl;
qh = c / (2.0 + c);
ql = 0.0;
_fp_normalize(qh, ql);
ql = ((ch - qh*(2.0 + ch)) + cl - qh*cl) / (2.0 + c);
// (qh, ql) is now c/(2.0 + c)
rh = qh; // 18 bits bigger than low part will end up
q = qh + ql;
w = q*q;
rl = ql + q*w*(0.33333333333333333333 +
w*(0.20000000000000000000 +
w*(0.14285714285714285714 +
w*(0.11111111111111111111 +
w*(0.09090909090909090909)))));
//
// (rh, rl) is now atan(c) correct to double precision plus about 18 bits.
//
{ double temp;
static struct
{ double h;
double l;
} _log_table[] =
{
//
// The following values are (in extra precision) -log(n/16)/2 for n
// in the range 11 to 23 (i.e. roughly over sqrt(2)/2 to sqrt(2))
//
{ 0.1873466968536376953125, 2.786706765149099245e-8 },
{ 0.1438410282135009765625, 0.801238948715710950e-8 },
{ 0.103819668292999267578125, 1.409612298322959552e-8 },
{ 0.066765725612640380859375, -2.930037906928620319e-8 },
{ 0.0322692394256591796875, 2.114312640614896196e-8 },
{ 0.0, 0.0 },
{ -0.0303122997283935546875, -1.117982386660280307e-8 },
{ -0.0588915348052978515625, 1.697710612429310295e-8 },
{ -0.08592510223388671875, -2.622944289242004947e-8 },
{ -0.111571788787841796875, 1.313073691899185245e-8 },
{ -0.135966837406158447265625, -2.033566243215020975e-8 },
{ -0.159226894378662109375, 2.881939480146987639e-8 },
{ -0.18145275115966796875, 0.431498374218108783e-8 }
};
rh = fp_add(rh, _log_table[n-11].h, &temp);
rl = temp + _log_table[n-11].l + rl;
}
#define _exact_part_logroot2 0.3465735912322998046875
#define _approx_part_logroot2 (-9.5232714997888393927e-10)
// Multiply this by k and add it in
{ double temp, kd = static_cast<double>(k);
rh = fp_add(rh, kd*_exact_part_logroot2, &temp);
rl = rl + temp + kd*_approx_part_logroot2;
}
#undef _exact_part_logroot2
#undef _approx_part_logroot2
*logrh = rh;
*logrl = rl;
return;
}
Complex Cpow(Complex z1, Complex z2)
{ double a = z1.real, b = z1.imag,
c = z2.real, d = z2.imag;
int k, m, n;
double scale;
double logrh, logrl, thetah, thetal;
double r, i, rh, rl, ih, il, clow, dlow, q;
double cw, sw, cost, sint;
if (b == 0.0 && d == 0.0 &&
a >= 0.0)// Simple case if both args are real
{ z1.real = std::pow(a, c);
z1.imag = 0.0;
return z1;
}
//
// Start by scaling z1 by dividing out a power of 2 so that |z1| is
// fairly close to 1
//
if (a == 0.0)
{ if (b == 0.0) return z1; // 0.0**anything is really an error
// The exact values returned by frexp do not matter here
static_cast<void>(std::frexp(b, &k));
}
else
{ static_cast<void>(std::frexp(a, &k));
if (b != 0.0)
{ int n;
static_cast<void>(std::frexp(b, &n));
if (n > k) k = n;
}
}
scale = std::ldexp(1.0, k);
a /= scale;
b /= scale;
//
// The idea next is to express z1 as r*exp(i theta), then z1**z2
// is exp(z2*log(z1)) and the exponent simplifies to
// (c*log r - d*theta) + i(c theta + d log r).
// Note r = scale*sqrt(a*a + b*b) now.
// The argument for exp() must be computed to noticably more than
// regular precision, since otherwise exp() greatly magnifies the
// error in the real part (if it is large and positive) and range
// reduction in the imaginary part can equally lead to accuracy
// problems. Neither c nor d can usefully be anywhere near the
// extreme range of floating point values, so I will not even try
// to scale them, thus I will end up happy(ish) if I can compute
// atan2(b, a) and log(|z1|) in one-and-a-half precision form.
// It would be best to compute theta in units of pi/4 rather than in
// raidians, since then the case of z^n (integer n) with arg(z) an
// exact multiple of pi/4 would work out better. However at present I
// just hope that the 1.5-precision working is good enough.
//
extended_atan2(b, a, &thetah, &thetal);
extended_log(k, a, b, &logrh, &logrl);
// Normalise all numbers
clow = 0.0;
dlow = 0.0;
_fp_normalize(c, clow);
_fp_normalize(d, dlow);
// (rh, rl) = c*logr - d*theta;
rh = c*logrh - d*thetah; // No rounding in this computation
rl = c*logrl + clow*(logrh + logrl) - d*thetal - dlow*
(thetah + thetal);
// (ih, il) = c*theta + d*logr;
ih = c*thetah + d*logrh; // No rounding in this computation
il = c*thetal + clow*(thetah + thetal) + d*logrl + dlow*
(logrh + logrl);
//
// Now it remains to take the exponential of the extended precision
// value in ((rh, rl), (ih, il)).
// Range reduce the real part by multiples of log(2), and the imaginary
// part by multiples of pi/2.
//
rh = fp_add(rh, rl, &rl); // renormalise
r = rh + rl; // Approximate value
#define _recip_log_2 1.4426950408889634074
q = r * _recip_log_2;
m = (q < 0.0) ? static_cast<int>(q - 0.5) : static_cast<int>(q + 0.5);
q = static_cast<double>(m);
#undef _recip_log_2
//
// log 2 = 11629080/2^24 - 0.000 00000 19046 54299 95776 78785
// to reasonable accuracy. It is vital that the exact part be
// read in as a number with lots of low zero bits, so when it gets
// multiplied by the integer q there is NO rounding needed.
//
#define _exact_part_log2 0.693147182464599609375
#define _approx_part_log2 (-1.9046542999577678785418e-9)
rh = rh - q*_exact_part_log2;
rl = rl - q*_approx_part_log2;
#undef _exact_part_log2
#undef _approx_part_log2
r = std::exp(rh + rl); // This should now be accurate enough
ih = fp_add(ih, il, &il);
i = ih + il; // Approximate value
#define _recip_pi_by_2 0.6366197723675813431
q = i * _recip_pi_by_2;
n = (q < 0.0) ? static_cast<int>(q - 0.5) : static_cast<int>(q + 0.5);
q = static_cast<double>(n);
//
// pi/2 = 105414357/2^26 + 0.000 00000 09920 93579 68054 04416 39751
// to reasonable accuracy. It is vital that the exact part be
// read in as a number with lots of low zero bits, so when it gets
// multiplied by the integer q there is NO rounding needed.
//
#define _exact_part_pi2 1.57079632580280303955078125
#define _approx_part_pi2 9.92093579680540441639751e-10
ih = ih - q*_exact_part_pi2;
il = il - q*_approx_part_pi2;
#undef _recip_pi_by_2
#undef _exact_part_pi2
#undef _approx_part_pi2
i = ih + il; // Now accurate enough
//
// Having done super-careful range reduction I can call the regular
// sin/cos routines here. If sin/cos could both be computed together
// that could speed things up a little bit, but by this stage they have
// not much in common.
//
cw = std::cos(i);
sw = std::sin(i);
switch (n & 3) // quadrant control
{ default:
case 0: cost = cw; sint = sw; break;
case 1: cost = -sw; sint = cw; break;
case 2: cost = -cw; sint = -sw; break;
case 3: cost = sw; sint = -cw; break;
}
//
// Now, at long last, I can assemble the results and return.
//
z1.real = std::ldexp(r*cost, m);
z1.imag = std::ldexp(r*sint, m);
return z1;
}
//
// End of complex-to-complex-power code.
//
// end of arith07.cpp
| 36.914697 | 85 | 0.587143 |
85c99d2b6b4215afc6f0ae82c6234c5939f9b5cc | 7,056 | cpp | C++ | src/testcase/backtrace.cpp | jjg1914/testcase | 1edca3295ea65d654f0b363bd0bde8c0f0b653f3 | [
"MIT"
] | null | null | null | src/testcase/backtrace.cpp | jjg1914/testcase | 1edca3295ea65d654f0b363bd0bde8c0f0b653f3 | [
"MIT"
] | null | null | null | src/testcase/backtrace.cpp | jjg1914/testcase | 1edca3295ea65d654f0b363bd0bde8c0f0b653f3 | [
"MIT"
] | null | null | null | #include <bfd.h>
#include <execinfo.h>
#include <cxxabi.h>
#include <csignal>
#include <cmath>
#include <map>
#include <string>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <memory>
#include "testcase/backtrace.h"
using namespace std;
using namespace testcase;
#define BACKTRACE_BUF_SIZE \
(sizeof(backtrace_buf)/sizeof(backtrace_buf[0]))
namespace {
backtrace_exception_f exception_handler;
void* backtrace_buf[1024];
struct BFD_info {
bool found;
string filename;
string functionname;
unsigned int line;
};
struct BFD {
static void init();
BFD(const string &fname);
~BFD();
BFD_info addr_info(const string &addr);
bfd_vma addr_vma(const string &addr);
private:
static void find_addr(bfd* p, asection *section, void *data);
bfd* ptr_bfd;
map<string,bfd_vma> map_syms;
static bfd_vma pc;
static asymbol **info_symtab;
static bfd_boolean info_found;
static const char* info_filename;
static const char* info_functionname;
static unsigned int info_line;
};
std::string sym2fname(const char *sym);
std::string sym2addr(const char *sym);
void handle_terminate();
void handle_sigsegv(int);
void handle_sigfpe(int);
void handle_sigill(int);
void handle_sigbus(int);
}
bfd_vma BFD::pc;
asymbol **BFD::info_symtab = NULL;
bfd_boolean BFD::info_found = 0;
const char* BFD::info_filename;
const char* BFD::info_functionname;
unsigned int BFD::info_line;
void BFD::init()
{
bfd_init();
}
BFD::BFD(const string &fname)
: ptr_bfd(bfd_openr(fname.c_str(),NULL))
{
char **matching;
if (ptr_bfd &&
!bfd_check_format(ptr_bfd, bfd_archive) &&
bfd_check_format_matches(ptr_bfd, bfd_object, &matching) &&
bfd_get_file_flags(ptr_bfd) & HAS_SYMS) {
unsigned int size;
asymbol **symtab;
long symc = bfd_read_minisymbols(ptr_bfd, 0, (void**) &symtab, &size);
if (symc == 0) {
symc = bfd_read_minisymbols(ptr_bfd, 1, (void**) &symtab, &size);
}
for (int i = 0; i < symc; ++i) {
symbol_info info;
bfd_symbol_info(symtab[i], &info);
map_syms.emplace(symtab[i]->name, info.value);
}
}
}
BFD::~BFD()
{
if (ptr_bfd) {
bfd_close(ptr_bfd);
}
}
BFD_info BFD::addr_info(const string &addr)
{
BFD_info rval;
pc = addr_vma(addr);
rval.found = (info_found = 0);
bfd_map_over_sections(ptr_bfd,BFD::find_addr, NULL);
if (info_found) {
rval.found = true;
rval.filename = (info_filename ? info_filename : "");
rval.functionname = (info_functionname ? info_functionname :
"Anonymous Function");
rval.line = info_line;
}
return rval;
}
bfd_vma BFD::addr_vma(const string &addr)
{
int i = addr.find_last_of('+');
bfd_vma base = 0;
if (i > 0) {
string sym = addr.substr(0,i);
auto it = map_syms.find(sym);
if (it != map_syms.end()) {
base = it->second;
}
}
bfd_vma offset = bfd_scan_vma(addr.substr(i + 1).c_str(), NULL, 16);
return base + offset;
}
void BFD::find_addr(bfd* p, asection *section, void *)
{
bfd_vma vma;
bfd_size_type size;
if (info_found)
return;
if ((bfd_get_section_flags(p, section) & SEC_ALLOC) == 0)
return;
vma = bfd_get_section_vma(p, section);
if (pc < vma)
return;
size = bfd_get_section_size(section);
if (pc >= vma + size)
return;
info_found = bfd_find_nearest_line(p, section, info_symtab, pc - vma,
&info_filename, &info_functionname, &info_line);
}
namespace {
std::string sym2fname(const char *sym) {
string base(sym);
int i = base.size() - 1;
while (base[i] != '(') {
--i;
}
return base.substr(0,i);
}
std::string sym2addr(const char *sym) {
string base(sym);
int e = base.size() - 1, s;
while (base[e] != ')') {
--e;
}
s = e;
while (base[s] != '(') {
--s;
}
if (e - s == 1) {
e = base.size() - 1;
while (base[e] != ']') {
--e;
}
s = e;
while (base[s] != '[') {
--s;
}
}
return base.substr(s + 1,e - s - 1);
}
void handle_terminate()
{
static bool recursive_guard = 0;
static int init_depth = 0;
ErrorInfo info(ErrorInfo::ETERM, backtrace_depth());
try {
if (recursive_guard) {
exception e;
info.depth = init_depth;
exception_handler(info, e);
} else {
recursive_guard = true;
init_depth = info.depth;;
throw;
}
} catch (exception &e) {
info.eno = ErrorInfo::EEXP;
exception_handler(info, e);
} catch (...) {
exception e;
info.eno = ErrorInfo::EUNKNOWN;
exception_handler(info, e);
}
}
void handle_sigsegv(int)
{
ErrorInfo info(ErrorInfo::ESEGV, backtrace_depth());
exception e;
exception_handler(info, e);
}
void handle_sigfpe(int)
{
ErrorInfo info(ErrorInfo::EFPE, backtrace_depth());
exception e;
exception_handler(info, e);
}
void handle_sigill(int)
{
ErrorInfo info(ErrorInfo::EILL, backtrace_depth());
exception e;
exception_handler(info, e);
}
void handle_sigbus(int)
{
ErrorInfo info(ErrorInfo::EBUS, backtrace_depth());
exception e;
exception_handler(info, e);
}
}
testcase::ErrorInfo::ErrorInfo(Errno eno, int depth)
: eno(eno),
depth(depth)
{}
std::string testcase::sbacktrace(int bottom, int top)
{
stringstream ss;
int size = backtrace((void**)&backtrace_buf,BACKTRACE_BUF_SIZE);
char **sym = backtrace_symbols(backtrace_buf, size);
BFD::init();
map<string,BFD> str2bfd;
int s = size - bottom + 1;
int width = log10(size - top - 1 - s) + 1;
for (int i = s; i < size - top - 1; ++i) {
string fname(sym2fname(sym[i]));
BFD& rbfd = str2bfd.emplace(fname, fname).first->second;
BFD_info info = rbfd.addr_info(sym2addr(sym[i]));
if (info.found) {
ss << setw(width) << (i - s);
ss << ": " << backtrace_demangle(info.functionname) << endl;
ss << string(width + 2,' ');
ss << "[" << info.filename << ":" << info.line << "]" << endl;
ss << string(width + 2,' ');
ss << fname << "(+0x" << hex << rbfd.addr_vma(sym2addr(sym[i])) << ")";
ss << dec << endl;
} else {
ss << setw(width) << (i - s) << ": " << sym[i] << endl;
}
}
free(sym);
return ss.str();
}
void testcase::backtrace_exception(const std::function<void(const ErrorInfo&,
const std::exception &e)> &f)
{
exception_handler = f;
set_terminate(handle_terminate);
signal(SIGSEGV,handle_sigsegv);
signal(SIGFPE,handle_sigfpe);
signal(SIGILL,handle_sigill);
signal(SIGBUS,handle_sigbus);
}
std::string testcase::backtrace_demangle(const std::string &sym)
{
int status;
unique_ptr<char> realname(abi::__cxa_demangle(sym.c_str(), 0, 0, &status));
if (status) {
return sym;
} else {
return realname.get();
}
}
int testcase::backtrace_depth()
{
return backtrace((void**)&backtrace_buf,BACKTRACE_BUF_SIZE) - 1;
}
void testcase::backtrace_trap()
{
raise(SIGTRAP);
}
| 21.512195 | 77 | 0.618906 |
85cb6cbecfb350484fccd1aee3264ef374dbd7b6 | 4,152 | cpp | C++ | src/guacamole/guac_clipboard.cpp | unk0rrupt/collab-vm-server | 30a18cc91b757216a08e900826b589ce29bc3bf0 | [
"Apache-2.0"
] | 74 | 2020-12-20T19:29:21.000Z | 2021-12-04T14:59:29.000Z | src/guacamole/guac_clipboard.cpp | unk0rrupt/collab-vm-server | 30a18cc91b757216a08e900826b589ce29bc3bf0 | [
"Apache-2.0"
] | 2 | 2020-12-27T12:10:50.000Z | 2021-01-24T12:38:24.000Z | src/guacamole/guac_clipboard.cpp | unk0rrupt/collab-vm-server | 30a18cc91b757216a08e900826b589ce29bc3bf0 | [
"Apache-2.0"
] | 4 | 2020-12-20T14:28:11.000Z | 2021-08-20T17:01:11.000Z | /*
* Copyright (C) 2014 Glyptodon LLC
*
* 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.
*/
#define _CRT_SECURE_NO_WARNINGS
#include "config.h"
#include "guac_clipboard.h"
#include "guacamole/protocol.h"
#include "guacamole/stream.h"
#include "GuacClient.h"
#include "GuacUser.h"
#include <string.h>
#include <stdlib.h>
guac_common_clipboard* guac_common_clipboard_alloc(int size) {
guac_common_clipboard* clipboard = (guac_common_clipboard*)malloc(sizeof(guac_common_clipboard));
/* Init clipboard */
clipboard->mimetype[0] = '\0';
clipboard->buffer = (char*)malloc(size);
clipboard->length = 0;
clipboard->available = size;
return clipboard;
}
void guac_common_clipboard_free(guac_common_clipboard* clipboard) {
free(clipboard->buffer);
free(clipboard);
}
/**
* Callback for guac_client_foreach_user() which sends clipboard data to each
* connected client.
*/
static void __send_user_clipboard(GuacUser* user, void* data) {
guac_common_clipboard* clipboard = (guac_common_clipboard*) data;
char* current = clipboard->buffer;
int remaining = clipboard->length;
/* Begin stream */
guac_stream* stream = user->AllocStream();
guac_protocol_send_clipboard(user->socket_, stream, clipboard->mimetype);
user->Log(GUAC_LOG_DEBUG,
"Created stream %i for %s clipboard data.",
stream->index, clipboard->mimetype);
/* Split clipboard into chunks */
while (remaining > 0) {
/* Calculate size of next block */
int block_size = GUAC_COMMON_CLIPBOARD_BLOCK_SIZE;
if (remaining < block_size)
block_size = remaining;
/* Send block */
guac_protocol_send_blob(user->socket_, stream, current, block_size);
user->Log(GUAC_LOG_DEBUG,
"Sent %i bytes of clipboard data on stream %i.",
block_size, stream->index);
/* Next block */
remaining -= block_size;
current += block_size;
}
user->Log(GUAC_LOG_DEBUG,
"Clipboard stream %i complete.",
stream->index);
/* End stream */
guac_protocol_send_end(user->socket_, stream);
user->FreeStream(stream);
}
void guac_common_clipboard_send(guac_common_clipboard* clipboard, GuacClient* client) {
//guac_client_log(client, GUAC_LOG_DEBUG, "Broadcasting clipboard to all connected users.");
//guac_client_foreach_user(client, __send_user_clipboard, clipboard);
//guac_client_log(client, GUAC_LOG_DEBUG, "Broadcast of clipboard complete.");
}
void guac_common_clipboard_reset(guac_common_clipboard* clipboard, const char* mimetype) {
clipboard->length = 0;
strncpy(clipboard->mimetype, mimetype, sizeof(clipboard->mimetype)-1);
}
void guac_common_clipboard_append(guac_common_clipboard* clipboard, const char* data, int length) {
/* Truncate data to available length */
int remaining = clipboard->available - clipboard->length;
if (remaining < length)
length = remaining;
/* Append to buffer */
memcpy(clipboard->buffer + clipboard->length, data, length);
/* Update length */
clipboard->length += length;
}
| 32.692913 | 99 | 0.71315 |
85cc1d3b70ab1457358c4c505c56772a8f8ae098 | 2,749 | cpp | C++ | src/MeshDataBuffer.cpp | jaredmulconry/GLProj | 722fc9804cf6bd2ee0098e6eed9261198f55d0b9 | [
"MIT"
] | 1 | 2016-11-28T07:14:41.000Z | 2016-11-28T07:14:41.000Z | src/MeshDataBuffer.cpp | jaredmulconry/GLProj | 722fc9804cf6bd2ee0098e6eed9261198f55d0b9 | [
"MIT"
] | null | null | null | src/MeshDataBuffer.cpp | jaredmulconry/GLProj | 722fc9804cf6bd2ee0098e6eed9261198f55d0b9 | [
"MIT"
] | null | null | null | #include "MeshDataBuffer.hpp"
#include "GLFW/glfw3.h"
namespace GlProj
{
namespace Graphics
{
MeshDataBuffer::MeshDataBuffer(BufferType bufferType, GLsizeiptr dataSize, const GLvoid* data,
GLenum dataType, GLint elemsPerVert, BufferUsage usage)
: bufferType(GLenum(bufferType))
, dataType(dataType)
, elementsPerVertex(elemsPerVert)
{
glGenBuffers(1, &meshDataHandle);
glBindBuffer(this->bufferType, meshDataHandle);
glBufferData(this->bufferType, dataSize, data, GLenum(usage));
}
MeshDataBuffer::MeshDataBuffer(MeshDataBuffer&& x) noexcept
: meshDataHandle(x.meshDataHandle)
, bufferType(x.bufferType)
, dataType(x.dataType)
, elementsPerVertex(x.elementsPerVertex)
{
x.meshDataHandle = invalidHandle;
}
MeshDataBuffer& MeshDataBuffer::operator=(MeshDataBuffer&& x) noexcept
{
if (this != &x)
{
if (meshDataHandle != invalidHandle)
{
glDeleteBuffers(1, &meshDataHandle);
}
meshDataHandle = x.meshDataHandle;
bufferType = x.bufferType;
dataType = x.dataType;
elementsPerVertex = x.elementsPerVertex;
x.meshDataHandle = invalidHandle;
}
return *this;
}
MeshDataBuffer::~MeshDataBuffer()
{
if (meshDataHandle != invalidHandle)
{
glDeleteBuffers(1, &meshDataHandle);
}
}
GLuint MeshDataBuffer::GetHandle() const noexcept
{
return meshDataHandle;
}
BufferType MeshDataBuffer::GetBufferType() const noexcept
{
return BufferType(bufferType);
}
GLenum MeshDataBuffer::GetDataType() const noexcept
{
return dataType;
}
GLint MeshDataBuffer::GetElementsPerVertex() const noexcept
{
return elementsPerVertex;
}
void MeshDataBuffer::UpdateData(GLintptr offset, GLsizeiptr dataSize, const GLvoid * data) const noexcept
{
glBufferSubData(bufferType, offset, dataSize, data);
}
void* MeshDataBuffer::MapBuffer(GLintptr offset, GLsizeiptr dataSize, GLbitfield access) const noexcept
{
return glMapBufferRange(bufferType, offset, dataSize, access);
}
void MeshDataBuffer::UnmapBuffer() const noexcept
{
glUnmapBuffer(bufferType);
}
void MeshDataBuffer::Bind() const noexcept
{
glBindBuffer(bufferType, GetHandle());
}
void MeshDataBuffer::BindBase(GLuint index) const noexcept
{
glBindBufferBase(bufferType, index, GetHandle());
}
void MeshDataBuffer::BindRange(GLuint index, GLintptr offset, GLsizeiptr size) const noexcept
{
glBindBufferRange(bufferType, index, GetHandle(), offset, size);
}
bool operator==(const MeshDataBuffer& x, const MeshDataBuffer& y) noexcept
{
return x.meshDataHandle == y.meshDataHandle;
}
bool operator!=(const MeshDataBuffer& x, const MeshDataBuffer& y) noexcept
{
return !(x == y);
}
}
}
| 26.95098 | 107 | 0.719534 |
85cd11adad48cfa373d705f644b8c537794fde31 | 7,135 | cc | C++ | test/web/test_parser.cc | protocolocon/nanoWeb | a89b3f9d9c9b7421a5005971565795519728f31b | [
"BSD-2-Clause"
] | null | null | null | test/web/test_parser.cc | protocolocon/nanoWeb | a89b3f9d9c9b7421a5005971565795519728f31b | [
"BSD-2-Clause"
] | null | null | null | test/web/test_parser.cc | protocolocon/nanoWeb | a89b3f9d9c9b7421a5005971565795519728f31b | [
"BSD-2-Clause"
] | null | null | null | /* -*- mode: c++; coding: utf-8; c-file-style: "stroustrup"; -*-
Contributors: Asier Aguirre
All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE.txt file.
*/
#include "catch.hpp"
#include "ml_parser.h"
#define _ "\n"
#define DUMP(x, ...) x, ##__VA_ARGS__
using namespace std;
using namespace webui;
namespace {
bool stringCompare(const char* str, const char* pos, int size) {
return int(strlen(str)) == size && !strncmp(str, pos, size);
}
}
TEST_CASE("parser: id", "[parser]") {
MLParser ml;
const char* str("s0mething");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Id);
CHECK(stringCompare("s0mething", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: number", "[parser]") {
MLParser ml;
const char* str("123.4");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Number);
CHECK(stringCompare("123.4", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: number negative", "[parser]") {
MLParser ml;
const char* str("-123.4");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Number);
CHECK(stringCompare("-123.4", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: number invalid", "[parser]") {
MLParser ml;
const char* str("-12.3.4");
CHECK(!ml.parse(str, strlen(str)));
str = "12f";
CHECK(!ml.parse(str, strlen(str)));
}
TEST_CASE("parser: function", "[parser]") {
MLParser ml;
const char* str("combine(id1, id2, id3)");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 4);
CHECK(ml[0].type() == MLParser::EntryType::Function);
CHECK(ml[1].type() == MLParser::EntryType::Id);
CHECK(ml[2].type() == MLParser::EntryType::Id);
CHECK(ml[3].type() == MLParser::EntryType::Id);
CHECK(ml[0].next == ml.size());
CHECK(stringCompare("combine", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: function empty", "[parser]") {
MLParser ml;
const char* str("combine()");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Function);
CHECK(ml[0].next == ml.size());
CHECK(stringCompare("combine", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: color", "[parser]") {
MLParser ml;
const char* str("#1234abcd");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Color);
CHECK(stringCompare("#1234abcd", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: string", "[parser]") {
MLParser ml;
const char* str("\"str\"");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::String);
CHECK(stringCompare("\"str\"", ml[0].pos, ml.size(0)));
}
TEST_CASE("parser: list", "[parser]") {
MLParser ml;
const char* str("[#ffaacc, someId, [id5, id6], anotherId]");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 7);
CHECK(ml[0].type() == MLParser::EntryType::List);
CHECK(ml[3].type() == MLParser::EntryType::List);
CHECK(stringCompare("#ffaacc", ml[1].pos, ml.size(1)));
CHECK(stringCompare("someId", ml[2].pos, ml.size(2)));
CHECK(stringCompare("id5", ml[4].pos, ml.size(4)));
CHECK(stringCompare("id6", ml[5].pos, ml.size(5)));
CHECK(stringCompare("anotherId", ml[6].pos, ml.size(6)));
}
TEST_CASE("parser: operation", "[parser]") {
MLParser ml;
const char* str("a + b * (c + f(d))");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 8);
CHECK(ml[1].type() == MLParser::EntryType::Operator);
}
TEST_CASE("parser: operation invalid", "[parser]") {
MLParser ml;
const char* str("a + + b");
CHECK(!ml.parse(str, strlen(str)));
}
TEST_CASE("parser: operation invalid 2", "[parser]") {
MLParser ml;
const char* str("* c");
CHECK(!ml.parse(str, strlen(str)));
}
TEST_CASE("parser: object", "[parser]") {
MLParser ml;
const char* str("Object { // comment"
_" key: value // comment"
_" id: [list] // comment"
_" obj { } // comment"
_" obj2 { // comment"
_" obj3 { // comment"
_" [ // block"
_" id: f(x) // comment"
_" ] // comment"
_" } // comment"
_" } // comment"
_"} // comment");
REQUIRE(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
CHECK(ml[0].type() == MLParser::EntryType::Object);
CHECK(ml[0].next == ml.size());
}
TEST_CASE("parser: wildcar", "[parser]") {
MLParser ml;
const char* str("@");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 1);
CHECK(ml[0].type() == MLParser::EntryType::Wildcar);
CHECK(ml[0].next == ml.size());
}
TEST_CASE("parser: attributes", "[parser]") {
MLParser ml;
const char* str("self.width");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 2);
CHECK(ml[0].type() == MLParser::EntryType::Id);
CHECK(ml[1].type() == MLParser::EntryType::Attribute);
}
TEST_CASE("parser: assign", "[parser]") {
MLParser ml;
const char* str("a = 7");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 3);
CHECK(ml[0].type() == MLParser::EntryType::Id);
CHECK(ml[1].type() == MLParser::EntryType::Operator);
CHECK(ml[2].type() == MLParser::EntryType::Number);
}
TEST_CASE("parser: failing case operation", "[parser]") {
MLParser ml;
const char* str("(12 + 21) / 2");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 5);
}
TEST_CASE("parser: failing case operation 2", "[parser]") {
MLParser ml;
const char* str("f(x + w*0.5, (y-2) + h*0.5)");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 13);
CHECK(ml[2].next == 6);
}
TEST_CASE("parser: assign op", "[parser]") {
MLParser ml;
const char* str("x ^= 1");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 3);
CHECK(ml[1].type() == MLParser::EntryType::Operator);
}
TEST_CASE("parser: complex object properties", "[parser]") {
MLParser ml;
const char* str("Object {"
_" x: y + 1"
_" y: (x * 5) + 2"
_"}");
CHECK(ml.parse(str, strlen(str)));
DUMP(ml.dumpTree());
REQUIRE(ml.size() == 11);
CHECK(ml[2].next == 5);
CHECK(ml[6].next == 11);
}
| 30.361702 | 68 | 0.55417 |
85cfdef4c6e0b72a70a5a5674f7cb49381df7379 | 4,605 | cpp | C++ | Sources/RealSense/Microsoft.Psi.RealSense_Interop.Windows.x64/RealSenseDeviceUnmanaged.cpp | pat-sweeney/psi | 273b6d442821cc9942953ea6b51cfcff0edda11f | [
"MIT"
] | 332 | 2019-05-10T20:30:40.000Z | 2022-03-14T08:42:33.000Z | Sources/RealSense/Microsoft.Psi.RealSense_Interop.Windows.x64/RealSenseDeviceUnmanaged.cpp | pat-sweeney/psi | 273b6d442821cc9942953ea6b51cfcff0edda11f | [
"MIT"
] | 117 | 2019-06-12T21:13:03.000Z | 2022-03-19T00:32:20.000Z | Sources/RealSense/Microsoft.Psi.RealSense_Interop.Windows.x64/RealSenseDeviceUnmanaged.cpp | pat-sweeney/psi | 273b6d442821cc9942953ea6b51cfcff0edda11f | [
"MIT"
] | 73 | 2019-05-08T21:39:06.000Z | 2022-03-24T08:34:26.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "RealSenseDeviceUnmanaged.h"
#include "librealsense2\h\rs_sensor.h"
#pragma managed(push, off)
RealSenseDeviceUnmanaged::RealSenseDeviceUnmanaged()
{
refCount = 0;
}
RealSenseDeviceUnmanaged::~RealSenseDeviceUnmanaged()
{
pipeline.stop();
}
#ifdef DUMP_DEVICE_INFO
void RealSenseDeviceUnmanaged::DumpDeviceInfo()
{
rs2::context ctx;
rs2::device_list devices = ctx.query_devices();
for (rs2::device device : devices)
{
wchar_t buf[1024];
swprintf(buf, L"Device: %S\n", device.get_info(RS2_CAMERA_INFO_NAME));
OutputDebugString(buf);
std::vector<rs2::sensor> sensors = device.query_sensors();
for (rs2::sensor sensor : sensors)
{
swprintf(buf, L"Sensor: %S\n", sensor.get_info(RS2_CAMERA_INFO_NAME));
OutputDebugString(buf);
std::vector<rs2::stream_profile> strmProfiles = sensor.get_stream_profiles();
for (int i = 0; i < strmProfiles.size(); i++)
{
rs2::stream_profile sprof = strmProfiles[i];
int w, h;
rs2_get_video_stream_resolution(sprof.get(), &w, &h, nullptr);
swprintf(buf, L"Profile %d: StrmIndex:%d StrmType:%S Width:%d Height:%d Format:%S FPS:%d\n",
i,
sprof.stream_index(),
rs2_stream_to_string(sprof.stream_type()),
w, h,
rs2_format_to_string(sprof.format()),
sprof.fps());
OutputDebugString(buf);
}
for (int i = 0; i < RS2_OPTION_COUNT; i++)
{
rs2_option option_type = static_cast<rs2_option>(i);
if (sensor.supports(option_type))
{
const char* description = sensor.get_option_description(option_type);
swprintf(buf, L" Option:%S\n", description);
OutputDebugString(buf);
float current_value = sensor.get_option(option_type);
swprintf(buf, L" Value:%f\n", current_value);
OutputDebugString(buf);
}
}
}
}
}
#endif // DUMP_DEVICE_INFO
unsigned int RealSenseDeviceUnmanaged::Initialize()
{
try
{
rs2::config config;
config.enable_all_streams();
rs2::pipeline_profile pipeprof = pipeline.start();
// Read 30 frames so that things like autoexposure settle
for (int i = 0; i < 30; i++)
{
try
{
pipeline.wait_for_frames();
}
catch (...)
{
}
}
rs2::frameset frame = pipeline.wait_for_frames();
rs2::video_frame colorFrame = frame.get_color_frame();
if (colorFrame)
{
colorWidth = colorFrame.get_width();
colorHeight = colorFrame.get_height();
colorBpp = colorFrame.get_bits_per_pixel();
colorStride = colorFrame.get_stride_in_bytes();
}
rs2::depth_frame depthFrame = frame.get_depth_frame();
if (depthFrame)
{
depthWidth = depthFrame.get_width();
depthHeight = depthFrame.get_height();
depthBpp = depthFrame.get_bits_per_pixel();
depthStride = depthFrame.get_stride_in_bytes();
}
}
catch (...)
{
return E_UNEXPECTED;
}
return 0;
}
unsigned int RealSenseDeviceUnmanaged::ReadFrame(char *colorBuffer, unsigned int colorBufferLen, char *depthBuffer, unsigned int depthBufferLen)
{
try
{
rs2::frameset frame = pipeline.wait_for_frames();
auto colorFrame = frame.get_color_frame();
int w = colorFrame.get_width();
int h = colorFrame.get_height();
int stride = colorFrame.get_stride_in_bytes();
int bpp = colorFrame.get_bytes_per_pixel();
unsigned int colorFrameSize = h * stride;
if (colorFrameSize > colorBufferLen)
{
return E_UNEXPECTED;
}
char *srcRow = (char*)colorFrame.get_data();
char *dstRow = colorBuffer;
for (int y = 0; y < h; y++)
{
char *srcCol = srcRow;
char *dstCol = dstRow;
for (int x = 0; x < w; x++)
{
dstCol[2] = srcCol[0];
dstCol[1] = srcCol[1];
dstCol[0] = srcCol[2];
srcCol += bpp;
dstCol += 3;
}
srcRow += stride;
dstRow += w * 3;
}
auto depthFrame = frame.get_depth_frame();
unsigned int depthFrameSize = depthFrame.get_height() * depthFrame.get_stride_in_bytes();
if (depthFrameSize > depthBufferLen)
{
return E_UNEXPECTED;
}
memcpy(depthBuffer, depthFrame.get_data(), depthFrameSize);
}
catch (...)
{
}
return S_OK;
}
unsigned int RealSenseDeviceUnmanaged::AddRef()
{
return refCount++;
}
unsigned int RealSenseDeviceUnmanaged::Release()
{
unsigned int refcnt = --refCount;
if (refcnt == 0)
{
delete this;
}
return refcnt;
}
unsigned int CreateRealSenseDeviceUnmanaged(IRealSenseDeviceUnmanaged **device)
{
RealSenseDeviceUnmanaged *dev = new RealSenseDeviceUnmanaged();
if (dev == nullptr)
{
return E_OUTOFMEMORY;
}
dev->Initialize();
dev->AddRef();
*device = dev;
return S_OK;
}
#pragma managed(pop)
| 24.365079 | 144 | 0.686862 |
85d8971a1c6bc4ddede096086254af866af86abd | 4,427 | hpp | C++ | Firmware/communication/can/can_simple.hpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | 1 | 2021-06-08T13:10:27.000Z | 2021-06-08T13:10:27.000Z | Firmware/communication/can/can_simple.hpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | null | null | null | Firmware/communication/can/can_simple.hpp | takijo0116/ODrive | 4c01d0bff2a1c4a67e0f9979c9797b846f5de5d2 | [
"MIT"
] | null | null | null | #ifndef __CAN_SIMPLE_HPP_
#define __CAN_SIMPLE_HPP_
#include <interfaces/canbus.hpp>
#include "axis.hpp"
class CANSimple {
public:
enum {
MSG_CO_NMT_CTRL = 0x000, // CANOpen NMT Message REC
MSG_ODRIVE_HEARTBEAT,
MSG_ODRIVE_ESTOP,
MSG_GET_MOTOR_ERROR, // Errors
MSG_GET_ENCODER_ERROR,
MSG_GET_SENSORLESS_ERROR,
MSG_SET_AXIS_NODE_ID,
MSG_SET_AXIS_REQUESTED_STATE,
MSG_SET_AXIS_STARTUP_CONFIG,
MSG_GET_ENCODER_ESTIMATES,
MSG_GET_ENCODER_COUNT,
MSG_SET_CONTROLLER_MODES,
MSG_SET_INPUT_POS,
MSG_SET_INPUT_VEL,
MSG_SET_INPUT_TORQUE,
MSG_SET_LIMITS,
MSG_START_ANTICOGGING,
MSG_SET_TRAJ_VEL_LIMIT,
MSG_SET_TRAJ_ACCEL_LIMITS,
MSG_SET_TRAJ_INERTIA,
MSG_GET_IQ,
MSG_GET_SENSORLESS_ESTIMATES,
MSG_RESET_ODRIVE,
MSG_GET_VBUS_VOLTAGE,
MSG_CLEAR_ERRORS,
MSG_CO_HEARTBEAT_CMD = 0x700, // CANOpen NMT Heartbeat SEND
};
CANSimple(CanBusBase* canbus) : canbus_(canbus) {}
bool init(fibre::Callback<bool, float, fibre::Callback<void>> timer, uint32_t tx_slots_start, uint32_t tx_slots_end, uint32_t rx_slot);
private:
struct PeriodicHandler {
CANSimple* parent_;
Axis* axis;
int type;
uint32_t* interval;
uint32_t last;
void trigger() { parent_->send_periodic(this); }
};
bool renew_subscription(size_t i);
void on_received(const can_Message_t& msg);
//void on_sent(bool success);
void send_periodic(PeriodicHandler* handler);
void do_command(Axis& axis, const can_Message_t& cmd);
// Get functions (msg.rtr bit must be set)
void get_heartbeat(const Axis& axis, can_Message_t& txmsg);
void get_motor_error_callback(const Axis& axis, can_Message_t& txmsg);
void get_encoder_error_callback(const Axis& axis, can_Message_t& txmsg);
void get_sensorless_error_callback(const Axis& axis, can_Message_t& txmsg);
void get_encoder_estimates_callback(const Axis& axis, can_Message_t& txmsg);
void get_encoder_count_callback(const Axis& axis, can_Message_t& txmsg);
void get_iq_callback(const Axis& axis, can_Message_t& txmsg);
void get_sensorless_estimates_callback(const Axis& axis, can_Message_t& txmsg);
void get_vbus_voltage_callback(const Axis& axis, can_Message_t& txmsg);
// Set functions
static void set_axis_nodeid_callback(Axis& axis, const can_Message_t& msg);
static void set_axis_requested_state_callback(Axis& axis, const can_Message_t& msg);
static void set_axis_startup_config_callback(Axis& axis, const can_Message_t& msg);
static void set_input_pos_callback(Axis& axis, const can_Message_t& msg);
static void set_input_vel_callback(Axis& axis, const can_Message_t& msg);
static void set_input_torque_callback(Axis& axis, const can_Message_t& msg);
static void set_controller_modes_callback(Axis& axis, const can_Message_t& msg);
static void set_limits_callback(Axis& axis, const can_Message_t& msg);
static void set_traj_vel_limit_callback(Axis& axis, const can_Message_t& msg);
static void set_traj_accel_limits_callback(Axis& axis, const can_Message_t& msg);
static void set_traj_inertia_callback(Axis& axis, const can_Message_t& msg);
static void set_linear_count_callback(Axis& axis, const can_Message_t& msg);
// Other functions
static void estop_callback(Axis& axis, const can_Message_t& msg);
static void clear_errors_callback(Axis& axis, const can_Message_t& msg);
static void start_anticogging_callback(const Axis& axis, const can_Message_t& msg);
static constexpr uint8_t NUM_NODE_ID_BITS = 6;
static constexpr uint8_t NUM_CMD_ID_BITS = 11 - NUM_NODE_ID_BITS;
// Utility functions
static constexpr uint32_t get_node_id(uint32_t msgID) {
return (msgID >> NUM_CMD_ID_BITS); // Upper 6 or more bits
};
static constexpr uint8_t get_cmd_id(uint32_t msgID) {
return (msgID & 0x01F); // Bottom 5 bits
}
CanBusBase* canbus_;
CanBusBase::CanSubscription* subscription_handles_[AXIS_COUNT];
fibre::Callback<bool, float, fibre::Callback<void>> timer_;
uint32_t tx_slots_start_;
uint32_t tx_slots_end_;
uint32_t response_tx_slot_;
uint32_t rx_slot_;
std::array<PeriodicHandler, 2 * AXIS_COUNT> periodic_handlers_;
};
#endif | 38.833333 | 139 | 0.727355 |
85d93d6a22aedcccd4bfe212c8e59a9be7b48290 | 2,387 | cpp | C++ | PA/Laborator/2020-2021/lab05 - Backtracking/cpp/task-1/main.cpp | mihai-constantin/ACS | 098c99d82dad8fb5d0e909da930c72f1185a99e2 | [
"Apache-2.0"
] | null | null | null | PA/Laborator/2020-2021/lab05 - Backtracking/cpp/task-1/main.cpp | mihai-constantin/ACS | 098c99d82dad8fb5d0e909da930c72f1185a99e2 | [
"Apache-2.0"
] | null | null | null | PA/Laborator/2020-2021/lab05 - Backtracking/cpp/task-1/main.cpp | mihai-constantin/ACS | 098c99d82dad8fb5d0e909da930c72f1185a99e2 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <fstream>
#include <vector>
#include <unordered_set>
using namespace std;
class Task {
public:
void solve() {
read_input();
print_output(get_result());
}
private:
int n, k;
void read_input() {
ifstream fin("in");
fin >> n >> k;
fin.close();
}
void bkt(int step, int stop, vector<int> &domain, vector<int> &solution, unordered_set<int> &visited, vector<vector<int> > &all) {
if (step == stop) {
all.push_back(solution);
return;
}
for (int i = 0; i < domain.size(); i++) {
if (visited.find(domain[i]) == visited.end()) {
visited.insert(domain[i]);
solution[step] = domain[i];
bkt(step + 1, stop, domain, solution, visited, all);
visited.erase(domain[i]);
}
}
}
vector<vector<int> > get_result() {
vector<vector<int> > all;
// TODO: Construiti toate aranjamentele de N luate cate K ale
// multimii {1, ..., N}.
//
// Pentru a adauga un nou aranjament:
// vector<int> aranjament;
// all.push_back(aranjament);
unordered_set<int> visited;
vector<int> solution(k);
vector<int> domain(n);
for (int i = 0; i < n; i++) {
domain[i] = i + 1;
}
bkt(0, k, domain, solution, visited, all);
return all;
}
void print_output(const vector<vector<int> >& result) {
ofstream fout("out");
fout << result.size() << '\n';
for (size_t i = 0; i < result.size(); i++) {
for (size_t j = 0; j < result[i].size(); j++) {
fout << result[i][j] << (j + 1 != result[i].size() ? ' ' : '\n');
}
}
fout.close();
}
};
// [ATENTIE] NU modifica functia main!
int main() {
// * se aloca un obiect Task pe heap
// (se presupune ca e prea mare pentru a fi alocat pe stiva)
// * se apeleaza metoda solve()
// (citire, rezolvare, printare)
// * se distruge obiectul si se elibereaza memoria
auto* task = new (std::nothrow) Task{}; // hint: cppreference/nothrow
if (!task) {
std::cerr << "new failed: WTF are you doing? Throw your PC!\n";
return -1;
}
task->solve();
delete task;
return 0;
}
| 27.125 | 134 | 0.509426 |
85e3a224111597a9bf265290809deab4b227b0c2 | 9,112 | cpp | C++ | SVEngine/src/node/SVScene.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 34 | 2018-09-28T08:28:27.000Z | 2022-01-15T10:31:41.000Z | SVEngine/src/node/SVScene.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | null | null | null | SVEngine/src/node/SVScene.cpp | SVEChina/SVEngine | 56174f479a3096e57165448142c1822e7db8c02f | [
"MIT"
] | 8 | 2018-10-11T13:36:35.000Z | 2021-04-01T09:29:34.000Z | //
// SVScene.cpp
// SVEngine
// Copyright 2017-2020
// yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li
//
#include "SVScene.h"
#include "SVCameraNode.h"
#include "SVNode.h"
#include "SVNodeVisit.h"
#include "../app/SVGlobalMgr.h"
#include "../app/SVGlobalParam.h"
#include "../basesys/SVStaticData.h"
#include "../rendercore/SVRenderMgr.h"
#include "../rendercore/SVRenderScene.h"
#include "../rendercore/SVRenderer.h"
#include "../rendercore/SVRenderObject.h"
#include "../rendercore/SVRenderCmd.h"
#include "../event/SVEventMgr.h"
#include "../event/SVEvent.h"
#include "../event/SVOpEvent.h"
#include "../basesys/SVSceneMgr.h"
#include "../basesys/SVCameraMgr.h"
#include "../basesys/SVConfig.h"
#include "../mtl/SVTexMgr.h"
#include "../mtl/SVTexture.h"
SVTree4::SVTree4(SVInst *_app)
:SVGBase(_app){
m_treeLock = MakeSharedPtr<SVLock>();
for(s32 i=0;i<4;i++){
m_pTreeNode[i] = nullptr;
}
m_node = nullptr;
}
SVTree4::~SVTree4(){
m_node = nullptr;
for(s32 i=0;i<4;i++){
m_pTreeNode[i] = nullptr;
}
m_treeLock = nullptr;
}
//ไธ็ๅคงๅฐๅๆทฑๅบฆ
void SVTree4::create(SVBoundBox& _box,s32 _depth){
m_treeBox = _box;
//ๆๅปบๅบๆฏๆ
if(_depth>0){
FVec3 t_max = _box.getMax();
FVec3 t_min = _box.getMin();
FVec3 t_center = (t_max + t_min)*0.5f;
//0 ็ฌฌไธ่ฑก้
SVBoundBox t_box0(t_center,t_max);
m_pTreeNode[0] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[0]->create(t_box0,_depth-1);
//1 ็ฌฌไบ่ฑก้
SVBoundBox t_box1( FVec3(t_min.x,t_center.y,0.0f),FVec3(t_center.x,t_max.y,0.0f) );
m_pTreeNode[1] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[1]->create(t_box1,_depth-1);
//2 ็ฌฌไธ่ฑก้
SVBoundBox t_box2(t_min,t_center);
m_pTreeNode[2] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[2]->create(t_box2,_depth-1);
//3 ็ฌฌๅ่ฑก้
SVBoundBox t_box3( FVec3(t_center.x,t_min.y,0.0f),FVec3(t_max.x,t_center.y,0.0f) );
m_pTreeNode[3] = MakeSharedPtr<SVTree4>(mApp);
m_pTreeNode[3]->create(t_box3,_depth-1);
}else{
//ๅถๅญ่็น
m_node = MakeSharedPtr<SVNode>(mApp);
}
}
void SVTree4::destroy(){
m_treeLock->lock();
for(s32 i=0;i<4;i++){
if(m_pTreeNode[i]){
m_pTreeNode[i]->destroy();
}
}
m_treeLock->unlock();
clearNode();
}
void SVTree4::update(f32 _dt){
m_treeLock->lock();
//ๆฌ่บซๆ่ฝฝ็่็น่ฟ่กๆดๆฐ
if(m_node) {
m_node->deep_update(_dt);
}else{
for(s32 i=0;i<4;i++){
if(m_pTreeNode[i]){
m_pTreeNode[i]->update(_dt);
}
}
}
m_treeLock->unlock();
}
void SVTree4::visit(SVVisitorBasePtr _visitor){
m_treeLock->lock();
if(m_node) {
m_node->deep_visit(_visitor);
}else{
for(s32 i=0;i<4;i++){
if(m_pTreeNode[i]){
m_pTreeNode[i]->visit(_visitor);
}
}
}
m_treeLock->unlock();
}
bool SVTree4::_isIn(SVNodePtr _node) {
FVec3 t_pos = _node->getPosition();
//่ฟๅzๅ
ๆนไธบไบ0๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ
t_pos.z = 0;
//ๅจๅ
้จ(ไปฅ1๏ผ2๏ผ3๏ผ4)็ฐ่ฑกไธบ้กบๅบ
if( m_treeBox.inside(t_pos) ){
return true;
}
return false;
}
void SVTree4::addNode(SVNodePtr _node, s32 iZOrder){
if (_node){
_node->setZOrder(iZOrder);
addNode(_node);
}
}
//ๅขๅ ่็น
void SVTree4::addNode(SVNodePtr _node) {
if(m_node) {
m_node->addChild(_node);
}else{
for(s32 i=0;i<4;i++){
if( m_pTreeNode[i]->_isIn(_node) ){
m_pTreeNode[i]->addNode(_node);
break;
}
}
}
}
//็งป้ค่็น
bool SVTree4::removeNode(SVNodePtr _node) {
bool t_ret = false;
if(m_node) {
t_ret = m_node->removeChild(_node);
}else{
for(s32 i=0;i<4;i++){
if( m_pTreeNode[i]->removeNode(_node) ) {
return true;
}
}
}
return t_ret;
}
//ๆธ
็่็น
void SVTree4::clearNode() {
if(m_node) {
m_node->clearChild();
}else{
for(s32 i=0;i<4;i++){
m_pTreeNode[i]->clearNode();
}
}
}
bool SVTree4::hasNode(SVNodePtr _node) {
if(m_node) {
return m_node->hasChild(_node);
}else{
for(s32 i=0;i<4;i++){
if( m_pTreeNode[i]->hasNode(_node) ){
return true;
}
}
}
return false;
}
//้ป่พๅบๆฏ
SVScene::SVScene(SVInst *_app,cptr8 _name)
:SVGBase(_app) {
m_name = _name;
m_color.setColorARGB(0x00000000);
m_worldW = 0;
m_worldH = 0;
m_worldD = 0;
//ๅบๆฏๆ
m_pSceneTree = MakeSharedPtr<SVTree4>(_app);
//ๆธฒๆๅบๆฏ
m_pRenderScene = MakeSharedPtr<SVRenderScene>(_app);
}
SVScene::~SVScene() {
if(m_pSceneTree){
m_pSceneTree->destroy();
m_pSceneTree = nullptr;
}
m_pRenderScene = nullptr;
}
void SVScene::create(f32 _worldw ,f32 _worldh,s32 _depth){
m_worldW = _worldw;
m_worldH = _worldh;
m_worldD = _depth;
if(m_pSceneTree){
SVBoundBox _box;
FVec3 t_min,t_max;
t_min.set(-0.5f*_worldw,-0.5f*_worldh, 0.0f);
t_max.set(0.5f*_worldw,0.5f*_worldh, 0.0f);
_box.set(t_min, t_max);
m_pSceneTree->create(_box,_depth);
}
s32 m_sw = mApp->m_pGlobalParam->m_inner_width;
s32 m_sh = mApp->m_pGlobalParam->m_inner_height;
SVCameraNodePtr mainCamera = mApp->getCameraMgr()->getMainCamera();
if(mainCamera) {
mainCamera->resetCamera(m_sw,m_sh);
}
//
SVCameraNodePtr uiCamera = mApp->getCameraMgr()->getUICamera();
if(uiCamera) {
uiCamera->resetCamera(m_sw,m_sh);
}
//
}
void SVScene::destroy(){
}
void SVScene::addNode(SVNodePtr _node){
if(_node && m_pSceneTree){
m_pSceneTree->addNode(_node);
}
}
void SVScene::addNode(SVNodePtr _node,s32 _zorder){
if(_node && m_pSceneTree){
_node->setZOrder(_zorder);
addNode(_node);
}
}
void SVScene::removeNode(SVNodePtr _node){
if(_node && m_pSceneTree){
m_pSceneTree->removeNode(_node);
}
}
void SVScene::active() {
}
void SVScene::unactive() {
}
void SVScene::setSceneColor(f32 _r,f32 _g,f32 _b,f32 _a) {
m_color.setColor(_r, _g, _b, _a);
}
void SVScene::update(f32 dt) {
//้ๅๅบๆฏๆ
if(m_pSceneTree){
m_pSceneTree->update(dt);
}
//
SVRendererPtr t_renderer = mApp->getRenderer();
if( t_renderer && t_renderer->hasSVTex(E_TEX_MAIN) ){
if (m_pRenderScene && false == m_pRenderScene->isSuspend() ) {
SVRenderCmdFboBindPtr t_fbo_bind = MakeSharedPtr<SVRenderCmdFboBind>(t_renderer->getRenderTexture());
t_fbo_bind->mTag = "main_frame_bind";
m_pRenderScene->pushRenderCmd(RST_SCENE_BEGIN, t_fbo_bind);
//
SVRenderCmdClearPtr t_clear = MakeSharedPtr<SVRenderCmdClear>();
t_clear->mTag = "main_frame_clear";
t_clear->setRenderer(t_renderer);
t_clear->setClearColor(m_color.r, m_color.g, m_color.b, m_color.a);
m_pRenderScene->pushRenderCmd(RST_SCENE_BEGIN, t_clear);
//
SVRenderCmdFboUnbindPtr t_fbo_unbind = MakeSharedPtr<SVRenderCmdFboUnbind>(t_renderer->getRenderTexture());
t_fbo_unbind->mTag = "main_frame_unbind";
m_pRenderScene->pushRenderCmd(RST_SCENE_END, t_fbo_unbind);
}
}
}
void SVScene::visit(SVVisitorBasePtr _visitor){
if( m_pSceneTree ){
m_pSceneTree->visit(_visitor);
}
}
SVRenderScenePtr SVScene::getRenderRS(){
return m_pRenderScene;
}
bool SVScene::procEvent(SVEventPtr _event) {
return true;
}
//ๅบๅๅๅบๆฏ
void SVScene::toJSON(RAPIDJSON_NAMESPACE::Document::AllocatorType &_allocator,
RAPIDJSON_NAMESPACE::Value &_objValue) {
RAPIDJSON_NAMESPACE::Value locationObj(RAPIDJSON_NAMESPACE::kObjectType);//ๅๅปบไธไธชObject็ฑปๅ็ๅ
็ด
locationObj.AddMember("name", RAPIDJSON_NAMESPACE::StringRef(m_name.c_str()), _allocator);
u32 t_color = m_color.getColorARGB();
locationObj.AddMember("color", t_color, _allocator);
locationObj.AddMember("worldw", m_worldW, _allocator);
locationObj.AddMember("worldh", m_worldH, _allocator);
locationObj.AddMember("worldd", m_worldD, _allocator);
//ๅบๅๅๆ ? ่ฆๅ่ฟไนๅคๆๅ
if(m_pSceneTree){
}
//
_objValue.AddMember("SVScene", locationObj, _allocator);
}
void SVScene::fromJSON(RAPIDJSON_NAMESPACE::Value &item) {
if (item.HasMember("name") && item["name"].IsString()) {
m_name = item["name"].GetString();
}
if (item.HasMember("color") && item["color"].IsUint()) {
u32 t_color = item["color"].GetUint();
m_color.setColorARGB(t_color);
}
if (item.HasMember("worldw") && item["worldw"].IsFloat()) {
m_worldW = item["worldw"].GetFloat();
}
if (item.HasMember("worldh") && item["worldh"].IsFloat()) {
m_worldH = item["worldh"].GetFloat();
}
if (item.HasMember("worldd") && item["worldd"].IsInt()) {
m_worldD = item["worldd"].GetInt();
}
//
if(!m_pSceneTree){
create(m_worldW,m_worldH,m_worldD);
}
}
| 26.259366 | 119 | 0.605685 |
85e7b434e4ae6c6d34529f621c507473dfc60304 | 1,067 | hpp | C++ | include/edlib/Hamiltonians/TITFIsing.hpp | chaeyeunpark/ExactDiagonalization | c93754e724486cc68453399c5dda6a2dadf45cb8 | [
"MIT"
] | 1 | 2021-04-24T08:47:05.000Z | 2021-04-24T08:47:05.000Z | include/edlib/Hamiltonians/TITFIsing.hpp | chaeyeunpark/ExactDiagonalization | c93754e724486cc68453399c5dda6a2dadf45cb8 | [
"MIT"
] | 1 | 2021-09-28T19:02:14.000Z | 2021-09-28T19:02:14.000Z | include/edlib/Hamiltonians/TITFIsing.hpp | chaeyeunpark/ExactDiagonalization | c93754e724486cc68453399c5dda6a2dadf45cb8 | [
"MIT"
] | 1 | 2020-03-22T18:59:11.000Z | 2020-03-22T18:59:11.000Z | #ifndef ED_TITFI_HPP
#define ED_TITFI_HPP
#include <cstdint>
#include <cassert>
#include <algorithm>
#include <map>
#include <boost/dynamic_bitset.hpp>
//#include "BitOperations.h"
#include "../Basis/AbstractBasis1D.hpp"
template<typename UINT>
class TITFIsing
{
private:
const edlib::AbstractBasis1D<UINT>& basis_;
double J_;
double h_;
public:
TITFIsing(const edlib::AbstractBasis1D<UINT>& basis, double J, double h)
: basis_(basis), J_(J), h_(h)
{
}
std::map<std::size_t,double> getCol(UINT n) const
{
unsigned int N = basis_.getN();
UINT a = basis_.getNthRep(n);
const boost::dynamic_bitset<> bs(N, a);
std::map<std::size_t, double> m;
for(unsigned int i = 0; i < N; i++)
{
//Next-nearest
{
unsigned int j = (i+1)%N;
int sgn = (1-2*bs[i])*(1-2*bs[j]);
m[n] += -J_*sgn; //ZZ
UINT s = a;
s ^= basis_.mask({i});
int bidx;
double coeff;
std::tie(bidx, coeff) = basis_.hamiltonianCoeff(s, n);
if(bidx >= 0)
m[bidx] += -h_*coeff;
}
}
return m;
}
};
#endif //ED_TITFI_HPP
| 18.084746 | 73 | 0.618557 |
85e81958bc8b94020364f88526924ae55a5866d5 | 2,836 | cpp | C++ | ExtraLifeEngine/Obsolete/RemovedVoxel/Voxel/Neutral/Terrain/TerrainGeneration.cpp | paulburgess1357/ExtraLifeEngine | e0d1f95fa57ea9e5016d1e3800815cdb24b1eb0f | [
"MIT"
] | 1 | 2020-11-13T05:39:46.000Z | 2020-11-13T05:39:46.000Z | ExtraLifeEngine/Obsolete/RemovedVoxel/Voxel/Neutral/Terrain/TerrainGeneration.cpp | paulburgess1357/ExtraLifeEngine | e0d1f95fa57ea9e5016d1e3800815cdb24b1eb0f | [
"MIT"
] | null | null | null | ExtraLifeEngine/Obsolete/RemovedVoxel/Voxel/Neutral/Terrain/TerrainGeneration.cpp | paulburgess1357/ExtraLifeEngine | e0d1f95fa57ea9e5016d1e3800815cdb24b1eb0f | [
"MIT"
] | null | null | null | #include "TerrainGeneration.h"
#include <cmath>
namespace ExtraLife {
noise::module::Perlin TerrainGeneration::m_perlin_noise;
int TerrainGeneration::generate_top_layer(const WorldPosition& starting_world_position, const int x_local, const int z_local, const int x_block_qty, const int y_block_qty, const int z_block_qty){
m_perlin_noise.SetOctaveCount(1); // 1 to 6
m_perlin_noise.SetFrequency(1); // 1 to 16
m_perlin_noise.SetPersistence(0); // 0 to 1
const glm::vec3 start_position = starting_world_position.get_vec3();
const double nx = (static_cast<double>(x_local + start_position.x) / x_block_qty - 0.5f);
const double nz = (static_cast<double>(z_local + start_position.z) / z_block_qty - 0.5f);
double noise1 = 1.0 * generate_noise(1.0 * nx, 1.0 * nz);
double noise2 = 0.5 * generate_noise(2.0 * nx + 3.48, 2.0 * nz + 8.74);
double noise3 = 0.25 * generate_noise(4.0 * nx + 6.81, 4.0 * nz + 1.85);
double total_noise = (noise1 + noise2 + noise3) / (1.0 + 0.5 + 0.25);
//total_noise = pow(total_noise, 1.2);
total_noise = round(total_noise * y_block_qty) / y_block_qty;
int height = total_noise * y_block_qty; // 1.0f + 0.5f + 0.25f
// std::cout << height << std::endl;
//int height = generate_noise(nx, nz) * y_block_qty; // + 2 makes tabletops
if (height > y_block_qty) {
height = y_block_qty;
}
if (height < 1) {
height = 1;
}
return height;
}
double TerrainGeneration::generate_noise(const double nx, const double nz){
return m_perlin_noise.GetValue(nx, 0.0f, nz) / 2.0f + 0.5f;
}
int TerrainGeneration::generate_top_layer2(const WorldPosition& starting_world_position, const int x_local, const int z_local, const int x_block_qty, const int y_block_qty, const int z_block_qty) {
m_perlin_noise.SetOctaveCount(1); // 1 to 6
m_perlin_noise.SetFrequency(1); // 1 to 16
m_perlin_noise.SetPersistence(0); // 0 to 1
const glm::vec3 start_position = starting_world_position.get_vec3();
const double nx = (static_cast<double>(x_local + start_position.x) / x_block_qty - 0.5f);
const double nz = (static_cast<double>(z_local + start_position.z) / z_block_qty - 0.5f);
double noise1 = 1.5 * generate_noise(1.0 * nx, 1.0 * nz);
double noise2 = 0.1 * generate_noise(2.0 * nx + 3.48, 2.0 * nz + 8.74);
double noise3 = 0.1 * generate_noise(4.0 * nx + 6.81, 4.0 * nz + 1.85);
double total_noise = (noise1 + noise2 + noise3) / (1.0 + 0.5 + 0.25);
//total_noise = pow(total_noise, 1.2);
total_noise = round(total_noise * y_block_qty) / y_block_qty;
int height = total_noise * y_block_qty; // 1.0f + 0.5f + 0.25f
// std::cout << height << std::endl;
//int height = generate_noise(nx, nz) * y_block_qty; // + 2 makes tabletops
if (height > y_block_qty) {
height = y_block_qty;
}
if (height < 1) {
height = 1;
}
return height;
}
} // namespace ExtraLife | 32.976744 | 197 | 0.692877 |
85e909132693dfd1cd383f02695d85108c993a7b | 1,182 | hpp | C++ | src/nxt_ipc.hpp | syldrathecat/nxtlauncher | 9856999bed2531067a44a319a8b37f726d2ffb0a | [
"Unlicense"
] | 13 | 2016-09-15T23:04:48.000Z | 2021-02-27T01:42:31.000Z | src/nxt_ipc.hpp | syldrathecat/nxtlauncher | 9856999bed2531067a44a319a8b37f726d2ffb0a | [
"Unlicense"
] | 13 | 2017-04-22T16:00:07.000Z | 2020-10-13T18:18:29.000Z | src/nxt_ipc.hpp | syldrathecat/nxtlauncher | 9856999bed2531067a44a319a8b37f726d2ffb0a | [
"Unlicense"
] | 2 | 2016-09-15T19:49:24.000Z | 2018-12-28T03:11:50.000Z | #ifndef NXT_IPC_HPP
#define NXT_IPC_HPP
#include "nxt_fifo.hpp"
#include "nxt_message.hpp"
#include <functional>
#include <map>
// Creates and manages a pair of named pipes for communicating with the client
class nxt_ipc
{
public:
using handler_t = std::function<void(nxt_message&)>;
private:
nxt_fifo m_fifo_in;
nxt_fifo m_fifo_out;
std::map<int, handler_t> m_handlers;
void handle(nxt_message& message);
public:
// Initializes the files for IPC
nxt_ipc(const char* fifo_in_filename, const char* fifo_out_filename);
// Not copyable
nxt_ipc(const nxt_ipc&) = delete;
nxt_ipc& operator=(const nxt_ipc&) = delete;
// Moveable, but probably a bad idea if handlers reference the original
nxt_ipc(nxt_ipc&&) = default;
nxt_ipc& operator=(nxt_ipc&&) = default;
// Registers a handler for a given message ID
// Registering new handlers will overwrite old ones
void register_handler(int message_id, handler_t handler);
// Starts pumping messages and executing handlers
// (expected to be called from a separate thread)
void operator()();
// Sends a message to the client
void send(const nxt_message& msg);
};
#endif // NXT_IPC_HPP
| 23.64 | 78 | 0.733503 |
85f1f0920a744c4e5ecaada128864ecc85a924ea | 982 | cc | C++ | kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc | transcript/DNAnexus_apps | 12c2ba6f57b805a9fcf6e1da4f9d64394ef72256 | [
"MIT"
] | 3 | 2015-11-20T19:40:29.000Z | 2019-07-25T15:34:24.000Z | kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc | transcript/DNAnexus_apps | 12c2ba6f57b805a9fcf6e1da4f9d64394ef72256 | [
"MIT"
] | null | null | null | kraken/resources/home/dnanexus/jellyfish-1.1.11/jellyfish/dna_codes.cc | transcript/DNAnexus_apps | 12c2ba6f57b805a9fcf6e1da4f9d64394ef72256 | [
"MIT"
] | 2 | 2018-09-20T08:28:36.000Z | 2019-03-06T06:26:52.000Z | #include <jellyfish/dna_codes.hpp>
#define R -1
#define I -2
#define O -3
#define A 0
#define C 1
#define G 2
#define T 3
const char jellyfish::dna_codes[256] = {
O, O, O, O, O, O, O, O, O, O, I, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, R, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, A, R, C, R, O, O, G, R, O, O, R, O, R, R, O,
O, O, R, R, T, O, R, R, R, R, O, O, O, O, O, O,
O, A, R, C, R, O, O, G, R, O, O, R, O, R, R, O,
O, O, R, R, T, O, R, R, R, R, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O,
O, O, O, O, O, O, O, O, O, O, O, O, O, O, O, O
};
| 33.862069 | 50 | 0.376782 |
85f21279c2ed92b54cf93e1bc15da260fe5fffc6 | 7,756 | hpp | C++ | include/GlobalNamespace/LocalNetworkPlayersViewController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/LocalNetworkPlayersViewController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/GlobalNamespace/LocalNetworkPlayersViewController.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: NetworkPlayersViewController
#include "GlobalNamespace/NetworkPlayersViewController.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine::UI
namespace UnityEngine::UI {
// Forward declaring type: Toggle
class Toggle;
}
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: LocalNetworkPlayerModel
class LocalNetworkPlayerModel;
// Forward declaring type: INetworkConfig
class INetworkConfig;
// Forward declaring type: INetworkPlayerModel
class INetworkPlayerModel;
}
// Forward declaring namespace: HMUI
namespace HMUI {
// Forward declaring type: ToggleBinder
class ToggleBinder;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0xBA
#pragma pack(push, 1)
// Autogenerated type: LocalNetworkPlayersViewController
class LocalNetworkPlayersViewController : public GlobalNamespace::NetworkPlayersViewController {
public:
// private UnityEngine.UI.Toggle _enableNetworkingToggle
// Size: 0x8
// Offset: 0x90
UnityEngine::UI::Toggle* enableNetworkingToggle;
// Field size check
static_assert(sizeof(UnityEngine::UI::Toggle*) == 0x8);
// private UnityEngine.UI.Toggle _enableOpenPartyToggle
// Size: 0x8
// Offset: 0x98
UnityEngine::UI::Toggle* enableOpenPartyToggle;
// Field size check
static_assert(sizeof(UnityEngine::UI::Toggle*) == 0x8);
// [InjectAttribute] Offset: 0xE25520
// private readonly LocalNetworkPlayerModel _localNetworkPlayerModel
// Size: 0x8
// Offset: 0xA0
GlobalNamespace::LocalNetworkPlayerModel* localNetworkPlayerModel;
// Field size check
static_assert(sizeof(GlobalNamespace::LocalNetworkPlayerModel*) == 0x8);
// [InjectAttribute] Offset: 0xE25530
// private readonly INetworkConfig _networkConfig
// Size: 0x8
// Offset: 0xA8
GlobalNamespace::INetworkConfig* networkConfig;
// Field size check
static_assert(sizeof(GlobalNamespace::INetworkConfig*) == 0x8);
// private HMUI.ToggleBinder _toggleBinder
// Size: 0x8
// Offset: 0xB0
HMUI::ToggleBinder* toggleBinder;
// Field size check
static_assert(sizeof(HMUI::ToggleBinder*) == 0x8);
// private System.Boolean _enableBroadcasting
// Size: 0x1
// Offset: 0xB8
bool enableBroadcasting;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _allowAnyoneToJoin
// Size: 0x1
// Offset: 0xB9
bool allowAnyoneToJoin;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: LocalNetworkPlayersViewController
LocalNetworkPlayersViewController(UnityEngine::UI::Toggle* enableNetworkingToggle_ = {}, UnityEngine::UI::Toggle* enableOpenPartyToggle_ = {}, GlobalNamespace::LocalNetworkPlayerModel* localNetworkPlayerModel_ = {}, GlobalNamespace::INetworkConfig* networkConfig_ = {}, HMUI::ToggleBinder* toggleBinder_ = {}, bool enableBroadcasting_ = {}, bool allowAnyoneToJoin_ = {}) noexcept : enableNetworkingToggle{enableNetworkingToggle_}, enableOpenPartyToggle{enableOpenPartyToggle_}, localNetworkPlayerModel{localNetworkPlayerModel_}, networkConfig{networkConfig_}, toggleBinder{toggleBinder_}, enableBroadcasting{enableBroadcasting_}, allowAnyoneToJoin{allowAnyoneToJoin_} {}
// private System.Void HandleNetworkingToggleChanged(System.Boolean enabled)
// Offset: 0x10D48F4
void HandleNetworkingToggleChanged(bool enabled);
// private System.Void HandleOpenPartyToggleChanged(System.Boolean openParty)
// Offset: 0x10D4904
void HandleOpenPartyToggleChanged(bool openParty);
// private System.Void RefreshParty(System.Boolean overrideHide)
// Offset: 0x10D4790
void RefreshParty(bool overrideHide);
// public override System.String get_myPartyTitle()
// Offset: 0x10D45B8
// Implemented from: NetworkPlayersViewController
// Base method: System.String NetworkPlayersViewController::get_myPartyTitle()
::Il2CppString* get_myPartyTitle();
// public override System.String get_otherPlayersTitle()
// Offset: 0x10D4600
// Implemented from: NetworkPlayersViewController
// Base method: System.String NetworkPlayersViewController::get_otherPlayersTitle()
::Il2CppString* get_otherPlayersTitle();
// public override INetworkPlayerModel get_networkPlayerModel()
// Offset: 0x10D4648
// Implemented from: NetworkPlayersViewController
// Base method: INetworkPlayerModel NetworkPlayersViewController::get_networkPlayerModel()
GlobalNamespace::INetworkPlayerModel* get_networkPlayerModel();
// protected override System.Void NetworkPlayersViewControllerDidActivate(System.Boolean firstActivation, System.Boolean addedToHierarchy)
// Offset: 0x10D4650
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::NetworkPlayersViewControllerDidActivate(System.Boolean firstActivation, System.Boolean addedToHierarchy)
void NetworkPlayersViewControllerDidActivate(bool firstActivation, bool addedToHierarchy);
// protected override System.Void DidDeactivate(System.Boolean removedFromHierarchy, System.Boolean screenSystemDisabling)
// Offset: 0x10D48B0
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::DidDeactivate(System.Boolean removedFromHierarchy, System.Boolean screenSystemDisabling)
void DidDeactivate(bool removedFromHierarchy, bool screenSystemDisabling);
// protected override System.Void OnDestroy()
// Offset: 0x10D48C0
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::OnDestroy()
void OnDestroy();
// public System.Void .ctor()
// Offset: 0x10D4914
// Implemented from: NetworkPlayersViewController
// Base method: System.Void NetworkPlayersViewController::.ctor()
// Base method: System.Void ViewController::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static LocalNetworkPlayersViewController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::LocalNetworkPlayersViewController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<LocalNetworkPlayersViewController*, creationType>()));
}
}; // LocalNetworkPlayersViewController
#pragma pack(pop)
static check_size<sizeof(LocalNetworkPlayersViewController), 185 + sizeof(bool)> __GlobalNamespace_LocalNetworkPlayersViewControllerSizeCheck;
static_assert(sizeof(LocalNetworkPlayersViewController) == 0xBA);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::LocalNetworkPlayersViewController*, "", "LocalNetworkPlayersViewController");
| 52.405405 | 675 | 0.746648 |
85fa1b1b64a0a9bf281e92dcf003ea04f2beab63 | 7,853 | cpp | C++ | obliczanie-wieku/AgeCalculator.cpp | MHellFire/random-stuff | f8d05af9019df67fcf7164a3b716e4db17d18e6a | [
"MIT"
] | null | null | null | obliczanie-wieku/AgeCalculator.cpp | MHellFire/random-stuff | f8d05af9019df67fcf7164a3b716e4db17d18e6a | [
"MIT"
] | null | null | null | obliczanie-wieku/AgeCalculator.cpp | MHellFire/random-stuff | f8d05af9019df67fcf7164a3b716e4db17d18e6a | [
"MIT"
] | null | null | null | /*********************************************************************************
* This file is part of Age Calculator. *
* *
* Copyright ยฉ 2019 Mariusz Helfajer *
* *
* This software may be modified and distributed under the terms *
* of the MIT license. See the LICENSE files for details. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to deal *
* in the Software without restriction, including without limitation the rights *
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell *
* copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, *
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN *
* THE SOFTWARE. *
* *******************************************************************************/
#include <iostream>
#include <cmath>
#include <ctime>
#include <QDate>
#include <QtMath>
// Returns age[0] = years; age[1] = months; age[2] = days;
// or nullptr if any of the given dates is not valid or if the birth date is from the future.
int* calculateAge(const QDate &birthDate, const QDate &todayDate)
{
// check if the birth date is valid date
if (!birthDate.isValid())
return nullptr;
// check if the today date is valid date
if (!todayDate.isValid())
return nullptr;
// check if the birth date is not from the future
if (birthDate > todayDate)
return nullptr;
int *age = new int[3]; // age[0] = years; age[1] = months; age[2] = days;
int t1 = birthDate.year()*12 + birthDate.month() - 1; // total months for birthdate
int t2 = todayDate.year()*12 + todayDate.month() - 1; // total months for now
int dm = t2 - t1; // delta months
if (todayDate.day() >= birthDate.day())
{
age[0] = qFloor(dm/12); // years
age[1] = dm%12; // months
age[2] = todayDate.day() - birthDate.day(); // days
}
else
{
dm--;
age[0] = qFloor(dm/12); // years
age[1] = dm%12; // months
age[2] = birthDate.daysInMonth() - birthDate.day() + todayDate.day(); // days
}
return age;
}
// Returns true if the specified year is a leap year; otherwise returns false.
bool isLeapYear(int year)
{
// No year 0 in Gregorian calendar, so -1, -5, -9 etc are leap years
// ISO 8601 - year 0000 is being equal to 1 BC
if (year < 1)
++year;
return ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0));
}
// Returns the number of days in the month (28 to 31) for given date. Returns 0 if the date is invalid.
int daysInMonth(const tm &date)
{
const char monthDays[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (date.tm_mon == 2 && isLeapYear(date.tm_year))
return 29;
else
return monthDays[date.tm_mon];
}
// Returns age[0] = years; age[1] = months; age[2] = days;
// or nullptr if any of the given dates is not valid or if the birth date is from the future.
int* calculateAge2(const tm &birthDate, const tm &todayDate)
{
// TODO: check if dates are valid
// check if the birth date is not from the future
if (birthDate.tm_year > todayDate.tm_year)
return nullptr;
else if (birthDate.tm_year == todayDate.tm_year && birthDate.tm_mon > todayDate.tm_mon)
return nullptr;
else if (birthDate.tm_year == todayDate.tm_year && birthDate.tm_mon > todayDate.tm_mon && birthDate.tm_mday > todayDate.tm_mday)
return nullptr;
int *age = new int[3]; // age[0] = years; age[1] = months; age[2] = days;
int t1 = birthDate.tm_year*12 + birthDate.tm_mon - 1; // total months for birthdate
int t2 = todayDate.tm_year*12 + todayDate.tm_mon - 1; // total months for now
int dm = t2 - t1; // delta months
if (todayDate.tm_mday >= birthDate.tm_mday)
{
age[0] = int(floor(dm/12)); // years
age[1] = dm%12; // months
age[2] = todayDate.tm_mday - birthDate.tm_mday; // days
}
else
{
dm--;
age[0] = int(floor(dm/12)); // years
age[1] = dm%12; // months
age[2] = daysInMonth(birthDate) - birthDate.tm_mday + todayDate.tm_mday; // days
}
return age;
}
int main(int argc, char *argv[])
{
(void)(argc);
(void)(argv);
QDate birthDate(QDate(2006, 1, 30));
QDate currentDate(QDate::currentDate());
int *tmp = calculateAge(birthDate, currentDate);
if (tmp != nullptr)
{
std::cout << "Birth date: " << birthDate.toString("dd.MM.yyyy").toStdString() << std::endl;
std::cout << "Current date: " << currentDate.toString("dd.MM.yyyy").toStdString() << std::endl;
std::cout << "Years: " << tmp[0] << std::endl;
std::cout << "Months: " << tmp[1] << std::endl;
std::cout << "Days: " << tmp[2] << std::endl << std::endl;
}
delete []tmp;
tm birthDate2;
birthDate2.tm_year = birthDate.year();
birthDate2.tm_mon = birthDate.month();
birthDate2.tm_mday = birthDate.day();
tm currentDate2;
currentDate2.tm_year = currentDate.year();
currentDate2.tm_mon = currentDate.month();
currentDate2.tm_mday = currentDate.day();
int *tmp2 = calculateAge2(birthDate2, currentDate2);
if (tmp2 != nullptr)
{
char date[11];
birthDate2.tm_year-=1900; // int tm_year; years since 1900
birthDate2.tm_mon-=1; // int tm_mon; months since January [0, 11]
if (strftime(date, sizeof(date), "%d.%m.%Y", &birthDate2) != 0)
{
std::cout << "Birth date: " << date << std::endl;
}
currentDate2.tm_year-=1900; // int tm_year; years since 1900
currentDate2.tm_mon-=1; // int tm_mon; months since January [0, 11]
if (strftime(date, sizeof(date), "%d.%m.%Y", ¤tDate2) != 0)
{
std::cout << "Current date: " << date << std::endl;
}
std::cout << "Years: " << tmp2[0] << std::endl;
std::cout << "Months: " << tmp2[1] << std::endl;
std::cout << "Days: " << tmp2[2] << std::endl << std::endl;
}
delete []tmp2;
}
| 41.771277 | 132 | 0.517255 |
85fc290a665174108915a6b4f77f7fc8b8808d7b | 459 | hpp | C++ | src/app.hpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | src/app.hpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | src/app.hpp | trazfr/alarm | ea511eb0f16945de2005d828f452c76fce9d77e7 | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
/**
* @brief Represents the whole application
*/
class App
{
public:
struct Impl;
/**
* @attention the class keeps a reference to constructor's arguments. Make sure they stay valid
*/
explicit App(const char *configurationFile);
~App();
/**
* Runs the application
*
* This method only returns at exit time
*/
void run();
private:
std::unique_ptr<Impl> pimpl;
};
| 15.827586 | 99 | 0.614379 |
85fe846c064c03a415db9da5779bc34a873d8e03 | 436 | cpp | C++ | matrix_using_array.cpp | xeroxzen/C-Crash-Course | d394d6d91f4f0126b3742a9d11abc129f3daaeb4 | [
"MIT"
] | 1 | 2022-02-09T00:47:25.000Z | 2022-02-09T00:47:25.000Z | matrix_using_array.cpp | xeroxzen/C-Crash-Course | d394d6d91f4f0126b3742a9d11abc129f3daaeb4 | [
"MIT"
] | null | null | null | matrix_using_array.cpp | xeroxzen/C-Crash-Course | d394d6d91f4f0126b3742a9d11abc129f3daaeb4 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
//Declare a 2 dimensional array of a 3x3 matrix
//Each matrix element has a value of 1 or 0
int matrix[3][3] = {
{1, 0, 1},
{0, 1, 0},
{1, 0, 1}
};
//print out the matrix
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
return 0;
} | 20.761905 | 51 | 0.444954 |
85ff51c427c7553b4d4520a5dca730d35c5948db | 917 | cpp | C++ | fenwick_tree/coder_rating.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | 1 | 2020-08-11T17:50:01.000Z | 2020-08-11T17:50:01.000Z | fenwick_tree/coder_rating.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | null | null | null | fenwick_tree/coder_rating.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define ll long long int
using namespace std;
#define F first
#define S second
void update(ll index, vector<ll> &BIT){
for(ll i=index;i<=100000;i+=i&(-i)){
BIT[i]++;
}
}
ll query(ll index, vector<ll> &BIT){
ll count=0;
for(ll i=index;i>0;i-=i&(-i)){
count+=BIT[i];
}
return count;
}
int main(){
vector<ll> BIT(100001,0);
BIT[0]=0;
ll n;
cin>>n;
vector<pair<pair<ll,ll>,ll>> v(n);
for(ll i=0;i<n;i++){
ll x,y;
cin>>x>>y;
v[i]={{x,y},i};
}
ll ans[n];
sort(v.begin(),v.end());
for(ll i=0;i<n;i++){
ll end=i;
while(end<n and v[i].F.F==v[end].F.F and v[i].F.S==v[end].F.S){
end++;
}
for(ll j=i;j<end;j++){
ans[v[j].S]=query(v[j].F.S,BIT);
}
for(ll j=i;j<end;j++){
update(v[j].F.S,BIT);
}
i=end;
i--;
}
for(ll i=0;i<n;i++){
cout<<ans[i]<<endl;
}
return 0;
} | 17.634615 | 68 | 0.485278 |
65a0b02f10bf6c385424cfdc0344cdf983b4fa58 | 1,352 | hpp | C++ | render_view.hpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | render_view.hpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | render_view.hpp | piccolo255/pde-pathtracer | d754583a308975b68675076f68f1194cbaa906ca | [
"Unlicense"
] | null | null | null | #ifndef RENDER_VIEW_HPP
#define RENDER_VIEW_HPP
// Qt includes
#include <QWidget>
#include <QPainter>
#include <QList>
#include <QMap>
// C++ includes
// math expression parsing header
#include "muParser.h"
// Local includes
#include "ode_pathtracer.hpp"
class RenderView : public QWidget
{
Q_OBJECT
public:
explicit RenderView( QRect viewportArea
, QString transformationX
, QString transformationY
, QStringList paramNames
, QWidget *parent = 0 );
~RenderView();
void updateObjects( QList<PointValues> pointPathList, int maxPathLength );
private:
QRect viewRect;
QRect viewRectAlwaysVisible;
double pointX;
double pointY;
double t;
// QStringList paramsName;
// QMap<QString, double> paramsVal;
// QMap<QString, int> paramsIndex;
QVector<double> paramVals;
QVector<mu::Parser *> coordinateParsers;
QVector<QLineF> segments;
QVector<QColor> colors;
int maxSegments = 0;
void updateViewRect( QSize newViewRectSize );
void updateColors();
void ParserError( mu::Parser::exception_type &e );
signals:
public slots:
// QWidget interface
protected:
void paintEvent( QPaintEvent *event ) override;
void resizeEvent( QResizeEvent *event ) override;
};
#endif // RENDER_VIEW_HPP
| 21.460317 | 77 | 0.674556 |
65a34c65c61e56339bec1735c5007ea2009e2588 | 853 | cpp | C++ | dark_roads.cpp | mvgmb/Marathon | 0dcc428a5e6858e2427fb40cefbd7453d1abcdb5 | [
"Xnet",
"X11"
] | null | null | null | dark_roads.cpp | mvgmb/Marathon | 0dcc428a5e6858e2427fb40cefbd7453d1abcdb5 | [
"Xnet",
"X11"
] | null | null | null | dark_roads.cpp | mvgmb/Marathon | 0dcc428a5e6858e2427fb40cefbd7453d1abcdb5 | [
"Xnet",
"X11"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int parent[200005];
int size[200005];
vector<tuple<int,int,int> > lis;
int find(int x) {
if(x != parent[x]) parent[x] = find(parent[x]);
return parent[x];
}
bool same(int a, int b) {
return find(a) == find(b);
}
void unite(int a,int b) {
a = find(a);
b = find(b);
if(size[a] < size[b]) swap(a,b);
size[a] += size[b];
parent[b] = a;
}
int main() {
int m, n, u, v, w, i, c, tot;
while(cin >> m >> n && m != 0 && n != 0) {
for(i=0;i<m;i++) {
parent[i] = i;
size[i] = 1;
}
lis.clear();
tot = 0;
while(n--) {
cin >> u >> v >> w;
tot += w;
lis.push_back(make_tuple(w,u,v));
}
sort(lis.begin(),lis.end());
c = 0;
for(i=0;i<lis.size();i++) {
tie(w,u,v) = lis[i];
if(!same(u,v)) {
c += w;
unite(u,v);
}
}
cout << (tot- c) << endl;
}
return 0;
} | 16.403846 | 48 | 0.494725 |
65a4129133678830b35540e7196ade3735b0d039 | 6,191 | cpp | C++ | flume/util/hadoop_conf_test.cpp | advancedxy/bigflow_python | 8a244b483404fde7afc42eee98bc964da8ae03e2 | [
"Apache-2.0"
] | 1 | 2021-02-18T20:13:34.000Z | 2021-02-18T20:13:34.000Z | flume/util/hadoop_conf_test.cpp | advancedxy/bigflow_python | 8a244b483404fde7afc42eee98bc964da8ae03e2 | [
"Apache-2.0"
] | null | null | null | flume/util/hadoop_conf_test.cpp | advancedxy/bigflow_python | 8a244b483404fde7afc42eee98bc964da8ae03e2 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
*
* Copyright (c) 2013 Baidu, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**************************************************************************/
// Author: Zhang Yuncong (zhangyuncong@baidu.com)
//
// Description: Flume hadoop conf util test
#include <stdlib.h>
#include "flume/util/hadoop_conf.h"
#include "gtest/gtest.h"
namespace baidu {
namespace flume {
namespace util {
TEST(TestHadoopConf, TestFromFile) {
// backup & clear sys env
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
unsetenv(kHadoopJobUgi);
unsetenv(kFsDefaultName);
HadoopConf conf("testdata/hadoop-site.xml");
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ("test,test", conf.hadoop_job_ugi());
ASSERT_EQ("hdfs://baidu.com:1234", conf.fs_defaultfs());
// restore sys env if necessary
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
}
}
TEST(TestHadoopConf, TestFromEnv) {
// backup & set sys env
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
const char* kExpectUgi = "env,env";
const char* kExpectFsName = "hdfs:///env.com:37213";
setenv(kHadoopJobUgi, kExpectUgi, 1);
setenv(kFsDefaultName, kExpectFsName, 1);
HadoopConf conf("testdata/hadoop-site.xml");
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
// restore sys env
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
} else {
unsetenv(kHadoopJobUgi);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
} else {
unsetenv(kFsDefaultName);
}
}
TEST(TestHadoopConf, TestFromMap) {
const char* kExpectUgi = "app,app";
const char* kExpectFsName = "hdfs://app.com:34275";
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
conf_map[kFsDefaultName] = kExpectFsName;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
}
TEST(TestHadoopConf, TestPartialOverwrite1) {
// get fs name from conf file
// get ugi from conf map
char* env_fs_name = getenv(kFsDefaultName);
unsetenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ("hdfs://baidu.com:1234", conf.fs_defaultfs());
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
}
}
TEST(TestHadoopConf, TestPartialOverwrite2) {
// get fs name from env
// get ugi from conf map
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
const char* kExpectFsName = "hdfs:///env.com:37213";
setenv(kHadoopJobUgi, "ignore.me", 1);
setenv(kFsDefaultName, kExpectFsName, 1);
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
} else {
unsetenv(kHadoopJobUgi);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
} else {
unsetenv(kFsDefaultName);
}
}
TEST(TestHadoopConf, TestMapOverwriteAll) {
// get both fs name and ugi from map
char* env_ugi = getenv(kHadoopJobUgi);
char* env_fs_name = getenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
const char* kExpectFsName = "hdfs:///env.com:37213";
setenv(kHadoopJobUgi, "ignore.me", 1);
setenv(kFsDefaultName, "hdfs:///ignore.me:too", 1);
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
conf_map[kFsDefaultName] = kExpectFsName;
HadoopConf conf("testdata/hadoop-site.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_EQ(kExpectFsName, conf.fs_defaultfs());
if (env_ugi != NULL) {
setenv(kHadoopJobUgi, env_ugi, 1);
} else {
unsetenv(kHadoopJobUgi);
}
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
} else {
unsetenv(kFsDefaultName);
}
}
TEST(TestHadoopConf, TestEmptyFsDefaultName) {
char* env_fs_name = getenv(kFsDefaultName);
unsetenv(kFsDefaultName);
const char* kExpectUgi = "app,app";
HadoopConf::JobConfMap conf_map;
conf_map[kHadoopJobUgi] = kExpectUgi;
HadoopConf conf("testdata/hadoop-site-partial.xml", conf_map);
ASSERT_EQ("testdata/hadoop-site-partial.xml", conf.hadoop_conf_path());
ASSERT_EQ(kExpectUgi, conf.hadoop_job_ugi());
ASSERT_TRUE(conf.fs_defaultfs().empty());
if (env_fs_name != NULL) {
setenv(kFsDefaultName, env_fs_name, 1);
}
}
} // namespace util
} // namespace flume
} // namespace baidu
| 31.586735 | 76 | 0.666613 |
65a4e8c1c6e529c6cdc1a015ccca4a644b955680 | 279 | cpp | C++ | Codeforces Online Judge Solve/all divs/main (9).cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/all divs/main (9).cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | Codeforces Online Judge Solve/all divs/main (9).cpp | Remonhasan/programming-solve | 5a4ac8c738dd361e1c974162e0eaebbaae72fd80 | [
"Apache-2.0"
] | null | null | null | /*last time Tumi ami from uap*/
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
ll a,ami;
cin>>a>>ami;
ll tumi=a;
ll taka=0;
while(tumi<ami){
tumi*=a;
taka++;
}
if(tumi==ami)
cout<<"YES"<<endl<<taka;
else
cout<<"NO";
return 0;
}
| 13.285714 | 31 | 0.598566 |
65a7e5b33be85651a29dc2490c23261a3b75f8c4 | 1,709 | cpp | C++ | 00.ATM/Funzioni/01.Login.cpp | JavaSoftwareEntwickler/C-ATM | 16452ec7f5d3d2a10e3e7137c5f0dcd762de25a2 | [
"Unlicense"
] | null | null | null | 00.ATM/Funzioni/01.Login.cpp | JavaSoftwareEntwickler/C-ATM | 16452ec7f5d3d2a10e3e7137c5f0dcd762de25a2 | [
"Unlicense"
] | null | null | null | 00.ATM/Funzioni/01.Login.cpp | JavaSoftwareEntwickler/C-ATM | 16452ec7f5d3d2a10e3e7137c5f0dcd762de25a2 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
using namespace std;
bool login(char [], char []);
int main()
{
char userId[7] = "ciccio", psw[5] = "1234";
bool accesso=login(psw, userId);
}
bool login(char psw[], char userId[])
{
char userIdDigitata[20], pswDigitata[20];
bool accessoAtm = false;
int tentativi = 4;
do
{
tentativi --;
printf("UserId..");
scanf("%s", &userIdDigitata);
printf("Password..");
scanf("%s", &pswDigitata);
int comaparaId =strcmp(userId, userIdDigitata);
int comaparaPsw=strcmp(psw, pswDigitata);
if ((comaparaId ==0) && (comaparaPsw==0))
{
system("cls");
tentativi=0;
accessoAtm = true;// acessoAtm diventa : uno! quindi entrare nel modulo menu dell'ATM
printf("\n%s", "***Connessione in corso.....");
}
else if (tentativi>1)
{
system("cls");
printf("Hai ancora %d tentativi\n",tentativi);
}
else if (tentativi==1)
{
system("cls");
printf("*******************\n*Ultimo tentativo *\n");
printf("*******************\nSe sbagli anche questo tentativo\n");
printf("l'account verra' bloccato.\n**************************\n");
}
else
{
system("cls");
printf("%s","**LogOut****Account bloccato****");
tentativi=0;
accessoAtm = false; // acessoAtm diventa :zero
}
}
while(tentativi!=0);
return accessoAtm;
}
| 23.410959 | 98 | 0.475717 |
65a835ddf980515a6d34e3cce94fb15b7fd256e1 | 2,935 | hpp | C++ | componentLibraries/defaultLibrary/Signal/Sources&Sinks/SignalPulseWave.hpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | componentLibraries/defaultLibrary/Signal/Sources&Sinks/SignalPulseWave.hpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | componentLibraries/defaultLibrary/Signal/Sources&Sinks/SignalPulseWave.hpp | mjfwest/hopsan | 77a0a1e69fd9588335b7e932f348972186cbdf6f | [
"Apache-2.0"
] | null | null | null | /*-----------------------------------------------------------------------------
Copyright 2017 Hopsan Group
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.
The full license is available in the file LICENSE.
For details about the 'Hopsan Group' or information about Authors and
Contributors see the HOPSANGROUP and AUTHORS files that are located in
the Hopsan source code root directory.
-----------------------------------------------------------------------------*/
//!
//! @file SignalPulse.hpp
//! @author Peter Nordin <peter.nordin@liu.se>
//! @date 2012-03-29
//!
//! @brief Contains a pulse wave (train) signal generator
//!
//$Id$
#ifndef SIGNALPULSEWAVE_HPP
#define SIGNALPULSEWAVE_HPP
#include "ComponentEssentials.h"
#include <cmath>
namespace hopsan {
//!
//! @brief
//! @ingroup SignalComponents
//!
class SignalPulseWave : public ComponentSignal
{
private:
double *mpBaseValue;
double *mpStartTime;
double *mpPeriodT;
double *mpDutyCycle;
double *mpAmplitude;
double *mpOut;
public:
static Component *Creator()
{
return new SignalPulseWave();
}
void configure()
{
addInputVariable("y_0", "Base Value", "", 0.0, &mpBaseValue);
addInputVariable("y_A", "Amplitude", "", 1.0, &mpAmplitude);
addInputVariable("t_start", "Start Time", "Time", 0.0, &mpStartTime);
addInputVariable("dT", "Time Period", "Time", 1.0, &mpPeriodT);
addInputVariable("D", "Duty Cycle, (ratio 0<=x<=1)", "", 0.5, &mpDutyCycle);
addOutputVariable("out", "PulseWave", "", &mpOut);
}
void initialize()
{
(*mpOut) = (*mpBaseValue);
}
void simulateOneTimestep()
{
// +0.5*mTimestep to avoid ronding issues
const double time = (mTime-(*mpStartTime)+0.5*mTimestep);
const double periodT = (*mpPeriodT);
const bool high = (time - std::floor(time/periodT)*periodT) < (*mpDutyCycle)*periodT;
if ( (time > 0) && high)
{
(*mpOut) = (*mpBaseValue) + (*mpAmplitude); //During pulse
}
else
{
(*mpOut) = (*mpBaseValue); //Not during pulse
}
}
};
}
#endif // SIGNALPULSEWAVE_HPP
| 29.059406 | 97 | 0.563203 |
65aa4f8a689a10358a5296a8ff5330621cee12ca | 248 | cpp | C++ | smartvacuum/main.cpp | willianbrun/smartvacuum | 923394d0f3ec91613dec179ae826c9408a98d356 | [
"MIT"
] | null | null | null | smartvacuum/main.cpp | willianbrun/smartvacuum | 923394d0f3ec91613dec179ae826c9408a98d356 | [
"MIT"
] | null | null | null | smartvacuum/main.cpp | willianbrun/smartvacuum | 923394d0f3ec91613dec179ae826c9408a98d356 | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
a.setApplicationName("Smart Vacuum");
a.setOrganizationName("UPF");
MainWindow w;
w.show();
return a.exec();
}
| 17.714286 | 41 | 0.645161 |
65acc90ed1a5c8e334436ca0894d3f2b89478da0 | 23,489 | hpp | C++ | include/ak_toolkit/markable.hpp | akrzemi1/markable | fc435319fb32ed5753e6ae6762f78d98e0d33c73 | [
"BSL-1.0"
] | 82 | 2016-03-12T11:53:55.000Z | 2022-02-17T15:18:02.000Z | include/ak_toolkit/markable.hpp | akrzemi1/markable | fc435319fb32ed5753e6ae6762f78d98e0d33c73 | [
"BSL-1.0"
] | 10 | 2016-03-12T13:53:49.000Z | 2020-12-17T22:20:16.000Z | include/ak_toolkit/markable.hpp | akrzemi1/markable | fc435319fb32ed5753e6ae6762f78d98e0d33c73 | [
"BSL-1.0"
] | 11 | 2016-09-01T15:53:32.000Z | 2021-09-28T15:51:32.000Z | // Copyright (C) 2015-2021 Andrzej Krzemienski.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
#define AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
#include <cassert>
#include <utility>
#include <limits>
#include <new>
#include <type_traits>
#include <limits>
# if defined AK_TOOLKIT_WITH_CONCEPTS
#include <concepts>
# endif
#if defined AK_TOOLBOX_NO_ARVANCED_CXX11
# define AK_TOOLKIT_NOEXCEPT
# define AK_TOOLKIT_IS_NOEXCEPT(E) true
# define AK_TOOLKIT_CONSTEXPR
# define AK_TOOLKIT_CONSTEXPR_OR_CONST const
# define AK_TOOLKIT_EXPLICIT_CONV
# define AK_TOOLKIT_NOEXCEPT_AS(E)
#else
# define AK_TOOLKIT_NOEXCEPT noexcept
# define AK_TOOLKIT_IS_NOEXCEPT(E) noexcept(E)
# define AK_TOOLKIT_CONSTEXPR constexpr
# define AK_TOOLKIT_CONSTEXPR_OR_CONST constexpr
# define AK_TOOLKIT_EXPLICIT_CONV explicit
# define AK_TOOLKIT_NOEXCEPT_AS(E) noexcept(noexcept(E))
# define AK_TOOLKIT_CONSTEXPR_NOCONST // fix in the future
#endif
#ifndef AK_TOOLKIT_LIKELY
# if defined __GNUC__
# define AK_TOOLKIT_LIKELY(EXPR) __builtin_expect(!!(EXPR), 1)
# else
# define AK_TOOLKIT_LIKELY(EXPR) (!!(EXPR))
# endif
#endif
#ifndef AK_TOOLKIT_ASSERT
# if defined NDEBUG
# define AK_TOOLKIT_ASSERT(EXPR) void(0)
# else
# define AK_TOOLKIT_ASSERT(EXPR) ( AK_TOOLKIT_LIKELY(EXPR) ? void(0) : []{assert(!#EXPR);}() )
# endif
#endif
#ifndef AK_TOOLKIT_ASSERTED_EXPRESSION
# if defined NDEBUG
# define AK_TOOLKIT_ASSERTED_EXPRESSION(CHECK, EXPR) (EXPR)
# else
# define AK_TOOLKIT_ASSERTED_EXPRESSION(CHECK, EXPR) (AK_TOOLKIT_LIKELY(CHECK) ? (EXPR) : ([]{assert(!#CHECK);}(), (EXPR)))
# endif
#endif
#if defined __cpp_concepts && __cpp_concepts == 201507
// TODO: will conditionally support concepts
#endif
namespace ak_toolkit {
namespace markable_ns {
# if defined AK_TOOLKIT_WITH_CONCEPTS
template <typename MP>
concept mark_policy =
requires
{
typename MP::value_type;
typename MP::storage_type;
typename MP::reference_type;
typename MP::representation_type;
} &&
requires(const typename MP::representation_type & cr,
typename MP::representation_type && rr,
const typename MP::storage_type & s,
const typename MP::value_type & cv,
typename MP::value_type && rv)
{
{ MP::marked_value() }
-> ::std::convertible_to<typename MP::representation_type>;
{ MP::is_marked_value(cr) }
-> ::std::convertible_to<bool>;
{ MP::access_value(s) }
-> ::std::same_as<typename MP::reference_type>;
{ MP::representation(s) }
-> ::std::same_as<const typename MP::representation_type &>;
{ MP::store_value(cv) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_value(::std::move(rv)) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_representation(cr) }
-> ::std::convertible_to<typename MP::storage_type>;
{ MP::store_representation(::std::move(rr)) }
-> ::std::convertible_to<typename MP::storage_type>;
};
# define AK_TOOLKIT_MARK_POLICY mark_policy
# else
# define AK_TOOLKIT_MARK_POLICY typename
# endif
struct default_tag{};
template <typename T, typename REPT = T, typename CREF = const T&, typename STOR = REPT>
struct markable_type
{
typedef T value_type; // the type we claim we (optionally) store
typedef REPT representation_type; // the type we use to represent the marked state
typedef CREF reference_type; // the type that we return upon "dereference"
typedef STOR storage_type; // the type we use for storage
static AK_TOOLKIT_CONSTEXPR reference_type access_value(const storage_type& v) { return reference_type(v); }
static AK_TOOLKIT_CONSTEXPR const representation_type& representation(const storage_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR const storage_type& store_value(const value_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR storage_type&& store_value(value_type&& v) { return std::move(v); }
static AK_TOOLKIT_CONSTEXPR const storage_type& store_representation(const representation_type& v) { return v; }
static AK_TOOLKIT_CONSTEXPR storage_type&& store_representation(representation_type&& v) { return std::move(v); }
};
template <typename T, T Val>
struct mark_int : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT { return Val; }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(T v) AK_TOOLKIT_NOEXCEPT { return v == Val; }
};
template <typename FPT>
struct mark_fp_nan : markable_type<FPT>
{
static AK_TOOLKIT_CONSTEXPR FPT marked_value() AK_TOOLKIT_NOEXCEPT { return std::numeric_limits<FPT>::quiet_NaN(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(FPT v) AK_TOOLKIT_NOEXCEPT { return v != v; }
};
template <typename T> // requires Regular<T>
struct mark_value_init : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT_AS(T()) { return T(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const T& v) AK_TOOLKIT_NOEXCEPT_AS(T()) { return v == T(); }
};
template <typename T>
struct mark_stl_empty : markable_type<T>
{
static AK_TOOLKIT_CONSTEXPR T marked_value() AK_TOOLKIT_NOEXCEPT_AS(T()) { return T(); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const T& v) { return v.empty(); }
};
template <typename OT>
struct mark_optional : markable_type<typename OT::value_type, OT>
{
typedef typename OT::value_type value_type;
typedef OT storage_type;
static OT marked_value() AK_TOOLKIT_NOEXCEPT { return OT(); }
static bool is_marked_value(const OT& v) { return !v; }
static const value_type& access_value(const storage_type& v) { return *v; }
static storage_type store_value(const value_type& v) { return v; }
static storage_type store_value(value_type&& v) { return std::move(v); }
};
struct mark_bool : markable_type<bool, char, bool>
{
static AK_TOOLKIT_CONSTEXPR char marked_value() AK_TOOLKIT_NOEXCEPT { return char(2); }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(char v) AK_TOOLKIT_NOEXCEPT { return v == 2; }
static AK_TOOLKIT_CONSTEXPR bool access_value(const char& v) { return bool(v); }
static AK_TOOLKIT_CONSTEXPR char store_value(const bool& v) { return v; }
};
#ifndef AK_TOOLBOX_NO_UNDERLYING_TYPE
template <typename Enum, typename std::underlying_type<Enum>::type Val>
struct mark_enum : markable_type<Enum, typename std::underlying_type<Enum>::type, Enum>
{
typedef markable_type<Enum, typename std::underlying_type<Enum>::type, Enum> base;
static_assert(std::is_enum<Enum>::value, "mark_enum only works with enum types");
#else
template <typename Enum, int Val>
struct mark_enum : markable_type<Enum, int, Enum>
{
typedef markable_type<Enum, int, Enum> base;
static_assert(sizeof(Enum) == sizeof(int), "in this compiler underlying type of enum must be int");
#endif // AK_TOOLBOX_NO_UNDERLYING_TYPE
typedef typename base::representation_type representation_type;
typedef typename base::storage_type storage_type;
static AK_TOOLKIT_CONSTEXPR representation_type marked_value() AK_TOOLKIT_NOEXCEPT { return Val; }
static AK_TOOLKIT_CONSTEXPR bool is_marked_value(const representation_type& v) AK_TOOLKIT_NOEXCEPT { return v == Val; }
static AK_TOOLKIT_CONSTEXPR Enum access_value(const storage_type& v) AK_TOOLKIT_NOEXCEPT { return static_cast<Enum>(v); }
static AK_TOOLKIT_CONSTEXPR storage_type store_value(const Enum& v) AK_TOOLKIT_NOEXCEPT { return static_cast<storage_type>(v); }
};
namespace detail_ {
struct _init_nothing_tag {};
template <typename MP>
union dual_storage_union
{
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
char _nothing;
value_type _value;
representation_type _marking;
constexpr explicit dual_storage_union(_init_nothing_tag) AK_TOOLKIT_NOEXCEPT
: _nothing() {}
constexpr explicit dual_storage_union(representation_type && v) AK_TOOLKIT_NOEXCEPT_AS(representation_type(std::move(v)))
: _marking(std::move(v)) {}
constexpr explicit dual_storage_union(value_type && v) AK_TOOLKIT_NOEXCEPT_AS(value_type(std::move(v)))
: _value(std::move(v)) {}
constexpr explicit dual_storage_union(const value_type& v) AK_TOOLKIT_NOEXCEPT_AS(value_type(std::move(v)))
: _value(v) {}
~dual_storage_union() {/* nothing here; will be properly destroyed by the owner */}
};
template <typename MVP, typename = void>
struct check_safe_dual_storage_exception_safety : ::std::true_type {};
template <typename MVP>
struct check_safe_dual_storage_exception_safety<MVP, typename MVP::is_safe_dual_storage_mark_policy>
: std::integral_constant<bool, AK_TOOLKIT_IS_NOEXCEPT(typename MVP::representation_type(MVP::marked_value()))>
{
};
} // namespace detail_
template <typename T>
struct representation_of
{
static_assert(sizeof(T) == 0, "class template representation_of<T> needs to be specialized for your type");
};
template <typename MP>
struct dual_storage
{
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
typedef typename MP::reference_type reference_type;
private:
typedef detail_::dual_storage_union<MP> union_type;
union_type value_;
private:
void* address() { return static_cast<void*>(std::addressof(value_)); }
void construct_value(const value_type& v) { ::new (address()) value_type(v); }
void construct_value(value_type&& v) { ::new (address()) value_type(std::move(v)); }
void change_to_value(const value_type& v)
try {
destroy_storage();
construct_value(v);
}
catch (...)
{ // now, neither value nor no-value. We have to try to assign no-value
construct_storage_checked();
throw;
}
void change_to_value(value_type&& v)
try {
destroy_storage();
construct_value(std::move(v));
}
catch (...)
{ // now, neither value nor no-value. We have to try to assign no-value
construct_storage_checked();
throw;
}
void construct_storage() { ::new (address()) representation_type(MP::marked_value()); }
void construct_storage_checked() AK_TOOLKIT_NOEXCEPT { construct_storage(); } // std::terminate() if MP::marked_value() throws
void destroy_value() AK_TOOLKIT_NOEXCEPT { as_value().value_type::~value_type(); }
void destroy_storage() AK_TOOLKIT_NOEXCEPT { representation().representation_type::~representation_type(); }
public:
void clear_value() AK_TOOLKIT_NOEXCEPT { destroy_value(); construct_storage(); } // std::terminate() if MP::marked_value() throws
bool has_value() const AK_TOOLKIT_NOEXCEPT { return !MP::is_marked_value(representation()); }
value_type& as_value() { return value_._value; }
const value_type& as_value() const { return value_._value; }
public:
representation_type& representation() AK_TOOLKIT_NOEXCEPT { return value_._marking; }
const representation_type& representation() const AK_TOOLKIT_NOEXCEPT { return value_._marking; }
constexpr explicit dual_storage(representation_type&& mv) AK_TOOLKIT_NOEXCEPT_AS(union_type(std::move(mv)))
: value_(std::move(mv)) {}
constexpr explicit dual_storage(const value_type& v) AK_TOOLKIT_NOEXCEPT_AS(union_type(v))
: value_(v) {}
constexpr explicit dual_storage(value_type&& v) AK_TOOLKIT_NOEXCEPT_AS(union_type(std::move(v)))
: value_(std::move(v)) {}
dual_storage(const dual_storage& rhs) // TODO: add noexcept
: value_(detail_::_init_nothing_tag{})
{
if (rhs.has_value())
construct_value(rhs.as_value());
else
construct_storage();
}
dual_storage(dual_storage&& rhs) // TODO: add noexcept
: value_(detail_::_init_nothing_tag{})
{
if (rhs.has_value())
construct_value(std::move(rhs.as_value()));
else
construct_storage();
}
void operator=(const dual_storage& rhs)
{
if (has_value() && rhs.has_value())
{
as_value() = rhs.as_value();
}
else if (has_value() && !rhs.has_value())
{
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(rhs.as_value());
}
}
void operator=(dual_storage&& rhs) // TODO: add noexcept
{
if (has_value() && rhs.has_value())
{
as_value() = std::move(rhs.as_value());
}
else if (has_value() && !rhs.has_value())
{
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(std::move(rhs.as_value()));
}
}
void swap_impl(dual_storage& rhs)
{
using namespace std;
if (has_value() && rhs.has_value())
{
swap(as_value(), rhs.as_value());
}
else if (has_value() && !rhs.has_value())
{
rhs.change_to_value(std::move(as_value()));
clear_value();
}
else if (!has_value() && rhs.has_value())
{
change_to_value(std::move(rhs.as_value()));
rhs.clear_value();
}
}
friend void swap(dual_storage& lhs, dual_storage& rhs) { lhs.swap_impl(rhs); }
~dual_storage()
{
if (has_value())
destroy_value();
else
destroy_storage();
}
};
template <typename MPT, typename T, typename REP_T = typename representation_of<T>::type>
struct markable_dual_storage_type_unsafe
{
static_assert(sizeof(T) == sizeof(REP_T), "representation of T has to have the same size and alignment as T");
static_assert(std::is_standard_layout<T>::value, "T must be a Standard Layout type");
static_assert(std::is_standard_layout<REP_T>::value, "representation of T must be a Standard Layout type");
#ifndef AK_TOOLBOX_NO_ARVANCED_CXX11
static_assert(alignof(T) == alignof(REP_T), "representation of T has to have the same alignment as T");
#endif // AK_TOOLBOX_NO_ARVANCED_CXX11
// TODO: in C++20: static_assert(std::is_layout_compatible_v<T, REP_T>, "representation of T has to be layout-compatible with T");
typedef T value_type;
typedef REP_T representation_type;
typedef const T& reference_type;
typedef dual_storage<MPT> storage_type;
static reference_type access_value(const storage_type& v)
{ return v.as_value(); }
static const representation_type& representation(const storage_type& v)
{ return v.representation(); }
static storage_type store_value(const value_type& v)
{ return storage_type(v); }
static storage_type store_value(value_type&& v)
{ return storage_type(std::move(v)); }
static storage_type store_representation(const representation_type& r)
{ return storage_type(r); }
static storage_type store_representation(representation_type&& r)
{ return storage_type(std::move(r)); }
};
template <typename MPT, typename T, typename REP_T = typename representation_of<T>::type>
struct markable_dual_storage_type : markable_dual_storage_type_unsafe<MPT, T, REP_T>
{
// The presence of this typedef is a request to check if T is nothrow move constructible
typedef void is_safe_dual_storage_mark_policy;
};
// ### Ordering policies
class order_none {};
template <AK_TOOLKIT_MARK_POLICY MP, typename OP = order_none>
class markable;
class order_by_representation
{
template <typename MP, typename OP>
static bool unique_marked_value(const markable<MP, OP>& mk)
{
// returns false if mk has no value but its storage is different
// than the MP::marked_value().
return mk.has_value() || mk.representation_value() == MP::marked_value();
}
public:
template <typename MP, typename OP>
static auto equal(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.representation_value() == r.representation_value())
{
assert(unique_marked_value(l));
assert(unique_marked_value(r));
return l.representation_value() == r.representation_value();
}
template <typename MP, typename OP>
static auto less(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.representation_value() < r.representation_value())
{
assert(unique_marked_value(l));
assert(unique_marked_value(r));
return l.representation_value() < r.representation_value();
}
};
class order_by_value
{
public:
template <typename MP, typename OP>
static auto equal(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.value() == r.value())
{
return !l.has_value() ? !r.has_value() : r.has_value() && l.value() == r.value();
}
template <typename MP, typename OP>
static auto less(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(l.value() < r.value())
{
return !r.has_value() ? false : (!l.has_value() ? true : l.value() < r.value());
}
};
struct with_representation_t
{
AK_TOOLKIT_CONSTEXPR explicit with_representation_t() {}
};
AK_TOOLKIT_CONSTEXPR_OR_CONST with_representation_t with_representation {};
template <AK_TOOLKIT_MARK_POLICY MP, typename OP>
class markable
{
// The following assert is only in case a safe dual storage is used.
// It then checks if the value_type is nothrow move constructible.
// I cannot check it inside the dual storage, because I need a complete
// type to determine nothrow traits.
static_assert (detail_::check_safe_dual_storage_exception_safety<MP>::value,
"while building a markable type: representation of T must not throw exceptions from move constructor or when creating the marked value");
public:
typedef typename MP::value_type value_type;
typedef typename MP::representation_type representation_type;
typedef typename MP::reference_type reference_type;
private:
typename MP::storage_type _storage;
public:
AK_TOOLKIT_CONSTEXPR markable() AK_TOOLKIT_NOEXCEPT_AS(MP::marked_value())
: _storage(MP::store_representation(MP::marked_value())) {}
AK_TOOLKIT_CONSTEXPR explicit markable(const value_type& v)
: _storage(MP::store_value(v)) {}
AK_TOOLKIT_CONSTEXPR explicit markable(value_type&& v)
: _storage(MP::store_value(std::move(v))) {}
AK_TOOLKIT_CONSTEXPR explicit markable(with_representation_t, const representation_type& r)
: _storage(MP::store_representation(r)) {}
AK_TOOLKIT_CONSTEXPR explicit markable(with_representation_t, representation_type&& r)
: _storage(MP::store_representation(::std::move(r))) {}
AK_TOOLKIT_CONSTEXPR bool has_value() const {
return !MP::is_marked_value(MP::representation(_storage));
}
AK_TOOLKIT_CONSTEXPR reference_type value() const { return AK_TOOLKIT_ASSERT(has_value()), MP::access_value(_storage); }
AK_TOOLKIT_CONSTEXPR representation_type const& representation_value() const {
return MP::representation(_storage);
}
void assign(value_type&& v) { _storage = MP::store_value(std::move(v)); }
void assign(const value_type& v) { _storage = MP::store_value(v); }
void assign_representation(representation_type&& s) { _storage = MP::store_representation(std::move(s)); }
void assign_representation(representation_type const& s) { _storage = MP::store_representation(s); }
friend void swap(markable& lhs, markable& rhs) {
using std::swap; swap(lhs._storage, rhs._storage);
}
};
template <typename MP, typename OP>
auto operator==(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::equal(l, r))
{
return OP::equal(l, r);
}
template <typename MP, typename OP>
auto operator!=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::equal(l, r))
{
return !OP::equal(l, r);
}
template <typename MP, typename OP>
auto operator<(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return OP::less(l, r);
}
template <typename MP, typename OP>
auto operator>(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return OP::less(r, l);
}
template <typename MP, typename OP>
auto operator<=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return !OP::less(r, l);
}
template <typename MP, typename OP>
auto operator>=(const markable<MP, OP>& l, const markable<MP, OP>& r)
-> decltype(OP::less(l, r))
{
return !OP::less(l, r);
}
// This defines a customization point for selecting the default makred value
// policy for a given type
template <typename T, typename = void>
struct default_mark_policy
{
using type = mark_value_init<T>;
};
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_integral<T>::value>::type>
{
using type = mark_int<T, std::numeric_limits<T>::max()>;
};
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_floating_point<T>::value>::type>
{
using type = mark_fp_nan<T>;
};
template <>
struct default_mark_policy<bool, void>
{
using type = mark_bool;
};
#ifndef AK_TOOLBOX_NO_UNDERLYING_TYPE
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
using type = mark_enum<T, std::numeric_limits<typename std::underlying_type<T>::type>::max()>;
};
#else
template <typename T>
struct default_mark_policy<T, typename std::enable_if<std::is_enum<T>::value>::type>
{
using type = mark_enum<T, std::numeric_limits<int>::max()>;
};
#endif
template <typename T>
using default_markable = markable<typename default_mark_policy<T>::type, order_by_value>;
} // namespace markable_ns
using markable_ns::markable;
using markable_ns::markable_type;
using markable_ns::markable_dual_storage_type;
using markable_ns::markable_dual_storage_type_unsafe;
using markable_ns::mark_bool;
using markable_ns::mark_int;
using markable_ns::mark_fp_nan;
using markable_ns::mark_value_init;
using markable_ns::mark_optional;
using markable_ns::mark_stl_empty;
using markable_ns::mark_enum;
using markable_ns::order_none;
using markable_ns::order_by_representation;
using markable_ns::order_by_value;
using markable_ns::default_markable;
using markable_ns::with_representation;
using markable_ns::with_representation_t;
# if defined AK_TOOLKIT_WITH_CONCEPTS
using markable_ns::mark_policy;
static_assert(mark_policy<mark_bool>, "mark_policy test failed");
static_assert(mark_policy<mark_int<int, 0>>, "mark_policy test failed");
static_assert(mark_policy<mark_fp_nan<float>>, "mark_policy test failed");
static_assert(mark_policy<mark_value_init<int>>, "mark_policy test failed");
# endif
} // namespace ak_toolkit
// hashing
namespace std
{
template <typename MP>
struct hash<ak_toolkit::markable<MP, ak_toolkit::order_by_representation>>
{
typedef typename hash<typename MP::representation_type>::result_type result_type;
typedef ak_toolkit::markable<MP, ak_toolkit::order_by_representation> argument_type;
constexpr result_type operator()(argument_type const& arg) const {
return std::hash<typename MP::representation_type>{}(arg.representation_value());
}
};
template <typename MP>
struct hash<ak_toolkit::markable<MP, ak_toolkit::order_by_value>>
{
typedef typename hash<typename MP::value_type>::result_type result_type;
typedef ak_toolkit::markable<MP, ak_toolkit::order_by_value> argument_type;
constexpr result_type operator()(argument_type const& arg) const {
return arg.has_value() ? std::hash<typename MP::value_type>{}(arg.value()) : result_type{};
}
};
} // namespace std
#endif //AK_TOOLBOX_COMPACT_OPTIONAL_HEADER_GUARD_
| 33.036568 | 154 | 0.726255 |
65afd1192c8f3c63a733e303442998fd22a9fc21 | 1,130 | hpp | C++ | src/game-objects/turret.hpp | Blackhawk-TA/TowerDefense | db852a65cae9579074e435fb0245fd9b69fb720d | [
"MIT"
] | 1 | 2022-01-02T15:02:09.000Z | 2022-01-02T15:02:09.000Z | src/game-objects/turret.hpp | Blackhawk-TA/TowerDefense | db852a65cae9579074e435fb0245fd9b69fb720d | [
"MIT"
] | null | null | null | src/game-objects/turret.hpp | Blackhawk-TA/TowerDefense | db852a65cae9579074e435fb0245fd9b69fb720d | [
"MIT"
] | 1 | 2021-05-02T18:25:51.000Z | 2021-05-02T18:25:51.000Z | //
// Created by Daniel Peters on 08.04.21.
//
#pragma once
#include "../utils/utils.hpp"
using namespace blit;
class Turret {
public:
explicit Turret(Point position, TurretFacingDirection facing_direction);
void draw();
Rect get_rectangle() const;
TurretFacingDirection get_facing_direction();
uint8_t get_damage() const;
Point get_range() const;
Point get_barrel_position() const;
void animate();
bool is_animation_pending() const;
void activate_animation_pending();
private:
const uint8_t damage = 19;
const std::array<uint8_t, 5> animation_sprite_ids = {0, 56, 57, 58};
const Point range = Point(1, 4); // How far it can shoot to the left/right and forward
const Rect sprite_facing_up = Rect(10, 1, 1, 2);
const Rect sprite_facing_down = Rect(7, 2, 1, 2);
const Rect sprite_facing_left = Rect(8, 2, 2, 1);
Point spawn_position;
Point animation_position;
Point barrel_position; //The position where the turret fires from
Rect sprite;
SpriteTransform transform;
SpriteTransform animation_transform;
TurretFacingDirection facing_direction;
uint8_t animation_sprite_index;
bool animation_pending;
};
| 27.560976 | 87 | 0.761947 |
65b3d0ef272427bbf9499c284f7b66a4af56504a | 17,757 | cc | C++ | informal_code/cfsqp/local_fan.cc | fbrausse/flyspeck | 66f4ef0f9252c382333586fc07787e64d8a4bbfb | [
"MIT"
] | 125 | 2016-03-22T22:29:23.000Z | 2022-02-15T05:43:43.000Z | informal_code/cfsqp/local_fan.cc | fbrausse/flyspeck | 66f4ef0f9252c382333586fc07787e64d8a4bbfb | [
"MIT"
] | 4 | 2015-10-13T17:38:34.000Z | 2020-11-26T19:54:19.000Z | informal_code/cfsqp/local_fan.cc | fbrausse/flyspeck | 66f4ef0f9252c382333586fc07787e64d8a4bbfb | [
"MIT"
] | 9 | 2017-06-21T08:48:56.000Z | 2021-05-13T02:07:27.000Z | /* ========================================================================== */
/* FLYSPECK - CFSQP */
/* */
/* Nonlinear Inequalities, C++ Nonrigorous Numerical Optimization */
/* Chapter: Local Fan */
/* Author: Thomas C. Hales */
/* Date: 2010-03-01 */
/* ========================================================================== */
#include <iomanip.h>
#include <iostream.h>
#include <math.h>
#include "Minimizer.h"
#include "numerical.h"
// local_fan.cc
// $ make local_fan.o
// $ ./local_fan.o
// constructor calls optimizer. No need to place in main loop.
class trialdata {
public:
trialdata(Minimizer M,char* s) {
M.coutReport(s);
};
};
double Power(double a,int b) {
return pow(a,(float) b);
}
int trialcount = 300;
double eps = 1.0e-6;
double s2 = sqrt(2.0);
double s8 = sqrt(8.0);
double h0 = 1.26;
double sol0 = 0.5512855984325309;
////////// NEW INEQ
double taum_d1(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum(y1+h,y2,y3,y4,y5,y6)-taum(y1,y2,y3,y4,y5,y6))/h;
}
double taum_d2(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum(y1+h,y2,y3,y4,y5,y6)-2*taum(y1,y2,y3,y4,y5,y6) + taum(y1-h,y2,y3,y4,y5,y6))/(h*h);
}
// this is minimized. failure reported if min is negative.
void t1(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum_d1(y[0],y[1],y[2],y[3],y[4],y[5]) ;
*ret = r*r ;
}
Minimizer m1() {
double xmin[6]= {2,2,2,2.52,2.52,2};
double xmax[6]= {2.52,2.52,2.52,3.0,2.52,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t1;
return M;
}
//trialdata d1(m1(),"ID[DWXPIHA] ID[] d1: extreme-- FALSE!!. Gives C/E to y1-deformaton");
////////// NEW INEQ
////////// NEW INEQ
// d0
double gt0(double a,double b,double c,double e1,double e2,double e3) {
return( dih_y(2,2,2,a,b,c)*e1
+ dih2_y(2,2,2,a,b,c)*e2
+ dih3_y(2,2,2,a,b,c)*e3);
}
double gt1(double a,double b,double c,double e1,double e2,double e3) {
return( (-4*(Power(a,4)*e1 + 8*(Power(b,2) - Power(c,2))*(e2 - e3) -
Power(a,2)*(16*e1 + (-8 + Power(b,2))*e2 +
(-8 + Power(c,2))*e3)))/(a*(16-a*a)) );
}
double gt2(double a,double b,double c,double e1,double e2,double e3) {
double num = 8*(2*Power(a,10)*e1 - 256*Power(Power(b,2) - Power(c,2),3)*
(e2 - e3) - Power(a,6)*
(2*(-256 + Power(b,4) - 2*Power(b,2)*Power(c,2) +
Power(c,4))*e1 +
(Power(b,4)*(-8 + Power(c,2)) -
16*Power(b,2)*(3 + Power(c,2)) +
16*(16 + 9*Power(c,2)))*e2 +
(Power(b,2)*(144 - 16*Power(c,2) + Power(c,4)) -
8*(-32 + 6*Power(c,2) + Power(c,4)))*e3) +
Power(a,8)*(-64*e1 -
6*((-8 + Power(b,2))*e2 + (-8 + Power(c,2))*e3)) -
2*Power(a,4)*(Power(b,2) - Power(c,2))*
(Power(b,4)*e2 + 8*Power(c,2)*(4*e1 + 9*e2 - 7*e3) +
384*(e2 - e3) - Power(c,4)*e3 +
Power(b,2)*(-32*e1 + (56 - 9*Power(c,2))*e2 +
9*(-8 + Power(c,2))*e3)) +
16*Power(a,2)*(Power(b,2) - Power(c,2))*
(Power(b,4)*(e2 - 3*e3) -
4*Power(b,2)*(8*e1 + (-20 + 3*Power(c,2))*e2 -
3*(-4 + Power(c,2))*e3) +
Power(c,2)*(32*e1 + 3*(16 + Power(c,2))*e2 -
(80 + Power(c,2))*e3))) ;
double den = Power(a* (16 - a*a),2);
return( num/den);
}
//constraint delta>0, deriv2>0.
void deltaposlast(int numargs,int whichFn,double* y, double* ret,void*) {
double a = y[3]; double b = y[4]; double c= y[5];
double e1 = y[0]; double e2 = y[1]; double e3 = y[2];
double deriv = gt1(a,b,c,e1,e2,e3);
double deriv2 = gt2(a,b,c,e1,e2,e3);
double r= -deriv2;
if (whichFn==1) { r = -delta_y(2,2,2,y[3],y[4],y[5]); }
*ret = r;
}
// this is minimized. failure reported if min is negative.
void t0(int numargs,int whichFn,double* y, double* ret,void*) {
double a = y[3]; double b = y[4]; double c= y[5];
double e1 = y[0]; double e2 = y[1]; double e3 = y[2];
double deriv= gt1(a,b,c,e1,e2,e3);
double deriv2 = gt2(a,b,c,e1,e2,e3);
double r= deriv*deriv - 0.01*deriv2;
// 0.00001 -> 0.00129
// 0.0001 -> 0.01289
// 0.001 -> 0.1225
// 0.01 -> 0.89 // use this
// 0.1 -> -655.814.
*ret = r ;
}
Minimizer m0() {
double t = 1.0 + sol0/pi();
double xmin[6]= {1,1,1,2/h0,2/h0,2/h0};
double xmax[6]= {t,t,t,4,4,4};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t0;
return M;
}
trialdata d0(m0(),"ID[2065952723] d0: Lexell variant.");
double cc(double y1,double y2,double y,double a,double b) {
// Delta_y(y1,y2,y,a,b,cc)=0.
double x1 = y1*y1;
double x2 = y2*y2;
double x = y*y;
double aa = a*a;
double bb = b*b;
double ub = U(bb,x,x1);
double ua = U(aa,x,x2);
double dd = -aa*bb + aa*x + bb*x - x*x + aa*x1 + x*x1 + bb*x2 + x*x2 - x1*x2;
double c = (1.0/(2.0*x))*(dd + sqrt(ua*ub));
return sqrt(c);
}
double taum_e0(double y1,double y2,double y3,double y4,double y5,double y) {
double a = 2.0;
double b = 2.0;
double c = cc(y1,y2,y,a,b);
return taum(y1,y2,y3,y4,y5,c) + pi()*rho(y);
}
double taum_e1(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum_e0(y1,y2,y3,y4,y5,y6+h)-taum_e0(y1,y2,y3,y4,y5,y6))/h;
}
double taum_e2(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-4;
return (taum_e0(y1,y2,y3,y4,y5,y6+h)-2*taum_e0(y1,y2,y3,y4,y5,y6) + taum_e0(y1,y2,y3,y4,y5,y6-h))/(h*h);
}
void c2(int numargs,int whichFn,double* y, double* ret,void*) {
*ret = -taum_e2(y[0],y[1],y[2],y[3],y[4],y[5]);
}
// this is minimized. failure reported if min is negative.
void t2(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum_e1(y[0],y[1],y[2],y[3],y[4],y[5]) ;
double r2 = taum_e2(y[0],y[1],y[2],y[3],y[4],y[5]) ;
*ret = r*r ;
// 0.01 gives neg
//
}
Minimizer m2() {
double xmin[6]= {2,2,2,2,2,2};
double xmax[6]= {2.52,2.52,2.52,4.0,2.52,2.52};
Minimizer M(trialcount,6,1,xmin,xmax);
M.func = t2;
M.cFunc = c2;
return M;
}
//trialdata d2(m2(),"experiment ID[] ID[] d2: gives C/E to a particular deformation. Adjusting the height at a flat vertex.");
////////// NEW INEQ
double taum4_d1(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-8;
return (taum(y1,y2,y3,y4+h,y5,y6)-taum(y1,y2,y3,y4,y5,y6))/h;
}
double taum4_d2(double y1,double y2,double y3,double y4,double y5,double y6) {
double h = 1.0e-4;
return (taum(y1,y2,y3,y4+h,y5,y6)-2*taum(y1,y2,y3,y4,y5,y6) + taum(y1,y2,y3,y4-h,y5,y6))/(h*h);
}
void t11(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum4_d1(y[0],y[1],y[2],y[3],y[4],y[5])+taum4_d1(y[6],y[1],y[2],y[3],y[7],y[8]);
double s= taum4_d2(y[0],y[1],y[2],y[3],y[4],y[5])+taum4_d2(y[6],y[1],y[2],y[3],y[7],y[8]);
*ret = r*r - 0.01*s ;
}
void c11(int numargs,int whichFn,double* y, double* ret,void*) {
double s= taum4_d2(y[0],y[1],y[2],y[3],y[4],y[5])+taum4_d2(y[6],y[1],y[2],y[3],y[7],y[8]);
switch(whichFn) {
case 1: *ret = y[3]-crossdiag(y);
break;
case 2: *ret = dih3_y(y[0],y[1],y[2],y[3],y[4],y[5]) + dih_y(y[2],y[1],y[6],y[8],y[7],y[3]) - pi();
break;
case 3: *ret = - delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
case 4: *ret = - delta_y(y[2],y[1],y[6],y[8],y[7],y[3]);
break;
case 5: *ret = -s;
break;
default: *ret = -s;
break;
}
}
Minimizer m11() {
double xmin[9]= {2,2,2, 2.52,2,2.52, 2,2,2};
double xmax[9]= {2.52,2.52,2.52, 3.9,2.52,3.9, 2.52,2.52,2.52};//ok to 4.0
Minimizer M(trialcount,9,4,xmin,xmax);
M.func = t11;
M.cFunc = c11;
return M;
}
trialdata d11(m11(),"m11: ID[2986512815] cc:qua: two simplices common diagonal, no local minimum, (not full domain)");
/*
Minimizer M(trialcount*300,9,4,xmin,xmax);
constrained min: 0.0049666912319060166
variables: {2.02287626223235639, 2.52000000000000002, 2.5199999999994307, 2.86885817213602401, 2.00649572338011328, 2.58689726914902973, 2.00000000000637002, 2.00000000000699529, 2.00000000000699529}
*/
////////// NEW INEQ
void t12(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5]) + 1.0e-8;
*ret = r;
}
Minimizer m12() {
double xmin[6]= {2,2,2,2,2,2};
double xmax[6]= {2.52,2.52,2.52,2,2,2};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t12;
return M;
}
trialdata d12(m12(),"d12: ID[6147439478] Main Inequality Triangles [3,0]");
////////// NEW INEQ
void t13(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])-0.103;
*ret = r;
}
Minimizer m13() {
double xmin[6]= {2,2,2,2,2,2.52};
double xmax[6]= {2.52,2.52,2.52,2,2,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t13;
return M;
}
trialdata d13(m13(),"d13: ID[4760233334] Main Inequality Triangles [2,1]");
////////// NEW INEQ
void t14(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])-0.2759;
*ret = r;
}
Minimizer m14() {
double xmin[6]= {2,2,2,2,2.52,2.52};
double xmax[6]= {2.52,2.52,2.52,2,2.52,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t14;
return M;
}
trialdata d14(m14(),"d14: ID[4663664691] Main Inequality Triangles [1,2]");
////////// NEW INEQ
void t15(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])-0.4488;
*ret = r;
}
Minimizer m15() {
double xmin[6]= {2,2,2,2.52,2.52,2.52};
double xmax[6]= {2.52,2.52,2.52,2.52,2.52,2.52};
Minimizer M(trialcount,6,0,xmin,xmax);
M.func = t15;
return M;
}
trialdata d15(m15(),"d15: ID[9098044151] Main Inequality Triangles [0,3]");
////////// NEW INEQ
void t16(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.206;
*ret = r;
}
Minimizer m16() {
double xmin[9]= {2,2,2,2.52,2,2,2,2,2};
double xmax[9]= {2.52,2.52,2.52,sqrt(8.0),2,2,2.52,2,2};
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t16;
return M;
}
trialdata d16(m16(),"d16: ID[] Main Inequality Quad [4,0]");
////////// NEW INEQ
void t17(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.3789;
*ret = r;
}
Minimizer m17() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2,2};
double xmax[9]= {2.52,2.52,2.52,3.1,2.52,2,2.52,2,2}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t17;
return M;
}
trialdata d17(m17(),"d17: ID[] Main Inequality Quad [3,1]");
////////// NEW INEQ
void t18(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
Minimizer m18() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2.52,2};
double xmax[9]= {2.52,2.52,2.52,3.22,2.52,2,2.52,2.52,2}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t18;
return M;
}
trialdata d18(m18(),"d18: ID[] Main Inequality Quad [2,2]a");
////////// NEW INEQ
void t19(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
Minimizer m19() {
double xmin[9]= {2,2,2,2.52,2.52,2.52,2,2,2};
double xmax[9]= {2.52,2.52,2.52,3.2,2.52,2.52,2.52,2,2}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t19;
return M;
}
trialdata d19(m19(),"d19: ID[] Main Inequality Quad [2,2]b");
////////// NEW INEQ
void t20(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
Minimizer m20() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2,2.52};
double xmax[9]= {2.52,2.52,2.52,3.2,2.52,2,2.52,2,2.52}; // shorter diag.
Minimizer M(trialcount,9,0,xmin,xmax);
M.func = t20;
return M;
}
trialdata d20(m20(),"d20: ID[] Main Inequality Quad [2,2]c");
////////// NEW INEQ
void t21(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])+taum(y[6],y[1],y[2],y[3],y[7],y[8])-0.5518;
*ret = r;
}
void c21(int numargs,int whichFn,double* y, double* ret,void*) {
double r= -crossdiag(y) + y[3];
*ret = r;
}
Minimizer m21() {
double xmin[9]= {2,2,2,2.52,2.52,2,2,2,2.52};
double xmax[9]= {2.52,2.52,2.52,3.57,2.52,2.52,2.52,2.52,2.52}; // shorter diag.
Minimizer M(trialcount,9,1,xmin,xmax);
M.func = t21;
M.cFunc = c21;
return M;
}
trialdata d21(m21(),"d21: ID[] Main Inequality Quad [2,2]d");
////////// NEW INEQ
void t22(int numargs,int whichFn,double* y, double* ret,void*) {
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])
+taum(y[0],y[2],y[6],y[7],y[8],y[4])
+taum(y[0],y[6],y[9],y[10],y[11],y[8])
-0.4819;
*ret = r;
}
void c22(int numargs,int whichFn,double* y, double* ret,void*) {
double r = 0;
switch(whichFn) {
case 1: r = dih_y(y[0],y[1],y[2],y[3],y[4],y[5])
+dih_y(y[0],y[2],y[6],y[7],y[8],y[4])
+dih_y(y[0],y[6],y[9],y[10],y[11],y[8]) - dih_y(y[0],y[1],y[9],2.52,y[11],y[5]);
break;
case 2:
r = dih_y(y[2],y[0],y[1],y[5],y[3],y[4]) + dih_y(y[2],y[0],y[6],y[8],y[7],y[4])
- dih_y(y[2],y[1],y[6],2.52,y[7],y[3]);
break;
case 3:
r = dih_y(y[6],y[2],y[0],y[4],y[8],y[7])+dih_y(y[6],y[0],y[9],y[11],y[10],y[8])
- dih_y(y[6],y[2],y[9],2.52,y[10],y[7]);
break;
case 4:
r=delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
default:
r=delta_y(y[0],y[6],y[9],y[10],y[11],y[8]);
break;
}
*ret = -r;
}
Minimizer m22() {
double xmin[12]= {2,2,2, 2,2.52,2, 2,2,2.52, 2,2,2};
double xmax[12]= {2.52,2.52,2.52, 2,3,2, 2.52,2,3, 2.52,2,2};
Minimizer M(trialcount,12,5,xmin,xmax);
M.func = t22;
M.cFunc = c22;
return M;
}
trialdata d22(m22(),"d22: ID[] Main Inequality Pent [5,0] (not full domain)");
////////// NEW INEQ
void t23(int numargs,int whichFn,double* y, double* ret,void*) {
// these label vertices of triangulation of a pentagon.
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])
+taum(y[0],y[2],y[6],y[7],y[8],y[4])
+taum(y[0],y[6],y[9],y[10],y[11],y[8])
-0.6548;
*ret = r;
}
void c23(int numargs,int whichFn,double* y, double* ret,void*) {
double r = 0;
switch(whichFn) {
case 1: r = dih_y(y[0],y[1],y[2],y[3],y[4],y[5])
+dih_y(y[0],y[2],y[6],y[7],y[8],y[4])
+dih_y(y[0],y[6],y[9],y[10],y[11],y[8]) - dih_y(y[0],y[1],y[9],2.52,y[11],y[5]);
break;
case 2:
r = dih_y(y[2],y[0],y[1],y[5],y[3],y[4]) + dih_y(y[2],y[0],y[6],y[8],y[7],y[4])
- dih_y(y[2],y[1],y[6],2.52,y[7],y[3]);
break;
case 3:
r = dih_y(y[6],y[2],y[0],y[4],y[8],y[7])+dih_y(y[6],y[0],y[9],y[11],y[10],y[8])
- dih_y(y[6],y[2],y[9],2.52,y[10],y[7]);
break;
case 4:
r=delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
default:
r=delta_y(y[0],y[6],y[9],y[10],y[11],y[8]);
break;
}
*ret = -r;
}
Minimizer m23() {
double xmin[12]= {2,2,2, 2,2.52,2, 2,2.52,2.52, 2,2,2};
double xmax[12]= {2.52,2.52,2.52, 2.52,3,2.52, 2.52,2.52,3, 2.52,2.52,2.52};
Minimizer M(trialcount,12,5,xmin,xmax);
M.func = t23;
M.cFunc = c23;
return M;
}
trialdata d23(m23(),"d23: ID[] Main Inequality Pent [4,1] (not full domain)");
////////// NEW INEQ
void t24(int numargs,int whichFn,double* y, double* ret,void*) {
// these label vertices of triangulation of a hexagon.
double r= taum(y[0],y[1],y[2],y[3],y[4],y[5])
+taum(y[6],y[1],y[2],y[3],y[7],y[8])
+taum(y[9],y[0],y[2],y[4],y[11],y[10])
+taum(y[12],y[0],y[1],y[5],y[13],y[14])
-0.7578;
*ret = r;
}
void c24(int numargs,int whichFn,double* y, double* ret,void*) {
double r = 0;
switch(whichFn) {
case 1: r = dih_y(y[0],y[1],y[2],y[3],y[4],y[5])
+dih_y(y[0],y[12],y[1],y[13],y[5],y[14])
+dih_y(y[0],y[9],y[2],y[11],y[4],y[10])
- dih_y(y[0],y[9],y[12],2.52,y[14],y[10]);
break;
case 2:
r = dih_y(y[1],y[0],y[2],y[4],y[3],y[5])
+dih_y(y[1],y[0],y[12],y[14],y[13],y[5])
+dih_y(y[1],y[2],y[6],y[7],y[8],y[3])
- dih_y(y[1],y[12],y[6],2.52,y[8],y[13]);
break;
case 3:
r = dih_y(y[2],y[1],y[0],y[5],y[4],y[3])
+dih_y(y[2],y[6],y[1],y[8],y[3],y[7])
+dih_y(y[2],y[0],y[9],y[10],y[11],y[4])
- dih_y(y[2],y[9],y[6],2.52,y[7],y[11]);
break;
case 4:
r=delta_y(y[6],y[1],y[2],y[3],y[7],y[8]);
break;
case 5:
r=delta_y(y[9],y[0],y[2],y[4],y[11],y[10]);
break;
case 6:
r=delta_y(y[12],y[0],y[1],y[5],y[13],y[14]);
break;
case 7:
r = crossdiag(y) - y[3];
break;
case 8:
r = y[3]- y[4];
break;
case 9:
r = delta_y(y[0],y[1],y[2],y[3],y[4],y[5]);
break;
default: r = y[4]-y[5];
}
*ret = -r;
}
Minimizer m24() {
double xmin[15]= {2,2,2, 2.52,2.52,2.52, 2,2,2, 2,2,2, 2,2,2};
double xmax[15]= {2.52,2.52,2.52, 3.8,3.8,3.8, 2.52,2.52,2.52, 2.52,2.52,2.52, 2.52,2.52,2.52};
Minimizer M(trialcount,15,10,xmin,xmax);
M.func = t24;
M.cFunc = c24;
return M;
}
trialdata d24(m24(),"d24: ID[] Main Inequality Hex [6,0] (not full domain)");
int main()
{
// cout << dih_y (2.01,2.02,2.03,2.04,2.05,2.06);;
double y[9] = {2.01757248069328288, 2.00385313357932526, 2.05784751769748242,
2.66743320268093287, 2.02045376048810033, 3.7968261622461,
2.08361068848451136, 2.17839994782590241, 2.01394807769320305};
cout << dih3_y(y[0],y[1],y[2],y[3],y[4],y[5]) + dih_y(y[2],y[1],y[6],y[8],y[7],y[3]) - pi();
}
| 32.403285 | 199 | 0.545982 |
65b4ff162151685abad28b68ececdc12f4190c3b | 1,347 | hpp | C++ | stan/math/prim/fun/pow.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-06-14T14:33:37.000Z | 2020-06-14T14:33:37.000Z | stan/math/prim/fun/pow.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | null | null | null | stan/math/prim/fun/pow.hpp | bayesmix-dev/math | 3616f7195adc95ef8e719a2af845d61102bc9272 | [
"BSD-3-Clause"
] | 1 | 2020-05-10T12:55:07.000Z | 2020-05-10T12:55:07.000Z | #ifndef STAN_MATH_PRIM_FUN_POW_HPP
#define STAN_MATH_PRIM_FUN_POW_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/fun/constants.hpp>
#include <stan/math/prim/functor/apply_scalar_binary.hpp>
#include <cmath>
#include <complex>
namespace stan {
namespace math {
namespace internal {
/**
* Return the first argument raised to the power of the second
* argument. At least one of the arguments must be a complex number.
*
* @tparam U type of base
* @tparam V type of exponent
* @param[in] x base
* @param[in] y exponent
* @return base raised to the power of the exponent
*/
template <typename U, typename V>
inline complex_return_t<U, V> complex_pow(const U& x, const V& y) {
return exp(y * log(x));
}
} // namespace internal
/**
* Enables the vectorised application of the pow function, when
* the first and/or second arguments are containers.
*
* @tparam T1 type of first input
* @tparam T2 type of second input
* @param a First input
* @param b Second input
* @return pow function applied to the two inputs.
*/
template <typename T1, typename T2, require_any_container_t<T1, T2>* = nullptr>
inline auto pow(const T1& a, const T2& b) {
return apply_scalar_binary(a, b, [&](const auto& c, const auto& d) {
using std::pow;
return pow(c, d);
});
}
} // namespace math
} // namespace stan
#endif
| 26.411765 | 79 | 0.709725 |
65b6e02cc3a10b30145392598890c316458aa999 | 641 | cpp | C++ | Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | 20 | 2018-01-19T06:28:36.000Z | 2021-08-06T14:06:13.000Z | Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | null | null | null | Sunny-Core/01_FRAMEWORK/graphics/ModelManager.cpp | adunStudio/Sunny | 9f71c1816aa62bbc0d02d2f8d6414f4bf9aee7e7 | [
"Apache-2.0"
] | 3 | 2019-01-29T08:58:04.000Z | 2021-01-02T06:33:20.000Z | #include "ModelManager.h"
namespace sunny
{
namespace graphics
{
std::map<std::string, Model*> ModelManager::s_map;
Model* ModelManager::Add(const::std::string& name, Model* Model)
{
s_map[name] = Model;
return Model;
}
void ModelManager::Clean()
{
for (auto it = s_map.begin(); it != s_map.end(); ++it)
{
if (it->second)
{
delete it->second;
}
}
}
Model* ModelManager::Get(const std::string& name)
{
return s_map[name];
}
Mesh* ModelManager::GetMesh(const std::string& name)
{
if (s_map[name] == nullptr) return nullptr;
return s_map[name]->GetMesh();
}
}
} | 16.435897 | 66 | 0.599064 |
65c8012df9eabd09c01fa12e47b597f1c3679be8 | 3,453 | hxx | C++ | src/istream/Handler.hxx | CM4all/beng-proxy | ce5a81f7969bc5cb6c5985cdc98f61ef8b5c6159 | [
"BSD-2-Clause"
] | 35 | 2017-08-16T06:52:26.000Z | 2022-03-27T21:49:01.000Z | src/istream/Handler.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | 2 | 2017-12-22T15:34:23.000Z | 2022-03-08T04:15:23.000Z | src/istream/Handler.hxx | nn6n/beng-proxy | 2cf351da656de6fbace3048ee90a8a6a72f6165c | [
"BSD-2-Clause"
] | 8 | 2017-12-22T15:11:47.000Z | 2022-03-15T22:54:04.000Z | /*
* Copyright 2007-2021 CM4all GmbH
* All rights reserved.
*
* author: Max Kellermann <mk@cm4all.com>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* FOUNDATION 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.
*/
#pragma once
#include "Result.hxx"
#include "io/FdType.hxx"
#include "util/Compiler.h"
#include <exception>
#include <sys/types.h>
/** data sink for an istream */
class IstreamHandler {
public:
/**
* Data is available and the callee shall invoke
* Istream::FillBucketList() and Istream::ConsumeBucketList().
*
* This is the successor to OnData() and OnDirect(). Once
* everything has been migrated to #IstreamBucketList, these
* methods can be removed.
*
* @return true if the caller shall invoke OnData() or OnDirect(),
* false if data has already been handled or if the #Istream has
* been closed
*/
virtual bool OnIstreamReady() noexcept {
return true;
}
/**
* Data is available as a buffer.
* This function must return 0 if it has closed the stream.
*
* @param data the buffer
* @param length the number of bytes available in the buffer, greater than 0
* @return the number of bytes consumed, 0 if writing would block
* (caller is responsible for registering an event) or if the
* stream has been closed
*/
virtual size_t OnData(const void *data, size_t length) noexcept = 0;
/**
* Data is available in a file descriptor.
* This function must return 0 if it has closed the stream.
*
* @param type what kind of file descriptor?
* @param fd the file descriptor
* @param max_length don't read more than this number of bytes
* @return the number of bytes consumed, or one of the
* #istream_result values
*/
virtual ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) noexcept {
gcc_unreachable();
}
/**
* End of file encountered.
*/
virtual void OnEof() noexcept = 0;
/**
* The istream has ended unexpectedly, e.g. an I/O error.
*
* The method Istream::Close() will not result in a call to
* this callback, since the caller is assumed to be the
* istream handler.
*
* @param error an exception describing the error condition
*/
virtual void OnError(std::exception_ptr error) noexcept = 0;
};
| 32.885714 | 77 | 0.726615 |
65c87d7b4a07e75b0d89fbd8d6e9c91e2fc6b6b7 | 1,405 | cpp | C++ | CloudDisk_Client/httpresponse.cpp | G-Club/c-cpp | e89f8efae357fc8349d0d66f1aef703a6a287bef | [
"Apache-2.0"
] | null | null | null | CloudDisk_Client/httpresponse.cpp | G-Club/c-cpp | e89f8efae357fc8349d0d66f1aef703a6a287bef | [
"Apache-2.0"
] | 1 | 2017-02-07T00:49:21.000Z | 2017-02-16T00:55:28.000Z | CloudDisk_Client/httpresponse.cpp | G-Club/c-cpp | e89f8efae357fc8349d0d66f1aef703a6a287bef | [
"Apache-2.0"
] | null | null | null | #include "httpresponse.h"
HttpResponse::HttpResponse()
{
}
HttpResponse HttpResponse::FromByteArray(QByteArray &format)
{
/*
HTTP/1.1 200 OK\r\nServer: nginx/1.10.1\r\nDate: Sat, 29 Jul 2017 00:41:44 GMT\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\nConnection: keep-alive\r\n\r\n27\r\n{\"status\":201,\"error\":201,\"msg\":\"succ\"}\r\n0\r\n\r\n
*/
QString string(format),respline,data;
HttpResponse resp;
int index=-1,status;
index=string.indexOf("\r\n");
if(index<0)
{
return resp;
}
respline=string.left(index);
status=respline.split(' ').at(1).toInt();
index=string.indexOf("\r\n\r\n");
if(index<0)
{
return resp;
}
data=string.right(string.length()-index-4);
index=data.indexOf("\r\n");
data=data.right(data.length()-index-2);
index=data.indexOf("\r\n");
data=data.left(index);
resp.setData(data);
resp.setRespline(respline);
resp.setStatus(status);
return resp;
}
QString HttpResponse::getData() const
{
return data;
}
void HttpResponse::setData(const QString &value)
{
data = value;
}
QString HttpResponse::getRespline() const
{
return respline;
}
void HttpResponse::setRespline(const QString &value)
{
respline = value;
}
int HttpResponse::getStatus() const
{
return status;
}
void HttpResponse::setStatus(int value)
{
status = value;
}
| 19.513889 | 235 | 0.648399 |
65c917836d9576fc136a7db14443d06dd5eb9319 | 478 | cpp | C++ | Backdoor.Win32.C.a/ifmirc.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | 2 | 2021-02-04T06:47:45.000Z | 2021-07-28T10:02:10.000Z | Backdoor.Win32.C.a/ifmirc.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | Backdoor.Win32.C.a/ifmirc.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | #include "Include.h"
#include "Hell.h"
BOOL mirccmd(char *cmd)
{
HWND mwnd = FindWindow("mIRC",NULL);
if (mwnd) {
HANDLE hFileMap = CreateFileMapping(INVALID_HANDLE_VALUE,0,PAGE_READWRITE,0,4096,"mIRC");
LPSTR mData = (LPSTR)MapViewOfFile(hFileMap,FILE_MAP_ALL_ACCESS,0,0,0);
sprintf(mData, cmd);
SendMessage(mwnd,WM_USER + 200,1,0);
SendMessage(mwnd,WM_USER + 201,1,0);
UnmapViewOfFile(mData);
CloseHandle(hFileMap);
return TRUE;
} else
return FALSE;
} | 25.157895 | 91 | 0.717573 |
65ca00f755a60e996fd58344181d3d3ed0424b23 | 5,916 | cpp | C++ | meeting-qt/setup/src/dui/Core/Placeholder.cpp | GrowthEase/- | 5cc7cab95fc309049de8023ff618219dff22d773 | [
"MIT"
] | 48 | 2022-03-02T07:15:08.000Z | 2022-03-31T08:37:33.000Z | meeting-qt/setup/src/dui/Core/Placeholder.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 1 | 2022-02-16T01:54:05.000Z | 2022-02-16T01:54:05.000Z | meeting-qt/setup/src/dui/Core/Placeholder.cpp | chandarlee/Meeting | 9350fdea97eb2cdda28b8bffd9c4199de15460d9 | [
"MIT"
] | 9 | 2022-03-01T13:41:37.000Z | 2022-03-10T06:05:23.000Z | /**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
#include "StdAfx.h"
namespace ui
{
PlaceHolder::PlaceHolder()
{
}
PlaceHolder::~PlaceHolder()
{
}
std::wstring PlaceHolder::GetName() const
{
return m_sName;
}
std::string PlaceHolder::GetUTF8Name() const
{
int multiLength = WideCharToMultiByte(CP_UTF8, NULL, m_sName.c_str(), -1, NULL, 0, NULL, NULL);
if (multiLength <= 0)
return "";
std::unique_ptr<char[]> strName(new char[multiLength]);
WideCharToMultiByte(CP_UTF8, NULL, m_sName.c_str(), -1, strName.get(), multiLength, NULL, NULL);
std::string res = strName.get();
return res;
}
void PlaceHolder::SetName(const std::wstring& pstrName)
{
m_sName = pstrName;
}
void PlaceHolder::SetUTF8Name(const std::string& pstrName)
{
int wideLength = MultiByteToWideChar(CP_UTF8, NULL, pstrName.c_str(), -1, NULL, 0);
if (wideLength <= 0)
{
m_sName = _T("");
return;
}
std::unique_ptr<wchar_t[]> strName(new wchar_t[wideLength]);
MultiByteToWideChar(CP_UTF8, NULL, pstrName.c_str(), -1, strName.get(), wideLength);
m_sName = strName.get();
}
Window* PlaceHolder::GetWindow() const
{
return m_pWindow;
}
void PlaceHolder::SetWindow(Window* pManager, Box* pParent, bool bInit)
{
m_pWindow = pManager;
m_pParent = pParent;
if (bInit && m_pParent) Init();
}
void PlaceHolder::SetWindow(Window* pManager)
{
m_pWindow = pManager;
}
void PlaceHolder::Init()
{
DoInit();
}
void PlaceHolder::DoInit()
{
}
CSize PlaceHolder::EstimateSize(CSize szAvailable)
{
return m_cxyFixed;
}
bool PlaceHolder::IsVisible() const
{
return m_bVisible && m_bInternVisible;
}
bool PlaceHolder::IsFloat() const
{
return m_bFloat;
}
void PlaceHolder::SetFloat(bool bFloat)
{
if (m_bFloat == bFloat) return;
m_bFloat = bFloat;
ArrangeAncestor();
}
int PlaceHolder::GetFixedWidth() const
{
return m_cxyFixed.cx;
}
void PlaceHolder::SetFixedWidth(int cx, bool arrange)
{
if (cx < 0 && cx != DUI_LENGTH_STRETCH && cx != DUI_LENGTH_AUTO) {
ASSERT(FALSE);
return;
}
if (m_cxyFixed.cx != cx)
{
m_cxyFixed.cx = cx;
if (arrange) {
ArrangeAncestor();
}
else {
m_bReEstimateSize = true;
}
}
//if( !m_bFloat ) ArrangeAncestor();
//else Arrange();
}
int PlaceHolder::GetFixedHeight() const
{
return m_cxyFixed.cy;
}
void PlaceHolder::SetFixedHeight(int cy)
{
if (cy < 0 && cy != DUI_LENGTH_STRETCH && cy != DUI_LENGTH_AUTO) {
ASSERT(FALSE);
return;
}
if (m_cxyFixed.cy != cy)
{
m_cxyFixed.cy = cy;
ArrangeAncestor();
}
//if( !m_bFloat ) ArrangeAncestor();
//else Arrange();
}
int PlaceHolder::GetMinWidth() const
{
return m_cxyMin.cx;
}
void PlaceHolder::SetMinWidth(int cx)
{
if (m_cxyMin.cx == cx) return;
if (cx < 0) return;
m_cxyMin.cx = cx;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMaxWidth() const
{
return m_cxyMax.cx;
}
void PlaceHolder::SetMaxWidth(int cx)
{
if (m_cxyMax.cx == cx) return;
m_cxyMax.cx = cx;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMinHeight() const
{
return m_cxyMin.cy;
}
void PlaceHolder::SetMinHeight(int cy)
{
if (m_cxyMin.cy == cy) return;
if (cy < 0) return;
m_cxyMin.cy = cy;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetMaxHeight() const
{
return m_cxyMax.cy;
}
void PlaceHolder::SetMaxHeight(int cy)
{
if (m_cxyMax.cy == cy) return;
m_cxyMax.cy = cy;
if (!m_bFloat) ArrangeAncestor();
else Arrange();
}
int PlaceHolder::GetWidth() const
{
return m_rcItem.right - m_rcItem.left;
}
int PlaceHolder::GetHeight() const
{
return m_rcItem.bottom - m_rcItem.top;
}
UiRect PlaceHolder::GetPos(bool bContainShadow) const
{
return m_rcItem;
}
void PlaceHolder::SetPos(UiRect rc)
{
m_rcItem = rc;
}
void PlaceHolder::Arrange()
{
if (GetFixedWidth() == DUI_LENGTH_AUTO || GetFixedHeight() == DUI_LENGTH_AUTO)
{
ArrangeAncestor();
}
else
{
ArrangeSelf();
}
}
void PlaceHolder::ArrangeAncestor()
{
m_bReEstimateSize = true;
if (!m_pWindow || !m_pWindow->GetRoot())
{
if (GetParent()) {
GetParent()->ArrangeSelf();
}
else {
ArrangeSelf();
}
}
else
{
Control* parent = GetParent();
while (parent && (parent->GetFixedWidth() == DUI_LENGTH_AUTO || parent->GetFixedHeight() == DUI_LENGTH_AUTO))
{
parent->SetReEstimateSize(true);
parent = parent->GetParent();
}
if (parent)
{
parent->ArrangeSelf();
}
else //่ฏดๆrootๅ
ทๆAutoAdjustSizeๅฑๆง
{
m_pWindow->GetRoot()->ArrangeSelf();
}
}
}
void PlaceHolder::ArrangeSelf()
{
if (!IsVisible()) return;
m_bReEstimateSize = true;
m_bIsArranged = true;
Invalidate();
if (m_pWindow != NULL) m_pWindow->SetArrange(true);
}
void PlaceHolder::Invalidate() const
{
if (!IsVisible()) return;
UiRect invalidateRc = GetPosWithScrollOffset();
if (m_pWindow != NULL) m_pWindow->Invalidate(invalidateRc);
}
UiRect PlaceHolder::GetPosWithScrollOffset() const
{
UiRect pos = GetPos();
pos.Offset(-GetScrollOffset().x, -GetScrollOffset().y);
return pos;
}
CPoint PlaceHolder::GetScrollOffset() const
{
CPoint scrollPos;
Control* parent = GetParent();
ListBox* lbParent = dynamic_cast<ListBox*>(parent);
if (lbParent && lbParent->IsVScrollBarValid() && IsFloat()) {
return scrollPos;
}
while (parent && (!dynamic_cast<ListBox*>(parent) || !dynamic_cast<ListBox*>(parent)->IsVScrollBarValid()))
{
parent = parent->GetParent();
}
if (parent) { //่ฏดๆๆงไปถๅจListboxๅ
้จ
ListBox* listbox = (ListBox*)parent;
scrollPos.x = listbox->GetScrollPos().cx;
scrollPos.y = listbox->GetScrollPos().cy;
}
return scrollPos;
}
bool PlaceHolder::IsArranged() const
{
return m_bIsArranged;
}
bool IsChild(PlaceHolder* pAncestor, PlaceHolder* pControl)
{
while (pControl && pControl != pAncestor)
{
pControl = pControl->GetParent();
}
return pControl != nullptr;
}
} | 17.298246 | 111 | 0.686782 |
65cac9339ad22493786ffac70178bd54c71a106a | 5,177 | cpp | C++ | test/test_symbol_normalizer.cpp | atlimited/resembla | 82293cecfccfca6e2a95688b21f0659ba75e8cae | [
"Apache-2.0"
] | 65 | 2017-07-24T12:59:05.000Z | 2021-09-29T03:08:57.000Z | test/test_symbol_normalizer.cpp | atlimited/resembla | 82293cecfccfca6e2a95688b21f0659ba75e8cae | [
"Apache-2.0"
] | 3 | 2017-07-26T03:25:28.000Z | 2019-01-26T15:08:53.000Z | test/test_symbol_normalizer.cpp | tuem/resembla | ff39ac1b6904fc018bb691d77ca468772600f731 | [
"Apache-2.0"
] | 6 | 2017-09-25T10:39:17.000Z | 2019-12-24T09:45:24.000Z | /*
Resembla
https://github.com/tuem/resembla
Copyright 2017 Takashi Uemura
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 <string>
#include <iostream>
#include "Catch/catch.hpp"
#include "string_util.hpp"
#include "symbol_normalizer.hpp"
using namespace resembla;
void test_symbol_normalizer_noramlize_symbol(const std::wstring& input, const std::wstring& correct, bool to_lower = false)
{
init_locale();
SymbolNormalizer normalize("../misc/icu/normalization/", "resembla", "nfkc", to_lower);
auto answer = normalize(input);
#ifdef DEBUG
std::wcerr << "input : \"" << input << L"\"" << std::endl;
std::wcerr << "answer : \"" << answer << L"\"" << std::endl;
std::wcerr << "correct: \"" << correct << L"\"" << std::endl;
std::cerr << "dump input : ";
for(auto c: input){
std::cerr << std::hex << (int)c << " ";
}
std::cerr << std::endl;
std::cerr << "dump answer : ";
for(auto c: answer){
std::cerr << std::hex << (int)c << " ";
}
std::cerr << std::endl;
std::cerr << "dump correct: ";
for(auto c: correct){
std::cerr << std::hex << (int)c << " ";
}
std::cerr << std::endl;
#endif
CHECK(answer == correct);
}
TEST_CASE( "empty symbol normalizer", "[language]" ) {
std::string input = "๏ผจ๏ฝ
LLoใ๏ผ ๏ผ๏ผ
!๏ผ๏ผ๏ผ!";
SymbolNormalizer normalize_nothing("", "", "", false);
CHECK(normalize_nothing(input) == "๏ผจ๏ฝ
LLoใ๏ผ ๏ผ๏ผ
!๏ผ๏ผ๏ผ!");
SymbolNormalizer normalize_case("", "", "", true);
CHECK(normalize_case(input) == "๏ฝ๏ฝ
lloใ๏ผ ๏ผ๏ผ
!๏ผ๏ผ๏ผ!");
}
TEST_CASE( "normalize symbols", "[language]" ) {
test_symbol_normalizer_noramlize_symbol(L"", L"");
test_symbol_normalizer_noramlize_symbol(L"ใในใ", L"ใในใ");
test_symbol_normalizer_noramlize_symbol(L"๏ฝฑ๏ฝถ๏ฝป๏พ๏พ
", L"ใขใซใตใฟใ");
test_symbol_normalizer_noramlize_symbol(L"TEST", L"TEST");
test_symbol_normalizer_noramlize_symbol(L"test", L"test");
test_symbol_normalizer_noramlize_symbol(L"๏ผก๏ผข๏ผฃ๏ผค๏ผฅ", L"ABCDE");
test_symbol_normalizer_noramlize_symbol(L"๏ฝฑ๏พ๏พ๏ฝถ๏พ๏พ", L"ใขใใซใ");
test_symbol_normalizer_noramlize_symbol(L"ใ๏พ๏พใใ", L"ใใใใ");
// double quote
test_symbol_normalizer_noramlize_symbol(L"\u0022\u201c\u201d", L"\u0022\u0022\u0022");
// single quote
test_symbol_normalizer_noramlize_symbol(L"\u0027\u2018\u2019", L"\u0027\u0027\u0027");
// space
test_symbol_normalizer_noramlize_symbol(L"\u0020\u200A\uFEFF\u000D\u000A", L"\u0020\u0020\u0020\u0020\u0020");
// hyphen
test_symbol_normalizer_noramlize_symbol(L"\u002D\u00AD\u02D7\u058A\u2010\u2011\u2012\u2013\u2043\u207B\u208B\u2212", L"\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D\u002D");
// macron
test_symbol_normalizer_noramlize_symbol(L"\u30FC\u2014\u2015\u2500\u2501\uFE63\uFF0D\uFF70", L"\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC\u30FC");
// tilde
test_symbol_normalizer_noramlize_symbol(L"\u007E\u301C\uFF5E\u02DC\u1FC0\u2053\u223C\u223F\u3030", L"\u007E\u007E\u007E\u007E\u007E\u007E\u007E\u007E\u007E");
// yen sign
test_symbol_normalizer_noramlize_symbol(L"\u00A5\u005C\uFFE5", L"\u00A5\u00A5\u00A5");
test_symbol_normalizer_noramlize_symbol(L"0123456789", L"0123456789");
test_symbol_normalizer_noramlize_symbol(L"๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ", L"0123456789");
test_symbol_normalizer_noramlize_symbol(L"ABCDEFGHIJKLMNOPQRSTUVWXYZ", L"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
test_symbol_normalizer_noramlize_symbol(L"๏ผก๏ผข๏ผฃ๏ผค๏ผฅ๏ผฆ๏ผง๏ผจ๏ผฉ๏ผช๏ผซ๏ผฌ๏ผญ๏ผฎ๏ผฏ๏ผฐ๏ผฑ๏ผฒ๏ผณ๏ผด๏ผต๏ผถ๏ผท๏ผธ๏ผน๏ผบ", L"ABCDEFGHIJKLMNOPQRSTUVWXYZ");
test_symbol_normalizer_noramlize_symbol(L"abcdefghijklmnopqrstuvwxyz", L"abcdefghijklmnopqrstuvwxyz");
test_symbol_normalizer_noramlize_symbol(L"๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ
๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ๏ฝ", L"abcdefghijklmnopqrstuvwxyz");
test_symbol_normalizer_noramlize_symbol(L"!\"#$%&'()*+,-./:;<>?@[\\]^_`{|}", L"!\"#$%&'()*+,-./:;<>?@[ยฅ]^_`{|}");
test_symbol_normalizer_noramlize_symbol(L"๏ผโโ๏ผ๏ผ๏ผ
๏ผโโ๏ผ๏ผ๏ผ๏ผ๏ผโ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ ๏ผปยฅ๏ฟฅ๏ผฝ๏ผพ๏ผฟ๏ฝ๏ฝ๏ฝ๏ฝ", L"!\"\"#$%&''()*+,-./:;<>?@[ยฅยฅ]^_`{|}");
test_symbol_normalizer_noramlize_symbol(L"=ใใใปใใ", L"=ใใใปใใ");
test_symbol_normalizer_noramlize_symbol(L"๏ผ๏ฝก๏ฝค๏ฝฅ๏ฝข๏ฝฃ", L"=ใใใปใใ");
test_symbol_normalizer_noramlize_symbol(L"ใในใ!", L"ใในใ!");
test_symbol_normalizer_noramlize_symbol(L"ใในใ๏ผ", L"ใในใ!");
test_symbol_normalizer_noramlize_symbol(L"ใในใ?", L"ใในใ?");
test_symbol_normalizer_noramlize_symbol(L"ใในใ๏ผ", L"ใในใ?");
test_symbol_normalizer_noramlize_symbol(L"ใในใใงใ๏ผ", L"ใในใใงใ.");
test_symbol_normalizer_noramlize_symbol(L"ใใใซใกใฏใใในใใงใ", L"ใใใซใกใฏใใในใใงใ");
test_symbol_normalizer_noramlize_symbol(L"Hello, thisใis aใtest.", L"Hello, this is a test.");
test_symbol_normalizer_noramlize_symbol(L"Apple, APPLE, apple and ๏ผก๏ผฐ๏ผฐ๏ผฌ๏ผฅ", L"apple, apple, apple and apple", true);
}
| 42.089431 | 198 | 0.696156 |
65cc3b176f8ee372a5ec0242581be5d84ffe7496 | 12,616 | cpp | C++ | IPC_communication/nmsgpack.cpp | ehrenmann1977/Tutorials_Qt_QML | 591161f584acc75390075fdfdecb8f00fafc5050 | [
"BSD-3-Clause"
] | null | null | null | IPC_communication/nmsgpack.cpp | ehrenmann1977/Tutorials_Qt_QML | 591161f584acc75390075fdfdecb8f00fafc5050 | [
"BSD-3-Clause"
] | null | null | null | IPC_communication/nmsgpack.cpp | ehrenmann1977/Tutorials_Qt_QML | 591161f584acc75390075fdfdecb8f00fafc5050 | [
"BSD-3-Clause"
] | null | null | null | #include "nmsgpack.h"
/* class creation
* designed for sender-receiver mode, communication between 2 apps on same pc
* for other polling modes read nanomsg documentation
* std::string localurl (default): tcp://127.0.0.1:5000
* bool nodemode: Sender mode (default) => flase, Receiver mode => true
*
*/
nmsgpack::nmsgpack(QObject *parent, bool nodemode, std::string localurl) : QObject(parent)
{
const char* url=localurl.c_str();
socket=nm_init_socket(url,nodemode); // initialize the socket
}
/* fillDataBuffer
* this is to fill the databuffer and to compress (packe) it into a local msgpack buffer
* that is used when sending data out. This msgpack buffer can be send with nm_send(sock,sbuf)
*/
void nmsgpack::fillDataBuffer(uint64_t element1, bool element2, std::string element3)
{
DataPatern dp;
dp.element1=element1;
dp.element2=element2;
dp.element3=element3;
size_t buflen=0;
dataBuffer = prepare_buffer(dp, buflen);
}
/* sendBuffer
* this is the method that sends the buffer out
*/
int nmsgpack::sendBuffer(void)
{
int r=nm_send(socket, dataBuffer);
return r;
}
/* reciveBuffer
* this is the buffer receiving method
* it prints the data within unpacking
*/
DataPatern nmsgpack::receiveBuffer(void)
{
msgpack_object depacked;
DataPatern dp; //final data
dp = nm_recv(socket, depacked);
if (depacked.type == MSGPACK_OBJECT_ARRAY){
printf("number of elements = %d \n", depacked.via.array.size); //3
printf("element 1 = %llu \n", dp.element1);
printf("element 2 = %d \n", dp.element2); //element 2 correct -> false
printf("element 3 = %s \n", dp.element3.c_str()); //element 3 correct -> example
}
return dp;
}
/* destroyBuffer
* this function must be called at the end
*/
void nmsgpack::destroyBuffer(void)
{
msgpack_sbuffer_destroy(&dataBuffer);
}
/* Local Functions ********************************/
/* -----------------------------------------------*/
// function to convert decimal to hexadecimal
void nmsgpack::decToHexa(int n, char *hexa)
{
// char array to store hexadecimal number
//char hexaDeciNum[100];
// counter for hexadecimal number array
int i = 0;
while(n!=0)
{
// temporary variable to store remainder
int temp = 0;
// storing remainder in temp variable.
temp = n % 16;
// check if temp < 10
if(temp < 10)
{
hexa[i] = temp + 48;
i++;
}
else
{
hexa[i] = temp + 55;
i++;
}
n = n/16;
}
// printing hexadecimal number array in reverse order
for(int j=i-1; j>=0; j--)
std::cout << hexa[j];
}
// Function to convert hexadecimal to decimal
int nmsgpack::hexaToDecimal(unsigned char hexVal[], int len)
{
// Initializing base value to 1, i.e 16^0
int base = 1;
int dec_val = 0;
// Extracting characters as digits from last character
for (int i=len-1; i>=0; i--)
{
// if character lies in '0'-'9', converting
// it to integral 0-9 by subtracting 48 from
// ASCII value.
if (hexVal[i]>='0' && hexVal[i]<='9')
{
dec_val += (hexVal[i] - 48)*base;
// incrementing base by power
base = base * 16;
}
// if character lies in 'A'-'F' , converting
// it to integral 10 - 15 by subtracting 55
// from ASCII value
else if (hexVal[i]>='A' && hexVal[i]<='F')
{
dec_val += (hexVal[i] - 55)*base;
// incrementing base by power
base = base*16;
}
}
return dec_val;
}
/* print: This function prints hex values starting at point buf,
* with length of len. It is used intensively in testing.
*/
void nmsgpack::print(const char *buf, unsigned int len)
{
size_t i = 0;
for(; i < len ; ++i)
printf("%02x ", 0xff & buf[i]);
printf("\n");
}
/* prints nanomsg fatal error
*/
void nmsgpack::fatal(const char *func)
{
fprintf(stderr, "%s: %s\n", func, nn_strerror(nn_errno()));
exit(1);
}
/* this function takes a msgpack buffer and serializes it
* input: msgpack buffer, length of the array
* output: serializedbuffer: pointer to first element in the membuf array
* after being serialized
* note: length of the array may be used to find pointer starting for additional elements in future
* supressed the warning for now, but len may be useful in future
*/
void nmsgpack::serialize(msgpack_sbuffer buf, char *serializedbuffer, uint len)
{
char *data;
data=buf.data;
size_t alloc=buf.alloc;
size_t size=buf.size;
memcpy (serializedbuffer,&alloc,sizeof(size_t)); //take first element which is integer (see DataPatern struct)
memcpy (&serializedbuffer[0]+sizeof(size_t),data,size); //take 2nd element which is boolean by its pointer
memcpy (&serializedbuffer[0]+sizeof(size_t)+size,&size,sizeof(size_t)); //take 3rd element which is string by its starting pointer
Q_UNUSED(len);
}
/* prepare_buffer prepares the msgpack buffer from given datapatern structure for send purposes
* input: DataPatern structure (see above)
* output: msgpack_packer buffer
* buflen: bufferlength
*/
msgpack_sbuffer nmsgpack::prepare_buffer(DataPatern dp, size_t &buflen)
{
//prepare the packaged msgpack structure
msgpack_sbuffer sbuf;
msgpack_packer pk;
/* msgpack::sbuffer is a simple buffer implementation. */
msgpack_sbuffer_init(&sbuf);
//---------------------------------- Used in Example --------------
/* serialize values into the buffer using msgpack_sbuffer_write callback function. */
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
msgpack_pack_array(&pk, 3); //adjust number of elements in a package
msgpack_pack_int(&pk, dp.element1); //first element is int with value 1
if(dp.element2)
{
msgpack_pack_true(&pk); //second element is boolean with value true
}
else {
msgpack_pack_false(&pk); //second element is boolean with value true
}
//prepare the string count
size_t c=dp.element3.length(); // 7
const char* element3pt=dp.element3.c_str();
msgpack_pack_str(&pk, c); //third element is a string with 7 characters
msgpack_pack_str_body(&pk, element3pt, c); //fill the element string
//-----------------------------------------------------------------
/* serialize values into the buffer using msgpack_sbuffer_write callback function. */
TelegramPatern dp1;
msgpack_packer_init(&pk, &sbuf, msgpack_sbuffer_write);
msgpack_pack_array(&pk, 7); //adjust number of elements in a package
msgpack_pack_char(&pk,0x02); //STX: 1 Byte
msgpack_pack_str(&pk,2); //NA : 2 Byte
msgpack_pack_str_body(&pk,&dp1.NA[0],2);
msgpack_pack_str(&pk,4); //Auftrag: 4 Byte
msgpack_pack_str_body(&pk,&dp1.Auftrag[0],4);
msgpack_pack_str(&pk,4); //data length
msgpack_pack_str_body(&pk,&dp1.Fieldlen[0],4);
//convert hex to decimal to know the length of the adress
int dataln=hexaToDecimal(dp1.Fieldlen,4);
char * dd = (char *) malloc(dataln);
// prtint this message to be sure
print(sbuf.data, static_cast<uint>(sbuf.size));
buflen=sbuf.size+2*(sizeof(size_t));//2* because of alloc and size
return sbuf;
}
/* deserialize: this funciton deserializes (converts data from nanomsg to msgpack format) data
* input: *buf: received buffer from nano msg
* datalen: this is length of data in the package received from nanomsg
* output: rbuf: byref filled msgpack buffer
*/
void nmsgpack::deserialize(char *buf, msgpack_sbuffer &rbuf, size_t datalen)
{
//deserialize the data back from nanomsg to the msgpack structure
//first paramater that filled was alloc, then data, then size
size_t tmp;
memcpy(&tmp,buf,sizeof(size_t)); //copy the size first
rbuf.size=tmp;
//char data[rbuf.size]; //to supress variable size of array
char *data = static_cast<char *>(malloc(rbuf.size));
memcpy(&data[0],buf+sizeof(rbuf.size),static_cast<size_t>(datalen)); //copy the data second
//printf("filled data \n");
//print(&data[0],rbuf.size);
rbuf.data=&data[0];
memcpy(&tmp,buf+sizeof(size_t)+rbuf.size,sizeof(size_t)); //copy the alloc last
rbuf.alloc=tmp;
//end deserialization
}
/* unpacking: this function unpacks data given in a msgpack structure into
* msgpack_object that holds the elements. Aditionally it stores them
* into a local structure representing transmission data pattern */
void nmsgpack::unpacking(msgpack_sbuffer rbuf, msgpack_object &depacked, DataPatern &dp)
{
/* deserialize the buffer into msgpack_object instance. */
msgpack_zone mempool;
/* deserialized object is valid during the msgpack_zone instance alive. */
msgpack_zone_init(&mempool, 2048);
msgpack_unpack(rbuf.data, rbuf.size, nullptr, &mempool, &depacked);
/* print the deserialized object. */
msgpack_object_print(stdout, depacked);
puts(""); //we have object array in the struct
if (depacked.type == MSGPACK_OBJECT_ARRAY){
// printf("number of elements = %d \n", depacked.via.array.size); //3
uint64_t element1= depacked.via.array.ptr[0].via.u64;
// printf("element 1 = %llu \n", element1);
dp.element1=element1;
bool element2 = depacked.via.array.ptr[1].via.boolean;
// printf("element 2 = %d \n", element2); //element 2 correct -> false
dp.element2 = element2;
msgpack_object_str element3 = depacked.via.array.ptr[2].via.str;
// print(element3.ptr,element3.size); //element 3 correct -> example
std::string e3(element3.size,'0');
memcpy(&e3[0], element3.ptr, element3.size);
dp.element3 = e3;
}
msgpack_zone_destroy(&mempool);
}
/* nm_send: This function takes a msgpack_packer bufer that holds data should be send
* but in msgpack format. It then serializes the data into a serial buffer
* and sends it out through nanomsg
* input: socket: integer representing socket number
* msgpack_sbuffer sbuf: buffer holding exchange data pattern
* output: int r: number of packets being sent
*/
int nmsgpack::nm_send(int socket, msgpack_sbuffer sbuf)
{
//serialize data and deliver to nanomsg
//use serialize function
unsigned int len=uint(sbuf.size+2*(sizeof(size_t)));//2* because of alloc and size
//char membuf[len]; //supress variable length array
char *membuf = static_cast<char *>(malloc(len));
serialize(sbuf,&membuf[0],len);
print(membuf,len);
int r=nn_send(socket, &membuf[0], len, 0);
return r;
}
/* nm_recv: This function is the package interface, it uses the above code
* to receive data from nanomsg and convert it into msgpack_object;
* input: socket value
* output: msgpack_object: by reference incase there is a need to access object data
* datapattern : original sent data structure
*/
DataPatern nmsgpack::nm_recv(int sock, msgpack_object &depacked)
{
//initialize msgpack reception object
DataPatern dp;
//receive data from nanomsg
char *buf = nullptr;
int msglen = nn_recv(sock, &buf, NN_MSG, 0); //nanomessage length
//print(buf,msglen);
//deserialize the data back from nanomsg to the msgpack structure
msgpack_sbuffer rbuf;
if (msglen>0)
{
deserialize(buf,rbuf, static_cast<size_t>(msglen));
unpacking(rbuf,depacked,dp);
}
return dp;
}
/* nm_init_socket: This function initializes the nanomsg socket
* and returns the socket number.
* input: url: nanomsg binding url ex tcp://127.0.0.1:5000
* mode: 0 or false= Node0: Main node, it binds to the address
* 1 or true = Node1: Auxiliary node, it connects to the address
* ourput: socket value
*
*/
int nmsgpack::nm_init_socket(const char *url, bool recv_mode)
{
int sock;
if ((sock = nn_socket(AF_SP, NN_PAIR)) < 0) {
fatal("nn_socket");
}
if (recv_mode) //Receiver (Node 1, Auxiliary node)
{
if (nn_connect(sock, url) < 0) {
fatal("nn_connect");
}
}
else //Sender (node 0, server, main node)
{
if (nn_bind(sock, url) < 0) {
fatal("nn_bind");
}
}
int to = 100;
if (nn_setsockopt(sock, NN_SOL_SOCKET, NN_RCVTIMEO, &to,sizeof (to)) < 0) {
fatal("nn_setsockopt");
}
return sock;
}
| 31.150617 | 138 | 0.64228 |
65cca26ab81c68c2201bde3223830ec49d11faa7 | 7,042 | cc | C++ | google/cloud/storage/status_or_test.cc | roopak-qlogic/google-cloud-cpp | ed129e4c955e99d4dacb822503d95e374605c438 | [
"Apache-2.0"
] | null | null | null | google/cloud/storage/status_or_test.cc | roopak-qlogic/google-cloud-cpp | ed129e4c955e99d4dacb822503d95e374605c438 | [
"Apache-2.0"
] | null | null | null | google/cloud/storage/status_or_test.cc | roopak-qlogic/google-cloud-cpp | ed129e4c955e99d4dacb822503d95e374605c438 | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Google LLC
//
// 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 "google/cloud/storage/status_or.h"
#include "google/cloud/testing_util/expect_exception.h"
#include <gmock/gmock.h>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace {
using ::testing::HasSubstr;
TEST(StatusOrTest, DefaultConstructor) {
StatusOr<int> actual;
EXPECT_FALSE(actual.ok());
EXPECT_FALSE(actual.status().ok());
EXPECT_TRUE(not actual);
}
TEST(StatusOrTest, StatusConstructorNormal) {
StatusOr<int> actual(Status(404, "NOT FOUND", "It was there yesterday!"));
EXPECT_FALSE(actual.ok());
EXPECT_TRUE(not actual);
EXPECT_EQ(404, actual.status().status_code());
EXPECT_EQ("NOT FOUND", actual.status().error_message());
EXPECT_EQ("It was there yesterday!", actual.status().error_details());
}
TEST(StatusOrTest, StatusConstructorInvalid) {
testing_util::ExpectException<std::invalid_argument>(
[&] { StatusOr<int> actual(Status{}); },
[&](std::invalid_argument const& ex) {
EXPECT_THAT(ex.what(), HasSubstr("StatusOr"));
},
"exceptions are disabled: "
);
}
TEST(StatusOrTest, ValueConstructor) {
StatusOr<int> actual(42);
EXPECT_TRUE(actual.ok());
EXPECT_FALSE(not actual);
EXPECT_EQ(42, actual.value());
EXPECT_EQ(42, std::move(actual).value());
}
TEST(StatusOrTest, ValueConstAccessors) {
StatusOr<int> const actual(42);
EXPECT_TRUE(actual.ok());
EXPECT_EQ(42, actual.value());
EXPECT_EQ(42, std::move(actual).value());
}
TEST(StatusOrTest, ValueAccessorNonConstThrows) {
StatusOr<int> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrTest, ValueAccessorConstThrows) {
StatusOr<int> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrTest, StatusConstAccessors) {
StatusOr<int> const actual(Status(500, "BAD"));
EXPECT_EQ(500, actual.status().status_code());
EXPECT_EQ(500, std::move(actual).status().status_code());
}
TEST(StatusOrTest, ValueDeference) {
StatusOr<std::string> actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ("42", *actual);
EXPECT_EQ("42", std::move(actual).value());
}
TEST(StatusOrTest, ValueConstDeference) {
StatusOr<std::string> const actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ("42", *actual);
EXPECT_EQ("42", std::move(actual).value());
}
TEST(StatusOrTest, ValueArrow) {
StatusOr<std::string> actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ(std::string("42"), actual->c_str());
}
TEST(StatusOrTest, ValueConstArrow) {
StatusOr<std::string> const actual("42");
EXPECT_TRUE(actual.ok());
EXPECT_EQ(std::string("42"), actual->c_str());
}
TEST(StatusOrVoidTest, DefaultConstructor) {
StatusOr<void> actual;
EXPECT_FALSE(actual.ok());
EXPECT_FALSE(actual.status().ok());
}
TEST(StatusOrVoidTest, StatusConstructorNormal) {
StatusOr<void> actual(Status(404, "NOT FOUND", "It was there yesterday!"));
EXPECT_FALSE(actual.ok());
EXPECT_EQ(404, actual.status().status_code());
EXPECT_EQ("NOT FOUND", actual.status().error_message());
EXPECT_EQ("It was there yesterday!", actual.status().error_details());
}
TEST(StatusOrVoidTest, ValueConstructor) {
StatusOr<void> actual(Status{});
EXPECT_TRUE(actual.ok());
testing_util::ExpectNoException([&] { actual.value(); });
testing_util::ExpectNoException([&] { std::move(actual).value(); });
}
TEST(StatusOrVoidTest, ValueConstAccessors) {
StatusOr<void> const actual(Status{});
EXPECT_TRUE(actual.ok());
testing_util::ExpectNoException([&] { actual.value(); });
testing_util::ExpectNoException([&] { std::move(actual).value(); });
}
TEST(StatusOrVoidTest, ValueAccessorNonConstThrows) {
StatusOr<void> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrVoidTest, ValueAccessorConstThrows) {
StatusOr<void> actual(Status(500, "BAD"));
testing_util::ExpectException<RuntimeStatusError>(
[&] { actual.value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
testing_util::ExpectException<RuntimeStatusError>(
[&] { std::move(actual).value(); },
[&](RuntimeStatusError const& ex) {
EXPECT_EQ(500, ex.status().status_code());
EXPECT_EQ("BAD", ex.status().error_message());
},
"exceptions are disabled: BAD \\[500\\]"
);
}
TEST(StatusOrVoidTest, StatusConstAccessors) {
StatusOr<void> const actual(Status(500, "BAD"));
EXPECT_EQ(500, actual.status().status_code());
EXPECT_EQ(500, std::move(actual).status().status_code());
}
} // namespace
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
| 31.159292 | 77 | 0.668986 |
65d1b0b9ce08319e680aae4a187667943a9a6bd4 | 811 | hpp | C++ | src/morda/widgets/label/MouseCursor.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | 1 | 2018-10-27T05:07:05.000Z | 2018-10-27T05:07:05.000Z | src/morda/widgets/label/MouseCursor.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | src/morda/widgets/label/MouseCursor.hpp | Mactor2018/morda | 7194f973783b4472b8671fbb52e8c96e8c972b90 | [
"MIT"
] | null | null | null | #pragma once
#include "../Widget.hpp"
#include "../../res/ResCursor.hpp"
namespace morda{
/**
* @brief Mouse cursor widget.
* This widget displays mouse cursor.
* From GUI script this widget can be instantiated as "MouseCursor".
*
* @param cursor - reference to cursor resource.
*/
class MouseCursor : virtual public Widget{
std::shared_ptr<const ResCursor> cursor;
std::shared_ptr<const ResImage::QuadTexture> quadTex;
Vec2r cursorPos;
public:
MouseCursor(const stob::Node* chain = nullptr);
MouseCursor(const MouseCursor&) = delete;
MouseCursor& operator=(const MouseCursor&) = delete;
void setCursor(std::shared_ptr<const ResCursor> cursor);
bool onMouseMove(const morda::Vec2r& pos, unsigned pointerID) override;
void render(const morda::Matr4r& matrix) const override;
};
}
| 21.918919 | 72 | 0.731196 |
65e402da66d18090a23b95180787d18a0806e7a0 | 1,619 | hpp | C++ | CPP_Module_06/ex01/Serialize.hpp | Victor-Akio/CPP-42 | e6d64e4820ad31ae2cb353a4020d2acb8b5280eb | [
"MIT"
] | null | null | null | CPP_Module_06/ex01/Serialize.hpp | Victor-Akio/CPP-42 | e6d64e4820ad31ae2cb353a4020d2acb8b5280eb | [
"MIT"
] | null | null | null | CPP_Module_06/ex01/Serialize.hpp | Victor-Akio/CPP-42 | e6d64e4820ad31ae2cb353a4020d2acb8b5280eb | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Serialize.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: vminomiy <vminomiy@student.42sp.org.br> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/03/25 00:00:06 by vminomiy #+# #+# */
/* Updated: 2022/03/26 16:15:18 by vminomiy ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SERIALIZE_HPP
# define SERIALIZE_HPP
# include <iostream>
# include <stdint.h>
/* SERIALIZATION
** https://en.cppreference.com/w/cpp/language/reinterpret_cast
** https://www.tutorialspoint.com/cplusplus/cpp_casting_operators.htm
** UINTPTR_T - https://stackoverflow.com/questions/1845482/what-is-uintptr-t-data-type
** Usei a stdint.h no lugar da cstdint, pois a uintptr_t foi implementada originalmente na c++99(stdint.h)
** a cstdint corresponde ร c++11 que entra na categoriad e forbidden.
** A estrutura pode ter qualquer coisa dentro.. no caso sรณ para popular com algo, coloquei um "num"
*/
typedef struct s_data {
int num;
} Data;
uintptr_t serialize(Data* ptr);
Data* deserialize(uintptr_t raw);
#endif
| 46.257143 | 106 | 0.408894 |
65eb378757f196f1b0242237bbf7b0aab25022d1 | 1,112 | cpp | C++ | tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp | ridlo/kuliah_sains_komputasi | 83cd50857db2446bb41b78698a47a060e0eca5d8 | [
"MIT"
] | null | null | null | tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp | ridlo/kuliah_sains_komputasi | 83cd50857db2446bb41b78698a47a060e0eca5d8 | [
"MIT"
] | null | null | null | tugasMonteCarlo/tugasMonteCarlo-20912008-20912009/montePi.cpp | ridlo/kuliah_sains_komputasi | 83cd50857db2446bb41b78698a47a060e0eca5d8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <fstream>
#include <stdlib.h>
#include <time.h>
using namespace std;
double unirand()
{
return (double) rand()/ (double) RAND_MAX;
}
int main()
{
double pi, x, y, r;
unsigned int N=0, Ntot;
ofstream outfile;
outfile.open("rnd-pi.txt");
Ntot = 100000;
srand(time(NULL));
for (int i=0; i<Ntot; i++){
x = unirand();
y = unirand();
outfile << x << " " << y << "\n";
r = x*x + y*y;
if ( r <= 1. ) {
N++;}
}
outfile.close();
pi = (double)N/(double)Ntot * 4.;
printf("Hasil dari %d percobaan menghasilkan nilai PI = %f \n", Ntot, pi);
ofstream ploter;
ploter.open("pi-plot.in");
ploter << "# gnuplot command for plotting\n";
ploter << "set terminal wxt size 600, 500\n";
ploter << "set xrange [0:1]\n";
ploter << "set xlabel \"x\"\n";
ploter << "set ylabel \"y\"\n";
ploter << "plot \"rnd-pi.txt\" with dots, sqrt(1.-x*x)\n";
ploter.close();
system("gnuplot -persist < pi-plot.in");
return 0;
}
| 22.24 | 78 | 0.522482 |
65ec377cfee6e4d0b9d9cdac2342a92ccfa6aa3b | 14,844 | hpp | C++ | pennylane_lightning_gpu/src/util/cuda_helpers.hpp | PennyLaneAI/pennylane-lightning-gpu | 1b2a361f68c8580457e61cc706d644c4cbfe04ad | [
"Apache-2.0"
] | 9 | 2022-03-14T15:18:08.000Z | 2022-03-30T03:05:36.000Z | pennylane_lightning_gpu/src/util/cuda_helpers.hpp | PennyLaneAI/pennylane-lightning-gpu | 1b2a361f68c8580457e61cc706d644c4cbfe04ad | [
"Apache-2.0"
] | 6 | 2022-03-18T13:44:10.000Z | 2022-03-31T22:07:25.000Z | pennylane_lightning_gpu/src/util/cuda_helpers.hpp | PennyLaneAI/pennylane-lightning-gpu | 1b2a361f68c8580457e61cc706d644c4cbfe04ad | [
"Apache-2.0"
] | null | null | null | // Adapted from JET: https://github.com/XanaduAI/jet.git
// and from Lightning: https://github.com/PennylaneAI/pennylane-lightning.git
#pragma once
#include <algorithm>
#include <numeric>
#include <type_traits>
#include <vector>
#include <cuComplex.h>
#include <cublas_v2.h>
#include <cuda.h>
#include <custatevec.h>
#include "Error.hpp"
#include "Util.hpp"
namespace Pennylane::CUDA::Util {
#ifndef CUDA_UNSAFE
/**
* @brief Macro that throws Exception from CUDA failure error codes.
*
* @param err CUDA function error-code.
*/
#define PL_CUDA_IS_SUCCESS(err) \
PL_ABORT_IF_NOT(err == cudaSuccess, cudaGetErrorString(err))
/**
* @brief Macro that throws Exception from cuQuantum failure error codes.
*
* @param err cuQuantum function error-code.
*/
#define PL_CUSTATEVEC_IS_SUCCESS(err) \
PL_ABORT_IF_NOT(err == CUSTATEVEC_STATUS_SUCCESS, \
GetCuStateVecErrorString(err).c_str())
#else
#define PL_CUDA_IS_SUCCESS(err) \
{ static_cast<void>(err); }
#define PL_CUSTATEVEC_IS_SUCCESS(err) \
{ static_cast<void>(err); }
#endif
static const std::string
GetCuStateVecErrorString(const custatevecStatus_t &err) {
std::string result;
switch (err) {
case CUSTATEVEC_STATUS_SUCCESS:
result = "No errors";
break;
case CUSTATEVEC_STATUS_NOT_INITIALIZED:
result = "custatevec not initialized";
break;
case CUSTATEVEC_STATUS_ALLOC_FAILED:
result = "custatevec memory allocation failed";
break;
case CUSTATEVEC_STATUS_INVALID_VALUE:
result = "Invalid value";
break;
case CUSTATEVEC_STATUS_ARCH_MISMATCH:
result = "CUDA device architecture mismatch";
break;
case CUSTATEVEC_STATUS_EXECUTION_FAILED:
result = "custatevec execution failed";
break;
case CUSTATEVEC_STATUS_INTERNAL_ERROR:
result = "Internal custatevec error";
break;
case CUSTATEVEC_STATUS_NOT_SUPPORTED:
result = "Unsupported operation/device";
break;
case CUSTATEVEC_STATUS_INSUFFICIENT_WORKSPACE:
result = "Insufficient memory for gate-application workspace";
break;
case CUSTATEVEC_STATUS_SAMPLER_NOT_PREPROCESSED:
result = "Sampler not preprocessed";
break;
default:
result = "Status not found";
}
return result;
}
// SFINAE check for existence of real() method in complex type
template <typename CFP_t>
constexpr auto is_cxx_complex(const CFP_t &t) -> decltype(t.real(), bool()) {
return true;
}
// Catch-all fallback for CUDA complex types
constexpr bool is_cxx_complex(...) { return false; }
inline cuFloatComplex operator-(const cuFloatComplex &a) {
return {-a.x, -a.y};
}
inline cuDoubleComplex operator-(const cuDoubleComplex &a) {
return {-a.x, -a.y};
}
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static auto Div(const CFP_t_T &a, const CFP_t_U &b) -> CFP_t_T {
if constexpr (std::is_same_v<CFP_t_T, cuComplex> ||
std::is_same_v<CFP_t_T, float2>) {
return cuCdivf(a, b);
} else if (std::is_same_v<CFP_t_T, cuDoubleComplex> ||
std::is_same_v<CFP_t_T, double2>) {
return cuCdiv(a, b);
}
}
/**
* @brief Conjugate function for CXX & CUDA complex types
*
* @tparam CFP_t Complex data type. Supports std::complex<float>,
* std::complex<double>, cuFloatComplex, cuDoubleComplex
* @param a The given complex number
* @return CFP_t The conjuagted complex number
*/
template <class CFP_t> inline static constexpr auto Conj(CFP_t a) -> CFP_t {
if constexpr (std::is_same_v<CFP_t, cuComplex> ||
std::is_same_v<CFP_t, float2>) {
return cuConjf(a);
} else {
return cuConj(a);
}
}
/**
* @brief Compile-time scalar real times complex number.
*
* @tparam U Precision of real value `a`.
* @tparam T Precision of complex value `b` and result.
* @param a Real scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class Real_t, class CFP_t = cuDoubleComplex>
inline static constexpr auto ConstMultSC(Real_t a, CFP_t b) -> CFP_t {
if constexpr (std::is_same_v<CFP_t, cuDoubleComplex>) {
return make_cuDoubleComplex(a * b.x, a * b.y);
} else {
return make_cuFloatComplex(a * b.x, a * b.y);
}
}
/**
* @brief Utility to convert cuComplex types to std::complex types
*
* @tparam CFP_t cuFloatComplex or cuDoubleComplex types.
* @param a CUDA compatible complex type.
* @return std::complex converted a
*/
template <class CFP_t = cuDoubleComplex>
inline static constexpr auto cuToComplex(CFP_t a)
-> std::complex<decltype(a.x)> {
return std::complex<decltype(a.x)>{a.x, a.y};
}
/**
* @brief Utility to convert std::complex types to cuComplex types
*
* @tparam CFP_t std::complex types.
* @param a A std::complex type.
* @return cuComplex converted a
*/
template <class CFP_t = std::complex<double>>
inline static constexpr auto complexToCu(CFP_t a) {
if constexpr (std::is_same_v<CFP_t, std::complex<double>>) {
return make_cuDoubleComplex(a.real(), a.imag());
} else {
return make_cuFloatComplex(a.real(), a.imag());
}
}
/**
* @brief Compile-time scalar complex times complex.
*
* @tparam U Precision of complex value `a`.
* @tparam T Precision of complex value `b` and result.
* @param a Complex scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstMult(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
if constexpr (is_cxx_complex(b)) {
return {a.real() * b.real() - a.imag() * b.imag(),
a.real() * b.imag() + a.imag() * b.real()};
} else {
return {a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x};
}
}
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstMultConj(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
return ConstMult(Conj(a), b);
}
/**
* @brief Compile-time scalar complex summation.
*
* @tparam T Precision of complex value `a` and result.
* @tparam U Precision of complex value `b`.
* @param a Complex scalar value.
* @param b Complex scalar value.
* @return constexpr std::complex<T>
*/
template <class CFP_t_T, class CFP_t_U = CFP_t_T>
inline static constexpr auto ConstSum(CFP_t_T a, CFP_t_U b) -> CFP_t_T {
if constexpr (std::is_same_v<CFP_t_T, cuComplex> ||
std::is_same_v<CFP_t_T, float2>) {
return cuCaddf(a, b);
} else {
return cuCadd(a, b);
}
}
/**
* @brief Return complex value 1+0i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{1,0}
*/
template <class CFP_t> inline static constexpr auto ONE() -> CFP_t {
return {1, 0};
}
/**
* @brief Return complex value 0+0i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{0,0}
*/
template <class CFP_t> inline static constexpr auto ZERO() -> CFP_t {
return {0, 0};
}
/**
* @brief Return complex value 0+1i in the given precision.
*
* @tparam T Floating point precision type. Accepts `double` and `float`.
* @return constexpr std::complex<T>{0,1}
*/
template <class CFP_t> inline static constexpr auto IMAG() -> CFP_t {
return {0, 1};
}
/**
* @brief Returns sqrt(2) as a compile-time constant.
*
* @tparam T Precision of result. `double`, `float` are accepted values.
* @return constexpr T sqrt(2)
*/
template <class CFP_t> inline static constexpr auto SQRT2() {
if constexpr (std::is_same_v<CFP_t, float2> ||
std::is_same_v<CFP_t, cuFloatComplex>) {
return CFP_t{0x1.6a09e6p+0F, 0}; // NOLINT: To be replaced in C++20
} else if constexpr (std::is_same_v<CFP_t, double2> ||
std::is_same_v<CFP_t, cuDoubleComplex>) {
return CFP_t{0x1.6a09e667f3bcdp+0,
0}; // NOLINT: To be replaced in C++20
} else if constexpr (std::is_same_v<CFP_t, double>) {
return 0x1.6a09e667f3bcdp+0; // NOLINT: To be replaced in C++20
} else {
return 0x1.6a09e6p+0F; // NOLINT: To be replaced in C++20
}
}
/**
* @brief Returns inverse sqrt(2) as a compile-time constant.
*
* @tparam T Precision of result. `double`, `float` are accepted values.
* @return constexpr T 1/sqrt(2)
*/
template <class CFP_t> inline static constexpr auto INVSQRT2() -> CFP_t {
if constexpr (std::is_same_v<CFP_t, std::complex<float>> ||
std::is_same_v<CFP_t, std::complex<double>>) {
return CFP_t(1 / M_SQRT2, 0);
} else {
return Div(CFP_t{1, 0}, SQRT2<CFP_t>());
}
}
/**
* @brief cuBLAS backed inner product for GPU data.
*
* @tparam T Complex data-type. Accepts cuFloatComplex and cuDoubleComplex/
* @param v1 Device data pointer 1
* @param v2 Device data pointer 2
* @param data_size Lengtyh of device data.
* @return T Inner-product result
*/
template <class T = cuFloatComplex>
inline auto innerProdC_CUDA(const T *v1, const T *v2, const int data_size,
const cudaStream_t &streamId) -> T {
T result{0.0, 0.0}; // Host result
cublasHandle_t handle;
cublasCreate(&handle);
cublasSetStream(handle, streamId);
if constexpr (std::is_same_v<T, cuFloatComplex>) {
cublasCdotc(handle, data_size, v1, 1, v2, 1, &result);
} else if constexpr (std::is_same_v<T, cuDoubleComplex>) {
cublasZdotc(handle, data_size, v1, 1, v2, 1, &result);
}
cublasDestroy(handle);
return result;
}
/**
* If T is a supported data type for gates, this expression will
* evaluate to `true`. Otherwise, it will evaluate to `false`.
*
* Supported data types are `float2`, `double2`, and their aliases.
*
* @tparam T candidate data type
*/
template <class T>
constexpr bool is_supported_data_type =
std::is_same_v<T, cuComplex> || std::is_same_v<T, float2> ||
std::is_same_v<T, cuDoubleComplex> || std::is_same_v<T, double2>;
/**
* @brief Simple overloaded method to define CUDA data type.
*
* @param t
* @return cuDoubleComplex
*/
inline cuDoubleComplex getCudaType(const double &t) {
static_cast<void>(t);
return {};
}
/**
* @brief Simple overloaded method to define CUDA data type.
*
* @param t
* @return cuFloatComplex
*/
inline cuFloatComplex getCudaType(const float &t) {
static_cast<void>(t);
return {};
}
/**
* @brief Return the number of supported CUDA capable GPU devices.
*
* @return std::size_t
*/
inline int getGPUCount() {
int result;
PL_CUDA_IS_SUCCESS(cudaGetDeviceCount(&result));
return result;
}
/**
* @brief Return the current GPU device.
*
* @return int
*/
inline int getGPUIdx() {
int result;
PL_CUDA_IS_SUCCESS(cudaGetDevice(&result));
return result;
}
inline static void deviceReset() { PL_CUDA_IS_SUCCESS(cudaDeviceReset()); }
/**
* @brief Checks to see if the given GPU supports the PennyLane-Lightning-GPU
* device. Minimum supported architecture is SM 7.0.
*
* @param device_number GPU device index
* @return bool
*/
static bool isCuQuantumSupported(int device_number = 0) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_number);
return deviceProp.major >= 7;
}
/**
* @brief Get current GPU major.minor support
*
* @param device_number
* @return std::pair<int,int>
*/
static std::pair<int, int> getGPUArch(int device_number = 0) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device_number);
return std::make_pair(deviceProp.major, deviceProp.minor);
}
/** Chunk the data with the requested chunk size */
template <template <typename...> class Container, typename T>
auto chunkDataSize(const Container<T> &data, std::size_t chunk_size)
-> Container<Container<T>> {
Container<Container<T>> output;
for (std::size_t chunk = 0; chunk < data.size(); chunk += chunk_size) {
const auto chunk_end = std::min(data.size(), chunk + chunk_size);
output.emplace_back(data.begin() + chunk, data.begin() + chunk_end);
}
return output;
}
/** Chunk the data into the requested number of chunks */
template <template <typename...> class Container, typename T>
auto chunkData(const Container<T> &data, std::size_t num_chunks)
-> Container<Container<T>> {
const auto rem = data.size() % num_chunks;
const std::size_t div = static_cast<std::size_t>(data.size() / num_chunks);
if (!div) { // Match chunks to available work
return chunkDataSize(data, 1);
}
if (rem) { // We have an uneven split; ensure fair distribution
auto output =
chunkDataSize(Container<T>{data.begin(), data.end() - rem}, div);
auto output_rem =
chunkDataSize(Container<T>{data.end() - rem, data.end()}, div);
for (std::size_t idx = 0; idx < output_rem.size(); idx++) {
output[idx].insert(output[idx].end(), output_rem[idx].begin(),
output_rem[idx].end());
}
return output;
}
return chunkDataSize(data, div);
}
/** @brief `%CudaScopedDevice` uses RAII to select a CUDA device context.
*
* @see https://taskflow.github.io/taskflow/classtf_1_1cudaScopedDevice.html
*
* @note A `%CudaScopedDevice` instance cannot be moved or copied.
*
* @warning This class is not thread-safe.
*/
class CudaScopedDevice {
public:
/**
* @brief Constructs a `%CudaScopedDevice` using a CUDA device.
*
* @param device CUDA device to scope in the guard.
*/
CudaScopedDevice(int device) {
PL_CUDA_IS_SUCCESS(cudaGetDevice(&prev_device_));
if (prev_device_ == device) {
prev_device_ = -1;
} else {
PL_CUDA_IS_SUCCESS(cudaSetDevice(device));
}
}
/**
* @brief Destructs a `%CudaScopedDevice`, switching back to the previous
* CUDA device context.
*/
~CudaScopedDevice() {
if (prev_device_ != -1) {
// Throwing exceptions from a destructor can be dangerous.
// See https://isocpp.org/wiki/faq/exceptions#ctor-exceptions.
cudaSetDevice(prev_device_);
}
}
CudaScopedDevice() = delete;
CudaScopedDevice(const CudaScopedDevice &) = delete;
CudaScopedDevice(CudaScopedDevice &&) = delete;
private:
/// The previous CUDA device (or -1 if the device passed to the constructor
/// is the current CUDA device).
int prev_device_;
};
} // namespace Pennylane::CUDA::Util
| 31.119497 | 80 | 0.651846 |
65ed7938ab2812c404caebb3d26a88d4f07e2ff5 | 1,858 | cpp | C++ | examples/CherryPicker/general_example.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 7 | 2019-11-24T15:51:37.000Z | 2021-10-02T05:18:42.000Z | examples/CherryPicker/general_example.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2018-12-17T00:55:32.000Z | 2019-10-11T01:47:04.000Z | examples/CherryPicker/general_example.cpp | allison-group/indigox | 22657cb3ceb888049cc231e73d18fb2eac099604 | [
"MIT"
] | 2 | 2019-10-21T01:26:56.000Z | 2019-12-02T00:00:42.000Z | //
// C++ example that imports a molecule from an outputted binary (which you can produce from python with indigox.SaveMolecule)
// This example has CalculateElectrons on, so it will calculate formal charges and bond orders.
// Relies on the Python example having been run first so there is an Athenaeum to match the molecule to.
// Also assumes you are running from a build folder in the project root. If not, change example_folder_path below
//
#include <indigox/indigox.hpp>
#include <indigox/classes/athenaeum.hpp>
#include <indigox/classes/forcefield.hpp>
#include <indigox/classes/parameterised.hpp>
#include <indigox/algorithm/cherrypicker.hpp>
#include <experimental/filesystem>
int main() {
using namespace indigox;
namespace fs = std::experimental::filesystem;
using settings = indigox::algorithm::CherryPicker::Settings;
std::string example_folder_path = "../examples/CherryPicker/";
auto forceField = GenerateGROMOS54A7();
auto man_ath = LoadAthenaeum(example_folder_path + "ManualAthenaeum.ath");
// auto auto_ath = LoadAthenaeum(example_folder_path + "AutomaticAthenaeum.ath");
Molecule mol = LoadMolecule(example_folder_path + "TestMolecules/axinellinA.bin");
algorithm::CherryPicker cherryPicker(forceField);
cherryPicker.AddAthenaeum(man_ath);
cherryPicker.SetInt(settings::MinimumFragmentSize, 2);
cherryPicker.SetInt(settings::MaximumFragmentSize, 20);
cherryPicker.SetBool(settings::CalculateElectrons);
const indigox::ParamMolecule &molecule = cherryPicker.ParameteriseMolecule(mol);
//We can't save the parameterisation directly in ITP format from C++, but we save the binary molecule output
//which can be imported by the python module and outputted in ITP, IXD, PDB and RTP formats
SaveMolecule(mol, example_folder_path + "TestMolecules/axinellinA.out.param");
std::cout << "Done!\n";
}
| 41.288889 | 125 | 0.777718 |
65eecaa7eecf4b5dfad13c5cc46fe6e749fea72f | 3,007 | hpp | C++ | Include/LibYT/Concepts.hpp | MalteDoemer/YeetOS2 | 82be488ec1ed13e6558af4e248977dad317b3b85 | [
"BSD-2-Clause"
] | null | null | null | Include/LibYT/Concepts.hpp | MalteDoemer/YeetOS2 | 82be488ec1ed13e6558af4e248977dad317b3b85 | [
"BSD-2-Clause"
] | null | null | null | Include/LibYT/Concepts.hpp | MalteDoemer/YeetOS2 | 82be488ec1ed13e6558af4e248977dad317b3b85 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright 2021 Malte Dรถmer
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "StdLibExtras.hpp"
#include "Types.hpp"
namespace YT {
template<class T>
concept ArithmeticType = IsArithmetic<T>::value;
template<class T>
concept ConstType = IsConst<T>::value;
template<class T>
concept EnumType = IsEnum<T>::value;
template<class T>
concept FloatingPointType = IsFloatingPoint<T>::value;
template<class T>
concept FundamentalType = IsFundamental<T>::value;
template<class T>
concept IntegralType = IsIntegral<T>::value;
template<class T>
concept NullPointerType = IsNullPointer<T>::value;
template<class T>
concept SigendType = IsSigned<T>::value;
template<class T>
concept UnionType = IsUnion<T>::value;
template<class T>
concept UnsigendType = IsUnsigned<T>::value;
template<class T, class U>
concept SameAs = IsSame<T, U>::value;
template<class From, class To>
concept ConvertibleTo = IsConvertible<From, To>::value;
template<class T>
concept EqualityCompareable = requires(T a, T b)
{
{ a == b } -> ConvertibleTo<bool>;
{ a != b } -> ConvertibleTo<bool>;
};
template<class T>
concept Compareable = requires(T a, T b)
{
{ a == b } -> ConvertibleTo<bool>;
{ a != b } -> ConvertibleTo<bool>;
{ a <= b } -> ConvertibleTo<bool>;
{ a >= b } -> ConvertibleTo<bool>;
{ a < b } -> ConvertibleTo<bool>;
{ a > b } -> ConvertibleTo<bool>;
};
}
using YT::ArithmeticType;
using YT::Compareable;
using YT::ConstType;
using YT::ConvertibleTo;
using YT::EnumType;
using YT::EqualityCompareable;
using YT::FloatingPointType;
using YT::FundamentalType;
using YT::IntegralType;
using YT::NullPointerType;
using YT::SameAs;
using YT::SigendType;
using YT::UnionType;
using YT::UnsigendType; | 29.480392 | 81 | 0.736615 |
65f4694160beffb076d12e39d59639ef6df2e43d | 1,073 | cpp | C++ | AzureClient/AzureClient/EventHub.cpp | Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring | 695ca226ca0b9331a516573376323d71afb08f35 | [
"MIT"
] | 3 | 2019-05-22T22:03:50.000Z | 2020-11-25T11:56:38.000Z | AzureClient/AzureClient/EventHub.cpp | Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring | 695ca226ca0b9331a516573376323d71afb08f35 | [
"MIT"
] | null | null | null | AzureClient/AzureClient/EventHub.cpp | Ashish-Me2/Arduino-ESP8266-AzureIoTHub-MQTT-CameraMonitoring | 695ca226ca0b9331a516573376323d71afb08f35 | [
"MIT"
] | null | null | null | #include "EventHub.h"
String Eventhub::createSas(char *key, String url){
// START: Create SAS
// https://azure.microsoft.com/en-us/documentation/articles/service-bus-sas-overview/
// Where to get seconds since the epoch: local service, SNTP, RTC
sasExpiryTime = now() + sasExpiryPeriodInSeconds;
String stringToSign = url + "\n" + sasExpiryTime;
// START: Create signature
Sha256.initHmac((const uint8_t*)key, 44);
Sha256.print(stringToSign);
char* sign = (char*) Sha256.resultHmac();
int signLen = 32;
// END: Create signature
// START: Get base64 of signature
int encodedSignLen = base64_enc_len(signLen);
char encodedSign[encodedSignLen];
base64_encode(encodedSign, sign, signLen);
// END: Get base64 of signature
// SharedAccessSignature
return "sr=" + url + "&sig="+ urlEncode(encodedSign) + "&se=" + sasExpiryTime +"&skn=" + deviceId;
// END: create SAS
}
void Eventhub::initialiseHub() {
sasUrl = urlEncode("https://") + urlEncode(host) + urlEncode(EVENT_HUB_END_POINT);
endPoint = EVENT_HUB_END_POINT;
}
| 29.805556 | 100 | 0.698043 |
65f5030cb99991738a96f16d0715dee55bc429ea | 2,490 | hpp | C++ | src/key/key_wallet.hpp | feitebi/main-chain | d4f2c4bb99b083d6162614a9a6b684c66ddf5d88 | [
"MIT"
] | 1 | 2018-01-17T05:08:32.000Z | 2018-01-17T05:08:32.000Z | src/key/key_wallet.hpp | feitebi/main-chain | d4f2c4bb99b083d6162614a9a6b684c66ddf5d88 | [
"MIT"
] | null | null | null | src/key/key_wallet.hpp | feitebi/main-chain | d4f2c4bb99b083d6162614a9a6b684c66ddf5d88 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2013-2014 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of coinpp.
*
* coinpp is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COIN_KEY_WALLET_HPP
#define COIN_KEY_WALLET_HPP
#include <cstdint>
#include <string>
#include <coin/data_buffer.hpp>
#include <coin/key.hpp>
namespace coin {
/**
* Implements a wallet (private) key.
*/
class key_wallet : public data_buffer
{
public:
/**
* Constructor
*/
key_wallet(const std::int64_t & expires = 0);
/**
* Encodes.
*/
void encode();
/**
* Decodes
* @param buffer The data_buffer.
*/
void encode(data_buffer & buffer);
/**
* Decodes
*/
void decode();
/**
* Decodes
* @param buffer The data_buffer.
*/
void decode(data_buffer & buffer);
/**
* The private key.
*/
const key::private_t & key_private() const;
private:
/**
* The private key.
*/
key::private_t m_key_private;
/**
* The time created.
*/
std::int64_t m_time_created;
/**
* The time expires.
*/
std::int64_t m_time_expires;
/**
* The comment.
*/
std::string m_comment;
protected:
// ...
};
} // namespace coin
#endif // COIN_KEY_WALLET_HPP
| 24.653465 | 76 | 0.51245 |
65f78b8241e1cdf7e3674e5b1cf8e06515e1c5ba | 1,476 | cpp | C++ | test/test_dumpFHESetting.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | 5 | 2017-01-16T06:20:07.000Z | 2018-05-17T12:36:34.000Z | test/test_dumpFHESetting.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | null | null | null | test/test_dumpFHESetting.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | 2 | 2017-08-26T13:16:35.000Z | 2019-03-15T02:08:20.000Z | #include "utils/FHEUtils.hpp"
#include "utils/timer.hpp"
#include "fhe/EncryptedArray.h"
#include <string>
#include "algebra/NDSS.h"
void test_load(long m, long p, long r, long L)
{
MDL::Timer timer;
std::string path("fhe_setting");
timer.start();
FHEcontext context(m, p, r);
timer.end();
printf("Initial Context costed %f\n", timer.second());
timer.reset();
FHESecKey sk(context);
timer.end();
printf("Initial SK costed %f\n", timer.second());
timer.reset();
load_FHE_setting(path, context, sk);
timer.end();
printf("Load costed %f sec.\n", timer.second());
FHEPubKey pk = sk;
NTL::ZZX plain;
Ctxt ctxt(pk);
pk.Encrypt(ctxt, NTL::to_ZZX(10));
ctxt *= ctxt;
sk.Decrypt(plain, ctxt);
assert(plain == 100);
auto G = context.alMod.getFactorsOverZZ()[0];
EncryptedArray ea(context, G);
assert(ea.size() == 4);
}
void test_dump(long m, long p, long r, long L)
{
MDL::Timer timer;
timer.start();
dump_FHE_setting_to_file("fhe_setting_32", 80, m, p, r, L);
timer.end();
printf("Cost %f to dump m : %ld, p : %ld, r : %ld, L : %ld\n",
timer.second(), m, p, r, L);
}
int main(int argc, char *argv[]) {
ArgMapping arg;
long m, p, r, L;
arg.arg("m", m, "m");
arg.arg("p", p, "p");
arg.arg("r", r, "r");
arg.arg("L", L, "L");
arg.parse(argc, argv);
//test_load(m, p, r, L);
test_dump(m, p, r, L);
return 0;
}
| 23.0625 | 66 | 0.573171 |
65f7ae9a8d8b474c1e1ec8bb2150a22ff8451fb6 | 1,762 | cpp | C++ | moon-src/luabind/lua_http.cpp | leefy4415/moon | 2a2005306e9a685a6af899a0daae9c53603b38e4 | [
"MIT"
] | 1 | 2020-09-22T01:57:54.000Z | 2020-09-22T01:57:54.000Z | moon-src/luabind/lua_http.cpp | leefy4415/moon | 2a2005306e9a685a6af899a0daae9c53603b38e4 | [
"MIT"
] | null | null | null | moon-src/luabind/lua_http.cpp | leefy4415/moon | 2a2005306e9a685a6af899a0daae9c53603b38e4 | [
"MIT"
] | null | null | null | #include "sol/sol.hpp"
#include "common/http_util.hpp"
using namespace moon;
static sol::table bind_http(sol::this_state L)
{
sol::state_view lua(L);
sol::table module = lua.create_table();
module.set_function("parse_request", [](std::string_view data) {
std::string_view method;
std::string_view path;
std::string_view query_string;
std::string_view version;
http::case_insensitive_multimap_view header;
bool ok = http::request_parser::parse(data, method, path, query_string, version, header);
return std::make_tuple(ok, method, path, query_string, version, sol::as_table(header));
});
module.set_function("parse_response", [](std::string_view data) {
std::string_view version;
std::string_view status_code;
http::case_insensitive_multimap_view header;
bool ok = http::response_parser::parse(data, version, status_code, header);
return std::make_tuple(ok, version, status_code, sol::as_table(header));
});
module.set_function("parse_query_string", [](const std::string &data) {
return sol::as_table(http::query_string::parse(data));
});
module.set_function("create_query_string", [](sol::as_table_t<http::case_insensitive_multimap> src) {
return http::query_string::create(src.value());
});
module.set_function("urlencode", [](std::string_view src) {
return http::percent::encode(std::string{ src });
});
module.set_function("urldecode", [](std::string_view src) {
return http::percent::decode(std::string{ src });
});
return module;
}
extern "C"
{
int LUAMOD_API luaopen_http(lua_State *L)
{
return sol::stack::call_lua(L, 1, bind_http);
}
}
| 32.036364 | 105 | 0.658343 |
65fa36eff75fb1297b6d8f4576e3411c7e51c17c | 4,952 | cpp | C++ | modules/attention_segmentation/src/Texture.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 2 | 2021-02-22T11:36:33.000Z | 2021-07-20T11:31:08.000Z | modules/attention_segmentation/src/Texture.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | null | null | null | modules/attention_segmentation/src/Texture.cpp | v4r-tuwien/v4r | ff3fbd6d2b298b83268ba4737868bab258262a40 | [
"BSD-1-Clause",
"BSD-2-Clause"
] | 3 | 2018-10-19T10:39:23.000Z | 2021-04-07T13:39:03.000Z | /****************************************************************************
**
** Copyright (C) 2017 TU Wien, ACIN, Vision 4 Robotics (V4R) group
** Contact: v4r.acin.tuwien.ac.at
**
** This file is part of V4R
**
** V4R is distributed under dual licenses - GPLv3 or closed source.
**
** GNU General Public License Usage
** V4R is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** V4R 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.
**
** Please review the following information to ensure the GNU General Public
** License requirements will be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
**
** Commercial License Usage
** If GPL is not suitable for your project, you must purchase a commercial
** license to use V4R. Licensees holding valid commercial V4R licenses may
** use this file in accordance with the commercial license agreement
** provided with the Software or, alternatively, in accordance with the
** terms contained in a written agreement between you and TU Wien, ACIN, V4R.
** For licensing terms and conditions please contact office<at>acin.tuwien.ac.at.
**
**
** The copyright holder additionally grants the author(s) of the file the right
** to use, copy, modify, merge, publish, distribute, sublicense, and/or
** sell copies of their contributions without any restrictions.
**
****************************************************************************/
/**
* @file Texture.cpp
* @author Richtsfeld
* @date October 2012
* @version 0.1
* @brief Calculate texture feature to compare surface texture.
*/
#include "v4r/attention_segmentation/Texture.h"
namespace v4r {
/************************************************************************************
* Constructor/Destructor
*/
Texture::Texture() {
computed = false;
have_edges = false;
have_indices = false;
}
Texture::~Texture() {}
void Texture::setInputEdges(cv::Mat &_edges) {
if ((_edges.cols <= 0) || (_edges.rows <= 0)) {
LOG(ERROR) << "Invalid image (height|width must be > 1";
throw std::runtime_error("[Texture::setInputEdges] Invalid image (height|width must be > 1)");
}
if (_edges.type() != CV_8UC1) {
LOG(ERROR) << "Invalid image type (must be 8UC1)";
throw std::runtime_error("[Texture::setInputEdges] Invalid image type (must be 8UC1)");
}
edges = _edges;
width = edges.cols;
height = edges.rows;
have_edges = true;
computed = false;
indices.reset(new pcl::PointIndices);
for (int i = 0; i < width * height; i++) {
indices->indices.push_back(i);
}
}
void Texture::setIndices(pcl::PointIndices::Ptr _indices) {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::setIndices]: Error: No edges available.");
}
indices = _indices;
have_indices = true;
}
void Texture::setIndices(std::vector<int> &_indices) {
indices.reset(new pcl::PointIndices);
indices->indices = _indices;
}
void Texture::setIndices(cv::Rect _rect) {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::setIndices]: Error: No edges available.");
}
if (_rect.y >= height) {
_rect.y = height - 1;
}
if ((_rect.y + _rect.height) >= height) {
_rect.height = height - _rect.y;
}
if (_rect.x >= width) {
_rect.x = width - 1;
}
if ((_rect.x + _rect.width) >= width) {
_rect.width = width - _rect.x;
}
VLOG(1) << "_rect = " << _rect.x << ", " << _rect.y << ", " << _rect.x + _rect.width << ", "
<< _rect.y + _rect.height;
indices.reset(new pcl::PointIndices);
for (int r = _rect.y; r < (_rect.y + _rect.height); r++) {
for (int c = _rect.x; c < (_rect.x + _rect.width); c++) {
indices->indices.push_back(r * width + c);
}
}
have_indices = true;
}
void Texture::compute() {
if (!have_edges) {
LOG(ERROR) << "No edges available.";
throw std::runtime_error("[Texture::compute]: Error: No edges available.");
}
textureRate = 0.0;
if ((indices->indices.size()) <= 0) {
computed = true;
return;
}
int texArea = 0;
for (unsigned int i = 0; i < indices->indices.size(); i++) {
int x = indices->indices.at(i) % width;
int y = indices->indices.at(i) / width;
if (edges.at<uchar>(y, x) == 255)
texArea++;
}
textureRate = (double)((double)texArea / indices->indices.size());
computed = true;
}
double Texture::compare(Texture::Ptr t) {
if (!computed || !(t->getComputed())) {
LOG(ERROR) << "Texture is not computed.";
return 0.;
}
return 1. - fabs(textureRate - t->getTextureRate());
}
} // namespace v4r
| 28.45977 | 98 | 0.625606 |
65fac98ea13e3d3d783063a53fa92368dc96f3fe | 2,879 | cpp | C++ | Gems/Atom/RHI/Code/Source/RHI/BufferScopeAttachment.cpp | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Gems/Atom/RHI/Code/Source/RHI/BufferScopeAttachment.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Gems/Atom/RHI/Code/Source/RHI/BufferScopeAttachment.cpp | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <Atom/RHI/BufferScopeAttachment.h>
#include <Atom/RHI/BufferFrameAttachment.h>
#include <Atom/RHI/BufferView.h>
namespace AZ
{
namespace RHI
{
BufferScopeAttachment::BufferScopeAttachment(
Scope& scope,
FrameAttachment& attachment,
ScopeAttachmentUsage usage,
ScopeAttachmentAccess access,
const BufferScopeAttachmentDescriptor& descriptor)
: ScopeAttachment(scope, attachment, usage, access)
, m_descriptor{descriptor}
{
AZ_Assert(
m_descriptor.m_bufferViewDescriptor.m_elementSize > 0 &&
m_descriptor.m_bufferViewDescriptor.m_elementCount > 0,
"Invalid buffer view for attachment.");
if (m_descriptor.m_loadStoreAction.m_loadAction == AttachmentLoadAction::Clear)
{
AZ_Error("FrameScheduler", access == ScopeAttachmentAccess::ReadWrite, "Attempting to clear an attachment that is read-only");
}
}
const BufferScopeAttachmentDescriptor& BufferScopeAttachment::GetDescriptor() const
{
return m_descriptor;
}
const BufferView* BufferScopeAttachment::GetBufferView() const
{
return static_cast<const BufferView*>(ScopeAttachment::GetResourceView());
}
void BufferScopeAttachment::SetBufferView(ConstPtr<BufferView> bufferView)
{
SetResourceView(AZStd::move(bufferView));
}
const BufferFrameAttachment& BufferScopeAttachment::GetFrameAttachment() const
{
return static_cast<const BufferFrameAttachment&>(ScopeAttachment::GetFrameAttachment());
}
BufferFrameAttachment& BufferScopeAttachment::GetFrameAttachment()
{
return static_cast<BufferFrameAttachment&>(ScopeAttachment::GetFrameAttachment());
}
const BufferScopeAttachment* BufferScopeAttachment::GetPrevious() const
{
return static_cast<const BufferScopeAttachment*>(ScopeAttachment::GetPrevious());
}
BufferScopeAttachment* BufferScopeAttachment::GetPrevious()
{
return static_cast<BufferScopeAttachment*>(ScopeAttachment::GetPrevious());
}
const BufferScopeAttachment* BufferScopeAttachment::GetNext() const
{
return static_cast<const BufferScopeAttachment*>(ScopeAttachment::GetNext());
}
BufferScopeAttachment* BufferScopeAttachment::GetNext()
{
return static_cast<BufferScopeAttachment*>(ScopeAttachment::GetNext());
}
}
}
| 34.686747 | 142 | 0.657173 |
65faebe41985ba4358f801d511d4a70b4b67e77d | 218 | cc | C++ | versus/go/01-lambdas/capture.cc | JohnMurray/cpp-vs | def49c416b5abf161241e7c1d8b41e6b01fb8cac | [
"Apache-2.0"
] | 10 | 2018-05-07T03:00:00.000Z | 2022-03-14T14:26:27.000Z | versus/ruby/01-lambda/capture.cc | JohnMurray/cpp-vs | def49c416b5abf161241e7c1d8b41e6b01fb8cac | [
"Apache-2.0"
] | 35 | 2018-05-26T16:01:58.000Z | 2022-03-30T22:39:33.000Z | versus/ruby/01-lambda/capture.cc | JohnMurray/cpp-vs | def49c416b5abf161241e7c1d8b41e6b01fb8cac | [
"Apache-2.0"
] | 1 | 2018-07-17T12:47:24.000Z | 2018-07-17T12:47:24.000Z | #include <functional>
template<typename T>
std::function<T(T)> addX(T x) {
return [x](T n) -> T {
return n + x;
};
}
int main() {
auto addFive = addX<int>(5);
addFive(10);
// returns 15
} | 14.533333 | 32 | 0.527523 |
65fd59e4cfabee14ace590ae06057ad149f9857e | 91 | cpp | C++ | lib/test.cpp | foxbao/dbscan_fast | 538d2319f555a9ddd1e4959517194df55a86a5a4 | [
"MIT"
] | null | null | null | lib/test.cpp | foxbao/dbscan_fast | 538d2319f555a9ddd1e4959517194df55a86a5a4 | [
"MIT"
] | null | null | null | lib/test.cpp | foxbao/dbscan_fast | 538d2319f555a9ddd1e4959517194df55a86a5a4 | [
"MIT"
] | null | null | null | #include "include/test.hpp"
auto test::add(int a,int b)->decltype(a+b)
{
return a+b;
} | 15.166667 | 42 | 0.637363 |
65fefcd021e89ecb4ed1e867b85cec1a999e58a0 | 1,155 | cpp | C++ | test/LoggerTest.cpp | StergeZissakis/cppInfrastructure | 4a80341b68186bbbc61edcbbb32ea68dde0323f4 | [
"Apache-2.0"
] | null | null | null | test/LoggerTest.cpp | StergeZissakis/cppInfrastructure | 4a80341b68186bbbc61edcbbb32ea68dde0323f4 | [
"Apache-2.0"
] | null | null | null | test/LoggerTest.cpp | StergeZissakis/cppInfrastructure | 4a80341b68186bbbc61edcbbb32ea68dde0323f4 | [
"Apache-2.0"
] | null | null | null | #include "gtest/gtest.h"
#include "utils/Logger.h"
#include "Globals.h"
#include <algorithm>
TEST(LoggerTest, CtorDtor)
{
{
Globals::clogStream->str("");
Logger log("LoggerTest", "AutoObject");
EXPECT_GT(Globals::clogStream->str().size(), 0);
Globals::clogStream->str("");
}
EXPECT_GT(Globals::clogStream->str().size(), 0);
Globals::clogStream->str("");
}
TEST(LoggerTest, logFunction)
{
Globals::clogStream->str("");
Logger log("LoggerTest", "LogFunction");
Globals::clogStream->str("");
std::string logMsg = "Test Message";
log.log(logMsg);
EXPECT_GT(Globals::clogStream->str().size(), 0);
std::string clogCtx = Globals::clogStream->str();
EXPECT_TRUE(std::search(clogCtx.begin(), clogCtx.end(), logMsg.begin(), logMsg.end()) != clogCtx.end());
}
TEST(LoggerTest, Disabled)
{
Globals::clogStream->str("");
Logger::enabled = false;
{
Logger log("LoggerTest", "Disabled");
EXPECT_EQ(Globals::clogStream->str().size(), 0);
log.log("sample test");
EXPECT_EQ(Globals::clogStream->str().size(), 0);
}
Logger::enabled = true;
EXPECT_EQ(Globals::clogStream->str().size(), 0);
}
| 23.571429 | 106 | 0.644156 |
65ff56baa07cf766ac826e1603c5b3da5df944a6 | 327 | cpp | C++ | examples/nested_cpp/test/main.cpp | trflynn89/flymake | 9dcfbfd43f7d7987e903940bfed3cc416c39c9cb | [
"MIT"
] | null | null | null | examples/nested_cpp/test/main.cpp | trflynn89/flymake | 9dcfbfd43f7d7987e903940bfed3cc416c39c9cb | [
"MIT"
] | 1 | 2021-02-09T02:53:26.000Z | 2021-02-09T02:53:26.000Z | examples/nested_cpp/test/main.cpp | trflynn89/flymake | 9dcfbfd43f7d7987e903940bfed3cc416c39c9cb | [
"MIT"
] | null | null | null | #include "nested_cpp/outer_lib/inner_lib/inner_lib.hpp"
#include "nested_cpp/outer_lib/outer_lib.hpp"
#include <cassert>
#include <iostream>
int main()
{
assert(outer::outer_value() == 123);
assert(inner::outer_value() == 123);
assert(inner::inner_value() == 1989);
std::cout << "Passed!\n";
return 0;
}
| 20.4375 | 55 | 0.666667 |
65ffc9b0a240192ee6b9cc3dfd054327cc20d6cc | 2,356 | cpp | C++ | Engine/src/Render/Camera/icMaxCam.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Render/Camera/icMaxCam.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Render/Camera/icMaxCam.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null |
#include "Render/Camera/icMaxCam.h"
#include "Core/IO/icInput.h"
#include "Math/Matrix/icMatrix44.h"
icMaxCam::icMaxCam( void )
{
m_rZoom = 100.0f;
m_rXrot = 0.0f;
m_rYrot = 0.0f;
m_rZoomMin = 50.0f;
m_rZoomMax = 500.0f;
m_v3Center.Set(0.0f,0.0f,0.0f);
bEnableInput = true;
}
icMaxCam::~icMaxCam( void )
{
}
void icMaxCam::Update( const float fDeltaTime )
{
if (bEnableInput)
{
icInput* input = icInput::Instance();
if (input->IsDown(ICMOUSE_M) || input->IsDown(ICMOUSE_R))
{
if (input->IsDown(ICKEY_LALT))
{
// arc rotate
icReal x = input->GetAxis(ICAXIS_MOUSE_X) * fDeltaTime * 5000.0f * m_rZoom/m_rZoomMax;
icReal y = input->GetAxis(ICAXIS_MOUSE_Y) * fDeltaTime * 5000.0f * m_rZoom/m_rZoomMax;
if (m_rYrot > 0)
m_rYrot += y;
else
m_rYrot -= y;
m_rXrot -= x;
}
else
{
// pan
icReal z_amt = (m_rZoom - m_rZoomMin) + 0.05f * (m_rZoomMax - m_rZoomMin);
icReal x = input->GetAxis(ICAXIS_MOUSE_X) * fDeltaTime * 200.0f * z_amt;
icReal y = input->GetAxis(ICAXIS_MOUSE_Y) * fDeltaTime * 200.0f * z_amt;
m_v3Center += m_m44ViewMat.Transform(-x,-y,0.0f);
}
}
// handle zoom
icReal zoom = input->GetAxis(ICAXIS_MOUSE_Z);
m_rZoom -= zoom * fDeltaTime * 1000.0f;
m_rZoom = icClamp(m_rZoom, m_rZoomMin, m_rZoomMax);
}
// trimming
while (m_rYrot > IC_PI * 2.0f)
m_rYrot -= 2 * IC_PI;
while (m_rYrot < 0.0f)
m_rYrot += 2 * IC_PI;
while (m_rXrot > IC_PI * 2.0f)
m_rXrot -= 2 * IC_PI;
while (m_rXrot < 0.0f)
m_rXrot += 2 * IC_PI;
icReal theta = m_rXrot;
icReal phi = m_rYrot - IC_PI;
icReal Cx, Cy, Cz;
Cx = m_rZoom * icCos(theta) * icSin(phi);
Cy = m_rZoom * icCos(phi);
Cz = m_rZoom * icSin(theta) * icSin(phi);
icVector3 point(Cx,Cy,Cz);
icVector3 position = point + m_v3Center;
if (phi < 0.0)
icCreateLookAt(position, m_v3Center,icVector3(0.0f,-1.0,0.0f),m_m44ViewMat);
else
icCreateLookAt(position, m_v3Center,icVector3::Y_AXIS,m_m44ViewMat);
} | 26.47191 | 102 | 0.547114 |
5a0041876ba8347ac3bbbac0ac4158cb21da0ab3 | 804 | cpp | C++ | LeetCode/Daily-Challenge/Evaluate Reverse Polish Notation.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | 5 | 2021-02-14T17:48:21.000Z | 2022-01-24T14:29:44.000Z | LeetCode/Daily-Challenge/Evaluate Reverse Polish Notation.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | LeetCode/Daily-Challenge/Evaluate Reverse Polish Notation.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | class Solution {
public:
int evalRPN(vector<string>& tokens) {
stack<int> stk;
int a, b, res;
for(string i: tokens){
if(isOperator(i)){
a = stk.top();
stk.pop();
b = stk.top();
stk.pop();
if(i=="+") res = a+b;
else if(i=="-") res = b-a;
else if(i=="*") res = b*a;
else if(i=="/") res = b/a;
stk.push(res);
}
else {
stk.push(stoi(i));
}
}
return stk.top();
}
private:
bool isOperator(string ch){
if(ch=="+" or ch=="-" or ch=="*" or ch=="/") return true;
return false;
}
};
| 23.647059 | 65 | 0.334577 |
5a0052e98e648bb4eb323ab2d2191dcca614cd58 | 965 | cpp | C++ | workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp | wictus/oldScopeAnalysis | e8a15f11c504c1a1a880d4a5096cdbfac0edf2de | [
"MIT"
] | null | null | null | workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp | wictus/oldScopeAnalysis | e8a15f11c504c1a1a880d4a5096cdbfac0edf2de | [
"MIT"
] | null | null | null | workdir/ScopeAnalysis/LORAnalysis/SDAEstimateTOFCalib.cpp | wictus/oldScopeAnalysis | e8a15f11c504c1a1a880d4a5096cdbfac0edf2de | [
"MIT"
] | null | null | null | #include "./SDAEstimateTOFCalib.h"
SDAEstimateTOFCalib::SDAEstimateTOFCalib(const char* name, const char* title,
const char* in_file_suffix, const char* out_file_suffix, const double threshold) : JPetCommonAnalysisModule( name, title, in_file_suffix, out_file_suffix )
{
fSelectedThreshold = threshold;
}
SDAEstimateTOFCalib::~SDAEstimateTOFCalib(){}
void SDAEstimateTOFCalib::begin()
{
}
void SDAEstimateTOFCalib::exec()
{
fReader->getEntry(fEvent);
const JPetLOR& fLOR = dynamic_cast< JPetLOR& > ( fReader->getData() );
fTOFs.push_back( ( fLOR.getSecondHit().getTime() - fLOR.getFirstHit().getTime() ) );
fEvent++;
}
void SDAEstimateTOFCalib::end()
{
gStyle->SetOptFit(1);
TCanvas* c1 = new TCanvas();
TH1F* TOF = new TH1F("TOF", "TOF", 2000, -10, 10);
for( unsigned int i = 0; i < fTOFs.size(); i++)
{
TOF->Fill(fTOFs[i]/1000.0);
}
TOF->Sumw2();
TOF->Draw();
TOF->Fit("gaus","QI");
c1->SaveAs("TOF.png");
}
| 21.444444 | 170 | 0.674611 |
5a0780f127bedfcf86ba645ff619e9b50688403d | 3,445 | cpp | C++ | activemq-cpp/src/main/decaf/internal/util/concurrent/windows/Atomics.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 87 | 2015-03-02T17:58:20.000Z | 2022-02-11T02:52:52.000Z | activemq-cpp/src/main/decaf/internal/util/concurrent/windows/Atomics.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 3 | 2017-05-10T13:16:08.000Z | 2019-01-23T20:21:53.000Z | activemq-cpp/src/main/decaf/internal/util/concurrent/windows/Atomics.cpp | novomatic-tech/activemq-cpp | d6f76ede90d21b7ee2f0b5d4648e440e66d63003 | [
"Apache-2.0"
] | 71 | 2015-04-28T06:04:04.000Z | 2022-03-15T13:34:06.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <decaf/internal/util/concurrent/Atomics.h>
using namespace decaf::internal;
using namespace decaf::internal::util;
using namespace decaf::internal::util::concurrent;
////////////////////////////////////////////////////////////////////////////////
void Atomics::initialize() {
}
////////////////////////////////////////////////////////////////////////////////
void Atomics::shutdown() {
}
////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet32(volatile int* target, int expect, int update ) {
return ::InterlockedCompareExchange((volatile LONG*)target, update, expect) == (unsigned int)expect;
}
////////////////////////////////////////////////////////////////////////////////
bool Atomics::compareAndSet(volatile void** target, void* expect, void* update) {
return ::InterlockedCompareExchangePointer((volatile PVOID*)target, (void*)update, (void*)expect ) == (void*)expect;
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndSet(volatile int* target, int newValue) {
return ::InterlockedExchange((volatile LONG*)target, newValue);
}
////////////////////////////////////////////////////////////////////////////////
void* Atomics::getAndSet(volatile void** target, void* newValue) {
return InterlockedExchangePointer((volatile PVOID*)target, newValue);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndIncrement(volatile int* target) {
return ::InterlockedIncrement((volatile LONG*)target) - 1;
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndDecrement(volatile int* target) {
return ::InterlockedExchangeAdd((volatile LONG*)target, 0xFFFFFFFF);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::getAndAdd(volatile int* target, int delta) {
return ::InterlockedExchangeAdd((volatile LONG*)target, delta);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::addAndGet(volatile int* target, int delta) {
return ::InterlockedExchangeAdd((volatile LONG*)target, delta) + delta;
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::incrementAndGet(volatile int* target) {
return ::InterlockedIncrement((volatile LONG*)target);
}
////////////////////////////////////////////////////////////////////////////////
int Atomics::decrementAndGet(volatile int* target) {
return ::InterlockedExchangeAdd((volatile LONG*)target, 0xFFFFFFFF) - 1;
}
| 42.012195 | 120 | 0.53701 |
5a08229b925f117033174e8422230e6102f958af | 1,884 | cpp | C++ | Algorithms/0047.PermutationsII/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0047.PermutationsII/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | Algorithms/0047.PermutationsII/solution.cpp | stdstring/leetcode | 84e6bade7d6fc1a737eb6796cb4e2565440db5e3 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <vector>
#include "gtest/gtest.h"
namespace
{
class Solution
{
public:
std::vector<std::vector<int>> permuteUnique(std::vector<int> const &nums) const
{
std::vector<int> numbers(nums);
std::sort(numbers.begin(), numbers.end());
std::vector<bool> usedNumbers;
for (size_t index = 0; index < numbers.size(); ++index)
usedNumbers.push_back(false);
std::vector<int> current;
std::vector<std::vector<int>> dest;
generate(numbers, usedNumbers, current, dest);
return dest;
}
private:
void generate(std::vector<int> const &numbers, std::vector<bool> &usedNumbers, std::vector<int> ¤t, std::vector<std::vector<int>> &dest) const
{
size_t lastUsedIndex = numbers.size();
for (size_t index = 0; index < numbers.size(); ++index)
{
if (!usedNumbers[index])
{
if (lastUsedIndex != numbers.size() && numbers[lastUsedIndex] == numbers[index])
continue;
lastUsedIndex = index;
current.push_back(numbers[index]);
const bool isPermutation = current.size() == numbers.size();
if (isPermutation)
dest.push_back(current);
else
{
usedNumbers[index] = true;
generate(numbers, usedNumbers, current, dest);
usedNumbers[index] = false;
}
current.pop_back();
if (isPermutation)
return;
}
}
}
};
}
namespace PermutationsIITask
{
TEST(PermutationsIITaskTests, Examples)
{
const Solution solution;
ASSERT_EQ(std::vector<std::vector<int>>({{1, 1, 2}, {1, 2, 1}, {2, 1, 1}}), solution.permuteUnique({1, 1, 2}));
}
}
| 28.545455 | 152 | 0.54034 |
5a0b3da50722a12d419492b05989a6f544aef9dc | 1,006 | cpp | C++ | Binary_tree_Queue/Binary Tree-Queue.cpp | yuhsiang131/DSPractice | 3cfcbfc298eaa6a3e7202b1e93c257990b43ed9b | [
"MIT"
] | 1 | 2020-11-07T12:20:43.000Z | 2020-11-07T12:20:43.000Z | Binary_tree_Queue/Binary Tree-Queue.cpp | yuhsiang131/DSPractice | 3cfcbfc298eaa6a3e7202b1e93c257990b43ed9b | [
"MIT"
] | null | null | null | Binary_tree_Queue/Binary Tree-Queue.cpp | yuhsiang131/DSPractice | 3cfcbfc298eaa6a3e7202b1e93c257990b43ed9b | [
"MIT"
] | null | null | null | #include <iostream>
#include <queue>
using namespace std;
struct node{
char data;
struct node *left;
struct node *right;
};
queue<node*> qu;
void levelorder(node*);
int main(void){
node *root,*p1,*p2,*p3,*p4,*p5,*p6,*p7;
p1=new node;
p1->data='1';
root=p1;
p2=new node;
p2->data='2';
p3=new node;
p3->data='3';
p4=new node;
p4->data='4';
p5=new node;
p5->data='5';
p6=new node;
p6->data='6';
p7=new node;
p7->data='7';
p1->left=p2;
p1->right=p3;
p2->left=p4;
p2->right=p5;
p3->left=NULL;
p3->right=p6;
p4->left=NULL;
p4->right=p7;
p5->left=NULL;
p5->right=NULL;
p6->left=NULL;
p6->right=NULL;
p7->left=NULL;
p7->right=NULL;
levelorder(root);
cout << endl;
}
void levelorder(node *now){
qu.push(now);
while (!qu.empty()){
cout << qu.front()->data <<" ";
if (qu.front()->left!=NULL) {
qu.push(qu.front()->left);
}
if (qu.front()->right!=NULL){
qu.push(qu.front()->right);
}
qu.pop();
}
}
| 17.344828 | 41 | 0.55666 |
5a0bcd08a291c33b3102bcf3b66a712a36d9e8d3 | 7,830 | cc | C++ | drivers/bluetooth/lib/sm/util.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | drivers/bluetooth/lib/sm/util.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | drivers/bluetooth/lib/sm/util.cc | PowerOlive/garnet | 16b5b38b765195699f41ccb6684cc58dd3512793 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "util.h"
#include <openssl/aes.h>
#include <zircon/assert.h>
#include "garnet/drivers/bluetooth/lib/hci/util.h"
namespace btlib {
using common::BufferView;
using common::ByteBuffer;
using common::DeviceAddress;
using common::UInt128;
namespace sm {
namespace util {
namespace {
constexpr size_t kPreqSize = 7;
// Swap the endianness of a 128-bit integer. |in| and |out| should not be backed
// by the same buffer.
void Swap128(const UInt128& in, UInt128* out) {
ZX_DEBUG_ASSERT(out);
for (size_t i = 0; i < in.size(); ++i) {
(*out)[i] = in[in.size() - i - 1];
}
}
// XOR two 128-bit integers and return the result in |out|. It is possible to
// pass a pointer to one of the inputs as |out|.
void Xor128(const UInt128& int1, const UInt128& int2, UInt128* out) {
ZX_DEBUG_ASSERT(out);
uint64_t lower1 = *reinterpret_cast<const uint64_t*>(int1.data());
uint64_t upper1 = *reinterpret_cast<const uint64_t*>(int1.data() + 8);
uint64_t lower2 = *reinterpret_cast<const uint64_t*>(int2.data());
uint64_t upper2 = *reinterpret_cast<const uint64_t*>(int2.data() + 8);
uint64_t lower_res = lower1 ^ lower2;
uint64_t upper_res = upper1 ^ upper2;
std::memcpy(out->data(), &lower_res, 8);
std::memcpy(out->data() + 8, &upper_res, 8);
}
} // namespace
std::string IOCapabilityToString(IOCapability capability) {
switch (capability) {
case IOCapability::kDisplayOnly:
return "Display Only";
case IOCapability::kDisplayYesNo:
return "Display w/ Confirmation";
case IOCapability::kKeyboardOnly:
return "Keyboard";
case IOCapability::kNoInputNoOutput:
return "No I/O";
case IOCapability::kKeyboardDisplay:
return "Keyboard w/ Display";
default:
break;
}
return "(unknown)";
};
std::string PairingMethodToString(PairingMethod method) {
switch (method) {
case PairingMethod::kJustWorks:
return "Just Works";
case PairingMethod::kPasskeyEntryInput:
return "Passkey Entry (input)";
case PairingMethod::kPasskeyEntryDisplay:
return "Passkey Entry (display)";
case PairingMethod::kNumericComparison:
return "Numeric Comparison";
case PairingMethod::kOutOfBand:
return "OOB";
default:
break;
}
return "(unknown)";
}
PairingMethod SelectPairingMethod(bool sec_conn, bool local_oob, bool peer_oob,
bool mitm_required, IOCapability local_ioc,
IOCapability peer_ioc, bool local_initiator) {
if ((sec_conn && (local_oob || peer_oob)) ||
(!sec_conn && local_oob && peer_oob)) {
return PairingMethod::kOutOfBand;
}
// If neither device requires MITM protection or if the peer has not I/O
// capable, we select Just Works.
if (!mitm_required || peer_ioc == IOCapability::kNoInputNoOutput) {
return PairingMethod::kJustWorks;
}
// Select the pairing method by comparing I/O capabilities. The switch
// statement will return if an authenticated entry method is selected.
// Otherwise, we'll break out and default to Just Works below.
switch (local_ioc) {
case IOCapability::kNoInputNoOutput:
break;
case IOCapability::kDisplayOnly:
switch (peer_ioc) {
case IOCapability::kKeyboardOnly:
case IOCapability::kKeyboardDisplay:
return PairingMethod::kPasskeyEntryDisplay;
default:
break;
}
break;
case IOCapability::kDisplayYesNo:
switch (peer_ioc) {
case IOCapability::kDisplayYesNo:
return sec_conn ? PairingMethod::kNumericComparison
: PairingMethod::kJustWorks;
case IOCapability::kKeyboardDisplay:
return sec_conn ? PairingMethod::kNumericComparison
: PairingMethod::kPasskeyEntryDisplay;
case IOCapability::kKeyboardOnly:
return PairingMethod::kPasskeyEntryDisplay;
default:
break;
}
break;
case IOCapability::kKeyboardOnly:
return PairingMethod::kPasskeyEntryInput;
case IOCapability::kKeyboardDisplay:
switch (peer_ioc) {
case IOCapability::kKeyboardOnly:
return PairingMethod::kPasskeyEntryDisplay;
case IOCapability::kDisplayOnly:
return PairingMethod::kPasskeyEntryInput;
case IOCapability::kDisplayYesNo:
return sec_conn ? PairingMethod::kNumericComparison
: PairingMethod::kPasskeyEntryInput;
default:
break;
}
// If both devices have KeyboardDisplay then use Numeric Comparison
// if S.C. is supported. Otherwise, the initiator always displays and the
// responder inputs a passkey.
if (sec_conn) {
return PairingMethod::kNumericComparison;
}
return local_initiator ? PairingMethod::kPasskeyEntryDisplay
: PairingMethod::kPasskeyEntryInput;
}
return PairingMethod::kJustWorks;
}
void Encrypt(const common::UInt128& key, const common::UInt128& plaintext_data,
common::UInt128* out_encrypted_data) {
// Swap the bytes since "the most significant octet of key corresponds to
// key[0], the most significant octet of plaintextData corresponds to in[0]
// and the most significant octet of encryptedData corresponds to out[0] using
// the notation specified in FIPS-197" for the security function "e" (Vol 3,
// Part H, 2.2.1).
UInt128 be_k, be_pt, be_enc;
Swap128(key, &be_k);
Swap128(plaintext_data, &be_pt);
AES_KEY k;
AES_set_encrypt_key(be_k.data(), 128, &k);
AES_encrypt(be_pt.data(), be_enc.data(), &k);
Swap128(be_enc, out_encrypted_data);
}
void C1(const UInt128& tk, const UInt128& rand, const ByteBuffer& preq,
const ByteBuffer& pres, const DeviceAddress& initiator_addr,
const DeviceAddress& responder_addr, UInt128* out_confirm_value) {
ZX_DEBUG_ASSERT(preq.size() == kPreqSize);
ZX_DEBUG_ASSERT(pres.size() == kPreqSize);
ZX_DEBUG_ASSERT(out_confirm_value);
UInt128 p1, p2;
// Calculate p1 = pres || preq || ratโ || iatโ
hci::LEAddressType iat = hci::AddressTypeToHCI(initiator_addr.type());
hci::LEAddressType rat = hci::AddressTypeToHCI(responder_addr.type());
p1[0] = static_cast<uint8_t>(iat);
p1[1] = static_cast<uint8_t>(rat);
std::memcpy(p1.data() + 2, preq.data(), preq.size()); // Bytes [2-8]
std::memcpy(p1.data() + 2 + preq.size(), pres.data(), pres.size()); // [9-15]
// Calculate p2 = padding || ia || ra
BufferView ia = initiator_addr.value().bytes();
BufferView ra = responder_addr.value().bytes();
std::memcpy(p2.data(), ra.data(), ra.size()); // Lowest 6 bytes
std::memcpy(p2.data() + ra.size(), ia.data(), ia.size()); // Next 6 bytes
std::memset(p2.data() + ra.size() + ia.size(), 0,
p2.size() - ra.size() - ia.size()); // Pad 0s for the remainder
// Calculate the confirm value: e(tk, e(tk, rand XOR p1) XOR p2)
UInt128 tmp;
Xor128(rand, p1, &p1);
Encrypt(tk, p1, &tmp);
Xor128(tmp, p2, &tmp);
Encrypt(tk, tmp, out_confirm_value);
}
void S1(const UInt128& tk, const UInt128& r1, const UInt128& r2,
UInt128* out_stk) {
ZX_DEBUG_ASSERT(out_stk);
UInt128 r_prime;
// Take the lower 64-bits of r1 and r2 and concatanate them to produce
// rโ = r1โ || r2โ, where r2' contains the LSB and r1' the MSB.
constexpr size_t kHalfSize = sizeof(UInt128) / 2;
std::memcpy(r_prime.data(), r2.data(), kHalfSize);
std::memcpy(r_prime.data() + kHalfSize, r1.data(), kHalfSize);
// Calculate the STK: e(tk, rโ)
Encrypt(tk, r_prime, out_stk);
}
} // namespace util
} // namespace sm
} // namespace btlib
| 33.319149 | 80 | 0.667816 |
5a0c05852f5fee16463d763adeb77c37cc9d6582 | 1,579 | cc | C++ | chrome/browser/notifications/notification_ui_manager_android.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-01-25T10:18:18.000Z | 2021-01-23T15:29:56.000Z | chrome/browser/notifications/notification_ui_manager_android.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | chrome/browser/notifications/notification_ui_manager_android.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/notifications/notification_ui_manager_android.h"
#include "base/logging.h"
// static
NotificationUIManager* NotificationUIManager::Create(PrefService* local_state) {
return new NotificationUIManagerAndroid();
}
NotificationUIManagerAndroid::NotificationUIManagerAndroid() {
}
NotificationUIManagerAndroid::~NotificationUIManagerAndroid() {
}
void NotificationUIManagerAndroid::Add(const Notification& notification,
Profile* profile) {
// TODO(peter): Implement the NotificationUIManagerAndroid class.
NOTIMPLEMENTED();
}
bool NotificationUIManagerAndroid::Update(const Notification& notification,
Profile* profile) {
return false;
}
const Notification* NotificationUIManagerAndroid::FindById(
const std::string& notification_id) const {
return 0;
}
bool NotificationUIManagerAndroid::CancelById(
const std::string& notification_id) {
return false;
}
std::set<std::string>
NotificationUIManagerAndroid::GetAllIdsByProfileAndSourceOrigin(
Profile* profile,
const GURL& source) {
return std::set<std::string>();
}
bool NotificationUIManagerAndroid::CancelAllBySourceOrigin(
const GURL& source_origin) {
return false;
}
bool NotificationUIManagerAndroid::CancelAllByProfile(Profile* profile) {
return false;
}
void NotificationUIManagerAndroid::CancelAll() {
}
| 26.762712 | 80 | 0.746042 |
5a0d965c55380224342d8d28d30040184eb17c93 | 13,154 | cpp | C++ | src/learning/learning.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | 1 | 2022-02-24T03:39:05.000Z | 2022-02-24T03:39:05.000Z | src/learning/learning.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | 1 | 2022-02-24T06:59:59.000Z | 2022-03-04T01:25:09.000Z | src/learning/learning.cpp | raphaelsulzer/mesh-tools | 73150bec58813e2b9b750205807002a1c3f18884 | [
"MIT"
] | null | null | null | #include <base/cgal_typedefs.h>
#include <IO/fileIO.h>
#include <util/helper.h>
#include <util/geometricOperations.h>
#include <processing/tetIntersection.h>
#include <processing/rayTracingTet.h>
#include <processing/meshProcessing.h>
#include <processing/graphCut.h>
#include <processing/edgeManifoldness.h>
#include <processing/pointSetProcessing.h>
#include <processing/meshProcessing.h>
#include <learning/learning.h>
#include <learning/learningMath.h>
#include <learning/learningRayTracing.h>
#include <learning/learningIO.h>
#include <CGAL/point_generators_3.h>
#include <CGAL/Random.h>
#include <CGAL/boost/graph/convert_nef_polyhedron_to_polygon_mesh.h>
#include <CGAL/boost/graph/graph_traits_Polyhedron_3.h>
#include <boost/foreach.hpp>
#include <CGAL/Polygon_mesh_processing/distance.h>
#include <CGAL/polygon_mesh_processing.h>
#include <CGAL/optimal_bounding_box.h>
#include <CGAL/Side_of_triangle_mesh.h>
#include <util/helper.h>
#include <random>
using namespace std;
int labelObjectWithOpenGroundTruth(dirHolder dir, dataHolder& data, int sampling_points){
auto start = std::chrono::high_resolution_clock::now();
if(data.gt_poly.size_of_vertices() == 0){
cout << "\nERROR: you need to load a ground truth polygon (with -g) for scanning it" << endl;
return 1;
}
assert(sampling_points > 0);
cout << "\nLabelling cells with open ground truth and ray tracing..." << endl;
cout << "\t-sample " << sampling_points << endl;
// Initialize the point-in-polyhedron tester
// Construct AABB tree with a KdTree
SurfaceMesh smesh;
CGAL::copy_face_graph(data.gt_poly, smesh);
CGAL::Polygon_mesh_processing::remove_connected_components_of_negligible_size(smesh);
// dir.suffix = "_repaired_mesh";
// exportOFF(dir,smesh);
// cout << "gt centroid: " << data.gt_centroid << endl;
// Tree tree(faces(smesh).first, faces(smesh).second, smesh);
vector<face_descriptor> fds;
for(face_descriptor fd : faces(smesh)){
if(!CGAL::Polygon_mesh_processing::is_degenerate_triangle_face(fd,smesh))
fds.push_back(fd);
}
Tree tree(fds.begin(), fds.end(), smesh);
tree.accelerate_distance_queries();
// Polyhedron poly;
// CGAL::copy_face_graph(data.sm_obb, poly);
// Tree bb_tree(faces(data.sm_obb).first, faces(data.sm_obb).second, data.sm_obb);
// const Point_inside inside_bb(data.sm_obb);
int icount = 0;
int ncount = 0;
Delaunay::All_cells_iterator aci;
// random sampler
CGAL::Random random(42);
vector<Point> sampled_points;
double iperc;
double operc;
int newCellIndex = 0;
vector<Point> all_sampled_points;
vector<vertex_info> all_sampled_infos;
int progress = 0;
int total = data.Dt.number_of_cells();
for(aci = data.Dt.all_cells_begin(); aci != data.Dt.all_cells_end(); aci++){
// cout << progress++ << endl;
// if((progress*100/total) % 10 == 0 && (++progress*100/total) % 10 != 0)
// cout << progress << "/" << total << endl;
aci->info().global_idx=newCellIndex++;
if(data.Dt.is_infinite(aci)){
aci->info().gc_label = 1; // more likely that it is outside
aci->info().inside_score = 0.0;
aci->info().outside_score = 1.0;
continue;
}
// sample points inside the tet and check if they are inside or outside
double cinside=0;
double coutside=0;
Tetrahedron current_tet = data.Dt.tetrahedron(aci);
CGAL::Random_points_in_tetrahedron_3<Point> tet_point_sampler(current_tet, random);
sampled_points.clear();
CGAL::cpp11::copy_n(tet_point_sampler, sampling_points, std::back_inserter(sampled_points));
for(auto const& sampled_point : sampled_points){
// all_sampled_points.push_back(sampled_point);
// vertex_info vi;
// if(inside_bb(sampled_point) == CGAL::ON_UNBOUNDED_SIDE){
// vi.color = CGAL::violet();
// all_sampled_infos.push_back(vi);
// cinside+=1.0;
// }
// else{
Segment seg(sampled_point,data.gt_centroid);
int n = tree.number_of_intersected_primitives(seg);
// cout << "number of intersected primitives: " << n << endl;
if(n % 2){
cinside+=1.0;
// vi.color = CGAL::red();
// all_sampled_infos.push_back(vi);
}
else{
coutside+=1.0;
// vi.color = CGAL::blue();
// all_sampled_infos.push_back(vi);
}
// if(n == 0)
// vi.color = CGAL::yellow();
// else if(n == 1)
// vi.color = CGAL::green();
// else if(n == 2)
// vi.color = CGAL::blue();
// else if(n == 3)
// vi.color = CGAL::red();
// else
// vi.color = CGAL::black();
// all_sampled_infos.push_back(vi);
// }
}
iperc = cinside/(cinside+coutside);
operc = coutside/(cinside+coutside);
aci->info().outside_score = operc;
aci->info().inside_score = iperc;
// aci->info().gt_outside = operc;
// aci->info().gt_inside = iperc;
if(operc>iperc){
ncount++;
// aci->info().gc_label = 1;
}
else{
icount++;
// aci->info().gc_label = 0;
}
}
// dir.suffix = "_sampled";
// exportOptions eo;
// eo.color = true;
// exportPLY(dir,all_sampled_points,all_sampled_infos,eo);
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "\t-Labelled object with " << icount << "/" << ncount << "(inside/outside) = " << icount+ncount << " cells" << endl;
cout << "\t-in "<<duration.count() << "s" << endl;
if(icount == 0 || ncount == 0){
cout << "\nERROR: cells could not be labelled" << endl;
return 1;
}
return 0;
}
int labelObjectWithClosedGroundTruth(dirHolder dir, dataHolder& data, int sampling_points){
auto start = std::chrono::high_resolution_clock::now();
if(data.gt_poly.size_of_vertices() == 0){
cout << "\nERROR: you need to load a ground truth polygon (with -g) for scanning it" << endl;
return 1;
}
if(!data.gt_poly.is_closed()){
cout << "\nERROR: ground truth is not closed" << endl;
return 1;
}
assert(sampling_points > 0);
cout << "\nLabelling cells by sampling points inside cells..." << endl;
cout << "\t-sample " << sampling_points << endl;
// Initialize the point-in-polyhedron tester
// Construct AABB tree with a KdTree
SurfaceMesh smesh;
CGAL::copy_face_graph(data.gt_poly, smesh);
Tree tree(faces(smesh).first, faces(smesh).second, smesh);
// Tree tree(faces(data.gt_poly).first, faces(data.gt_poly).second, data.gt_poly);
tree.accelerate_distance_queries();
// Initialize the point-in-polyhedron tester
const Point_inside inside_tester(tree);
// Polyhedron poly;
// CGAL::copy_face_graph(data.sm_obb, poly);
//// Tree bb_tree(faces(data.sm_obb).first, faces(data.sm_obb).second, data.sm_obb);
// const Point_inside inside_bb(poly);
int icount = 0;
int ncount = 0;
Delaunay::All_cells_iterator aci;
// random sampler
CGAL::Random random(42);
vector<Point> sampled_points;
double iperc;
double operc;
int newCellIndex = 0;
vector<Point> all_sampled_points;
vector<vertex_info> all_sampled_infos;
for(aci = data.Dt.all_cells_begin(); aci != data.Dt.all_cells_end(); aci++){
aci->info().global_idx=newCellIndex++;
if(data.Dt.is_infinite(aci)){
aci->info().gc_label = 1; // more likely that it is outside
aci->info().inside_score = 0.0;
aci->info().outside_score = 1.0;
continue;
}
// sample points inside the tet and check if they are inside or outside
double cinside=0;
double coutside=0;
Tetrahedron current_tet = data.Dt.tetrahedron(aci);
CGAL::Random_points_in_tetrahedron_3<Point> tet_point_sampler(current_tet, random);
sampled_points.clear();
CGAL::cpp11::copy_n(tet_point_sampler, sampling_points, std::back_inserter(sampled_points));
for(auto const& sampled_point : sampled_points){
// all_sampled_points.push_back(sampled_point);
// vertex_info vi;
//// cout<<"\t check point "<< pcount++ <<"/"<<sampling_points<<endl;
// if(inside_bb(sampled_point) != CGAL::ON_BOUNDED_SIDE){
// vi.color = CGAL::green();
// all_sampled_infos.push_back(vi);
// coutside+=1.0;
// continue;
// }
if(inside_tester(sampled_point) == CGAL::ON_BOUNDED_SIDE){
cinside+=1.0;
// vi.color = CGAL::red();
// all_sampled_infos.push_back(vi);
}
else{
coutside+=1.0;
// vi.color = CGAL::blue();
// all_sampled_infos.push_back(vi);
}
}
iperc = cinside/(cinside+coutside);
operc = coutside/(cinside+coutside);
aci->info().outside_score = operc;
aci->info().inside_score = iperc;
if(operc>iperc){
ncount++;
// aci->info().gc_label = 1;
}
else{
icount++;
// aci->info().gc_label = 0;
}
}
// dir.suffix = "_sampled";
// exportOptions eo;
// eo.color = true;
// exportPLY(dir,all_sampled_points,all_sampled_infos,eo);
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "\t-Labelled object with " << icount << "/" << ncount << "(inside/outside) = " << icount+ncount << " cells" << endl;
cout << "\t-in "<<duration.count() << "s" << endl;
if(icount == 0 || ncount == 0){
cout << "\nERROR: cells could not be labelled" << endl;
return 1;
}
return 0;
}
#ifdef RECONBENCH
int labelObjectWithImplicit(dataHolder& data, int sampling_points){
auto start = std::chrono::high_resolution_clock::now();
assert(sampling_points > 0);
cout << "\nLabelling cells by sampling points inside cells: " << endl;
cout << "\t-sample " << sampling_points << endl;
int icount = 0;
int ncount = 0;
Delaunay::All_cells_iterator aci;
// random sampler
CGAL::Random random(42);
vector<Point> sampled_points;
double iperc;
double operc;
int newCellIndex = 0;
for(aci = data.Dt.all_cells_begin(); aci != data.Dt.all_cells_end(); aci++){
if(data.Dt.is_infinite(aci)){
aci->info().gc_label = 1; // more likely that it is outside
aci->info().inside_score = 0.2;
aci->info().outside_score = 0.8;
aci->info().global_idx=newCellIndex++;
continue;
}
aci->info().global_idx=newCellIndex++;
// sample points inside the tet and check if they are inside or outside
double cinside=0;
double coutside=0;
Tetrahedron current_tet = data.Dt.tetrahedron(aci);
CGAL::Random_points_in_tetrahedron_3<Point> tet_point_sampler(current_tet, random);
sampled_points.clear();
CGAL::cpp11::copy_n(tet_point_sampler, sampling_points, std::back_inserter(sampled_points));
for(auto const& sampled_point : sampled_points){
auto sampled_point_rb = point2Vector3RB(sampled_point);
if(data.implicit->function(sampled_point_rb) <= 0.0){
cinside+=1.0;
// Color col = CGAL::make_array((unsigned char)255, (unsigned char)0, (unsigned char)0);
// vertex_info vi;
// vi.color = col;
// all_sampled_infos.push_back(vi);
}
else{
coutside+=1.0;
// Color col = CGAL::make_array((unsigned char)0, (unsigned char)0, (unsigned char)255);
// vertex_info vi;
// vi.color = col;
// all_sampled_infos.push_back(vi);
}
}
iperc = cinside/(cinside+coutside);
operc = coutside/(cinside+coutside);
aci->info().outside_score = operc;
aci->info().inside_score = iperc;
if(operc>iperc){
ncount++;
aci->info().gc_label = 1;
}
else{
icount++;
aci->info().gc_label = 0;
}
}
auto stop = chrono::high_resolution_clock::now();
auto duration = chrono::duration_cast<std::chrono::seconds>(stop - start);
cout << "\t-Labelled object with " << icount << "/" << ncount << "(inside/outside) = " << icount+ncount << " cells" << endl;
cout << "\t-in "<<duration.count() << "s" << endl;
if(icount == 0 || ncount == 0)
return 0;
return 1;
}
#endif
| 34.344648 | 128 | 0.592443 |
5a110d9ca6988282ec336215a807428ea875e35f | 850 | hpp | C++ | pomdog/experimental/gui/debug_navigator.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 163 | 2015-03-16T08:42:32.000Z | 2022-01-11T21:40:22.000Z | pomdog/experimental/gui/debug_navigator.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 17 | 2015-04-12T20:57:50.000Z | 2020-10-10T10:51:45.000Z | pomdog/experimental/gui/debug_navigator.hpp | mogemimi/pomdog | 6dc6244d018f70d42e61c6118535cf94a9ee0618 | [
"MIT"
] | 21 | 2015-04-12T20:45:11.000Z | 2022-01-14T20:50:16.000Z | // Copyright mogemimi. Distributed under the MIT license.
#pragma once
#include "pomdog/basic/conditional_compilation.hpp"
#include "pomdog/chrono/duration.hpp"
#include "pomdog/chrono/game_clock.hpp"
#include "pomdog/experimental/gui/widget.hpp"
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_BEGIN
#include <deque>
#include <memory>
#include <string>
POMDOG_SUPPRESS_WARNINGS_GENERATED_BY_STD_HEADERS_END
namespace pomdog::gui {
class DebugNavigator final : public Widget {
public:
DebugNavigator(
const std::shared_ptr<UIEventDispatcher>& dispatcher,
const std::shared_ptr<GameClock>& clock);
void Draw(DrawingContext& drawingContext) override;
private:
std::shared_ptr<GameClock> clock;
std::deque<float> frameRates;
Duration duration;
std::string frameRateString;
};
} // namespace pomdog::gui
| 25 | 61 | 0.770588 |
5a12ddf110bcc68350b8090456384324420b49ae | 50,337 | cpp | C++ | data/cpp/7fa0c21b51343873f0140b810c2823ea_CraftingSessionHelper.cpp | maxim5/code-inspector | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | [
"Apache-2.0"
] | 5 | 2018-01-03T06:43:07.000Z | 2020-07-30T13:15:29.000Z | data/cpp/7fa0c21b51343873f0140b810c2823ea_CraftingSessionHelper.cpp | maxim5/code-inspector | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | [
"Apache-2.0"
] | null | null | null | data/cpp/7fa0c21b51343873f0140b810c2823ea_CraftingSessionHelper.cpp | maxim5/code-inspector | 14812dfbc7bac1d76c4d9e5be2cdf83fc1c391a1 | [
"Apache-2.0"
] | 2 | 2019-11-04T02:54:49.000Z | 2020-04-24T17:50:46.000Z | /*
---------------------------------------------------------------------------------------
This source file is part of SWG:ANH (Star Wars Galaxies - A New Hope - Server Emulator)
For more information, visit http://www.swganh.com
Copyright (c) 2006 - 2010 The SWG:ANH Team
---------------------------------------------------------------------------------------
Use of this source code is governed by the GPL v3 license that can be found
in the COPYING file or at http://www.gnu.org/licenses/gpl-3.0.html
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
---------------------------------------------------------------------------------------
*/
#include "CraftingSession.h"
#include "CraftBatch.h"
#include "CraftingSessionFactory.h"
#include "CraftingStation.h"
#include "CraftingTool.h"
#include "Datapad.h"
#include "DraftSchematic.h"
#include "DraftSlot.h"
#include "FactoryCrate.h"
#include "Inventory.h"
#include "Item.h"
#include "ManufacturingSchematic.h"
#include "ObjectControllerOpcodes.h"
#include "ObjectFactory.h"
#include "PlayerObject.h"
#include "ResourceContainer.h"
#include "ResourceManager.h"
#include "SchematicManager.h"
#include "WorldManager.h"
#include "nonPersistantObjectFactory.h"
#include "MessageLib/MessageLib.h"
#include "DatabaseManager/Database.h"
#include "DatabaseManager/DatabaseCallback.h"
#include "DatabaseManager/DatabaseResult.h"
#include "DatabaseManager/DataBinding.h"
#include "Utils/clock.h"
#include <boost/lexical_cast.hpp>
//=============================================================================
//
// Adjust an Itemstacks amount
// delete the stack if emptied
bool CraftingSession::AdjustComponentStack(Item* item, uint32 uses)
{
//is this a stack ???
if(item->hasAttribute("stacksize"))
{
//alter stacksize, delete if necessary
uint32 stackSize;
stackSize = item->getAttribute<uint32>("stacksize");
if(stackSize > uses)
{
//just adjust the stacks size
item->setAttributeIncDB("stacksize",boost::lexical_cast<std::string>(stackSize-uses));
}
if(stackSize < uses)
{
return false;
}
if(stackSize == uses)
{
//just adjust the stacks size
item->setAttributeIncDB("stacksize",boost::lexical_cast<std::string>(stackSize-uses));
}
}
else
//no stack, just a singular item
if(uses == 1)
{
DLOG(INFO) << "CraftingSession::AdjustComponentStack no stacksize attribute set stack to 1";
}
else
{
DLOG(INFO) << "CraftingSession::AdjustComponentStack no stacksize attribute return false";
return false;
}
return true;
}
//=============================================================================
//
// Adjust a factory crates amount
//
uint32 CraftingSession::AdjustFactoryCrate(FactoryCrate* crate, uint32 uses)
{
uint32 crateSize = 1;
uint32 stackSize = 1;
if(!crate->hasAttribute("factory_count"))
{
return 0;
}
crateSize = crate->getAttribute<uint32>("factory_count");
//============================================================================
//calculate the amount of stacks we need to remove from the crate
//
if(!crate->getLinkedObject()->hasAttribute("stacksize"))
{
stackSize = 1;
}
uint32 takeOut = 0;
uint32 amount = 0;
while(amount < uses)
{
takeOut++;
amount+= stackSize;
}
//============================================================================
//remove *amount* stacks from the crate
//
if(takeOut>crateSize)
{
DLOG(INFO) << "CraftingSession::AdjustFactoryCrate :: Crate does not have enough content";
return 0;
}
//only take away whole stacks
crate->decreaseContent(takeOut);
//we might need to send these updates to all players watching the parentcontainer
gMessageLib->sendUpdateCrateContent(crate,mOwner);
return takeOut;
}
//=============================================================================
//
// returns the serial of either a crate or component
// thats easy for stacks and a little more involved for factory crates
//
BString CraftingSession::ComponentGetSerial(Item* component)
{
BString componentSerial = "";
FactoryCrate* fC = dynamic_cast<FactoryCrate*>(component);
if(fC)
{
if(fC->getLinkedObject()->hasAttribute("serial"))
componentSerial = fC->getLinkedObject()->getAttribute<std::string>("serial").c_str();
return componentSerial;
}
if(component->hasAttribute("serial"))
componentSerial = component->getAttribute<std::string>("serial").c_str();
return componentSerial;
}
//=============================================================================
//
// returns the amount of the item useable
// thats easy for stacks and a little more involved for factory crates
// under the presumption that crates can hold stackable items, too
uint32 CraftingSession::getComponentOffer(Item* component, uint32 needed)
{
uint32 crateSize = 0;
mAsyncStackSize = 1;
FactoryCrate* fC = dynamic_cast<FactoryCrate*>(component);
if(fC)
{
if(!fC->hasAttribute("factory_count"))
{
DLOG(INFO) << "CraftingSession::prepareComponent crate without factory_count attribute";
return 0;
}
crateSize = fC->getAttribute<uint32>("factory_count");
mAsyncStackSize = 1;
if(!fC->getLinkedObject()->hasAttribute("stacksize"))
{
if(needed> crateSize)
return crateSize;
else
return needed;
}
mAsyncStackSize = fC->getLinkedObject()->getAttribute<uint32>("stacksize");
if(needed> (mAsyncStackSize*crateSize))
return mAsyncStackSize*crateSize;
else
return needed;
}
if(!component->hasAttribute("stacksize"))
{
return 1;
}
mAsyncStackSize = component->getAttribute<uint32>("stacksize");
if(needed> mAsyncStackSize)
return mAsyncStackSize;
else
return needed;
}
//=============================================================================
//
// preparing the component means creating copies for every slot of a stack and
// linking them to the slot so we can deal with deleted / traded crates / items when we empty the slot
// delete it out of the inventory/container if necessary
// otherwise adjust the stacksize
bool CraftingSession::prepareComponent(Item* component, uint32 needed, ManufactureSlot* manSlot)
{
FactoryCrate* fC = dynamic_cast<FactoryCrate*>(component);
if(fC)
{
uint32 amount = AdjustFactoryCrate(fC, needed);
DLOG(INFO) << "CraftingSession::prepareComponent FactoryCrate take " << amount;
//TODO - added stacks shouldnt have more items than maximally possible - needed is the amount needed for the slot
// that might be bigger than the max stack size
//create the new item - link it to the slot
mAsyncComponentAmount = needed;
mAsyncManSlot = manSlot;
//make sure we request the right amount of stacks
for(uint8 i = 0; i<amount; i++)
gObjectFactory->requestNewClonedItem(this,fC->getLinkedObject()->getId(),mManufacturingSchematic->getId());
// if its now empty remove it out of the inventory so we cant use it several times
// and destroy it while were at it
uint32 crateSize = fC->getAttribute<uint32>("factory_count");
if(!crateSize)
{
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(fC->getParentId()));
if(!tO)
{
assert(false);
return 0;
}
//just delete it
gMessageLib->sendDestroyObject(fC->getId(),mOwner);
gObjectFactory->deleteObjectFromDB(fC->getId());
tO->deleteObject(fC);
}
//dont send result - its a callback
return false;
}
//no stacksize or crate - do not bother with temporaries
if(!component->hasAttribute("stacksize"))
{
// remove it out of the inventory so we cant use it several times
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(component->getParentId()));
assert(tO && "CraftingSession::prepareComponent :: cant get parent");
tO->removeObject(component);
//leave parent_id untouched - we might need to readd it to the container
gMessageLib->sendContainmentMessage(component->getId(),mManufacturingSchematic->getId(),0xffffffff,mOwner);
//send result directly we dont have a callback
return true;
}
//only pure stacks remain
AdjustComponentStack(component, needed);
//create the new item - link it to the slot
mAsyncComponentAmount = needed;
mAsyncManSlot = manSlot;
gObjectFactory->requestNewClonedItem(this,component->getId(),mManufacturingSchematic->getId());
//delete the stack if empty
uint32 stackSize = component->getAttribute<uint32>("stacksize");
if(!stackSize)
{
//remove the item out of its container
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(component->getParentId()));
if(!tO)
{
assert(false);
return false;
}
//just delete it
tO->removeObject(component);
gWorldManager->destroyObject(component);
}
//dont send result - its a callback
return false;
}
//=============================================================================
//
// a component gets put into a manufacturing slot
//
void CraftingSession::handleFillSlotComponent(uint64 componentId,uint32 slotId,uint32 unknown,uint8 counter)
{
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(slotId);
Item* component = dynamic_cast<Item*>(gWorldManager->getObjectById(componentId));
//remove the component out of its container and attach it to the man schematic
//alternatively remove the amount necessary from a stack / crate
uint32 existingAmount = 0;
uint32 totalNeededAmount = manSlot->mDraftSlot->getNecessaryAmount();
BString componentSerial = "";
BString filledSerial = "";
componentSerial = ComponentGetSerial(component);
mAsyncSmallUpdate = false;
if((!component) || (!manSlot))
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
return;
}
// get the amount of already filled components
FilledResources::iterator filledResIt = manSlot->mFilledResources.begin();
while(filledResIt != manSlot->mFilledResources.end())
{
existingAmount += (*filledResIt).second;
++filledResIt;
}
if(existingAmount)
mAsyncSmallUpdate = true;
// update the needed amount
totalNeededAmount -= existingAmount;
// fail if its already complete
if(!totalNeededAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
return;
}
//mmh somehow some components are added several times
if(component->getParentId() == mManufacturingSchematic->getId())
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
return;
}
//ok we probably have a deal here - if its a crate we need to get a stack out - or more ?
// see how much this component stack /crate has to offer
mAsyncComponentAmount = getComponentOffer(component,totalNeededAmount);
if(!mAsyncComponentAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient_Size,counter,mOwner);
return;
}
//============================================================0
// deal - get the new items
// the callback will hit the handleObjectReady in craftingsession.cpp
if(!prepareComponent(component, mAsyncComponentAmount, manSlot))
{
mAsyncSlotId = slotId;
mAsyncCounter = counter;
// false means we use the callback.
return;
}
component->setParentId(mManufacturingSchematic->getId());
//it wasnt a crate / stack - process right here
//add the necessary information to the slot
manSlot->mUsedComponentStacks.push_back(std::make_pair(component,mAsyncComponentAmount));
manSlot->addComponenttoSlot(component->getId(),mAsyncComponentAmount,manSlot->mDraftSlot->getType());
// update the slot total resource amount
manSlot->setFilledAmount(manSlot->getFilledAmount()+mAsyncComponentAmount);
if(manSlot->getFilledAmount() == manSlot->mDraftSlot->getNecessaryAmount())
{
// update the total count of filled slots
mManufacturingSchematic->addFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
}
// update the slot contents, send all slots on first fill
// we need to make sure we only update lists with changes, so the lists dont desynchronize!
if(!mFirstFill)
{
mFirstFill = true;
gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
}
else if(mAsyncSmallUpdate == true)
{
gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
else
{
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
// done
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);
}
//=============================================================================
//
// an amount of resource gets put into a manufacturing slot
//
void CraftingSession::handleFillSlotResource(uint64 resContainerId,uint32 slotId,uint32 unknown,uint8 counter)
{
// update resource container
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(resContainerId));
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(slotId);
FilledResources::iterator filledResIt = manSlot->mFilledResources.begin();
//bool resourceBool = false;
bool smallupdate = false;
if(!resContainer)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
}
if(!manSlot)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Invalid_Slot,counter,mOwner);
}
uint32 availableAmount = resContainer->getAmount();
uint32 totalNeededAmount = manSlot->mDraftSlot->getNecessaryAmount();
uint32 existingAmount = 0;
uint64 containerResId = resContainer->getResourceId();
// see if something is filled already
existingAmount = manSlot->getFilledAmount();
// update the needed amount
totalNeededAmount -= existingAmount;
// fail if its already complete
if(!totalNeededAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
return;
}
//check whether we have the same resource - no go if its different - check for the slot being empty though
if(manSlot->getResourceId() && (containerResId != manSlot->getResourceId()))
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient,counter,mOwner);
return;
}
// see how much this container has to offer
// slot completely filled
if(availableAmount >= totalNeededAmount)
{
// add to the filled resources
filledResIt = manSlot->mFilledResources.begin();
while(filledResIt != manSlot->mFilledResources.end())
{
// already got something of that type filled
if(containerResId == (*filledResIt).first)
{
//hark in live the same resource gets added to a second slot
manSlot->mFilledResources.push_back(std::make_pair(containerResId,totalNeededAmount));
filledResIt = manSlot->mFilledResources.begin();
manSlot->setFilledType(DST_Resource);//4 resource has been filled
smallupdate = true;
break;
}
++filledResIt;
}
// nothing of that resource filled, add a new entry
if(filledResIt == manSlot->mFilledResources.end())
{
//resourceBool = true;
// only allow one unique type
if(manSlot->mFilledResources.empty())
{
manSlot->mFilledResources.push_back(std::make_pair(containerResId,totalNeededAmount));
manSlot->setFilledType(DST_Resource);
manSlot->mFilledIndicatorChange = true;
}
else
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Bad_Resource_Chosen,counter,mOwner);
return;
}
}
// update the container amount
uint32 newContainerAmount = availableAmount - totalNeededAmount;
// destroy if its empty
if(!newContainerAmount)
{
//now destroy it client side
gMessageLib->sendDestroyObject(resContainerId,mOwner);
gObjectFactory->deleteObjectFromDB(resContainer);
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
tO->deleteObject(resContainer);
}
// update it
else
{
resContainer->setAmount(newContainerAmount);
gMessageLib->sendResourceContainerUpdateAmount(resContainer,mOwner);
mDatabase->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",newContainerAmount,resContainer->getId());
}
// update the slot total resource amount
manSlot->setFilledAmount(manSlot->mDraftSlot->getNecessaryAmount());
// update the total count of filled slots
mManufacturingSchematic->addFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
}
// got only a bit
else
{
// add to the filled resources
uint64 containerResId = resContainer->getResourceId();
filledResIt = manSlot->mFilledResources.begin();
while(filledResIt != manSlot->mFilledResources.end())
{
// already got something of that type filled
if(containerResId == (*filledResIt).first)
{
//(*filledResIt).second += availableAmount;
manSlot->mFilledResources.push_back(std::make_pair(containerResId,availableAmount));
filledResIt = manSlot->mFilledResources.begin();
manSlot->setFilledType(DST_Resource);
smallupdate = true;
break;
}
++filledResIt;
}
// nothing of that resource filled, add a new entry
if(filledResIt == manSlot->mFilledResources.end())
{
// only allow one unique type
if(manSlot->mFilledResources.empty())
{
manSlot->mFilledResources.push_back(std::make_pair(containerResId,availableAmount));
manSlot->setFilledType(DST_Resource);
}
else
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Bad_Resource_Chosen,counter,mOwner);
return;
}
}
// destroy the container as its empty now
gMessageLib->sendDestroyObject(resContainerId,mOwner);
gObjectFactory->deleteObjectFromDB(resContainer);
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
tO->deleteObject(resContainer);
// update the slot total resource amount
manSlot->mFilled += availableAmount;
}
// update the slot contents, send all slots on first fill
// we need to make sure we only update lists with changes, so the lists dont desynchronize!
if(!mFirstFill)
{
mFirstFill = true;
gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
}
else if(smallupdate == true)
{
gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
else
{
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
// done
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);
}
//=============================================================================
//
// an amount of resource gets put into a manufacturing slot
//
void CraftingSession::handleFillSlotResourceRewrite(uint64 resContainerId,uint32 slotId,uint32 unknown,uint8 counter)
{
// update resource container
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(resContainerId));
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(slotId);
//bool resourceBool = false;
bool smallupdate = false;
if(!resContainer)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Ingredient_Not_In_Inventory,counter,mOwner);
}
if(!manSlot)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Invalid_Slot,counter,mOwner);
}
uint32 availableAmount = resContainer->getAmount();
uint32 totalNeededAmount = manSlot->mDraftSlot->getNecessaryAmount();
uint32 existingAmount = 0;
uint64 containerResId = resContainer->getResourceId();
// see if something is filled already
existingAmount = manSlot->getFilledAmount();
//check whether we have the same resource - if it's different replace the current resource with the new one
if(manSlot->getResourceId() && (containerResId != manSlot->getResourceId()))
{
// remove the old resource from the slot and input the new one.
emptySlot(slotId, manSlot, manSlot->getResourceId());
//gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Internal_Invalid_Ingredient,counter,mOwner);
//return;
}
else
{
// update the needed amount
totalNeededAmount -= existingAmount;
}
// fail if its already complete
if(!totalNeededAmount)
{
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_Slot_Already_Full,counter,mOwner);
return;
}
uint32 takeAmount = 0;
if(availableAmount >= totalNeededAmount)
{
takeAmount = totalNeededAmount;
}
else
{
takeAmount = availableAmount;
}
// add it to the slot get the update type
smallupdate = manSlot->addResourcetoSlot(containerResId,takeAmount,manSlot->mDraftSlot->getType());
// update the container amount
uint32 newContainerAmount = availableAmount - takeAmount;
updateResourceContainer(resContainer->getId(),newContainerAmount);
// update the slot total resource amount
manSlot->setFilledAmount(manSlot->getFilledAmount()+takeAmount);
if(manSlot->getFilledAmount() == manSlot->mDraftSlot->getNecessaryAmount())
{
// update the total count of filled slots
mManufacturingSchematic->addFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
}
// update the slot contents, send all slots on first fill
// we need to make sure we only update lists with changes, so the lists dont desynchronize!
if(!mFirstFill)
{
mFirstFill = true;
gMessageLib->sendDeltasMSCO_7(mManufacturingSchematic,mOwner);
}
else if(smallupdate == true)
{
gMessageLib->sendManufactureSlotUpdateSmall(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
else
{
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
// done
gMessageLib->sendCraftAcknowledge(opCraftFillSlot,CraftError_None,counter,mOwner);
}
//=============================================================================
//
// filled components get returned to the inventory
//
//
void CraftingSession::bagComponents(ManufactureSlot* manSlot,uint64 containerId)
{
//add the components back to the inventory (!!!)
manSlot->setFilledType(DST_Empty);
//put them into the inventory no matter what - only alternative might be a crafting stations hopper at one point ??
Inventory* inventory = dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory));
FilledComponent::iterator compIt = manSlot->mUsedComponentStacks.begin();
while(compIt != manSlot->mUsedComponentStacks.end())
{
Item* filledComponent = dynamic_cast<Item*>((*compIt).first);
if(!filledComponent)
{
return;
}
inventory->addObject(filledComponent);
gMessageLib->sendContainmentMessage(filledComponent->getId(),inventory->getId(),0xffffffff,mOwner);
filledComponent->setParentIdIncDB(inventory->getId());
compIt = manSlot->mUsedComponentStacks.erase(compIt);
continue;
}
manSlot->mUsedComponentStacks.clear();
manSlot->mFilledResources.clear();
}
void CraftingSession::destroyComponents()
{
uint8 amount = mManufacturingSchematic->getManufactureSlots()->size();
for (uint8 i = 0; i < amount; i++)
{
//iterate through our manslots which contain components
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(i);
manSlot->setFilledType(DST_Empty);
FilledComponent::iterator compIt = manSlot->mUsedComponentStacks.begin();
while(compIt != manSlot->mUsedComponentStacks.end())
{
Item* filledComponent = dynamic_cast<Item*>((*compIt).first);
if(!filledComponent)
{
return;
}
gObjectFactory->deleteObjectFromDB(filledComponent);
gMessageLib->sendDestroyObject(filledComponent->getId(),mOwner);
gWorldManager->destroyObject(filledComponent);
compIt = manSlot->mUsedComponentStacks.erase(compIt);
continue;
}
manSlot->mUsedComponentStacks.clear();
manSlot->mFilledResources.clear();
}
}
//=============================================================================
//
// filled resources get returned to the inventory
//
void CraftingSession::bagResource(ManufactureSlot* manSlot,uint64 containerId)
{
//iterates through the slots filled resources
//respectively create a new one if necessary
//TODO : what happens if the container is full ?
FilledResources::iterator resIt = manSlot->mFilledResources.begin();
manSlot->setFilledType(DST_Empty);
while(resIt != manSlot->mFilledResources.end())
{
uint32 amount = (*resIt).second;
// see if we can add it to an existing container
ObjectIDList* invObjects = dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory))->getObjects();
ObjectIDList::iterator listIt = invObjects->begin();
bool foundSameType = false;
while(listIt != invObjects->end())
{
// we are looking for resource containers
ResourceContainer* resCont = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById((*listIt)));
if(resCont)
{
uint32 targetAmount = resCont->getAmount();
uint32 maxAmount = resCont->getMaxAmount();
uint32 newAmount;
if((resCont->getResourceId() == (*resIt).first) && (targetAmount < maxAmount))
{
foundSameType = true;
newAmount = targetAmount + amount;
if(newAmount <= maxAmount)
{
// update target container
resCont->setAmount(newAmount);
gMessageLib->sendResourceContainerUpdateAmount(resCont,mOwner);
gWorldManager->getDatabase()->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",newAmount,resCont->getId());
}
// target container full, put in what fits, create a new one
else if(newAmount > maxAmount)
{
uint32 selectedNewAmount = newAmount - maxAmount;
resCont->setAmount(maxAmount);
gMessageLib->sendResourceContainerUpdateAmount(resCont,mOwner);
gWorldManager->getDatabase()->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",maxAmount,resCont->getId());
gObjectFactory->requestNewResourceContainer(dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)),(*resIt).first,mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)->getId(),99,selectedNewAmount);
}
break;
}
}
++listIt;
}
// or need to create a new one
if(!foundSameType)
{
gObjectFactory->requestNewResourceContainer(dynamic_cast<Inventory*>(mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)),(*resIt).first,mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)->getId(),99,amount);
}
++resIt;
}
}
//=============================================================================
//
// a manufacture slot is emptied
//
void CraftingSession::emptySlot(uint32 slotId,ManufactureSlot* manSlot,uint64 containerId)
{
//get ressources back in their stack
//or components back in the inventory
if(manSlot->getFilledType() == DST_Resource)
bagResource(manSlot,containerId);
else if(manSlot->getFilledType() != DST_Empty)
bagComponents(manSlot,containerId);
// update the slot
manSlot->mFilledResources.clear();
manSlot->mUsedComponentStacks.clear();
manSlot->setFilledType(DST_Empty);
// if it was completely filled, update the total amount of filled slots
if(manSlot->getFilledAmount() == manSlot->mDraftSlot->getNecessaryAmount())
{
mManufacturingSchematic->removeFilledSlot();
gMessageLib->sendUpdateFilledManufactureSlots(mManufacturingSchematic,mOwner);
//update the amount clientside, too ?
}
if(manSlot->getFilledAmount())
{
manSlot->setFilledAmount(0);
//only send when changes !!!!!
gMessageLib->sendManufactureSlotUpdate(mManufacturingSchematic,static_cast<uint8>(slotId),mOwner);
}
manSlot->setResourceId(0);
manSlot->setSerial("");
}
//=============================================================================
//this creates the serial for a crafted item
BString CraftingSession::getSerial()
{
int8 serial[12],chance[9];
bool found = false;
uint8 u;
for(uint8 i = 0; i < 8; i++)
{
while(!found)
{
found = true;
u = static_cast<uint8>(static_cast<double>(gRandom->getRand()) / (RAND_MAX + 1.0f) * (122.0f - 48.0f) + 48.0f);
//only 1 to 9 or a to z
if((u >57)&&(u <97))
found = false;
if((u < 48)||(u >122))
found = false;
}
chance[i] = u;
found = false;
}
chance[8] = 0;
sprintf(serial,"(%s)",chance);
return(BString(serial));
}
//=============================================================================
//gets the type of success / failure for experimentation
uint8 CraftingSession::_experimentRoll(uint32 expPoints)
{
if(mOwnerExpSkillMod > 125)
{
mOwnerExpSkillMod = 125;
}
int32 assRoll;
int32 riskRoll;
float ma = _calcAverageMalleability();
//high rating means lesser risk!!
float rating = 50.0f + ((ma - 500.0f) / 40.0f) + mOwnerExpSkillMod - (5.0f * expPoints);
rating -= (mManufacturingSchematic->getComplexity()/10);
rating += (mToolEffectivity/10);
float risk = 100.0f - rating;
riskRoll = (int32)(floor(((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f)));
if(riskRoll <= risk)
{
//ok we have some sort of failure
assRoll = (int32)(floor((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f));
int32 modRoll = (int32)(floor((double)(assRoll / 25)) + 4);
if(modRoll < 4)
modRoll = 4;
else if(modRoll > 8)
modRoll = 8;
return static_cast<uint8>(modRoll);
}
mManufacturingSchematic->setExpFailureChance(risk);
//ok we have some sort of success
assRoll = (int32) floor( (double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f) ;
int32 modRoll = static_cast<int32>(((assRoll - (rating * 0.4f)) / 15.0f) - (mToolEffectivity / 50.0f));
++modRoll;
//int32 modRoll = (gRandom->getRand() - (rating*0.2))/15;
//0 is amazing success
//1 is great success
//2 is good success
//3 moderate success
//4 success
//5 failure
//6 moderate failure
//7 big failure
//8 critical failure
// make sure we are in valid range
if(modRoll < 0)
modRoll = 0;
else if(modRoll > 4)
modRoll = 4;
return static_cast<uint8>(modRoll);
}
//=============================================================================
//this determines our success in the assembly of the item
uint8 CraftingSession::_assembleRoll()
{
// assembly roll, needs to be improved, maybe make a pool to draw results from, which is populated based on the skillmod
//int32 assRoll = (int32)(floor((float)(gRandom->getRand()%9) - ((float)assMod / 20.0f)));
int32 assRoll;
int32 riskRoll;
float ma = _calcAverageMalleability();
// make sure the values are valid and dont crash us cap it at 125
if(mOwnerAssSkillMod > 125)
{
mOwnerAssSkillMod = 125;
}
float rating = 50.0f + ((ma - 500.0f) / 40.0f) + mOwnerAssSkillMod - 5.0f;
rating += (mToolEffectivity/10);
rating -= (mManufacturingSchematic->getComplexity()/10);
float risk = 100.0f - rating;
mManufacturingSchematic->setExpFailureChance(risk);
riskRoll = (int32)(floor(((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f)));
//gLogger->logErrorF("Crafting","CraftingSession::_assembleRoll() relevant riskroll %u",riskRoll);
// ensure that every critical makes the nect critical less likely
// we dont want to have more than 3 criticals in a row
//gLogger->logErrorF("Crafting","CraftingSession::_assembleRoll() relevant criticalCount %u",mCriticalCount);
riskRoll += (mCriticalCount*5);
//gLogger->logErrorF("Crafting","CraftingSession::_assembleRoll() modified riskroll %u",riskRoll);
if((mCriticalCount == 3))
riskRoll = static_cast<uint32>(risk+1);
if(riskRoll <= risk)
{
//ok critical failure time !
mCriticalCount++;
return(8);
}
else
mCriticalCount = 0;
//ok we have some sort of success
assRoll = (int32)floor((double)gRandom->getRand() / (RAND_MAX + 1.0f) * (100.0f - 1.0f) + 1.0f) ;
int32 modRoll = static_cast<uint32>(((assRoll - (rating * 0.4f)) / 15.0f) - (mToolEffectivity / 50.0f));
//0 is amazing success
//1 is great success
//2 is good success
//3 success
//4 is moderate success
//5 marginally successful
//6 ok
//7 barely succesfull
//8 critical failure
// make sure we are in valid range
if(modRoll < 0)
modRoll = 0;
else if(modRoll > 7)
modRoll = 7;
return static_cast<uint8>(modRoll);
}
//=============================================================================
//
// calculate the maximum reachable percentage through assembly with the filled resources
//
float CraftingSession::_calcAverageMalleability()
{
FilledResources::iterator filledResIt;
ManufactureSlots* manSlots = mManufacturingSchematic->getManufactureSlots();
ManufactureSlots::iterator manIt = manSlots->begin();
CraftWeights::iterator weightIt;
ManufactureSlot* manSlot;
Resource* resource;
uint16 resAtt = 0;
uint8 slotCount = 0;
while(manIt != manSlots->end())
{
manSlot = (*manIt);
// skip if its a sub component slot
if(manSlot->mDraftSlot->getType() != 4)
{
++manIt;
continue;
}
// we limit it so that only the same resource can go into one slot, so grab only the first entry
filledResIt = manSlot->mFilledResources.begin();
if(manSlot->mFilledResources.empty())
{
//in case we can leave resource slots optionally emptymanSlot->mFilledResources
++manIt;
continue;
}
resource = gResourceManager->getResourceById((*filledResIt).first);
resAtt += resource->getAttribute(ResAttr_MA);
++slotCount;
++manIt;
}
return static_cast<float>(resAtt/slotCount);
}
//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::collectResources()
{
ManufactureSlots::iterator manIt = mManufacturingSchematic->getManufactureSlots()->begin();
int8 str[64];
int8 attr[64];
CheckResources::iterator checkResIt = mCheckRes.begin();
BString name;
while(manIt != mManufacturingSchematic->getManufactureSlots()->end())
{
//is it a resource??
if((*manIt)->mDraftSlot->getType() == DST_Resource)
{
//get resource name and amount
//we only can enter one res type in a slot so dont care about the other entries
FilledResources::iterator filledResIt = (*manIt)->mFilledResources.begin();
uint64 resID = (*filledResIt).first;
checkResIt = mCheckRes.find(resID);
if(checkResIt == mCheckRes.end())
{
mCheckRes.insert(std::make_pair(resID,(*filledResIt).second));
}
else
{
//uint32 amount = ((*checkResIt).second + (*filledResIt).second);
(*checkResIt).second += (*filledResIt).second;
//uint64 id = (*checkResIt).first;
//mCheckRes.erase(checkResIt);
//mCheckRes.insert(std::make_pair(id,amount));
}
}
manIt++;
}
checkResIt = mCheckRes.begin();
while(checkResIt != mCheckRes.end())
{
//build these attributes by hand the attribute wont be found in the attributes table its custom made
name = gResourceManager->getResourceById((*checkResIt).first)->getName();
sprintf(attr,"cat_manf_schem_ing_resource.\"%s",name .getAnsi());
BString attrName = BString(attr);
sprintf(str,"%u",(*checkResIt).second);
//add to the public attribute list
mManufacturingSchematic->addAttribute(attrName.getAnsi(),str);
//now add to the db
sprintf(str,"%s %u",name.getAnsi(),(*checkResIt).second);
//update db
//enter it slotdependent as we dont want to clot our attributes table with resources
//173 is cat_manf_schem_resource
mDatabase->executeSqlAsync(0,0,"INSERT INTO item_attributes VALUES (%"PRIu64",173,'%s',1,0)",mManufacturingSchematic->getId(),str);
//now enter it in the relevant manschem table so we can use it in factories
mDatabase->executeSqlAsync(0,0,"INSERT INTO manschemresources VALUES (NULL,%"PRIu64",%"PRIu64",%u)",mManufacturingSchematic->getId(),(*checkResIt).first,(*checkResIt).second);
checkResIt ++;
}
mCheckRes.clear();
}
//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::collectComponents()
{
ManufactureSlots::iterator manIt = mManufacturingSchematic->getManufactureSlots()->begin();
int8 str[64];
int8 attr[64];
CheckResources::iterator checkResIt = mCheckRes.begin();
BString name;
while(manIt != mManufacturingSchematic->getManufactureSlots()->end())
{
//is it a resource??
if(((*manIt)->mDraftSlot->getType() == DST_IdentComponent)||((*manIt)->mDraftSlot->getType() == DST_SimiliarComponent))
{
if(!(*manIt)->mFilledResources.size())
{
manIt++;
continue;
}
//get component serial and amount
//we only can enter one serial type in a slot so dont care about the other entries
FilledResources::iterator filledResIt = (*manIt)->mFilledResources.begin();
uint64 componentID = (*filledResIt).first;
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(componentID));
if(!tO)
{
//item not found??? wth
assert(false && "CraftingSession::collectComponents No tangible object found in world manager");
}
BString componentSerial = "";
if(tO->hasAttribute("serial"))
componentSerial = tO->getAttribute<std::string>("serial").c_str();
checkResIt = mCheckRes.find(componentID);
if(checkResIt == mCheckRes.end())
{
mCheckRes.insert(std::make_pair(componentID,(*filledResIt).second));
}
else
{
//uint32 amount = ((*checkResIt).second + (*filledResIt).second);
(*checkResIt).second += (*filledResIt).second;
//uint64 id = (*checkResIt).first;
//mCheckRes.erase(checkResIt);
//mCheckRes.insert(std::make_pair(id,amount));
}
}
manIt++;
}
checkResIt = mCheckRes.begin();
while(checkResIt != mCheckRes.end())
{
Item* tO = dynamic_cast<Item*>(gWorldManager->getObjectById((*checkResIt).first));
if(!tO)
{
continue;
}
BString componentSerial = "";
if(tO->hasAttribute("serial"))
componentSerial = tO->getAttribute<std::string>("serial").c_str();
name = tO->getName();
sprintf(attr,"cat_manf_schem_ing_component.\"%s",name .getAnsi());
BString attrName = BString(attr);
sprintf(str,"%u",(*checkResIt).second);
//add to the public attribute list
mManufacturingSchematic->addAttribute(attrName.getAnsi(),str);
//now add to the db
sprintf(str,"%s %u",name.getAnsi(),(*checkResIt).second);
//update db
//enter it slotdependent as we dont want to clot our attributes table with resources
//173 is cat_manf_schem_resource
mDatabase->executeSqlAsync(0,0,"INSERT INTO item_attributes VALUES (%"PRIu64",173,'%s',1,0)",mManufacturingSchematic->getId(),str);
//now enter it in the relevant manschem table so we can use it in factories
mDatabase->executeSqlAsync(0,0,"INSERT INTO manschemcomponents VALUES (NULL,%"PRIu64",%u,%s,%u)",mManufacturingSchematic->getId(),tO->getItemType(),componentSerial.getAnsi(),(*checkResIt).second);
checkResIt ++;
}
mCheckRes.clear();
}
//===============================================================================
//collects a resourcelist to give to a manufacturing schematic
//
void CraftingSession::updateResourceContainer(uint64 containerID, uint32 newAmount)
{
// destroy if its empty
if(!newAmount)
{
//now destroy it client side
gMessageLib->sendDestroyObject(containerID,mOwner);
gObjectFactory->deleteObjectFromDB(containerID);
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(containerID));
TangibleObject* tO = dynamic_cast<TangibleObject*>(gWorldManager->getObjectById(resContainer->getParentId()));
tO->deleteObject(resContainer);
}
// update it
else
{
ResourceContainer* resContainer = dynamic_cast<ResourceContainer*>(gWorldManager->getObjectById(containerID));
resContainer->setAmount(newAmount);
gMessageLib->sendResourceContainerUpdateAmount(resContainer,mOwner);
mDatabase->executeSqlAsync(NULL,NULL,"UPDATE resource_containers SET amount=%u WHERE id=%"PRIu64"",newAmount,resContainer->getId());
}
}
//===============================================================
// empties the slots of a man schem when a critical assembly error happens
// send
void CraftingSession::emptySlots(uint32 counter)
{
uint8 amount = mManufacturingSchematic->getManufactureSlots()->size();
for (uint8 i = 0; i < amount; i++)
{
ManufactureSlot* manSlot = mManufacturingSchematic->getManufactureSlots()->at(i);
if(manSlot)
{
emptySlot(i,manSlot,mOwner->getEquipManager()->getEquippedObject(CreatureEquipSlot_Inventory)->getId());
gMessageLib->sendCraftAcknowledge(opCraftEmptySlot,CraftError_None,static_cast<uint8>(counter),mOwner);
}
}
}
//===============================================================
// modifies an items attribute value
//
void CraftingSession::modifyAttributeValue(CraftAttribute* att, float attValue)
{
if(att->getType())
{
int32 intAtt = 0;
//is there an attribute of a component that affects us??
if(mManufacturingSchematic->hasPPAttribute(att->getAttributeKey()))
{
float attributeAddValue = mManufacturingSchematic->getPPAttribute<float>(att->getAttributeKey());
intAtt = (int32)(ceil(attributeAddValue));
}
intAtt += (int32)(ceil(attValue));
mItem->setAttributeIncDB(att->getAttributeKey(),boost::lexical_cast<std::string>(intAtt));
}
else
{
float f = rndFloat(attValue);
//is there an attribute of a component that affects us??
if(mManufacturingSchematic->hasPPAttribute(att->getAttributeKey()))
{
float attributeAddValue = mManufacturingSchematic->getPPAttribute<float>(att->getAttributeKey());
f += rndFloat(attributeAddValue);
}
//mItem->setAttributeIncDB(att->getAttributeKey(),boost::lexical_cast<std::string>(f));
mItem->setAttributeIncDB(att->getAttributeKey(),rndFloattoStr(f).getAnsi());
}
}
float CraftingSession::getPercentage(uint8 roll)
{
float percentage = 0.0;
switch(roll)
{
case 0 :
percentage = 0.08f;
break;
case 1 :
percentage = 0.07f;
break;
case 2 :
percentage = 0.06f;
break;
case 3 :
percentage = 0.02f;
break;
case 4 :
percentage = 0.01f;
break;
case 5 :
percentage = -0.0175f;
break; //failure
case 6 :
percentage = -0.035f;
break;//moderate failure
case 7 :
percentage = -0.07f;
break;//big failure
case 8 :
percentage = -0.14f;
break;//critical failure
}
return percentage;
}
//========================================================================================
// gets the ExperimentationRoll and initializes the experimental properties
// meaning an exp property which exists several times (with different resourceweights)
// gets the same roll assigned
uint8 CraftingSession::getExperimentationRoll(ExperimentationProperty* expProperty, uint8 expPoints)
{
ExperimentationProperties* expAllProps = mManufacturingSchematic->getExperimentationProperties();
ExperimentationProperties::iterator itAll = expAllProps->begin();
uint8 roll;
if(expProperty->mRoll == -1)
{
DLOG(INFO) << "CraftingSession:: expProperty is a Virgin!";
// get our Roll and take into account the relevant modifiers
roll = _experimentRoll(expPoints);
// now go through all properties and mark them when its this one!
// so we dont experiment two times on it!
itAll = expAllProps->begin();
while(itAll != expAllProps->end())
{
ExperimentationProperty* tempProperty = (*itAll);
if(expProperty->mExpAttributeName.getCrc() == tempProperty->mExpAttributeName.getCrc())
{
tempProperty->mRoll = roll;
}
itAll++;
}
}
else
{
roll = static_cast<uint8>(expProperty->mRoll);
DLOG(INFO) << "CraftingSession:: experiment expProperty isnt a virgin anymore ...(roll:" << roll;
}
return roll;
}
| 32.164217 | 288 | 0.618909 |
5a1420d1660d2c8ebe5911459718a6172f131fb9 | 3,888 | hpp | C++ | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 10 | 2021-03-29T13:52:06.000Z | 2022-03-10T02:24:25.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 1 | 2019-07-19T02:40:32.000Z | 2019-07-19T02:40:32.000Z | Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/common/pthreadcond.hpp | TiagoPedroByterev/openvpnclient-ios | a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76 | [
"MIT"
] | 7 | 2018-07-11T10:37:02.000Z | 2019-08-03T10:34:08.000Z | // OpenVPN -- An application to securely tunnel IP networks
// over a single port, with support for SSL/TLS-based
// session authentication and key exchange,
// packet encryption, packet authentication, and
// packet compression.
//
// Copyright (C) 2012-2017 OpenVPN Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License Version 3
// as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program in the COPYING file.
// If not, see <http://www.gnu.org/licenses/>.
#ifndef OPENVPN_COMMON_PTHREADCOND_H
#define OPENVPN_COMMON_PTHREADCOND_H
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <openvpn/common/stop.hpp>
namespace openvpn {
// Barrier class that is useful in cases where all threads
// need to reach a known point before executing some action.
// Note that this barrier implementation is
// constructed using C++11 condition variables.
class PThreadBarrier
{
enum State {
UNSIGNALED=0, // initial state
SIGNALED, // signal() was called
ERROR_THROWN, // error() was called
};
public:
// status return from wait()
enum Status {
SUCCESS=0, // successful
CHOSEN_ONE, // successful and chosen (only one thread is chosen)
TIMEOUT, // timeout
ERROR, // at least one thread called error()
};
PThreadBarrier(const int initial_limit = -1)
: stop(nullptr),
limit(initial_limit)
{
}
PThreadBarrier(Stop* stop_arg, const int initial_limit = -1)
: stop(stop_arg),
limit(initial_limit)
{
}
// All callers will increment count and block until
// count == limit. CHOSEN_ONE will be returned to
// the first caller to reach limit. This caller can
// then release all the other callers by calling
// signal().
int wait(const unsigned int seconds)
{
// allow asynchronous stop
Stop::Scope stop_scope(stop, [this]() {
error();
});
bool timeout = false;
int ret;
std::unique_lock<std::mutex> lock(mutex);
const unsigned int c = ++count;
while (state == UNSIGNALED
&& (limit < 0 || c < limit)
&& !timeout)
timeout = (cv.wait_for(lock, std::chrono::seconds(seconds)) == std::cv_status::timeout);
if (timeout)
ret = TIMEOUT;
else if (state == ERROR_THROWN)
ret = ERROR;
else if (state == UNSIGNALED && !chosen)
{
ret = CHOSEN_ONE;
chosen = true;
}
else
ret = SUCCESS;
return ret;
}
void set_limit(const int new_limit)
{
std::unique_lock<std::mutex> lock(mutex);
limit = new_limit;
cv.notify_all();
}
// Generally, only the CHOSEN_ONE calls signal() after its work
// is complete, to allow the other threads to pass the barrier.
void signal()
{
signal_(SIGNALED);
}
// Causes all threads waiting on wait() (and those which call wait()
// in the future) to exit with ERROR status.
void error()
{
signal_(ERROR_THROWN);
}
private:
void signal_(const State newstate)
{
std::unique_lock<std::mutex> lock(mutex);
if (state == UNSIGNALED)
{
state = newstate;
cv.notify_all();
}
}
std::mutex mutex;
std::condition_variable cv;
Stop* stop;
State state{UNSIGNALED};
bool chosen = false;
unsigned int count = 0;
int limit;
};
}
#endif
| 27 | 89 | 0.637088 |
5a19681fccf6da574551c4be56c4be8ac59960b0 | 4,833 | cpp | C++ | blast/src/algo/blast/api/local_search.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/algo/blast/api/local_search.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | blast/src/algo/blast/api/local_search.cpp | mycolab/ncbi-blast | e59746cec78044d2bf6d65de644717c42f80b098 | [
"Apache-2.0"
] | null | null | null | /* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Christiam Camacho
*
*/
/** @file local_search.cpp
* This file implements the Uniform Blast Search Interface in terms of
* the local BLAST database search class
* NOTE: This is OBJECT MANAGER DEPENDANT because of its use of CDbBlast!
*/
#include <ncbi_pch.hpp>
// Object includes
#include <objects/scoremat/Pssm.hpp>
#include <objects/scoremat/PssmWithParameters.hpp>
#include <objects/seqalign/Seq_align.hpp>
#include <objects/seqalign/Seq_align_set.hpp>
#include <objects/seqset/Seq_entry.hpp>
// Object manager dependencies
#include <algo/blast/api/seqsrc_seqdb.hpp>
#include <objmgr/object_manager.hpp>
// BLAST includes
#include <algo/blast/api/local_search.hpp>
#include <algo/blast/api/psiblast.hpp>
#include <algo/blast/api/objmgrfree_query_data.hpp>
#include "psiblast_aux_priv.hpp"
/** @addtogroup AlgoBlast
*
* @{
*/
BEGIN_NCBI_SCOPE
BEGIN_SCOPE(blast)
/// Supporting elements
//
// Factory
//
CRef<ISeqSearch>
CLocalSearchFactory::GetSeqSearch()
{
return CRef<ISeqSearch>(new CLocalSeqSearch());
}
CRef<IPssmSearch>
CLocalSearchFactory::GetPssmSearch()
{
return CRef<IPssmSearch>(new CLocalPssmSearch());
}
CRef<CBlastOptionsHandle>
CLocalSearchFactory::GetOptions(EProgram program)
{
// FIXME: should do some validation for acceptable programs by the
// implementation (i.e.: CDbBlast)
return CRef<CBlastOptionsHandle>(CBlastOptionsFactory::Create(program));
}
//
// Seq Search
//
// NOTE: Local search object is re-created every time it is run.
CRef<CSearchResultSet>
CLocalSeqSearch::Run()
{
if ( m_QueryFactory.Empty() ) {
NCBI_THROW(CSearchException, eConfigErr, "No queries specified");
}
if ( m_Database.Empty() ) {
NCBI_THROW(CSearchException, eConfigErr, "No database name specified");
}
if ( !m_SearchOpts ) {
NCBI_THROW(CSearchException, eConfigErr, "No options specified");
}
// This is delayed to this point to guarantee that the options are
// populated
m_LocalBlast.Reset(new CLocalBlast(m_QueryFactory, m_SearchOpts,
*m_Database));
return m_LocalBlast->Run();
}
void
CLocalSeqSearch::SetOptions(CRef<CBlastOptionsHandle> opts)
{
m_SearchOpts = opts;
}
void
CLocalSeqSearch::SetSubject(CConstRef<CSearchDatabase> subject)
{
m_Database = subject;
}
void
CLocalSeqSearch::SetQueryFactory(CRef<IQueryFactory> query_factory)
{
m_QueryFactory = query_factory;
}
//
// Psi Search
//
void
CLocalPssmSearch::SetOptions(CRef<CBlastOptionsHandle> opts)
{
m_SearchOpts = opts;
}
void
CLocalPssmSearch::SetSubject(CConstRef<CSearchDatabase> subject)
{
m_Subject = subject;
}
void
CLocalPssmSearch::SetQuery(CRef<objects::CPssmWithParameters> pssm)
{
CPsiBlastValidate::Pssm(*pssm);
m_Pssm = pssm;
}
CRef<CSearchResultSet>
CLocalPssmSearch::Run()
{
CConstRef<CPSIBlastOptionsHandle> psi_opts;
psi_opts.Reset(dynamic_cast<CPSIBlastOptionsHandle*>(&*m_SearchOpts));
if (psi_opts.Empty()) {
NCBI_THROW(CBlastException, eInvalidArgument,
"Options for CLocalPssmSearch are not PSI-BLAST");
}
CConstRef<CBioseq> query(&m_Pssm->GetPssm().GetQuery().GetSeq());
CRef<IQueryFactory> query_factory(new CObjMgrFree_QueryFactory(query)); /* NCBI_FAKE_WARNING */
CRef<CLocalDbAdapter> dbadapter(new CLocalDbAdapter(*m_Subject));
CPsiBlast psiblast(query_factory, dbadapter, psi_opts);
CRef<CSearchResultSet> retval = psiblast.Run();
return retval;
}
END_SCOPE(blast)
END_NCBI_SCOPE
/* @} */
| 26.85 | 99 | 0.699979 |
5a1c1bdce9d2b6701ef76bb1d6d295398535a614 | 1,505 | cpp | C++ | tests/algebra/operator/conjugate.cpp | qftphys/Simulate-the-non-equilibrium-dynamics-of-Fermionic-systems | 48d36fecbe4bc12af90f104cdf1f9f68352c508c | [
"MIT"
] | 2 | 2021-01-18T14:35:43.000Z | 2022-03-22T15:12:49.000Z | tests/algebra/operator/conjugate.cpp | f-koehler/ieompp | 48d36fecbe4bc12af90f104cdf1f9f68352c508c | [
"MIT"
] | null | null | null | tests/algebra/operator/conjugate.cpp | f-koehler/ieompp | 48d36fecbe4bc12af90f104cdf1f9f68352c508c | [
"MIT"
] | null | null | null | #include "operator.hpp"
using namespace ieompp::algebra;
TEST_CASE("conjugate_1")
{
const auto a = Operator1::make_creator(0ul), b = Operator1::make_annihilator(0ul);
Operator1 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("conjugate_2")
{
const auto a = Operator2::make_creator(0ul, true), b = Operator2::make_annihilator(0ul, true);
Operator2 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("conjugate_3")
{
const auto a = Operator3::make_creator(0ul, true, 'a'),
b = Operator3::make_annihilator(0ul, true, 'a');
Operator3 a_conj(a), b_conj(b);
a_conj.conjugate();
b_conj.conjugate();
REQUIRE(a_conj == b);
REQUIRE(b_conj == a);
}
TEST_CASE("get_conjugate_1")
{
const auto a = Operator1::make_creator(0ul), b = Operator1::make_annihilator(0ul);
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
TEST_CASE("get_conjugate_2")
{
const auto a = Operator2::make_creator(0ul, true), b = Operator2::make_annihilator(0ul, true);
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
TEST_CASE("get_conjugate_3")
{
const auto a = Operator3::make_creator(0ul, true, 'a'),
b = Operator3::make_annihilator(0ul, true, 'a');
REQUIRE(a.get_conjugate() == b);
REQUIRE(b.get_conjugate() == a);
}
| 24.274194 | 98 | 0.64186 |
5a1fe7ab79a62c09730683bfcb46fcec655160fd | 3,322 | cpp | C++ | src/debug_message.cpp | anima-libera/qwy2 | 4875caf8035c5fb60e12eaba787d29017ffa0ed8 | [
"Apache-2.0"
] | null | null | null | src/debug_message.cpp | anima-libera/qwy2 | 4875caf8035c5fb60e12eaba787d29017ffa0ed8 | [
"Apache-2.0"
] | null | null | null | src/debug_message.cpp | anima-libera/qwy2 | 4875caf8035c5fb60e12eaba787d29017ffa0ed8 | [
"Apache-2.0"
] | null | null | null |
#include "debug_message.hpp"
#include "opengl.hpp"
#include <SDL2/SDL.h>
#include <iostream>
namespace qwy2
{
using namespace std::literals::string_view_literals;
static std::string_view opengl_debug_message_source_name(GLenum source)
{
switch (source)
{
case GL_DEBUG_SOURCE_API:
return "API"sv;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
return "WINDOW_SYSTEM"sv;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
return "SHADER_COMPILER"sv;
case GL_DEBUG_SOURCE_THIRD_PARTY:
return "THIRD_PARTY"sv;
case GL_DEBUG_SOURCE_APPLICATION:
return "APPLICATION"sv;
case GL_DEBUG_SOURCE_OTHER:
return "OTHER"sv;
default:
return "NOT_A_SOURCE"sv;
}
}
static std::string_view opengl_debug_message_type_name(GLenum type)
{
switch (type)
{
case GL_DEBUG_TYPE_ERROR:
return "ERROR"sv;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
return "DEPRECATED_BEHAVIOR"sv;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
return "UNDEFINED_BEHAVIOR"sv;
case GL_DEBUG_TYPE_PORTABILITY:
return "PORTABILITY"sv;
case GL_DEBUG_TYPE_PERFORMANCE:
return "PERFORMANCE"sv;
case GL_DEBUG_TYPE_MARKER:
return "MARKER"sv;
case GL_DEBUG_TYPE_PUSH_GROUP:
return "PUSH_GROUP"sv;
case GL_DEBUG_TYPE_POP_GROUP:
return "POP_GROUP"sv;
case GL_DEBUG_TYPE_OTHER:
return "OTHER"sv;
default:
return "NOT_A_TYPE"sv;
}
}
static std::string_view opengl_debug_message_severity_name(GLenum type)
{
switch (type)
{
case GL_DEBUG_SEVERITY_HIGH:
return "HIGH"sv;
case GL_DEBUG_SEVERITY_MEDIUM:
return "MEDIUM"sv;
case GL_DEBUG_SEVERITY_LOW:
return "LOW"sv;
case GL_DEBUG_SEVERITY_NOTIFICATION:
return "NOTIFICATION"sv;
default:
return "NOT_A_SEVERITY"sv;
}
}
/* Debug message callback given to glDebugMessageCallback. Prints an error
* message to stderr. */
static void GLAPIENTRY opengl_debug_message_callback(
GLenum source, GLenum type, GLuint id, GLenum severity, [[maybe_unused]] GLsizei length,
GLchar const* message, [[maybe_unused]] void const* user_param)
{
#ifndef ENABLE_OPENGL_NOTIFICATIONS
/* Filter out non-error debug messages if not opted-in. */
if (type != GL_DEBUG_TYPE_ERROR)
{
return;
}
/* Note: The printing of non-error debug messages will often be similar to
* > OpenGL debug message (NOTIFICATION severity) API:OTHER(131185)
* > "Buffer detailed info: Buffer object 5
* > (bound to GL_ARRAY_BUFFER_ARB, usage hint is GL_DYNAMIC_DRAW)
* > will use VIDEO memory as the source for buffer object operations."
* (it looks like that on my machine). */
#endif
(type == GL_DEBUG_TYPE_ERROR ? std::cerr : std::cout)
<< "OpenGL debug message "
<< "(" << opengl_debug_message_severity_name(severity) << " severity) "
<< opengl_debug_message_source_name(source) << ":" << opengl_debug_message_type_name(type)
<< "(" << id << ") "
<< (type == GL_DEBUG_TYPE_ERROR ? "\x1b[31m" : "\x1b[34m") << message << "\x1b[39m"
<< std::endl;
}
void enable_opengl_debug_message()
{
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(opengl_debug_message_callback, nullptr);
}
void disable_opengl_debug_message()
{
glDisable(GL_DEBUG_OUTPUT);
}
void error_sdl2_fail(std::string_view operation)
{
std::cerr << "SDL2 error: " << operation << " failed: "
<< "\x1b[31m\"" << SDL_GetError() << "\"\x1b[39m" << std::endl;
}
} /* qwy2 */
| 27.00813 | 92 | 0.735099 |
5a205b4c2557930f1cd90d29161e4aa9bb755121 | 12,929 | cpp | C++ | Sources/simdlib/SimdSse2Texture.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | 6 | 2017-10-13T04:29:38.000Z | 2018-05-10T13:52:20.000Z | Sources/simdlib/SimdSse2Texture.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | Sources/simdlib/SimdSse2Texture.cpp | aestesis/Csimd | b333a8bb7e7f2707ed6167badb8002cfe3504bbc | [
"Apache-2.0"
] | null | null | null | /*
* Simd Library (http://ermig1979.github.io/Simd).
*
* Copyright (c) 2011-2017 Yermalayeu Ihar.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "Simd/SimdMemory.h"
#include "Simd/SimdExtract.h"
#include "Simd/SimdStore.h"
#include "Simd/SimdBase.h"
namespace Simd
{
#ifdef SIMD_SSE2_ENABLE
namespace Sse2
{
SIMD_INLINE __m128i TextureBoostedSaturatedGradient16(__m128i a, __m128i b, __m128i saturation, const __m128i & boost)
{
return _mm_mullo_epi16(_mm_max_epi16(K_ZERO, _mm_add_epi16(saturation, _mm_min_epi16(_mm_sub_epi16(b, a), saturation))), boost);
}
SIMD_INLINE __m128i TextureBoostedSaturatedGradient8(__m128i a, __m128i b, __m128i saturation, const __m128i & boost)
{
__m128i lo = TextureBoostedSaturatedGradient16(_mm_unpacklo_epi8(a, K_ZERO), _mm_unpacklo_epi8(b, K_ZERO), saturation, boost);
__m128i hi = TextureBoostedSaturatedGradient16(_mm_unpackhi_epi8(a, K_ZERO), _mm_unpackhi_epi8(b, K_ZERO), saturation, boost);
return _mm_packus_epi16(lo, hi);
}
template<bool align> SIMD_INLINE void TextureBoostedSaturatedGradient(const uint8_t * src, uint8_t * dx, uint8_t * dy,
size_t stride, __m128i saturation, __m128i boost)
{
const __m128i s10 = Load<false>((__m128i*)(src - 1));
const __m128i s12 = Load<false>((__m128i*)(src + 1));
const __m128i s01 = Load<align>((__m128i*)(src - stride));
const __m128i s21 = Load<align>((__m128i*)(src + stride));
Store<align>((__m128i*)dx, TextureBoostedSaturatedGradient8(s10, s12, saturation, boost));
Store<align>((__m128i*)dy, TextureBoostedSaturatedGradient8(s01, s21, saturation, boost));
}
template<bool align> void TextureBoostedSaturatedGradient(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t saturation, uint8_t boost, uint8_t * dx, size_t dxStride, uint8_t * dy, size_t dyStride)
{
assert(width >= A && int(2)*saturation*boost <= 0xFF);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dx) && Aligned(dxStride) && Aligned(dy) && Aligned(dyStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i _saturation = _mm_set1_epi16(saturation);
__m128i _boost = _mm_set1_epi16(boost);
memset(dx, 0, width);
memset(dy, 0, width);
src += srcStride;
dx += dxStride;
dy += dyStride;
for (size_t row = 2; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureBoostedSaturatedGradient<align>(src + col, dx + col, dy + col, srcStride, _saturation, _boost);
if(width != alignedWidth)
TextureBoostedSaturatedGradient<false>(src + width - A, dx + width - A, dy + width - A, srcStride, _saturation, _boost);
dx[0] = 0;
dy[0] = 0;
dx[width - 1] = 0;
dy[width - 1] = 0;
src += srcStride;
dx += dxStride;
dy += dyStride;
}
memset(dx, 0, width);
memset(dy, 0, width);
}
void TextureBoostedSaturatedGradient(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t saturation, uint8_t boost, uint8_t * dx, size_t dxStride, uint8_t * dy, size_t dyStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dx) && Aligned(dxStride) && Aligned(dy) && Aligned(dyStride))
TextureBoostedSaturatedGradient<true>(src, srcStride, width, height, saturation, boost, dx, dxStride, dy, dyStride);
else
TextureBoostedSaturatedGradient<false>(src, srcStride, width, height, saturation, boost, dx, dxStride, dy, dyStride);
}
template<bool align> SIMD_INLINE void TextureBoostedUv(const uint8_t * src, uint8_t * dst, __m128i min8, __m128i max8, __m128i boost16)
{
const __m128i _src = Load<align>((__m128i*)src);
const __m128i saturated = _mm_sub_epi8(_mm_max_epu8(min8, _mm_min_epu8(max8, _src)), min8);
const __m128i lo = _mm_mullo_epi16(_mm_unpacklo_epi8(saturated, K_ZERO), boost16);
const __m128i hi = _mm_mullo_epi16(_mm_unpackhi_epi8(saturated, K_ZERO), boost16);
Store<align>((__m128i*)dst, _mm_packus_epi16(lo, hi));
}
template<bool align> void TextureBoostedUv(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t boost, uint8_t * dst, size_t dstStride)
{
assert(width >= A && boost < 0x80);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
int min = 128 - (128/boost);
int max = 255 - min;
__m128i min8 = _mm_set1_epi8(min);
__m128i max8 = _mm_set1_epi8(max);
__m128i boost16 = _mm_set1_epi16(boost);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureBoostedUv<align>(src + col, dst + col, min8, max8, boost16);
if(width != alignedWidth)
TextureBoostedUv<false>(src + width - A, dst + width - A, min8, max8, boost16);
src += srcStride;
dst += dstStride;
}
}
void TextureBoostedUv(const uint8_t * src, size_t srcStride, size_t width, size_t height,
uint8_t boost, uint8_t * dst, size_t dstStride)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
TextureBoostedUv<true>(src, srcStride, width, height, boost, dst, dstStride);
else
TextureBoostedUv<false>(src, srcStride, width, height, boost, dst, dstStride);
}
template <bool align> SIMD_INLINE void TextureGetDifferenceSum(const uint8_t * src, const uint8_t * lo, const uint8_t * hi,
__m128i & positive, __m128i & negative, const __m128i & mask)
{
const __m128i _src = Load<align>((__m128i*)src);
const __m128i _lo = Load<align>((__m128i*)lo);
const __m128i _hi = Load<align>((__m128i*)hi);
const __m128i average = _mm_and_si128(mask, _mm_avg_epu8(_lo, _hi));
const __m128i current = _mm_and_si128(mask, _src);
positive = _mm_add_epi64(positive, _mm_sad_epu8(_mm_subs_epu8(current, average), K_ZERO));
negative = _mm_add_epi64(negative, _mm_sad_epu8(_mm_subs_epu8(average, current), K_ZERO));
}
template <bool align> void TextureGetDifferenceSum(const uint8_t * src, size_t srcStride, size_t width, size_t height,
const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, int64_t * sum)
{
assert(width >= A && sum != NULL);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i tailMask = ShiftLeft(K_INV_ZERO, A - width + alignedWidth);
__m128i positive = _mm_setzero_si128();
__m128i negative = _mm_setzero_si128();
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
TextureGetDifferenceSum<align>(src + col, lo + col, hi + col, positive, negative, K_INV_ZERO);
if(width != alignedWidth)
TextureGetDifferenceSum<false>(src + width - A, lo + width - A, hi + width - A, positive, negative, tailMask);
src += srcStride;
lo += loStride;
hi += hiStride;
}
*sum = ExtractInt64Sum(positive) - ExtractInt64Sum(negative);
}
void TextureGetDifferenceSum(const uint8_t * src, size_t srcStride, size_t width, size_t height,
const uint8_t * lo, size_t loStride, const uint8_t * hi, size_t hiStride, int64_t * sum)
{
if(Aligned(src) && Aligned(srcStride) && Aligned(lo) && Aligned(loStride) && Aligned(hi) && Aligned(hiStride))
TextureGetDifferenceSum<true>(src, srcStride, width, height, lo, loStride, hi, hiStride, sum);
else
TextureGetDifferenceSum<false>(src, srcStride, width, height, lo, loStride, hi, hiStride, sum);
}
template <bool align> void TexturePerformCompensation(const uint8_t * src, size_t srcStride, size_t width, size_t height,
int shift, uint8_t * dst, size_t dstStride)
{
assert(width >= A && shift > -0xFF && shift < 0xFF && shift != 0);
if(align)
{
assert(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride));
}
size_t alignedWidth = AlignLo(width, A);
__m128i tailMask = src == dst ? ShiftLeft(K_INV_ZERO, A - width + alignedWidth) : K_INV_ZERO;
if(shift > 0)
{
__m128i _shift = _mm_set1_epi8((char)shift);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
{
const __m128i _src = Load<align>((__m128i*) (src + col));
Store<align>((__m128i*) (dst + col), _mm_adds_epu8(_src, _shift));
}
if(width != alignedWidth)
{
const __m128i _src = Load<false>((__m128i*) (src + width - A));
Store<false>((__m128i*) (dst + width - A), _mm_adds_epu8(_src, _mm_and_si128(_shift, tailMask)));
}
src += srcStride;
dst += dstStride;
}
}
if(shift < 0)
{
__m128i _shift = _mm_set1_epi8((char)-shift);
for (size_t row = 0; row < height; ++row)
{
for (size_t col = 0; col < alignedWidth; col += A)
{
const __m128i _src = Load<align>((__m128i*) (src + col));
Store<align>((__m128i*) (dst + col), _mm_subs_epu8(_src, _shift));
}
if(width != alignedWidth)
{
const __m128i _src = Load<false>((__m128i*) (src + width - A));
Store<false>((__m128i*) (dst + width - A), _mm_subs_epu8(_src, _mm_and_si128(_shift, tailMask)));
}
src += srcStride;
dst += dstStride;
}
}
}
void TexturePerformCompensation(const uint8_t * src, size_t srcStride, size_t width, size_t height,
int shift, uint8_t * dst, size_t dstStride)
{
if(shift == 0)
{
if(src != dst)
Base::Copy(src, srcStride, width, height, 1, dst, dstStride);
return;
}
if(Aligned(src) && Aligned(srcStride) && Aligned(dst) && Aligned(dstStride))
TexturePerformCompensation<true>(src, srcStride, width, height, shift, dst, dstStride);
else
TexturePerformCompensation<false>(src, srcStride, width, height, shift, dst, dstStride);
}
}
#endif// SIMD_SSE2_ENABLE
}
| 48.605263 | 144 | 0.576997 |
5a2491b62de6d3e5599c47df6c0db8cbf3952adf | 2,073 | cpp | C++ | main_twoflavor.cpp | Sam91/vmc_general | cb2b0cb103a66307a3d78dbf137582a3ad224f8d | [
"MIT"
] | null | null | null | main_twoflavor.cpp | Sam91/vmc_general | cb2b0cb103a66307a3d78dbf137582a3ad224f8d | [
"MIT"
] | null | null | null | main_twoflavor.cpp | Sam91/vmc_general | cb2b0cb103a66307a3d78dbf137582a3ad224f8d | [
"MIT"
] | null | null | null | #include <iostream>
#include <iomanip>
#include "lwave2.h"
//#include "amperean.h"
int main(int argc, char *argv[])
{
int req_args = 6;
for(int i=0; i<argc; i++) cout << argv[i] << " ";
cout << endl;
if(argc-1<req_args) {
cout << "Error: incorrect number of arguments\n";
exit(-1);
}
int L = atoi(argv[1]);
lwave2* wf = new lwave2( L );
//amperean* wf = new amperean( L );
//double* dl = new double[4];
//dl[4] = 22.;
//some preparatory configuration of the wave function
//wf->set_lattice( "square" );
//wf->set_lattice( "checkerboard" );
wf->set_lattice( "triangular" );
wf->pars->apx = atoi(argv[2]); //boundary condition in x-direction
wf->pars->apy = atoi(argv[3]);
wf->pars->t1 = (double)atoi(argv[4])/100.; //nearest-neighbor hopping
wf->pars->dd = (double)atoi(argv[5])/100.; //pairing amplitude
// wf->pars->dd0 = (double)atoi(argv[5])/100.; //s-pairing for filled states
wf->pars->phi1 = (double)atoi(argv[6])/100.; //s-pairing for filled states
wf->pars->phi2 = (double)atoi(argv[7])/100.; //s-pairing for filled states
if( argc>=9 ) {
wf->pars->mu = (double)atoi(argv[8])/100.;
wf->pars->t1b = (double)atoi(argv[9])/100.;
wf->pars->t1c = (double)atoi(argv[10])/100.;
} else {
wf->pars->mu = .8;
wf->pars->t1b = wf->pars->t1;
wf->pars->t1c = wf->pars->t1;
}
// wf->pars->r = atoi(argv[6]); // orientation: 0=long axis, 1=short axis
// wf->pars->lth = atoi(argv[7])/100.; //controlling the decay of amperean pairing
// wf->pars->lr1 = atoi(argv[8])/100.;
// wf->pars->lr2 = atoi(argv[9])/100.;
//wf->print();
//create a vmc object and assign the wf
vmc* myvmc = new vmc();
wf->set_mc_length( 300 );
myvmc->set_wf( wf );
wf->findmu();
//wf->create_dd();
//wf->create_ad();
if( argc>=12 ) myvmc->initialize( atoi(argv[11]) ); //number of bins to average over
else myvmc->initialize( 30 ); //number of bins to average over
myvmc->run();
myvmc->calculate_statistics();
// wf->insert_db();
delete myvmc;
delete wf;
return 0;
}
| 25.592593 | 86 | 0.598649 |
5a29a9fb9ebfe976013020cee8c0125af6ab4f40 | 283 | cpp | C++ | Source/Platoon/PlatoonCharacter.cpp | bernhardrieder/Platoon-AI-Simulation-UE4 | f5a3062cea090ddaae35fc97209212c8f8b4bdd9 | [
"Unlicense"
] | 1 | 2018-09-04T19:48:09.000Z | 2018-09-04T19:48:09.000Z | Source/Platoon/PlatoonCharacter.cpp | bernhardrieder/Platoon-AI-Simulation | f5a3062cea090ddaae35fc97209212c8f8b4bdd9 | [
"Unlicense"
] | null | null | null | Source/Platoon/PlatoonCharacter.cpp | bernhardrieder/Platoon-AI-Simulation | f5a3062cea090ddaae35fc97209212c8f8b4bdd9 | [
"Unlicense"
] | null | null | null | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Platoon.h"
#include "PlatoonCharacter.h"
APlatoonCharacter::APlatoonCharacter()
{
PrimaryActorTick.bCanEverTick = false;
PrimaryActorTick.bStartWithTickEnabled = false;
AActor::SetActorHiddenInGame(true);
} | 23.583333 | 60 | 0.791519 |
5a2ae39e781bb0be9e81f6fa5e4c9652c2588bd7 | 721 | cpp | C++ | code archive/GJ/a024.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 4 | 2018-04-08T08:07:58.000Z | 2021-06-07T14:55:24.000Z | code archive/GJ/a024.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | null | null | null | code archive/GJ/a024.cpp | brianbbsu/program | c4505f2b8c0b91010e157db914a63c49638516bc | [
"MIT"
] | 1 | 2018-10-29T12:37:25.000Z | 2018-10-29T12:37:25.000Z | /**********************************************************************************/
/* Problem: a024 "ๆๆไฝๆธๅ" from while ่ฟดๅ */
/* Language: C++ */
/* Result: AC (4ms, 184KB) on ZeroJudge */
/* Author: briansu at 2016-08-25 22:23:33 */
/**********************************************************************************/
#include <iostream>
#include <math.h>
#include <string.h>
using namespace std;
int main()
{
long int n;
cin>>n;
long int m=0;
while(n>0)
{
m+=n%10;
n=floor(n/10);
}
cout<<m;
} | 27.730769 | 84 | 0.281553 |
5a2dac2d68c6ed1ae3f4fa685a3aaa591922f468 | 466 | cpp | C++ | LeetCode/InterviewSchool/125. Valid Palindrome.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | 5 | 2021-02-14T17:48:21.000Z | 2022-01-24T14:29:44.000Z | LeetCode/InterviewSchool/125. Valid Palindrome.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | LeetCode/InterviewSchool/125. Valid Palindrome.cpp | Sowmik23/All-Codes | 212ef0d940fa84624bb2972a257768a830a709a3 | [
"MIT"
] | null | null | null | class Solution {
public:
bool isPalindrome(string s) {
string str = "";
for(int i=0;i<s.size();i++){
if((s[i]>='A' and s[i]<='Z') or (s[i]>='a' and s[i]<='z') or (s[i]>='0' and s[i]<='9')){
str+=tolower(s[i]);
}
}
// cout<<str<<endl;
for(int i=0;i<str.size()/2;i++){
if(str[i]!=str[str.size()-i-1]) return false;
}
return true;
}
};
| 24.526316 | 100 | 0.38412 |
5a3140d44c0243e438b833f769575bea720da7e6 | 8,090 | cpp | C++ | packages/cat/tso2Impact/scenarioAggr.cpp | USEPA/Water-Security-Toolkit | 6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb | [
"BSD-3-Clause"
] | 3 | 2019-06-10T18:04:14.000Z | 2020-12-05T18:11:40.000Z | packages/cat/tso2Impact/scenarioAggr.cpp | USEPA/Water-Security-Toolkit | 6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb | [
"BSD-3-Clause"
] | null | null | null | packages/cat/tso2Impact/scenarioAggr.cpp | USEPA/Water-Security-Toolkit | 6b6b68e0e1b3dcc8023b453ab48a64f7fd740feb | [
"BSD-3-Clause"
] | 2 | 2020-09-24T19:04:14.000Z | 2020-12-05T18:11:43.000Z | /* _________________________________________________________________________
*
* TEVA-SPOT Toolkit: Tools for Designing Contaminant Warning Systems
* Copyright (c) 2008 Sandia Corporation.
* This software is distributed under the BSD License.
* Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
* the U.S. Government retains certain rights in this software.
* For more information, see the README.txt file in the top SPOT directory.
* _________________________________________________________________________
*/
/**
* \file setupIPData.cpp
*
* Creates an input file for the GeneralSP.mod IP model.
*/
#ifdef HAVE_CONFIG_H
#include <teva_config.h>
#endif
#include <utilib/OptionParser.h>
#include <sp/ObjectiveAggr.h>
#include <sp/SPProblem.h>
#include "version.h"
using namespace std;
string dirname(string fullpath, char delimiter = '/')
{
int len = fullpath.length();
int pos = len - 1;
const char *str = fullpath.c_str();
string::reverse_iterator rit(fullpath.rbegin());
while (rit++ != fullpath.rend() && str[pos] != delimiter)
pos--;
pos = pos + 1;
return fullpath.substr(0, pos);
}
string basename(string fullpath, char delimiter = '/')
{
int len = fullpath.length();
int pos = len - 1;
const char *str = fullpath.c_str();
string::reverse_iterator rit(fullpath.rbegin());
while (rit++ != fullpath.rend() && str[pos] != delimiter)
pos--;
pos = pos + 1;
return fullpath.substr(pos, len - pos);
}
void write_aggregated_impact_file(std::string impactInputFileName,
std::string impactOutputFileName,
std::vector<scenario_group>& groups,
std::map<int, int>& group_map)
{
int eventIndex, nnodes;
int num_events = group_map.size();
int nevents2;
int num_aggr_events = groups.size();
std::ifstream in_imp_f(impactInputFileName.c_str());
int delayIndex = read_impact_preamble(in_imp_f, nnodes, 0);
in_imp_f >> eventIndex;
for (int i = 0; i < num_events; i++)
{
std::map<int, double> next_event_impacts;
std::vector<std::pair<int, int> > next_event_sequence;
int cur_index = eventIndex;
eventIndex = read_next_impact(in_imp_f, eventIndex,
next_event_impacts,
next_event_sequence, delayIndex);
int num_impacts = next_event_impacts.size();
int group_num = group_map[cur_index];
cout << "groups[" << group_num << "].ml : " <<
groups[group_num].max_length << endl;
for (int j = 0; j < groups[group_num].max_length; j++)
{
int id = -1;
if (j < next_event_impacts.size())
{
id = next_event_sequence[j].first;
}
if (group_num == 2)
{
}
groups[group_num].impacts[j] +=
next_event_impacts[id];
}
if (group_num == 2)
{
cout << "candidate longest event " << i << endl;
cout << "length: " << next_event_impacts.size() << endl;
cout << "group " << group_num << " max length: " << groups[group_num].max_length
<< endl;
}
if (next_event_impacts.size() == groups[group_num].max_length)
{
for (int j = 0; j < groups[group_num].max_length; j++)
{
groups[group_num].hit_sequence[j] =
next_event_sequence[j].first;
groups[group_num].hit_times[j] =
next_event_sequence[j].second;
}
}
}
std::string impact_dirname = dirname(impactInputFileName);
std::string impact_basename = basename(impactInputFileName);
std::string agImpactOutputFileName;
if (impactOutputFileName == "")
agImpactOutputFileName = impact_dirname + "aggr" + impact_basename;
else
agImpactOutputFileName = impactOutputFileName;
std::string agProbOutputFileName = agImpactOutputFileName + ".prob";
std::ofstream a_imp_f(agImpactOutputFileName.c_str());
std::ofstream a_prob_f(agProbOutputFileName.c_str());
a_imp_f << nnodes << endl;
a_imp_f << "1 0" << endl; // only support delay of 0 in current
// impact format; delays implemented in
// setupIPData, randomsample
for (int i = 0; i < num_aggr_events; i++)
{
// assuming uniform original event probabilities for now
groups[i].event_prob = groups[i].num_events / (double)num_events;
for (int j = 0; j < groups[i].max_length; j++)
{
groups[i].impacts[j] /= groups[i].num_events;
}
for (int j = 0; j < groups[i].max_length; j++)
{
int hitnode = groups[i].hit_sequence[j];
int hittime = groups[i].hit_times[j];
a_imp_f << i + 1 << " " << hitnode
<< " " << hittime
<< " " << groups[i].impacts[j] << std::endl;
}
a_prob_f << i + 1 << " " << groups[i].event_prob << endl;
}
a_imp_f.close();
a_prob_f.close();
}
/// The main routine for setupIPData
int main(int argc, char **argv)
{
try
{
string impactInputFile;
string impactOutputFile;
int numEvents = 0;
utilib::OptionParser options;
options.add_usage("scenarioAggr [options...] <impact-file>");
options.description = "A command to aggregate incidents in an impact file.";
std::string version = create_version("scenarioAggr", __DATE__, __TIME__);
options.version(version);
options.add("numEvents", numEvents, "The number of events before scenario aggregation.");
options.add("out", impactOutputFile, "The output impact filename.");
utilib::OptionParser::args_t args = options.parse_args(argc, argv);
if (options.help_option())
{
options.write(std::cout);
exit(1);
}
if (options.version_option())
{
options.print_version(std::cout);
exit(1);
}
if (args.size() < 2)
{
options.write(std::cerr);
return 1;
}
ifstream in_imp_f(args[1].c_str());
if (!in_imp_f)
EXCEPTION_MNGR(runtime_error, "Bad filename " << args[1]);
SPProblem info;
VecTrie<int, std::vector<int> > theScenarioAggrTrie;
//
// Read in the problem data
//
impactInputFile = args[1];
int eventIndex;
int nnodes;
int delayIndex = read_impact_preamble(in_imp_f, nnodes, 0);
in_imp_f >> eventIndex;
for (int i = 0; i < numEvents; i++)
{
std::map<int, double> next_event_impacts;
std::vector<std::pair<int, int> > next_event_sequence;
int cur_event = eventIndex;
eventIndex = read_next_impact(in_imp_f, eventIndex,
next_event_impacts,
next_event_sequence, delayIndex);
int num_impacts = next_event_impacts.size();
vector<int> hit_list;
for (int i = 0; i < int(next_event_impacts.size() - 1); i++)
{
// don't include dummy
hit_list.push_back(next_event_sequence[i].first);
}
VecTrieKey<int> key(hit_list);
VecTrieNode<int, vector<int> >* n = theScenarioAggrTrie.getnode(key);
if (!n)
{
std::vector<int> scenario_list;
theScenarioAggrTrie.insert(key, scenario_list);
}
else if (!n->hasdata())
{
std::vector<int> scenario_list;
n->setdata(scenario_list);
}
std::vector<int>& scenario_list = theScenarioAggrTrie.getdata(key);
scenario_list.push_back(cur_event);
}
in_imp_f.close();
std::vector<int> key;
std::vector<int> spine_scenarios;
std::vector<scenario_group> groups;
int num_groups = 0;
std::map<int, int> group_map;
ScenarioAggrVisitor vis(key, spine_scenarios, groups, group_map);
theScenarioAggrTrie.dfs(vis);
write_aggregated_impact_file(impactInputFile, impactOutputFile, groups, group_map);
}
STD_CATCH(;)
return 0;
}
| 33.292181 | 95 | 0.603461 |
5a32da1f1584d661f8cb825a427c9278b45bb704 | 222 | cpp | C++ | AudioElement.cpp | OneNot/SFML-PacGuy | d9eb17632e43335282c514027bb93879357bfa74 | [
"Unlicense"
] | null | null | null | AudioElement.cpp | OneNot/SFML-PacGuy | d9eb17632e43335282c514027bb93879357bfa74 | [
"Unlicense"
] | null | null | null | AudioElement.cpp | OneNot/SFML-PacGuy | d9eb17632e43335282c514027bb93879357bfa74 | [
"Unlicense"
] | null | null | null | #include "AudioElement.h"
AudioElement::AudioElement(std::string file)
{
if (!buffer.loadFromFile(file))
{
std::cout << "FAILED TO LOAD: " << file << std::endl;
//todo: error handling
}
sound.setBuffer(buffer);
}
| 18.5 | 55 | 0.666667 |
5a335c34ab3440d624cdf45ee4ead7a9672a0dfb | 571 | cpp | C++ | garbage/class_imple.cpp | wolfdale/Spaghetti-code | 9e395345e1420b9db021b21131601191a869db1d | [
"MIT"
] | 1 | 2018-05-18T16:07:11.000Z | 2018-05-18T16:07:11.000Z | garbage/class_imple.cpp | wolfdale/Spaghetti-code | 9e395345e1420b9db021b21131601191a869db1d | [
"MIT"
] | 5 | 2015-12-03T16:12:38.000Z | 2020-05-05T14:07:00.000Z | garbage/class_imple.cpp | wolfdale/Spaghetti-code | 9e395345e1420b9db021b21131601191a869db1d | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class item
{
int number;
float cost;
public:
void getdata(int a,float b); //Prototype decleration
void putdata(void)
{
cout<<"Number:"<<number<<"\n";
cout<<"Cost :"<<cost<<"\n";
}
};
//*************Member Function Definition******************//
void item::getdata(int a, float b)
{
number = a; // Private variables directly used
cost = b;
}
int main()
{
item x; //Object Declaration
cout<<"OBJECT X" << "\n";
x.getdata(5,5.8);
x.putdata();
return 0;
}
| 15.026316 | 61 | 0.537653 |
5a35d44b96820ecf83dd807b0a7b21df31f3efca | 2,027 | cc | C++ | Codeforces/339 Division 1/Problem B/B.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/339 Division 1/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/339 Division 1/Problem B/B.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include <bits/stdc++.h>
#define sd(x) scanf("%d",&x)
#define sd2(x,y) scanf("%d%d",&x,&y)
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z)
#define fi first
#define se second
#define pb(x) push_back(x)
#define mp(x,y) make_pair(x,y)
#define LET(x, a) __typeof(a) x(a)
#define foreach(it, v) for(LET(it, v.begin()); it != v.end(); it++)
#define _ ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define __ freopen("input.txt","r",stdin);freopen("output.txt","w",stdout);
#define func __FUNCTION__
#define line __LINE__
using namespace std;
typedef long long ll;
template<typename S, typename T>
ostream& operator<<(ostream& out, pair<S, T> const& p){out<<'('<<p.fi<<", "<<p.se<<')'; return out;}
template<typename T>
ostream& operator<<(ostream& out, vector<T> const & v){
ll l = v.size(); for(ll i = 0; i < l-1; i++) out<<v[i]<<' '; if(l>0) out<<v[l-1]; return out;}
void tr(){cout << endl;}
template<typename S, typename ... Strings>
void tr(S x, const Strings&... rest){cout<<x<<' ';tr(rest...);}
const ll N = 100100;
ll n, A, cf, cm, m;
vector<pair<ll, ll> > u, v;
ll ans[N], sum[N];
int main(){ _
cin >> n >> A >> cf >> cm >> m;
for(int i = 0; i < n; i++){
ll x; cin >> x;
u.pb(mp(x,i));
}
sort(u.begin(), u.end());
for(int i = 0; i < n; i++){
sum[i+1] = sum[i] + u[i].fi;
}
v = u;
ll force = -1, ansi = -1, ansm = -1;
for(int i = 0, j = 0; i <= n; i++){
ll cost = 0, tmp = 0;
cost = A*(n-i) - (sum[n] - sum[i]);
if(cost > m) continue;
tmp += (n-i)*cf;
ll rem = m - cost;
while(j < i and j*v[j].fi - sum[j] <= rem){
j++;
}
ll mn;
if(j > 0){
mn = min(A, (rem + sum[j])/j);
}
else{
mn = A;
}
tmp += mn*cm;
if(tmp > force){
force = tmp;
ansi = i;
ansm = mn;
}
}
cout << force << endl;
for(int i = 0; i < n; i++){
if(i < ansi){
v[i].fi = max(v[i].fi, ansm);
}
else v[i].fi = A;
ans[v[i].se] = v[i].fi;
}
for(int i = 0; i < n; i++){
cout << ans[i] << ' ';
}
cout << endl;
return 0;
}
| 19.304762 | 100 | 0.519487 |
5a36e0bd1c379ad2d5982af7133e70f963b417cd | 11,042 | cpp | C++ | Milestone 4/Milestone 4/Milestone 4/Main.cpp | Shantanu-Chauhan/RigidBody | 638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1 | [
"Apache-2.0"
] | 1 | 2020-09-26T11:59:55.000Z | 2020-09-26T11:59:55.000Z | Milestone 4/Milestone 4/Milestone 4/Main.cpp | Shantanu-Chauhan/RigidBody | 638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1 | [
"Apache-2.0"
] | null | null | null | Milestone 4/Milestone 4/Milestone 4/Main.cpp | Shantanu-Chauhan/RigidBody | 638e7fc248cccdfca21a12c6c80b2d9b7b23e7e1 | [
"Apache-2.0"
] | null | null | null | /* Start Header -------------------------------------------------------
Copyright (C) 2018 DigiPen Institute of Technology.
Reproduction or disclosure of this file or its contents without the prior
written consent of DigiPen Institute of Technology is prohibited.
File Name: Main.cpp
Purpose: Implementing Game Engine Architecture
Language: C++ language
Platform: Visual Studio Community 2017 - Visual C++ 15.8.2, Windows 10
Project: CS529_shantanu.chauhan_milestone1
Author: Shantanu Chauhan, shantanu.chauhan, 60002518
Creation date: 18th September 2018
- End Header --------------------------------------------------------*/
#include<GL/glew.h>
#include <SDL.h>
#include<SDL_opengl.h>
#include "stdio.h"
#include"src/Manager/Input Manager.h"
#include"src/Frame Rate Controller.h"
#include"Windows.h"
#include<iostream>
#include"src/Global_Header.h"
#include"src/Manager/Resource Manager.h"
#include"src/Manager/Game Object Manager.h"
#include"src/Manager/Event Manager.h"
#include"src/Game Object.h"
#include"Components/Sprite.h"
#include"Components/Transform.h"
#include"Components/Controller.h"
#include"Components/Component.h"
#include"src/ObjectFactory.h"
#include"Components/Body.h"
#include"src/Manager/PhysicsManager.h"
#include"src/Manager/CollisionManager.h"
#include"src/OpenGL/VertexBuffer.h"
#include"src/OpenGL/IndexBuffer.h"
#include"src/OpenGL/VertexArray.h"
#include"src/OpenGL/VertexBufferLayout.h"
#include"src/OpenGL/Texture.h"
#include"src/OpenGL/Shader.h"
#include"src/OpenGL/Renderer.h"
#include"glm/glm.hpp"
#include"glm/gtc/matrix_transform.hpp"
#include"imgui/imgui.h"
#include "imgui/imconfig.h"
#include"imgui/imgui_impl_sdl.h"
#include "imgui/imgui_impl_opengl3.h"
#include"src/Camera.h"
bool appIsRunning = true;
FrameRateController *gpFRC = nullptr;
Input_Manager *gpInputManager=nullptr;
ObjectFactory *gpGameObjectFactory = nullptr;
ResourceManager *gpResourceManager = nullptr;
GameObjectManager *gpGameObjectManager = nullptr;
PhysicsManager *gpPhysicsManager = nullptr;
CollisionManager *gpCollisionManager = nullptr;
EventManager *gpEventManager = nullptr;
Renderer *gpRenderer=nullptr;
Shader* shader=nullptr;
Camera *gpCamera = nullptr;
FILE _iob[] = { *stdin, *stdout, *stderr };
#define MAX_FRAME_RATE 60
extern "C" FILE * __cdecl __iob_func(void)
{
return _iob;
}
#pragma comment(lib, "legacy_stdio_definitions.lib")
int main(int argc, char* args[])
{
if (AllocConsole())
{
FILE* file;
freopen_s(&file, "CONOUT$", "wt", stdout);
freopen_s(&file, "CONOUT$", "wt", stderr);
freopen_s(&file, "CONOUT$", "wt", stdin);
SetConsoleTitle("CS550(MADE IT SOMEHOW!YES!) :-)");
}
SDL_Window *pWindow;
SDL_Surface *pWindowSurface;
int error = 0;
SDL_Surface *pImage = NULL;
// Initialize SDL
gpFRC = new FrameRateController(MAX_FRAME_RATE);//Paraeter is the FPS
gpInputManager =new Input_Manager();
gpGameObjectFactory = new ObjectFactory();
gpResourceManager = new ResourceManager();
gpGameObjectManager = new GameObjectManager();
gpCollisionManager = new CollisionManager();
gpEventManager = new EventManager();
gpRenderer = new Renderer();
gpCamera = new Camera(5, 10, 20, 0, 1, 0, -90, -15);
if((error = SDL_Init( SDL_INIT_VIDEO )) < 0 )
{
printf("Couldn't initialize SDL, error %i\n", error);
return 1;
}
pWindow = SDL_CreateWindow("CS550(MADE IT SOMEHOW!!!!) :-)", // window title
10, // initial x position
25, // initial y position
SCREEN_WIDTH, // width, in pixels
SCREEN_HEIGHT, // height, in pixels
SDL_WINDOW_OPENGL);
// Check that the window was successfully made
if (NULL == pWindow)
{
// In the event that the window could not be made...
printf("Could not create window: %s\n", SDL_GetError());
return 1;
}
auto OpenGL_context = SDL_GL_CreateContext(pWindow);
if (glewInit() != GLEW_OK)
printf(" Error in glew init\n");
pWindowSurface = SDL_GetWindowSurface(pWindow);
if (!pWindowSurface)
{
printf(SDL_GetError());
}
gpGameObjectFactory->LoadLevel("Title_Screenp.txt",false);
float positions[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,//* 0
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,// 1
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//** 2
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//** 3
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,// 4
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,//* 5
//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//*** 6
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,// 7
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,// 8
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,// 9
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,// 10
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//*** 11
//
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,//
//
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,//
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,//
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,//
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f //
};
//vid 9
unsigned int indices[] = {
0,1,2,
3,4,5,
6,7,8,
9,10,11,
12,13,14,
15,16,17,
18,19,20,
21,22,23,
24,25,26,
27,28,29,
30,31,32,
33,34,35,
};
//IMGUI
ImGui::CreateContext();
ImGui_ImplSDL2_InitForOpenGL(pWindow, OpenGL_context);
ImGui_ImplOpenGL3_Init("#version 330");
std::cout << glGetString(GL_RENDERER) << std::endl;
ImGui::StyleColorsDark();
//IMGUI
GLCall(glEnable(GL_BLEND));
glEnable(GL_DEPTH_TEST);
GLCall(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
{
VertexArray va;
VertexBuffer vb(positions, 36 * 5 * sizeof(float));
VertexBufferLayout layout;
layout.Push<float>(3);
layout.Push<float>(2);
va.AddBuffer(vb, layout);
IndexBuffer ib(indices, 36);
//------------------------------------------------------------------------------------
//Writing down the shader
shader = new Shader("src/res/shaders/Basic.shader");
shader->Bind();
//------------------------------------------------------------------------------------
gpPhysicsManager = new PhysicsManager();//Keep this after level loading so that bodies can be pushed into the broad phase
// Game loop
bool reverse = false;
bool pause = true;
float deltaTime = 0.016f;
bool debug = false;
bool step = false;
while (true == appIsRunning)
{
gpFRC->FrameStart();
gpInputManager->Update();
gpRenderer->Clear();
GLCall(glClearColor(0.5, 0.5, 0.5, 1.0));
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(pWindow);
ImGui::NewFrame();
if (gpInputManager->isTriggered(SDL_SCANCODE_SPACE))
pause = !pause;
if (gpInputManager->isTriggered(SDL_SCANCODE_R))//reverse time(this doesnt work)
{
pause = false;
reverse = !reverse;
}
if (gpInputManager->isTriggered(SDL_SCANCODE_O))//debug toggle
{
debug = !debug;
}
float frameTime = (float)gpFRC->GetFrameTime();
frameTime = frameTime / 1000.0f;
gpCamera->Update(gpInputManager,frameTime);
ImGui::Begin("MADE BY SHANTANU CHAUHAN!");
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("To move the camera use the arrow keys");
ImGui::Text("To rotate the camera right click and move the mouse");
ImGui::Text("Press 'O'(not zero! but 'o') to draw the mesh of the dynamicAABB tree");
ImGui::Text("Press '1' to get the BALL AND SOCKET JOINT");
ImGui::Text("Press '2' to get the big stack of cubes");
ImGui::Text("Press '3' to get the single stack of 10 cubes");
ImGui::Text("Press '4' to get HINGE JOINT");
ImGui::Text("Press '5' to get the BRIDGE");
ImGui::Text("Press 'SPACE' to pause/resume the simulation");
ImGui::Text("Press 'Enter' to step the physics update");
ImGui::Text("Press 'Escape' to close the application");
ImGui::End();
if (gpInputManager->isTriggered(SDL_SCANCODE_RETURN))//step
{
step = true;
frameTime = deltaTime;
}
if (gpInputManager->isTriggered(SDL_SCANCODE_1))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", false);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_2))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt",true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_3))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_4))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_5))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
if (gpInputManager->isTriggered(SDL_SCANCODE_6))//Load the big level
{
gpGameObjectFactory->LoadLevel("Title_Screenp.txt", true);
}
gpEventManager->Update(frameTime);
for (int i = 0; i < static_cast<int>(gpGameObjectManager->mGameobjects.size()); ++i)
{
gpGameObjectManager->mGameobjects[i]->Update();
}
if (step)
{
pause = false;
}
if(!pause)
gpPhysicsManager->Update(1/60.0f);//Physics update
if (step)
{
pause = true;
step = false;
}
//Dubug
for (auto go : gpGameObjectManager->mGameobjects)
{
Body *pBody = static_cast<Body*>(go->GetComponent(BODY));
//ImGui::SetNextWindowPosCenter(ImGuiCond_Once);
ImGui::Begin("Cubes data(You can move them but identifying which is which is hard)");
ImGui::PushID(pBody);
ImGui::SliderFloat3("Location:", &pBody->mPos.x, -5.0f, 5.0f);
ImGui::SliderFloat4("Quat:", &pBody->quaternion.x, -1.0f, 1.0f);
ImGui::SliderFloat4("Vel:", &pBody->mVel.x, -10.0f, 10.0f);
ImGui::SliderFloat4("angular", &pBody->AngularVelocity.x, -2.0f, 2.0f);
//ImGui::Text("Angular - x-%f,y-%f,z-%f", pBody->AngularVelocity.x, pBody->AngularVelocity.y, pBody->AngularVelocity.z);
ImGui::PopID();
ImGui::End();
}
//Draw All the game objects
gpGameObjectManager->DrawObjectDraw(va, ib, shader, debug);
//Debug
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
SDL_GL_SwapWindow(pWindow);
gpFRC->FrameEnd();
}
}
delete gpFRC;
delete shader;
delete gpRenderer;
delete gpEventManager;
delete gpCollisionManager;
delete gpPhysicsManager;
delete gpGameObjectManager;
delete gpResourceManager;
delete gpGameObjectFactory;
delete gpInputManager;
SDL_DestroyWindow(pWindow);
SDL_Quit();
return 0;
} | 29.134565 | 125 | 0.642003 |
5a3a649a9888e3e73c4dd200603fd798b553f153 | 711 | hpp | C++ | include/mh/network/server.hpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | include/mh/network/server.hpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | include/mh/network/server.hpp | overworks/MhGameLib | 87973e29633ed09a3fa51eb27ea7fc8af5e9d71b | [
"MIT"
] | null | null | null | #ifndef _MH_NETWORK_SERVER_HPP_
#define _MH_NETWORK_SERVER_HPP_
/*
* ์๋ฒ ์ธํฐํ์ด์ค
*/
#include <mh/types.hpp>
#define SERVER_INTERFACE(name)\
name();\
virtual ~name();\
virtual bool initialize( u32 address, u16 port );\
namespace Mh
{
namespace Network
{
class Socket;
// ์ ์ก ํ๋กํ ์ฝ
enum TP // Transfort protocol
{
TP_TCP, // ์ผ๋จ์ ์ด ๋๊ฐ๋ง...
TP_UDP,
};
struct ServerDesc
{
u32 addrees; // ์๋ฒ ์ฃผ์
u16 port; // ํฌํธ
TP protocol; // ์ ์ก ํ๋กํ ์ฝ(TCP, UDP)
};
class Server
{
public:
Server() {}
virtual ~Server() {}
virtual bool initialize( u32 address, u16 port ) = 0;
};
} // namespace Mh::Network
} // namespace Mh
#endif /* _MH_NETWORK_SERVER_HPP_ */ | 14.8125 | 56 | 0.618847 |
5a3c7f000ab12b0e63964ccd7e36f5e481fcae1a | 1,246 | cc | C++ | libs/fel/src/fel/file.cc | madeso/fel | 2ec89ce0195545385125d0a02c90aaa65492c1a9 | [
"MIT"
] | 3 | 2019-12-15T10:29:15.000Z | 2021-07-24T19:39:29.000Z | libs/fel/src/fel/file.cc | madeso/fel | 2ec89ce0195545385125d0a02c90aaa65492c1a9 | [
"MIT"
] | null | null | null | libs/fel/src/fel/file.cc | madeso/fel | 2ec89ce0195545385125d0a02c90aaa65492c1a9 | [
"MIT"
] | null | null | null | #include "fel/file.h"
#include <sstream>
#include <iostream>
#include <fstream>
#include <cassert>
namespace fel
{
File::File(const std::string& a_filename, const std::string& a_content)
: filename(a_filename)
, data(a_content)
{
}
FilePointer::FilePointer(const File& a_file)
: file(a_file)
{
}
bool
FilePointer::HasMore() const
{
return next_index < file.data.size();
}
char
FilePointer::Read()
{
if(next_index < file.data.size())
{
const auto read = file.data[next_index];
next_index += 1;
if(read == '\n')
{
location.line += 1;
location.column = 0;
}
else
{
location.column += 1;
}
return read;
}
else
{
return 0;
}
}
char
FilePointer::Peek(std::size_t advance) const
{
// assert(next_index > 0);
const auto index = next_index + advance - 1;
if(index < file.data.size())
{
return file.data[index];
}
else
{
return 0;
}
}
}
| 17.549296 | 75 | 0.457464 |