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
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
1e03dc884a7253fb4f979fff0ade588bf574bd4b
7,292
cxx
C++
portaudio/bindings/cpp/source/portaudiocpp/System.cxx
gergocs/cpmpvoice
f438efcddf10ef3d3e0664eca5ace81367629235
[ "Apache-2.0" ]
393
2021-07-04T20:27:15.000Z
2021-09-21T10:44:47.000Z
portaudio/bindings/cpp/source/portaudiocpp/System.cxx
gergocs/cpmpvoice
f438efcddf10ef3d3e0664eca5ace81367629235
[ "Apache-2.0" ]
41
2021-07-05T17:31:57.000Z
2021-09-14T03:51:01.000Z
portaudio/bindings/cpp/source/portaudiocpp/System.cxx
gergocs/cpmpvoice
f438efcddf10ef3d3e0664eca5ace81367629235
[ "Apache-2.0" ]
32
2021-07-05T12:34:57.000Z
2021-08-15T21:18:54.000Z
#include "portaudiocpp/System.hxx" #include <cstddef> #include <cassert> #include "portaudiocpp/HostApi.hxx" #include "portaudiocpp/Device.hxx" #include "portaudiocpp/Stream.hxx" #include "portaudiocpp/Exception.hxx" #include "portaudiocpp/SystemHostApiIterator.hxx" #include "portaudiocpp/SystemDeviceIterator.hxx" namespace portaudio { // ----------------------------------------------------------------------------------- // Static members: System *System::instance_ = NULL; int System::initCount_ = 0; HostApi **System::hostApis_ = NULL; Device **System::devices_ = NULL; Device *System::nullDevice_ = NULL; // ----------------------------------------------------------------------------------- int System::version() { return Pa_GetVersion(); } const char *System::versionText() { return Pa_GetVersionText(); } void System::initialize() { ++initCount_; if (initCount_ == 1) { // Create singleton: assert(instance_ == NULL); instance_ = new System(); // Initialize the PortAudio system: { PaError err = Pa_Initialize(); if (err != paNoError) throw PaException(err); } // Create and populate device array: { int numDevices = instance().deviceCount(); devices_ = new Device*[numDevices]; for (int i = 0; i < numDevices; ++i) devices_[i] = new Device(i); } // Create and populate host api array: { int numHostApis = instance().hostApiCount(); hostApis_ = new HostApi*[numHostApis]; for (int i = 0; i < numHostApis; ++i) hostApis_[i] = new HostApi(i); } // Create null device: nullDevice_ = new Device(paNoDevice); } } void System::terminate() { PaError err = paNoError; if (initCount_ == 1) { // Destroy null device: delete nullDevice_; // Destroy host api array: { if (hostApis_ != NULL) { int numHostApis = instance().hostApiCount(); for (int i = 0; i < numHostApis; ++i) delete hostApis_[i]; delete[] hostApis_; hostApis_ = NULL; } } // Destroy device array: { if (devices_ != NULL) { int numDevices = instance().deviceCount(); for (int i = 0; i < numDevices; ++i) delete devices_[i]; delete[] devices_; devices_ = NULL; } } // Terminate the PortAudio system: assert(instance_ != NULL); err = Pa_Terminate(); // Destroy singleton: delete instance_; instance_ = NULL; } if (initCount_ > 0) --initCount_; if (err != paNoError) throw PaException(err); } System &System::instance() { assert(exists()); return *instance_; } bool System::exists() { return (instance_ != NULL); } // ----------------------------------------------------------------------------------- System::HostApiIterator System::hostApisBegin() { System::HostApiIterator tmp; tmp.ptr_ = &hostApis_[0]; // begin (first element) return tmp; } System::HostApiIterator System::hostApisEnd() { int count = hostApiCount(); System::HostApiIterator tmp; tmp.ptr_ = &hostApis_[count]; // end (one past last element) return tmp; } HostApi &System::defaultHostApi() { PaHostApiIndex defaultHostApi = Pa_GetDefaultHostApi(); if (defaultHostApi < 0) throw PaException(defaultHostApi); return *hostApis_[defaultHostApi]; } HostApi &System::hostApiByTypeId(PaHostApiTypeId type) { PaHostApiIndex index = Pa_HostApiTypeIdToHostApiIndex(type); if (index < 0) throw PaException(index); return *hostApis_[index]; } HostApi &System::hostApiByIndex(PaHostApiIndex index) { if (index < 0 || index >= hostApiCount()) throw PaException(paInternalError); return *hostApis_[index]; } int System::hostApiCount() { PaHostApiIndex count = Pa_GetHostApiCount(); if (count < 0) throw PaException(count); return count; } // ----------------------------------------------------------------------------------- System::DeviceIterator System::devicesBegin() { DeviceIterator tmp; tmp.ptr_ = &devices_[0]; return tmp; } System::DeviceIterator System::devicesEnd() { int count = deviceCount(); DeviceIterator tmp; tmp.ptr_ = &devices_[count]; return tmp; } ////// /// Returns the System's default input Device, or the null Device if none /// was available. ////// Device &System::defaultInputDevice() { PaDeviceIndex index = Pa_GetDefaultInputDevice(); return deviceByIndex(index); } ////// /// Returns the System's default output Device, or the null Device if none /// was available. ////// Device &System::defaultOutputDevice() { PaDeviceIndex index = Pa_GetDefaultOutputDevice(); return deviceByIndex(index); } ////// /// Returns the Device for the given index. /// Will throw a paInternalError equivalent PaException if the given index /// is out of range. ////// Device &System::deviceByIndex(PaDeviceIndex index) { if (index < -1 || index >= deviceCount()) { throw PaException(paInternalError); } if (index == -1) return System::instance().nullDevice(); return *devices_[index]; } int System::deviceCount() { PaDeviceIndex count = Pa_GetDeviceCount(); if (count < 0) throw PaException(count); return count; } Device &System::nullDevice() { return *nullDevice_; } // ----------------------------------------------------------------------------------- void System::sleep(long msec) { Pa_Sleep(msec); } int System::sizeOfSample(PaSampleFormat format) { PaError err = Pa_GetSampleSize(format); if (err < 0) { throw PaException(err); return 0; } return err; } // ----------------------------------------------------------------------------------- System::System() { // (left blank intentionally) } System::~System() { // (left blank intentionally) } // ----------------------------------------------------------------------------------- } // namespace portaudio
23.675325
90
0.475453
gergocs
1e0516f8ddeaf90d4434c1e03eaf9fb150c014c7
8,298
hh
C++
libsrc/pylith/fekernels/DispVel.hh
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
null
null
null
libsrc/pylith/fekernels/DispVel.hh
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
null
null
null
libsrc/pylith/fekernels/DispVel.hh
Grant-Block/pylith
f6338261b17551eba879da998a5aaf2d91f5f658
[ "MIT" ]
null
null
null
/* -*- C++ -*- * * ---------------------------------------------------------------------- * * Brad T. Aagaard, U.S. Geological Survey * Charles A. Williams, GNS Science * Matthew G. Knepley, University of Chicago * * This code was developed as part of the Computational Infrastructure * for Geodynamics (http:*geodynamics.org). * * Copyright (c) 2010-2015 University of California, Davis * * See COPYING for license information. * * ---------------------------------------------------------------------- */ /** @file libsrc/fekernels/DispVel.hh * * Kernels for time evolution equation with displacement and velocity * solution fields. * * Solution fields: [disp(dim), vel(dim, optional)] * * Auxiliary fields: [...] (not used) * * \int_V \vec{\phi}_v \cdot \left( \frac{\partial \vec{u}(t)}{\partial t} \right) \, dV = * \int_V \vec{\phi}_v \cdot \vec{v}(t) \, dV. * * LHS Residual * * f0_DispVel: \vec{f0} = \frac{\partial \vec{u}(t)}{\partial t} * * RHS Residual * * g0_DispVel: \vec{g0} = \vec{v}(t) * * LHS Jacobian * * Jf0_veldisp_DispVelImplicit: s_tshift * * Jf0_veldisp_DispVelExplicit: 0 * * RHS Jacobian * * Jg0_velvel_DispVel: +1.0 * * ====================================================================== */ #if !defined(pylith_fekernels_DispVel_hh) #define pylith_fekernels_DispVel_hh // Include directives --------------------------------------------------- #include "fekernelsfwd.hh" // forward declarations #include "pylith/utils/types.hh" class pylith::fekernels::DispVel { // PUBLIC MEMBERS /////////////////////////////////////////////////////// public: /** Kernel interface. * * @param[in] dim Spatial dimension. * @param[in] numS Number of registered subfields in solution field. * @param[in] numA Number of registered subfields in auxiliary field. * @param[in] sOff Offset of registered subfields in solution field [numS]. * @param[in] sOff_x Offset of registered subfields in gradient of the solution field [numS]. * @param[in] s Solution field with all subfields. * @param[in] s_t Time derivative of solution field. * @param[in] s_x Gradient of solution field. * @param[in] aOff Offset of registered subfields in auxiliary field [numA] * @param[in] aOff_x Offset of registered subfields in gradient of auxiliary field [numA] * @param[in] a Auxiliary field with all subfields. * @param[in] a_t Time derivative of auxiliary field. * @param[in] a_x Gradient of auxiliary field. * @param[in] t Time for residual evaluation. * @param[in] x Coordinates of point evaluation. * @param[in] numConstants Number of registered constants. * @param[in] constants Array of registered constants. * @param[out] f0 [dim]. */ /** f0 function for displacement equation: f0u = \dot{u}. * * Solution fields: [disp(dim), vel(dim)] */ static void f0u(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar f0[]); /** f0 function for velocity equation: f0u = \dot{v}. * * Solution fields: [disp(dim), vel(dim)] */ static void f0v(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar f0[]); /** g0 function for displacement equation: g0u = v. * * Solution fields: [disp(dim), vel(dim)] */ static void g0u(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar g0[]); /** Jf0 function for displacement equation with zero values on diagonal. * * This is associated with the elasticity equation without intertia. * * Solution fields: [...] */ static void Jf0uu_zero(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithReal s_tshift, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar Jf0[]); /** Jf0 function for displacement equation: Jf0uu = s_tshift. * * Solution fields: [disp(dim), vel(dim)] */ static void Jf0uu_stshift(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithReal s_tshift, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar Jf0[]); /** Jg0 function for displacement equation: 1.0. * * Solution fields: [disp(dim), vel(dim)] */ static void Jg0uv(const PylithInt dim, const PylithInt numS, const PylithInt numA, const PylithInt sOff[], const PylithInt sOff_x[], const PylithScalar s[], const PylithScalar s_t[], const PylithScalar s_x[], const PylithInt aOff[], const PylithInt aOff_x[], const PylithScalar a[], const PylithScalar a_t[], const PylithScalar a_x[], const PylithReal t, const PylithReal s_tshift, const PylithScalar x[], const PylithInt numConstants, const PylithScalar constants[], PylithScalar Jg0[]); }; // DispVel #endif /* pylith_fekernels_DispVel_hh */ /* End of file */
33.595142
97
0.532056
Grant-Block
1e065030a3efebd8d5ad4edf227539dd0751669c
79,003
cpp
C++
emulator/src/devices/cpu/powerpc/ppccom.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/devices/cpu/powerpc/ppccom.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/devices/cpu/powerpc/ppccom.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Aaron Giles /*************************************************************************** ppccom.c Common PowerPC definitions and functions ***************************************************************************/ #include "emu.h" #include "ppccom.h" #include "ppcfe.h" #include "ppc_dasm.h" /*************************************************************************** DEBUGGING ***************************************************************************/ #define PRINTF_SPU (0) #define PRINTF_DECREMENTER (0) /*************************************************************************** CONSTANTS ***************************************************************************/ #define DOUBLE_SIGN (0x8000000000000000U) #define DOUBLE_EXP (0x7ff0000000000000U) #define DOUBLE_FRAC (0x000fffffffffffffU) #define DOUBLE_ZERO (0) /*************************************************************************** PRIVATE GLOBAL VARIABLES ***************************************************************************/ /* lookup table for FP modes */ static const uint8_t fpmode_source[4] = { uml::ROUND_ROUND, uml::ROUND_TRUNC, uml::ROUND_CEIL, uml::ROUND_FLOOR }; /* flag lookup table for SZ */ static const uint8_t sz_cr_table_source[32] = { /* ..... */ 0x4, /* ....C */ 0x4, /* ...V. */ 0x4, /* ...VC */ 0x4, /* ..Z.. */ 0x2, /* ..Z.C */ 0x2, /* ..ZV. */ 0x2, /* ..ZVC */ 0x2, /* .S... */ 0x8, /* .S..C */ 0x8, /* .S.V. */ 0x8, /* .S.VC */ 0x8, /* .SZ.. */ 0x2, /* .SZ.C */ 0x2, /* .SZV. */ 0x2, /* .SZVC */ 0x2, /* U.... */ 0x4, /* U...C */ 0x4, /* U..V. */ 0x4, /* U..VC */ 0x4, /* U.Z.. */ 0x2, /* U.Z.C */ 0x2, /* U.ZV. */ 0x2, /* U.ZVC */ 0x2, /* US... */ 0x8, /* US..C */ 0x8, /* US.V. */ 0x8, /* US.VC */ 0x8, /* USZ.. */ 0x2, /* USZ.C */ 0x2, /* USZV. */ 0x2, /* USZVC */ 0x2 }; /* flag lookup table for CMP */ static const uint8_t cmp_cr_table_source[32] = { /* ..... */ 0x4, /* ....C */ 0x4, /* ...V. */ 0x8, /* ...VC */ 0x8, /* ..Z.. */ 0x2, /* ..Z.C */ 0x2, /* ..ZV. */ 0x2, /* ..ZVC */ 0x2, /* .S... */ 0x8, /* .S..C */ 0x8, /* .S.V. */ 0x4, /* .S.VC */ 0x4, /* .SZ.. */ 0x2, /* .SZ.C */ 0x2, /* .SZV. */ 0x2, /* .SZVC */ 0x2, /* U.... */ 0x4, /* U...C */ 0x4, /* U..V. */ 0x8, /* U..VC */ 0x8, /* U.Z.. */ 0x2, /* U.Z.C */ 0x2, /* U.ZV. */ 0x2, /* U.ZVC */ 0x2, /* US... */ 0x8, /* US..C */ 0x8, /* US.V. */ 0x4, /* US.VC */ 0x4, /* USZ.. */ 0x2, /* USZ.C */ 0x2, /* USZV. */ 0x2, /* USZVC */ 0x2 }; /* flag lookup table for CMPL */ static const uint8_t cmpl_cr_table_source[32] = { /* ..... */ 0x4, /* ....C */ 0x8, /* ...V. */ 0x4, /* ...VC */ 0x8, /* ..Z.. */ 0x2, /* ..Z.C */ 0x2, /* ..ZV. */ 0x2, /* ..ZVC */ 0x2, /* .S... */ 0x4, /* .S..C */ 0x8, /* .S.V. */ 0x4, /* .S.VC */ 0x8, /* .SZ.. */ 0x2, /* .SZ.C */ 0x2, /* .SZV. */ 0x2, /* .SZVC */ 0x2, /* U.... */ 0x4, /* U...C */ 0x8, /* U..V. */ 0x4, /* U..VC */ 0x8, /* U.Z.. */ 0x2, /* U.Z.C */ 0x2, /* U.ZV. */ 0x2, /* U.ZVC */ 0x2, /* US... */ 0x4, /* US..C */ 0x8, /* US.V. */ 0x4, /* US.VC */ 0x8, /* USZ.. */ 0x2, /* USZ.C */ 0x2, /* USZV. */ 0x2, /* USZVC */ 0x2 }; /* flag lookup table for FCMP */ static const uint8_t fcmp_cr_table_source[32] = { /* ..... */ 0x4, /* ....C */ 0x8, /* ...V. */ 0x4, /* ...VC */ 0x8, /* ..Z.. */ 0x2, /* ..Z.C */ 0xa, /* ..ZV. */ 0x2, /* ..ZVC */ 0xa, /* .S... */ 0x4, /* .S..C */ 0x8, /* .S.V. */ 0x4, /* .S.VC */ 0x8, /* .SZ.. */ 0x2, /* .SZ.C */ 0xa, /* .SZV. */ 0x2, /* .SZVC */ 0xa, /* U.... */ 0x5, /* U...C */ 0x9, /* U..V. */ 0x5, /* U..VC */ 0x9, /* U.Z.. */ 0x3, /* U.Z.C */ 0xb, /* U.ZV. */ 0x3, /* U.ZVC */ 0xb, /* US... */ 0x5, /* US..C */ 0x9, /* US.V. */ 0x5, /* US.VC */ 0x9, /* USZ.. */ 0x3, /* USZ.C */ 0xb, /* USZV. */ 0x3, /* USZVC */ 0xb }; DEFINE_DEVICE_TYPE(PPC601, ppc601_device, "ppc601", "IBM PowerPC 601") DEFINE_DEVICE_TYPE(PPC602, ppc602_device, "ppc602", "IBM PowerPC 602") DEFINE_DEVICE_TYPE(PPC603, ppc603_device, "ppc603", "IBM PowerPC 603") DEFINE_DEVICE_TYPE(PPC603E, ppc603e_device, "ppc603e", "IBM PowerPC 603E") DEFINE_DEVICE_TYPE(PPC603R, ppc603r_device, "ppc603r", "IBM PowerPC 603R") DEFINE_DEVICE_TYPE(PPC604, ppc604_device, "ppc604", "IBM PowerPC 604") DEFINE_DEVICE_TYPE(MPC8240, mpc8240_device, "mpc8240", "IBM PowerPC MPC8240") DEFINE_DEVICE_TYPE(PPC403GA, ppc403ga_device, "ppc403ga", "IBM PowerPC 403GA") DEFINE_DEVICE_TYPE(PPC403GCX, ppc403gcx_device, "ppc403gcx", "IBM PowerPC 403GCX") DEFINE_DEVICE_TYPE(PPC405GP, ppc405gp_device, "ppc405gp", "IBM PowerPC 405GP") ppc_device::ppc_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock, int address_bits, int data_bits, powerpc_flavor flavor, uint32_t cap, uint32_t tb_divisor, address_map_constructor internal_map) : cpu_device(mconfig, type, tag, owner, clock) , device_vtlb_interface(mconfig, *this, AS_PROGRAM) , m_program_config("program", ENDIANNESS_BIG, data_bits, address_bits, 0, internal_map) , c_bus_frequency(0) , m_core(nullptr) , m_bus_freq_multiplier(1) , m_flavor(flavor) , m_cap(cap) , m_tb_divisor(tb_divisor) , m_cache(CACHE_SIZE + sizeof(internal_ppc_state)) , m_drcuml(nullptr) , m_drcfe(nullptr) , m_drcoptions(0) { m_program_config.m_logaddr_width = 32; m_program_config.m_page_shift = POWERPC_MIN_PAGE_SHIFT; // configure the virtual TLB set_vtlb_dynamic_entries(POWERPC_TLB_ENTRIES); if (m_cap & PPCCAP_603_MMU) set_vtlb_fixed_entries(PPC603_FIXED_TLB_ENTRIES); } //ppc403_device::ppc403_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) // : ppc_device(mconfig, PPC403, "PPC403", tag, owner, clock, "ppc403", 32?, 64?) //{ //} // //ppc405_device::ppc405_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) // : ppc_device(mconfig, PPC405, "PPC405", tag, owner, clock, "ppc405", 32?, 64?) //{ //} ppc603_device::ppc603_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, PPC603, tag, owner, clock, 32, 64, PPC_MODEL_603, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_603_MMU, 4, address_map_constructor()) { } ppc603e_device::ppc603e_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, PPC603E, tag, owner, clock, 32, 64, PPC_MODEL_603E, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_603_MMU, 4, address_map_constructor()) { } ppc603r_device::ppc603r_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, PPC603R, tag, owner, clock, 32, 64, PPC_MODEL_603R, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_603_MMU, 4, address_map_constructor()) { } ppc602_device::ppc602_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, PPC602, tag, owner, clock, 32, 64, PPC_MODEL_602, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_603_MMU, 4, address_map_constructor()) { } mpc8240_device::mpc8240_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, MPC8240, tag, owner, clock, 32, 64, PPC_MODEL_MPC8240, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_603_MMU, 4/* unknown */, address_map_constructor()) { } ppc601_device::ppc601_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, PPC601, tag, owner, clock, 32, 64, PPC_MODEL_601, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_MFIOC | PPCCAP_601BAT, 0/* no TB */, address_map_constructor()) { } ppc604_device::ppc604_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc_device(mconfig, PPC604, tag, owner, clock, 32, 64, PPC_MODEL_604, PPCCAP_OEA | PPCCAP_VEA | PPCCAP_FPU | PPCCAP_MISALIGNED | PPCCAP_604_MMU, 4, address_map_constructor()) { } ADDRESS_MAP_START(ppc4xx_device::internal_ppc4xx) AM_RANGE(0x40000000, 0x4000000f) AM_READWRITE8(ppc4xx_spu_r, ppc4xx_spu_w, 0xffffffff) ADDRESS_MAP_END ppc4xx_device::ppc4xx_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock, powerpc_flavor flavor, uint32_t cap, uint32_t tb_divisor) : ppc_device(mconfig, type, tag, owner, clock, 31, 32, flavor, cap, tb_divisor, address_map_constructor(FUNC(ppc4xx_device::internal_ppc4xx), this)) { } ppc403ga_device::ppc403ga_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc4xx_device(mconfig, PPC403GA, tag, owner, clock, PPC_MODEL_403GA, PPCCAP_4XX, 1) { } ppc403gcx_device::ppc403gcx_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc4xx_device(mconfig, PPC403GCX, tag, owner, clock, PPC_MODEL_403GCX, PPCCAP_4XX, 1) { } ppc405gp_device::ppc405gp_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : ppc4xx_device(mconfig, PPC405GP, tag, owner, clock, PPC_MODEL_405GP, PPCCAP_4XX | PPCCAP_VEA, 1) { } device_memory_interface::space_config_vector ppc_device::memory_space_config() const { return space_config_vector { std::make_pair(AS_PROGRAM, &m_program_config) }; } /*************************************************************************** INLINE FUNCTIONS ***************************************************************************/ /*------------------------------------------------- page_access_allowed - return true if we are allowed to access memory based on the type of access and the protection bits -------------------------------------------------*/ static inline bool page_access_allowed(int transtype, uint8_t key, uint8_t protbits) { if (key == 0) return (transtype == TRANSLATE_WRITE) ? (protbits != 3) : true; else return (transtype == TRANSLATE_WRITE) ? (protbits == 2) : (protbits != 0); } /*------------------------------------------------- get_cr - return the current CR value -------------------------------------------------*/ inline uint32_t ppc_device::get_cr() { return ((m_core->cr[0] & 0x0f) << 28) | ((m_core->cr[1] & 0x0f) << 24) | ((m_core->cr[2] & 0x0f) << 20) | ((m_core->cr[3] & 0x0f) << 16) | ((m_core->cr[4] & 0x0f) << 12) | ((m_core->cr[5] & 0x0f) << 8) | ((m_core->cr[6] & 0x0f) << 4) | ((m_core->cr[7] & 0x0f) << 0); } /*------------------------------------------------- set_cr - set the current CR value -------------------------------------------------*/ inline void ppc_device::set_cr(uint32_t value) { m_core->cr[0] = value >> 28; m_core->cr[1] = value >> 24; m_core->cr[2] = value >> 20; m_core->cr[3] = value >> 16; m_core->cr[4] = value >> 12; m_core->cr[5] = value >> 8; m_core->cr[6] = value >> 4; m_core->cr[7] = value >> 0; } /*------------------------------------------------- get_xer - return the current XER value -------------------------------------------------*/ inline uint32_t ppc_device::get_xer() { return m_core->spr[SPR_XER] | (m_core->xerso << 31); } /*------------------------------------------------- set_xer - set the current XER value -------------------------------------------------*/ inline void ppc_device::set_xer(uint32_t value) { m_core->spr[SPR_XER] = value & ~XER_SO; m_core->xerso = value >> 31; } /*------------------------------------------------- get_timebase - return the current timebase value -------------------------------------------------*/ inline uint64_t ppc_device::get_timebase() { if (!m_tb_divisor) { return (total_cycles() - m_tb_zero_cycles); } return (total_cycles() - m_tb_zero_cycles) / m_tb_divisor; } /*------------------------------------------------- set_timebase - set the timebase -------------------------------------------------*/ inline void ppc_device::set_timebase(uint64_t newtb) { m_tb_zero_cycles = total_cycles() - newtb * m_tb_divisor; } /*------------------------------------------------- get_decremeter - return the current decrementer value -------------------------------------------------*/ inline uint32_t ppc_device::get_decrementer() { int64_t cycles_until_zero = m_dec_zero_cycles - total_cycles(); cycles_until_zero = std::max<int64_t>(cycles_until_zero, 0); if (!m_tb_divisor) { return 0; } return cycles_until_zero / m_tb_divisor; } /*------------------------------------------------- set_decrementer - set the decremeter -------------------------------------------------*/ inline void ppc_device::set_decrementer(uint32_t newdec) { uint64_t cycles_until_done = ((uint64_t)newdec + 1) * m_tb_divisor; uint32_t curdec = get_decrementer(); if (!m_tb_divisor) { return; } if (PRINTF_DECREMENTER) { uint64_t total = total_cycles(); osd_printf_debug("set_decrementer: olddec=%08X newdec=%08X divisor=%d totalcyc=%08X%08X timer=%08X%08X\n", curdec, newdec, m_tb_divisor, (uint32_t)(total >> 32), (uint32_t)total, (uint32_t)(cycles_until_done >> 32), (uint32_t)cycles_until_done); } m_dec_zero_cycles = total_cycles() + cycles_until_done; m_decrementer_int_timer->adjust(cycles_to_attotime(cycles_until_done)); if ((int32_t)curdec >= 0 && (int32_t)newdec < 0) m_core->irq_pending |= 0x02; } #if 0 /*------------------------------------------------- is_nan_double - is a double value a NaN -------------------------------------------------*/ static inline int is_nan_double(double x) { uint64_t xi = *(uint64_t*)&x; return( ((xi & DOUBLE_EXP) == DOUBLE_EXP) && ((xi & DOUBLE_FRAC) != DOUBLE_ZERO) ); } #endif /*------------------------------------------------- is_qnan_double - is a double value a quiet NaN -------------------------------------------------*/ static inline int is_qnan_double(double x) { uint64_t xi = *(uint64_t*)&x; return( ((xi & DOUBLE_EXP) == DOUBLE_EXP) && ((xi & 0x0007fffffffffffU) == 0x000000000000000U) && ((xi & 0x000800000000000U) == 0x000800000000000U) ); } #if 0 /*------------------------------------------------- is_snan_double - is a double value a signaling NaN -------------------------------------------------*/ static inline int is_snan_double(double x) { uint64_t xi = *(uint64_t*)&x; return( ((xi & DOUBLE_EXP) == DOUBLE_EXP) && ((xi & DOUBLE_FRAC) != DOUBLE_ZERO) && ((xi & 0x0008000000000000U) == DOUBLE_ZERO) ); } #endif /*------------------------------------------------- is_infinity_double - is a double value infinity -------------------------------------------------*/ static inline int is_infinity_double(double x) { uint64_t xi = *(uint64_t*)&x; return( ((xi & DOUBLE_EXP) == DOUBLE_EXP) && ((xi & DOUBLE_FRAC) == DOUBLE_ZERO) ); } /*------------------------------------------------- is_normalized_double - is a double value normalized -------------------------------------------------*/ static inline int is_normalized_double(double x) { uint64_t exp; uint64_t xi = *(uint64_t*)&x; exp = (xi & DOUBLE_EXP) >> 52; return (exp >= 1) && (exp <= 2046); } /*------------------------------------------------- is_denormalized_double - is a double value denormalized -------------------------------------------------*/ static inline int is_denormalized_double(double x) { uint64_t xi = *(uint64_t*)&x; return( ((xi & DOUBLE_EXP) == 0) && ((xi & DOUBLE_FRAC) != DOUBLE_ZERO) ); } /*------------------------------------------------- sign_double - return sign of a double value -------------------------------------------------*/ static inline int sign_double(double x) { uint64_t xi = *(uint64_t*)&x; return ((xi & DOUBLE_SIGN) != 0); } /*************************************************************************** INITIALIZATION AND SHUTDOWN ***************************************************************************/ /*------------------------------------------------- device_start - initialize the powerpc_state structure based on the configured type -------------------------------------------------*/ void ppc_device::device_start() { /* allocate the core from the near cache */ m_core = (internal_ppc_state *)m_cache.alloc_near(sizeof(internal_ppc_state)); memset(m_core, 0, sizeof(internal_ppc_state)); m_entry = nullptr; m_nocode = nullptr; m_out_of_cycles = nullptr; m_tlb_mismatch = nullptr; m_swap_tgpr = nullptr; memset(m_lsw, 0, sizeof(m_lsw)); memset(m_stsw, 0, sizeof(m_stsw)); memset(m_read8, 0, sizeof(m_read8)); memset(m_write8, 0, sizeof(m_write8)); memset(m_read16, 0, sizeof(m_read16)); memset(m_read16mask, 0, sizeof(m_read16mask)); memset(m_write16, 0, sizeof(m_write16)); memset(m_write16mask, 0, sizeof(m_write16mask)); memset(m_read32, 0, sizeof(m_read32)); memset(m_read32align, 0, sizeof(m_read32align)); memset(m_read32mask, 0, sizeof(m_read32mask)); memset(m_write32, 0, sizeof(m_write32)); memset(m_write32align, 0, sizeof(m_write32align)); memset(m_write32mask, 0, sizeof(m_write32mask)); memset(m_read64, 0, sizeof(m_read64)); memset(m_read64mask, 0, sizeof(m_read64mask)); memset(m_write64, 0, sizeof(m_write64)); memset(m_write64mask, 0, sizeof(m_write64mask)); memset(m_exception, 0, sizeof(m_exception)); memset(m_exception_norecover, 0, sizeof(m_exception_norecover)); /* initialize the implementation state tables */ memcpy(m_fpmode, fpmode_source, sizeof(fpmode_source)); memcpy(m_sz_cr_table, sz_cr_table_source, sizeof(sz_cr_table_source)); memcpy(m_cmp_cr_table, cmp_cr_table_source, sizeof(cmp_cr_table_source)); memcpy(m_cmpl_cr_table, cmpl_cr_table_source, sizeof(cmpl_cr_table_source)); memcpy(m_fcmp_cr_table, fcmp_cr_table_source, sizeof(fcmp_cr_table_source)); /* initialize based on the config */ m_ppc_tb_base_icount = 0; m_ppc_dec_base_icount = 0; m_ppc_dec_trigger_cycle = 0; m_bus_freq_multiplier = 0; m_npc = 0; memset(m_dcr, 0, sizeof(m_dcr)); m_lr = 0; m_ctr = 0; m_xer = 0; m_pvr = 0; m_srr0 = 0; m_srr1 = 0; m_srr2 = 0; m_srr3 = 0; m_hid0 = 0; m_hid1 = 0; m_hid2 = 0; m_sdr1 = 0; memset(m_sprg, 0, sizeof(m_sprg)); m_dsisr = 0; m_dar = 0; m_ear = 0; m_dmiss = 0; m_dcmp = 0; m_hash1 = 0; m_hash2 = 0; m_imiss = 0; m_icmp = 0; m_rpa = 0; memset(m_ibat, 0, sizeof(m_ibat)); memset(m_dbat, 0, sizeof(m_dbat)); m_evpr = 0; m_exier = 0; m_exisr = 0; m_bear = 0; m_besr = 0; m_iocr = 0; memset(m_br, 0, sizeof(m_br)); m_iabr = 0; m_esr = 0; m_iccr = 0; m_dccr = 0; m_pit = 0; m_pit_counter = 0; m_pit_int_enable = 0; m_tsr = 0; m_dbsr = 0; m_sgr = 0; m_pid = 0; m_pbl1 = 0; m_pbl2 = 0; m_pbu1 = 0; m_pbu2 = 0; m_fit_bit = 0; m_fit_int_enable = 0; m_wdt_bit = 0; m_wdt_int_enable = 0; m_dac1 = 0; m_dac2 = 0; m_iac1 = 0; m_iac2 = 0; memset(&m_spu_old, 0, sizeof(m_spu_old)); memset(m_dma, 0, sizeof(m_dma)); m_dmasr = 0; m_reserved = 0; m_reserved_address = 0; m_interrupt_pending = 0; m_tb = 0; m_dec = 0; m_dec_frac = 0; memset(m_fpr, 0, sizeof(m_fpr)); m_lt = 0; m_sp = 0; m_tcr = 0; m_ibr = 0; m_esasrr = 0; m_sebr = 0; m_ser = 0; memset(&m_spu, 0, sizeof(m_spu)); m_pit_reload = 0; m_irqstate = 0; memset(m_buffered_dma_rate, 0, sizeof(m_buffered_dma_rate)); m_codexor = 0; m_system_clock = 0; m_cpu_clock = 0; m_tb_zero_cycles = 0; m_dec_zero_cycles = 0; m_arg1 = 0; m_fastram_select = 0; memset(m_fastram, 0, sizeof(m_fastram)); m_hotspot_select = 0; memset(m_hotspot, 0, sizeof(m_hotspot)); m_debugger_temp = 0; m_cache_line_size = 32; m_cpu_clock = clock(); m_program = &space(AS_PROGRAM); m_direct = m_program->direct<0>(); m_system_clock = c_bus_frequency != 0 ? c_bus_frequency : clock(); m_dcr_read_func = read32_delegate(); m_dcr_write_func = write32_delegate(); m_tb_divisor = (m_tb_divisor * clock() + m_system_clock / 2 - 1) / m_system_clock; m_codexor = 0; if (!(m_cap & PPCCAP_4XX) && space_config()->m_endianness != ENDIANNESS_NATIVE) m_codexor = 4; /* allocate a timer for the compare interrupt */ if ((m_cap & PPCCAP_OEA) && (m_tb_divisor)) m_decrementer_int_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::decrementer_int_callback), this)); /* and for the 4XX interrupts if needed */ if (m_cap & PPCCAP_4XX) { m_fit_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_fit_callback), this)); m_pit_timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_pit_callback), this)); m_spu.timer = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_spu_callback), this)); } if (m_cap & PPCCAP_4XX) { m_buffered_dma_timer[0] = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_buffered_dma_callback), this)); m_buffered_dma_timer[1] = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_buffered_dma_callback), this)); m_buffered_dma_timer[2] = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_buffered_dma_callback), this)); m_buffered_dma_timer[3] = machine().scheduler().timer_alloc(timer_expired_delegate(FUNC(ppc_device::ppc4xx_buffered_dma_callback), this)); m_buffered_dma_rate[0] = 10000; m_buffered_dma_rate[1] = 10000; m_buffered_dma_rate[2] = 10000; m_buffered_dma_rate[3] = 10000; } /* register for save states */ save_item(NAME(m_core->pc)); save_item(NAME(m_core->r)); save_item(NAME(m_core->f)); save_item(NAME(m_core->cr)); save_item(NAME(m_core->xerso)); save_item(NAME(m_core->fpscr)); save_item(NAME(m_core->msr)); save_item(NAME(m_core->sr)); save_item(NAME(m_core->spr)); save_item(NAME(m_dcr)); if (m_cap & PPCCAP_4XX) { save_item(NAME(m_spu.regs)); save_item(NAME(m_spu.txbuf)); save_item(NAME(m_spu.rxbuf)); save_item(NAME(m_spu.rxbuffer)); save_item(NAME(m_spu.rxin)); save_item(NAME(m_spu.rxout)); save_item(NAME(m_pit_reload)); save_item(NAME(m_irqstate)); } if (m_cap & PPCCAP_603_MMU) { save_item(NAME(m_core->mmu603_cmp)); save_item(NAME(m_core->mmu603_hash)); save_item(NAME(m_core->mmu603_r)); } save_item(NAME(m_core->irq_pending)); save_item(NAME(m_tb_zero_cycles)); save_item(NAME(m_dec_zero_cycles)); // Register debugger state state_add(PPC_PC, "PC", m_core->pc).formatstr("%08X"); state_add(PPC_MSR, "MSR", m_core->msr).formatstr("%08X"); state_add(PPC_CR, "CR", m_debugger_temp).callimport().callexport().formatstr("%08X"); state_add(PPC_LR, "LR", m_core->spr[SPR_LR]).formatstr("%08X"); state_add(PPC_CTR, "CTR", m_core->spr[SPR_CTR]).formatstr("%08X"); state_add(PPC_XER, "XER", m_debugger_temp).callimport().callexport().formatstr("%08X"); state_add(PPC_SRR0, "SRR0", m_core->spr[SPROEA_SRR0]).formatstr("%08X"); state_add(PPC_SRR1, "SRR1", m_core->spr[SPROEA_SRR1]).formatstr("%08X"); state_add(PPC_SPRG0, "SPRG0", m_core->spr[SPROEA_SPRG0]).formatstr("%08X"); state_add(PPC_SPRG1, "SPRG1", m_core->spr[SPROEA_SPRG1]).formatstr("%08X"); state_add(PPC_SPRG2, "SPRG2", m_core->spr[SPROEA_SPRG2]).formatstr("%08X"); state_add(PPC_SPRG3, "SPRG3", m_core->spr[SPROEA_SPRG3]).formatstr("%08X"); state_add(PPC_SDR1, "SDR1", m_core->spr[SPROEA_SDR1]).formatstr("%08X"); state_add(PPC_EXIER, "EXIER", m_dcr[DCR4XX_EXIER]).formatstr("%08X"); state_add(PPC_EXISR, "EXISR", m_dcr[DCR4XX_EXISR]).formatstr("%08X"); state_add(PPC_EVPR, "EVPR", m_core->spr[SPR4XX_EVPR]).formatstr("%08X"); state_add(PPC_IOCR, "IOCR", m_dcr[DCR4XX_EXISR]).formatstr("%08X"); state_add(PPC_TBH, "TBH", m_debugger_temp).callimport().callexport().formatstr("%08X"); state_add(PPC_TBL, "TBL", m_debugger_temp).callimport().callexport().formatstr("%08X"); state_add(PPC_DEC, "DEC", m_debugger_temp).callimport().callexport().formatstr("%08X"); for (int regnum = 0; regnum < 16; regnum++) state_add(PPC_SR0 + regnum, string_format("SR%d", regnum).c_str(), m_core->sr[regnum]).formatstr("%08X"); for (int regnum = 0; regnum < 32; regnum++) state_add(PPC_R0 + regnum, string_format("R%d", regnum).c_str(), m_core->r[regnum]).formatstr("%08X"); for (int regnum = 0; regnum < 32; regnum++) state_add(PPC_F0 + regnum, string_format("F%d", regnum).c_str(), m_core->f[regnum]).formatstr("%12s"); state_add(PPC_FPSCR, "FPSCR", m_core->fpscr).formatstr("%08X"); state_add(STATE_GENPC, "GENPC", m_core->pc).noshow(); state_add(STATE_GENPCBASE, "CURPC", m_core->pc).noshow(); state_add(STATE_GENSP, "GENSP", m_core->r[31]).noshow(); state_add(STATE_GENFLAGS, "GENFLAGS", m_debugger_temp).noshow().formatstr("%1s"); set_icountptr(m_core->icount); uint32_t flags = 0; /* initialize the UML generator */ m_drcuml = std::make_unique<drcuml_state>(*this, m_cache, flags, 8, 32, 2); /* add symbols for our stuff */ m_drcuml->symbol_add(&m_core->pc, sizeof(m_core->pc), "pc"); m_drcuml->symbol_add(&m_core->icount, sizeof(m_core->icount), "icount"); for (int regnum = 0; regnum < 32; regnum++) { char buf[10]; sprintf(buf, "r%d", regnum); m_drcuml->symbol_add(&m_core->r[regnum], sizeof(m_core->r[regnum]), buf); sprintf(buf, "fpr%d", regnum); m_drcuml->symbol_add(&m_core->f[regnum], sizeof(m_core->f[regnum]), buf); } for (int regnum = 0; regnum < 8; regnum++) { char buf[10]; sprintf(buf, "cr%d", regnum); m_drcuml->symbol_add(&m_core->cr[regnum], sizeof(m_core->cr[regnum]), buf); } m_drcuml->symbol_add(&m_core->xerso, sizeof(m_core->xerso), "xerso"); m_drcuml->symbol_add(&m_core->fpscr, sizeof(m_core->fpscr), "fpscr"); m_drcuml->symbol_add(&m_core->msr, sizeof(m_core->msr), "msr"); m_drcuml->symbol_add(&m_core->sr, sizeof(m_core->sr), "sr"); m_drcuml->symbol_add(&m_core->spr[SPR_XER], sizeof(m_core->spr[SPR_XER]), "xer"); m_drcuml->symbol_add(&m_core->spr[SPR_LR], sizeof(m_core->spr[SPR_LR]), "lr"); m_drcuml->symbol_add(&m_core->spr[SPR_CTR], sizeof(m_core->spr[SPR_CTR]), "ctr"); m_drcuml->symbol_add(&m_core->spr, sizeof(m_core->spr), "spr"); m_drcuml->symbol_add(&m_dcr, sizeof(m_dcr), "dcr"); m_drcuml->symbol_add(&m_core->param0, sizeof(m_core->param0), "param0"); m_drcuml->symbol_add(&m_core->param1, sizeof(m_core->param1), "param1"); m_drcuml->symbol_add(&m_core->irq_pending, sizeof(m_core->irq_pending), "irq_pending"); m_drcuml->symbol_add(&m_core->mode, sizeof(m_core->mode), "mode"); m_drcuml->symbol_add(&m_core->arg0, sizeof(m_core->arg0), "arg0"); m_drcuml->symbol_add(&m_arg1, sizeof(m_arg1), "arg1"); m_drcuml->symbol_add(&m_core->updateaddr, sizeof(m_core->updateaddr), "updateaddr"); m_drcuml->symbol_add(&m_core->swcount, sizeof(m_core->swcount), "swcount"); m_drcuml->symbol_add(&m_core->tempaddr, sizeof(m_core->tempaddr), "tempaddr"); m_drcuml->symbol_add(&m_core->tempdata, sizeof(m_core->tempdata), "tempdata"); m_drcuml->symbol_add(&m_core->fp0, sizeof(m_core->fp0), "fp0"); m_drcuml->symbol_add(&m_fpmode, sizeof(m_fpmode), "fpmode"); m_drcuml->symbol_add(&m_sz_cr_table, sizeof(m_sz_cr_table), "sz_cr_table"); m_drcuml->symbol_add(&m_cmp_cr_table, sizeof(m_cmp_cr_table), "cmp_cr_table"); m_drcuml->symbol_add(&m_cmpl_cr_table, sizeof(m_cmpl_cr_table), "cmpl_cr_table"); m_drcuml->symbol_add(&m_fcmp_cr_table, sizeof(m_fcmp_cr_table), "fcmp_cr_table"); /* initialize the front-end helper */ m_drcfe = std::make_unique<frontend>(*this, COMPILE_BACKWARDS_BYTES, COMPILE_FORWARDS_BYTES, SINGLE_INSTRUCTION_MODE ? 1 : COMPILE_MAX_SEQUENCE); /* compute the register parameters */ for (int regnum = 0; regnum < 32; regnum++) { m_regmap[regnum] = uml::mem(&m_core->r[regnum]); m_fdregmap[regnum] = uml::mem(&m_core->f[regnum]); } /* if we have registers to spare, assign r0, r1, r2 to leftovers */ if (!DISABLE_FAST_REGISTERS) { drcbe_info beinfo; m_drcuml->get_backend_info(beinfo); if (beinfo.direct_iregs > 5) m_regmap[0] = uml::I5; if (beinfo.direct_iregs > 6) m_regmap[1] = uml::I6; if (beinfo.direct_iregs > 7) m_regmap[2] = uml::I7; if (beinfo.direct_fregs > 3) m_fdregmap[0] = uml::F3; if (beinfo.direct_fregs > 4) m_fdregmap[1] = uml::F4; if (beinfo.direct_fregs > 5) m_fdregmap[2] = uml::F5; if (beinfo.direct_fregs > 6) m_fdregmap[3] = uml::F6; if (beinfo.direct_fregs > 7) m_fdregmap[30] = uml::F7; if (beinfo.direct_fregs > 8) m_fdregmap[31] = uml::F8; } /* mark the cache dirty so it is updated on next execute */ m_cache_dirty = true; } void ppc_device::state_export(const device_state_entry &entry) { switch (entry.index()) { case PPC_CR: m_debugger_temp = get_cr(); break; case PPC_XER: m_debugger_temp = get_xer(); break; case PPC_TBH: m_debugger_temp = get_timebase() >> 32; break; case PPC_TBL: m_debugger_temp = (uint32_t)get_timebase(); break; case PPC_DEC: m_debugger_temp = get_decrementer(); break; } } void ppc_device::state_import(const device_state_entry &entry) { switch (entry.index()) { case PPC_CR: set_cr(m_debugger_temp); break; case PPC_XER: set_xer(m_debugger_temp); break; case PPC_TBL: set_timebase((get_timebase() & ~u64(0x00ffffff00000000U)) | m_debugger_temp); break; case PPC_TBH: set_timebase((get_timebase() & ~u64(0x00000000ffffffffU)) | ((uint64_t)(m_debugger_temp & 0x00ffffff) << 32)); break; case PPC_DEC: set_decrementer(m_debugger_temp); break; } } void ppc_device::state_string_export(const device_state_entry &entry, std::string &str) const { switch (entry.index()) { case PPC_F0: str = string_format("%12f", m_core->f[0]); break; case PPC_F1: str = string_format("%12f", m_core->f[1]); break; case PPC_F2: str = string_format("%12f", m_core->f[2]); break; case PPC_F3: str = string_format("%12f", m_core->f[3]); break; case PPC_F4: str = string_format("%12f", m_core->f[4]); break; case PPC_F5: str = string_format("%12f", m_core->f[5]); break; case PPC_F6: str = string_format("%12f", m_core->f[6]); break; case PPC_F7: str = string_format("%12f", m_core->f[7]); break; case PPC_F8: str = string_format("%12f", m_core->f[8]); break; case PPC_F9: str = string_format("%12f", m_core->f[9]); break; case PPC_F10: str = string_format("%12f", m_core->f[10]); break; case PPC_F11: str = string_format("%12f", m_core->f[11]); break; case PPC_F12: str = string_format("%12f", m_core->f[12]); break; case PPC_F13: str = string_format("%12f", m_core->f[13]); break; case PPC_F14: str = string_format("%12f", m_core->f[14]); break; case PPC_F15: str = string_format("%12f", m_core->f[15]); break; case PPC_F16: str = string_format("%12f", m_core->f[16]); break; case PPC_F17: str = string_format("%12f", m_core->f[17]); break; case PPC_F18: str = string_format("%12f", m_core->f[18]); break; case PPC_F19: str = string_format("%12f", m_core->f[19]); break; case PPC_F20: str = string_format("%12f", m_core->f[20]); break; case PPC_F21: str = string_format("%12f", m_core->f[21]); break; case PPC_F22: str = string_format("%12f", m_core->f[22]); break; case PPC_F23: str = string_format("%12f", m_core->f[23]); break; case PPC_F24: str = string_format("%12f", m_core->f[24]); break; case PPC_F25: str = string_format("%12f", m_core->f[25]); break; case PPC_F26: str = string_format("%12f", m_core->f[26]); break; case PPC_F27: str = string_format("%12f", m_core->f[27]); break; case PPC_F28: str = string_format("%12f", m_core->f[28]); break; case PPC_F29: str = string_format("%12f", m_core->f[29]); break; case PPC_F30: str = string_format("%12f", m_core->f[30]); break; case PPC_F31: str = string_format("%12f", m_core->f[31]); break; } } /*------------------------------------------------- ppccom_exit - common cleanup/exit -------------------------------------------------*/ void ppc_device::device_stop() { } /*------------------------------------------------- ppccom_reset - reset the state of all the registers -------------------------------------------------*/ void ppc_device::device_reset() { /* initialize the OEA state */ if (m_cap & PPCCAP_OEA) { /* PC to the reset vector; MSR has IP set to start */ m_core->pc = 0xfff00100; m_core->msr = MSROEA_IP; /* reset the decrementer */ m_dec_zero_cycles = total_cycles(); if (m_tb_divisor) { decrementer_int_callback(nullptr, 0); } } /* initialize the 4XX state */ if (m_cap & PPCCAP_4XX) { /* PC to the last word; MSR to 0 */ m_core->pc = 0xfffffffc; m_core->msr = 0; /* reset the SPU status */ m_core->spr[SPR4XX_TCR] &= ~PPC4XX_TCR_WRC_MASK; m_spu.regs[SPU4XX_LINE_STATUS] = 0x06; } /* initialize the 602 HID0 register */ if (m_flavor == PPC_MODEL_602) m_core->spr[SPR603_HID0] = 1; /* time base starts here */ m_tb_zero_cycles = total_cycles(); /* clear interrupts */ m_core->irq_pending = 0; /* flush the TLB */ if (m_cap & PPCCAP_603_MMU) { for (int tlbindex = 0; tlbindex < PPC603_FIXED_TLB_ENTRIES; tlbindex++) { vtlb_load(tlbindex, 0, 0, 0); } } /* Mark the cache dirty */ m_core->mode = 0; m_cache_dirty = true; } /*------------------------------------------------- ppccom_dasm - handle disassembly for a CPU -------------------------------------------------*/ std::unique_ptr<util::disasm_interface> ppc_device::create_disassembler() { return std::make_unique<powerpc_disassembler>(); } /*------------------------------------------------- ppccom_dcstore_callback - call the dcstore callback if installed -------------------------------------------------*/ void ppc_device::ppccom_dcstore_callback() { if (!m_dcstore_cb.isnull()) { m_dcstore_cb(*m_program, m_core->param0, 0, 0xffffffff); } } /*************************************************************************** TLB HANDLING ***************************************************************************/ /*------------------------------------------------- ppccom_translate_address_internal - translate an address from logical to physical; shared between external requests and internal TLB filling -------------------------------------------------*/ uint32_t ppc_device::ppccom_translate_address_internal(int intention, offs_t &address) { int transpriv = ((intention & TRANSLATE_USER_MASK) == 0); // 1 for supervisor, 0 for user int transtype = intention & TRANSLATE_TYPE_MASK; offs_t hash, hashbase, hashmask; int batbase, batnum, hashnum; uint32_t segreg; /* 4xx case: "TLB" really just caches writes and checks compare registers */ if (m_cap & PPCCAP_4XX) { /* we don't support the MMU of the 403GCX */ if (m_flavor == PPC_MODEL_403GCX && (m_core->msr & MSROEA_DR)) fatalerror("MMU enabled but not supported!\n"); /* only check if PE is enabled */ if (transtype == TRANSLATE_WRITE && (m_core->msr & MSR4XX_PE)) { /* are we within one of the protection ranges? */ int inrange1 = ((address >> 12) >= (m_core->spr[SPR4XX_PBL1] >> 12) && (address >> 12) < (m_core->spr[SPR4XX_PBU1] >> 12)); int inrange2 = ((address >> 12) >= (m_core->spr[SPR4XX_PBL2] >> 12) && (address >> 12) < (m_core->spr[SPR4XX_PBU2] >> 12)); /* if PX == 1, writes are only allowed OUTSIDE of the bounds */ if (((m_core->msr & MSR4XX_PX) && (inrange1 || inrange2)) || (!(m_core->msr & MSR4XX_PX) && (!inrange1 && !inrange2))) return 0x002; } address &= 0x7fffffff; return 0x001; } /* only applies if we support the OEA */ if (!(m_cap & PPCCAP_OEA)) return 0x001; /* also no translation necessary if translation is disabled */ if ((transtype == TRANSLATE_FETCH && (m_core->msr & MSROEA_IR) == 0) || (transtype != TRANSLATE_FETCH && (m_core->msr & MSROEA_DR) == 0)) return 0x001; /* first scan the appropriate BAT */ if (m_cap & PPCCAP_601BAT) { for (batnum = 0; batnum < 4; batnum++) { uint32_t upper = m_core->spr[SPROEA_IBAT0U + 2*batnum + 0]; uint32_t lower = m_core->spr[SPROEA_IBAT0U + 2*batnum + 1]; int privbit = ((intention & TRANSLATE_USER_MASK) == 0) ? 3 : 2; // printf("bat %d upper = %08x privbit %d\n", batnum, upper, privbit); // is this pair valid? if (lower & 0x40) { uint32_t mask = ((lower & 0x3f) << 17) ^ 0xfffe0000; uint32_t addrout; uint32_t key = (upper >> privbit) & 1; /* check for a hit against this bucket */ if ((address & mask) == (upper & mask)) { /* verify protection; if we fail, return false and indicate a protection violation */ if (!page_access_allowed(transtype, key, upper & 3)) { return DSISR_PROTECTED | ((transtype == TRANSLATE_WRITE) ? DSISR_STORE : 0); } /* otherwise we're good */ addrout = (lower & mask) | (address & ~mask); address = addrout; // top 9 bits from top 9 of PBN return 0x001; } } } } else { batbase = (transtype == TRANSLATE_FETCH) ? SPROEA_IBAT0U : SPROEA_DBAT0U; for (batnum = 0; batnum < 4; batnum++) { uint32_t upper = m_core->spr[batbase + 2*batnum + 0]; /* check user/supervisor valid bit */ if ((upper >> transpriv) & 0x01) { uint32_t mask = (~upper << 15) & 0xfffe0000; /* check for a hit against this bucket */ if ((address & mask) == (upper & mask)) { uint32_t lower = m_core->spr[batbase + 2*batnum + 1]; /* verify protection; if we fail, return false and indicate a protection violation */ if (!page_access_allowed(transtype, 1, lower & 3)) { return DSISR_PROTECTED | ((transtype == TRANSLATE_WRITE) ? DSISR_STORE : 0); } /* otherwise we're good */ address = (lower & mask) | (address & ~mask); return 0x001; } } } } /* look up the segment register */ segreg = m_core->sr[address >> 28]; if (transtype == TRANSLATE_FETCH && (segreg & 0x10000000)) return DSISR_PROTECTED | ((transtype == TRANSLATE_WRITE) ? DSISR_STORE : 0); /* check for memory-forced I/O */ if (m_cap & PPCCAP_MFIOC) { if ((transtype != TRANSLATE_FETCH) && ((segreg & 0x87f00000) == 0x87f00000)) { address = ((segreg & 0xf)<<28) | (address & 0x0fffffff); return 1; } else if (segreg & 0x80000000) { fatalerror("PPC: Unhandled segment register %08x with T=1\n", segreg); } } /* get hash table information from SD1 */ hashbase = m_core->spr[SPROEA_SDR1] & 0xffff0000; hashmask = ((m_core->spr[SPROEA_SDR1] & 0x1ff) << 16) | 0xffff; hash = (segreg & 0x7ffff) ^ ((address >> 12) & 0xffff); /* if we're simulating the 603 MMU, fill in the data and stop here */ if (m_cap & PPCCAP_603_MMU) { uint32_t entry = vtlb_table()[address >> 12]; m_core->mmu603_cmp = 0x80000000 | ((segreg & 0xffffff) << 7) | (0 << 6) | ((address >> 22) & 0x3f); m_core->mmu603_hash[0] = hashbase | ((hash << 6) & hashmask); m_core->mmu603_hash[1] = hashbase | ((~hash << 6) & hashmask); if ((entry & (VTLB_FLAG_FIXED | VTLB_FLAG_VALID)) == (VTLB_FLAG_FIXED | VTLB_FLAG_VALID)) { address = (entry & 0xfffff000) | (address & 0x00000fff); return 0x001; } return DSISR_NOT_FOUND | ((transtype == TRANSLATE_WRITE) ? DSISR_STORE : 0); } /* loop twice over hashes */ for (hashnum = 0; hashnum < 2; hashnum++) { offs_t ptegaddr = hashbase | ((hash << 6) & hashmask); uint32_t *ptegptr = (uint32_t *)m_program->get_read_ptr(ptegaddr); /* should only have valid memory here, but make sure */ if (ptegptr != nullptr) { uint32_t targetupper = 0x80000000 | ((segreg & 0xffffff) << 7) | (hashnum << 6) | ((address >> 22) & 0x3f); int ptenum; /* scan PTEs */ for (ptenum = 0; ptenum < 8; ptenum++) if (ptegptr[BYTE_XOR_BE(ptenum * 2)] == targetupper) { uint32_t pteglower = ptegptr[BYTE_XOR_BE(ptenum * 2 + 1)]; /* verify protection; if we fail, return false and indicate a protection violation */ if (!page_access_allowed(transtype, (segreg >> (29 + transpriv)) & 1, pteglower & 3)) return DSISR_PROTECTED | ((transtype == TRANSLATE_WRITE) ? DSISR_STORE : 0); /* update page table bits */ if (!(intention & TRANSLATE_DEBUG_MASK)) { pteglower |= 0x100; if (transtype == TRANSLATE_WRITE) pteglower |= 0x080; ptegptr[BYTE_XOR_BE(ptenum * 2 + 1)] = pteglower; } /* otherwise we're good */ address = (pteglower & 0xfffff000) | (address & 0x00000fff); return (pteglower >> 7) & 1; } } /* invert the hash after the first round */ hash = ~hash; } /* we failed to find any match: not found */ return DSISR_NOT_FOUND | ((transtype == TRANSLATE_WRITE) ? DSISR_STORE : 0); } /*------------------------------------------------- ppccom_translate_address - translate an address from logical to physical -------------------------------------------------*/ bool ppc_device::memory_translate(int spacenum, int intention, offs_t &address) { /* only applies to the program address space */ if (spacenum != AS_PROGRAM) return true; /* translation is successful if the internal routine returns 0 or 1 */ return (ppccom_translate_address_internal(intention, address) <= 1); } /*------------------------------------------------- ppccom_tlb_fill - handle a missing TLB entry -------------------------------------------------*/ void ppc_device::ppccom_tlb_fill() { vtlb_fill(m_core->param0, m_core->param1); } /*------------------------------------------------- ppccom_tlb_flush - flush the entire TLB, including fixed entries -------------------------------------------------*/ void ppc_device::ppccom_tlb_flush() { vtlb_flush_dynamic(); } /*************************************************************************** OPCODE HANDLING ***************************************************************************/ /*------------------------------------------------- ppccom_get_dsisr - gets the DSISR value for a failing TLB lookup's data access exception. -------------------------------------------------*/ void ppc_device::ppccom_get_dsisr() { int intent = 0; if (m_core->param1 & 1) { intent = TRANSLATE_WRITE; } else { intent = TRANSLATE_READ; } m_core->param1 = ppccom_translate_address_internal(intent, m_core->param0); } /*------------------------------------------------- ppccom_execute_tlbie - execute a TLBIE instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_tlbie() { vtlb_flush_address(m_core->param0); } /*------------------------------------------------- ppccom_execute_tlbia - execute a TLBIA instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_tlbia() { vtlb_flush_dynamic(); } /*------------------------------------------------- ppccom_execute_tlbl - execute a TLBLD/TLBLI instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_tlbl() { uint32_t address = m_core->param0; int isitlb = m_core->param1; vtlb_entry flags; int entrynum; /* determine entry number; we use machine().rand() for associativity */ entrynum = ((address >> 12) & 0x1f) | (machine().rand() & 0x20) | (isitlb ? 0x40 : 0); /* determine the flags */ flags = VTLB_FLAG_VALID | VTLB_READ_ALLOWED | VTLB_FETCH_ALLOWED; if (m_core->spr[SPR603_RPA] & 0x80) flags |= VTLB_WRITE_ALLOWED; if (isitlb) flags |= VTLB_FETCH_ALLOWED; /* load the entry */ vtlb_load(entrynum, 1, address, (m_core->spr[SPR603_RPA] & 0xfffff000) | flags); } /*------------------------------------------------- ppccom_execute_mftb - execute an MFTB instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_mftb() { switch (m_core->param0) { /* user mode timebase read */ case SPRVEA_TBL_R: m_core->param1 = get_timebase(); break; case SPRVEA_TBU_R: m_core->param1 = get_timebase() >> 32; break; } } /*------------------------------------------------- ppccom_execute_mfspr - execute an MFSPR instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_mfspr() { /* handle OEA SPRs */ if (m_cap & PPCCAP_OEA) { switch (m_core->param0) { /* read-through no-ops */ case SPROEA_DSISR: case SPROEA_DAR: case SPROEA_SDR1: case SPROEA_SRR0: case SPROEA_SRR1: case SPROEA_EAR: case SPROEA_IBAT0L: case SPROEA_IBAT0U: case SPROEA_IBAT1L: case SPROEA_IBAT1U: case SPROEA_IBAT2L: case SPROEA_IBAT2U: case SPROEA_IBAT3L: case SPROEA_IBAT3U: case SPROEA_DBAT0L: case SPROEA_DBAT0U: case SPROEA_DBAT1L: case SPROEA_DBAT1U: case SPROEA_DBAT2L: case SPROEA_DBAT2U: case SPROEA_DBAT3L: case SPROEA_DBAT3U: case SPROEA_DABR: m_core->param1 = m_core->spr[m_core->param0]; return; /* decrementer */ case SPROEA_DEC: m_core->param1 = get_decrementer(); return; } } /* handle 603 SPRs */ if (m_cap & PPCCAP_603_MMU) { switch (m_core->param0) { /* read-through no-ops */ case SPR603_DMISS: case SPR603_DCMP: case SPR603_HASH1: case SPR603_HASH2: case SPR603_IMISS: case SPR603_ICMP: case SPR603_RPA: case SPR603_HID0: case SPR603_HID1: case SPR603_IABR: case SPR603_HID2: m_core->param1 = m_core->spr[m_core->param0]; return; /* timebase */ case SPR603_TBL_R: m_core->param1 = get_timebase(); return; case SPR603_TBU_R: m_core->param1 = (get_timebase() >> 32) & 0xffffff; return; } } /* handle 4XX SPRs */ if (m_cap & PPCCAP_4XX) { switch (m_core->param0) { /* read-through no-ops */ case SPR4XX_EVPR: case SPR4XX_ESR: case SPR4XX_SRR0: case SPR4XX_SRR1: case SPR4XX_SRR2: case SPR4XX_SRR3: case SPR4XX_TCR: case SPR4XX_TSR: case SPR4XX_IAC1: case SPR4XX_IAC2: case SPR4XX_DAC1: case SPR4XX_DAC2: case SPR4XX_DCCR: case SPR4XX_ICCR: case SPR4XX_PBL1: case SPR4XX_PBU1: case SPR4XX_PBL2: case SPR4XX_PBU2: m_core->param1 = m_core->spr[m_core->param0]; return; /* timebase */ case SPR4XX_TBLO: case SPR4XX_TBLU: m_core->param1 = get_timebase(); return; case SPR4XX_TBHI: case SPR4XX_TBHU: m_core->param1 = (get_timebase() >> 32) & 0xffffff; return; } } /* default handling */ osd_printf_debug("SPR %03X read\n", m_core->param0); m_core->param1 = m_core->spr[m_core->param0]; } /*------------------------------------------------- ppccom_execute_mtspr - execute an MTSPR instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_mtspr() { /* handle OEA SPRs */ if (m_cap & PPCCAP_OEA) { switch (m_core->param0) { /* write-through no-ops */ case SPROEA_DSISR: case SPROEA_DAR: case SPROEA_SRR0: case SPROEA_SRR1: case SPROEA_EAR: case SPROEA_DABR: m_core->spr[m_core->param0] = m_core->param1; return; /* registers that affect the memory map */ case SPROEA_SDR1: case SPROEA_IBAT0L: case SPROEA_IBAT0U: case SPROEA_IBAT1L: case SPROEA_IBAT1U: case SPROEA_IBAT2L: case SPROEA_IBAT2U: case SPROEA_IBAT3L: case SPROEA_IBAT3U: case SPROEA_DBAT0L: case SPROEA_DBAT0U: case SPROEA_DBAT1L: case SPROEA_DBAT1U: case SPROEA_DBAT2L: case SPROEA_DBAT2U: case SPROEA_DBAT3L: case SPROEA_DBAT3U: m_core->spr[m_core->param0] = m_core->param1; ppccom_tlb_flush(); return; /* decrementer */ case SPROEA_DEC: set_decrementer(m_core->param1); return; } } /* handle 603 SPRs */ if (m_cap & PPCCAP_603_MMU) { switch (m_core->param0) { /* read-only */ case SPR603_DMISS: case SPR603_DCMP: case SPR603_HASH1: case SPR603_HASH2: case SPR603_IMISS: case SPR603_ICMP: return; /* write-through no-ops */ case SPR603_RPA: case SPR603_HID0: case SPR603_HID1: case SPR603_IABR: case SPR603_HID2: m_core->spr[m_core->param0] = m_core->param1; return; /* timebase */ case SPR603_TBL_W: set_timebase((get_timebase() & ~u64(0xffffffff00000000U)) | m_core->param1); return; case SPR603_TBU_W: set_timebase((get_timebase() & ~u64(0x00000000ffffffffU)) | ((uint64_t)m_core->param1 << 32)); return; } } /* handle 4XX SPRs */ if (m_cap & PPCCAP_4XX) { uint32_t oldval = m_core->spr[m_core->param0]; switch (m_core->param0) { /* write-through no-ops */ case SPR4XX_EVPR: case SPR4XX_ESR: case SPR4XX_DCCR: case SPR4XX_ICCR: case SPR4XX_SRR0: case SPR4XX_SRR1: case SPR4XX_SRR2: case SPR4XX_SRR3: m_core->spr[m_core->param0] = m_core->param1; return; /* registers that affect the memory map */ case SPR4XX_PBL1: case SPR4XX_PBU1: case SPR4XX_PBL2: case SPR4XX_PBU2: m_core->spr[m_core->param0] = m_core->param1; ppccom_tlb_flush(); return; /* timer control register */ case SPR4XX_TCR: m_core->spr[SPR4XX_TCR] = m_core->param1 | (oldval & PPC4XX_TCR_WRC_MASK); if ((oldval ^ m_core->spr[SPR4XX_TCR]) & PPC4XX_TCR_FIE) ppc4xx_fit_callback(nullptr, false); if ((oldval ^ m_core->spr[SPR4XX_TCR]) & PPC4XX_TCR_PIE) ppc4xx_pit_callback(nullptr, false); return; /* timer status register */ case SPR4XX_TSR: m_core->spr[SPR4XX_TSR] &= ~m_core->param1; ppc4xx_set_irq_line(0, 0); return; /* PIT */ case SPR4XX_PIT: m_core->spr[SPR4XX_PIT] = m_core->param1; m_pit_reload = m_core->param1; ppc4xx_pit_callback(nullptr, false); return; /* timebase */ case SPR4XX_TBLO: set_timebase((get_timebase() & ~u64(0x00ffffff00000000U)) | m_core->param1); return; case SPR4XX_TBHI: set_timebase((get_timebase() & ~u64(0x00000000ffffffffU)) | ((uint64_t)(m_core->param1 & 0x00ffffff) << 32)); return; } } /* default handling */ osd_printf_debug("SPR %03X write = %08X\n", m_core->param0, m_core->param1); m_core->spr[m_core->param0] = m_core->param1; } /*------------------------------------------------- ppccom_execute_mfdcr - execute an MFDCR instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_mfdcr() { /* handle various DCRs */ switch (m_core->param0) { /* read-through no-ops */ case DCR4XX_BR0: case DCR4XX_BR1: case DCR4XX_BR2: case DCR4XX_BR3: case DCR4XX_BR4: case DCR4XX_BR5: case DCR4XX_BR6: case DCR4XX_BR7: case DCR4XX_BESR: case DCR4XX_DMASR: case DCR4XX_DMACT0: case DCR4XX_DMADA0: case DCR4XX_DMASA0: case DCR4XX_DMACC0: case DCR4XX_DMACR0: case DCR4XX_DMACT1: case DCR4XX_DMADA1: case DCR4XX_DMASA1: case DCR4XX_DMACC1: case DCR4XX_DMACR1: case DCR4XX_DMACT2: case DCR4XX_DMADA2: case DCR4XX_DMASA2: case DCR4XX_DMACC2: case DCR4XX_DMACR2: case DCR4XX_DMACT3: case DCR4XX_DMADA3: case DCR4XX_DMASA3: case DCR4XX_DMACC3: case DCR4XX_DMACR3: case DCR4XX_EXIER: case DCR4XX_EXISR: case DCR4XX_IOCR: m_core->param1 = m_dcr[m_core->param0]; return; } /* default handling */ if (m_dcr_read_func.isnull()) { osd_printf_debug("DCR %03X read\n", m_core->param0); if (m_core->param0 < ARRAY_LENGTH(m_dcr)) m_core->param1 = m_dcr[m_core->param0]; else m_core->param1 = 0; } else { m_core->param1 = m_dcr_read_func(*m_program,m_core->param0,0xffffffff); } } /*------------------------------------------------- ppccom_execute_mtdcr - execute an MTDCR instruction -------------------------------------------------*/ void ppc_device::ppccom_execute_mtdcr() { uint8_t oldval; /* handle various DCRs */ switch (m_core->param0) { /* write-through no-ops */ case DCR4XX_BR0: case DCR4XX_BR1: case DCR4XX_BR2: case DCR4XX_BR3: case DCR4XX_BR4: case DCR4XX_BR5: case DCR4XX_BR6: case DCR4XX_BR7: case DCR4XX_BESR: case DCR4XX_DMACT0: case DCR4XX_DMADA0: case DCR4XX_DMASA0: case DCR4XX_DMACC0: case DCR4XX_DMACT1: case DCR4XX_DMADA1: case DCR4XX_DMASA1: case DCR4XX_DMACC1: case DCR4XX_DMACT2: case DCR4XX_DMADA2: case DCR4XX_DMASA2: case DCR4XX_DMACC2: case DCR4XX_DMACT3: case DCR4XX_DMADA3: case DCR4XX_DMASA3: case DCR4XX_DMACC3: m_dcr[m_core->param0] = m_core->param1; return; /* DMA status */ case DCR4XX_DMASR: m_dcr[DCR4XX_DMASR] &= ~(m_core->param1 & 0xfff80070); ppc4xx_dma_update_irq_states(); return; /* interrupt enables */ case DCR4XX_EXIER: m_dcr[DCR4XX_EXIER] = m_core->param1; ppc4xx_set_irq_line(0, 0); return; /* interrupt clear */ case DCR4XX_EXISR: m_dcr[m_core->param0] &= ~m_core->param1; ppc4xx_set_irq_line(0, 0); return; /* DMA controls */ case DCR4XX_DMACR0: case DCR4XX_DMACR1: case DCR4XX_DMACR2: case DCR4XX_DMACR3: m_dcr[m_core->param0] = m_core->param1; if (m_core->param1 & PPC4XX_DMACR_CE) ppc4xx_dma_exec((m_core->param0 - DCR4XX_DMACR0) / 8); ppc4xx_dma_update_irq_states(); return; /* I/O control */ case DCR4XX_IOCR: oldval = m_dcr[m_core->param0]; m_dcr[m_core->param0] = m_core->param1; if ((oldval ^ m_core->param1) & 0x02) ppc4xx_spu_timer_reset(); return; } /* default handling */ if (m_dcr_write_func.isnull()) { osd_printf_debug("DCR %03X write = %08X\n", m_core->param0, m_core->param1); if (m_core->param0 < ARRAY_LENGTH(m_dcr)) m_dcr[m_core->param0] = m_core->param1; } else { m_dcr_write_func(*m_program,m_core->param0,m_core->param1,0xffffffff); } } /*************************************************************************** FLOATING POINT STATUS FLAGS HANDLING ***************************************************************************/ /*------------------------------------------------- ppccom_update_fprf - update the FPRF field of the FPSCR register -------------------------------------------------*/ void ppc_device::ppccom_update_fprf() { uint32_t fprf; double f = m_core->f[m_core->param0]; if (is_qnan_double(f)) { fprf = 0x11; } else if (is_infinity_double(f)) { if (sign_double(f)) /* -Infinity */ fprf = 0x09; else /* +Infinity */ fprf = 0x05; } else if (is_normalized_double(f)) { if (sign_double(f)) /* -Normalized */ fprf = 0x08; else /* +Normalized */ fprf = 0x04; } else if (is_denormalized_double(f)) { if (sign_double(f)) /* -Denormalized */ fprf = 0x18; else /* +Denormalized */ fprf = 0x14; } else { if (sign_double(f)) /* -Zero */ fprf = 0x12; else /* +Zero */ fprf = 0x02; } m_core->fpscr &= ~0x0001f000; m_core->fpscr |= fprf << 12; } /*************************************************************************** OEA HELPERS ***************************************************************************/ /*------------------------------------------------- decrementer_int_callback - callback that fires whenever a decrementer interrupt is generated -------------------------------------------------*/ TIMER_CALLBACK_MEMBER( ppc_device::decrementer_int_callback ) { uint64_t cycles_until_next; /* set the decrementer IRQ state */ m_core->irq_pending |= 0x02; /* advance by another full rev */ m_dec_zero_cycles += (uint64_t)m_tb_divisor << 32; cycles_until_next = m_dec_zero_cycles - total_cycles(); m_decrementer_int_timer->adjust(cycles_to_attotime(cycles_until_next)); } /*------------------------------------------------- ppc_set_dcstore_callback - installs a callback for detecting datacache stores with dcbst -------------------------------------------------*/ void ppc_device::ppc_set_dcstore_callback(write32_delegate callback) { m_dcstore_cb = callback; } void ppc_device::execute_set_input(int inputnum, int state) { switch (inputnum) { case PPC_IRQ: m_core->irq_pending = (m_core->irq_pending & ~1) | ((state != CLEAR_LINE) ? 1 : 0); break; } } void ppc4xx_device::execute_set_input(int inputnum, int state) { switch (inputnum) { case PPC_IRQ_LINE_0: ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_EXT0, state); break; case PPC_IRQ_LINE_1: ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_EXT1, state); break; case PPC_IRQ_LINE_2: ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_EXT2, state); break; case PPC_IRQ_LINE_3: ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_EXT3, state); break; case PPC_IRQ_LINE_4: ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_EXT4, state); break; } } /*************************************************************************** EMBEDDED 4XX HELPERS ***************************************************************************/ /*------------------------------------------------- ppc4xx_set_irq_line - PowerPC 4XX-specific IRQ line management -------------------------------------------------*/ void ppc_device::ppc4xx_set_irq_line(uint32_t bitmask, int state) { uint32_t oldstate = m_irqstate; uint32_t levelmask; /* set or clear the appropriate bit */ if (state != CLEAR_LINE) m_irqstate |= bitmask; else m_irqstate &= ~bitmask; /* if the state changed to on, edge trigger the interrupt */ if (((m_irqstate ^ oldstate) & bitmask) && (m_irqstate & bitmask)) m_dcr[DCR4XX_EXISR] |= bitmask; /* pass through all level-triggered interrupts */ levelmask = PPC4XX_IRQ_BIT_CRITICAL | PPC4XX_IRQ_BIT_SPUR | PPC4XX_IRQ_BIT_SPUT; levelmask |= PPC4XX_IRQ_BIT_JTAGR | PPC4XX_IRQ_BIT_JTAGT; levelmask |= PPC4XX_IRQ_BIT_DMA0 | PPC4XX_IRQ_BIT_DMA1 | PPC4XX_IRQ_BIT_DMA2 | PPC4XX_IRQ_BIT_DMA3; if (!(m_dcr[DCR4XX_IOCR] & 0x80000000)) levelmask |= PPC4XX_IRQ_BIT_EXT0; if (!(m_dcr[DCR4XX_IOCR] & 0x20000000)) levelmask |= PPC4XX_IRQ_BIT_EXT1; if (!(m_dcr[DCR4XX_IOCR] & 0x08000000)) levelmask |= PPC4XX_IRQ_BIT_EXT2; if (!(m_dcr[DCR4XX_IOCR] & 0x02000000)) levelmask |= PPC4XX_IRQ_BIT_EXT3; if (!(m_dcr[DCR4XX_IOCR] & 0x00800000)) levelmask |= PPC4XX_IRQ_BIT_EXT4; m_dcr[DCR4XX_EXISR] = (m_dcr[DCR4XX_EXISR] & ~levelmask) | (m_irqstate & levelmask); /* update the IRQ status */ m_core->irq_pending = ((m_dcr[DCR4XX_EXISR] & m_dcr[DCR4XX_EXIER]) != 0); if ((m_core->spr[SPR4XX_TCR] & PPC4XX_TCR_FIE) && (m_core->spr[SPR4XX_TSR] & PPC4XX_TSR_FIS)) m_core->irq_pending = true; if ((m_core->spr[SPR4XX_TCR] & PPC4XX_TCR_PIE) && (m_core->spr[SPR4XX_TSR] & PPC4XX_TSR_PIS)) m_core->irq_pending = true; } /*------------------------------------------------- ppc4xx_get_irq_line - PowerPC 4XX-specific IRQ line state getter -------------------------------------------------*/ int ppc_device::ppc4xx_get_irq_line(uint32_t bitmask) { return (m_irqstate & bitmask) ? ASSERT_LINE : CLEAR_LINE; } /*------------------------------------------------- ppc4xx_dma_update_irq_states - update the IRQ state for each DMA channel -------------------------------------------------*/ void ppc_device::ppc4xx_dma_update_irq_states() { /* update the IRQ state for each DMA channel */ for (int dmachan = 0; dmachan < 4; dmachan++) { bool irq_pending = false; // Channel interrupt enabled? if ((m_dcr[DCR4XX_DMACR0 + 8 * dmachan] & PPC4XX_DMACR_CIE)) { // Terminal count and end-of-transfer status bits int bitmask = 0x11 << (27 - dmachan); // Chained transfer status bit switch (dmachan) { case 0: bitmask |= 0x00080000; break; case 1: case 2: case 3: bitmask |= 1 << (7 - dmachan); break; } irq_pending = (m_dcr[DCR4XX_DMASR] & bitmask) != 0; } ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_DMA(dmachan), irq_pending ? ASSERT_LINE : CLEAR_LINE); } } /*------------------------------------------------- ppc4xx_dma_decrement_count - decrement the count on a channel and interrupt if configured to do so -------------------------------------------------*/ bool ppc_device::ppc4xx_dma_decrement_count(int dmachan) { uint32_t *dmaregs = &m_dcr[8 * dmachan]; /* decrement the counter */ dmaregs[DCR4XX_DMACT0]--; /* if non-zero, we keep going */ if ((dmaregs[DCR4XX_DMACT0] & 0xffff) != 0) return false; // if chained mode if (dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_CH) { dmaregs[DCR4XX_DMADA0] = dmaregs[DCR4XX_DMASA0]; dmaregs[DCR4XX_DMACT0] = dmaregs[DCR4XX_DMACC0]; dmaregs[DCR4XX_DMACR0] &= ~PPC4XX_DMACR_CH; switch (dmachan) { case 0: m_dcr[DCR4XX_DMASR] |= 0x00080000; break; case 1: case 2: case 3: m_dcr[DCR4XX_DMASR] |= 1 << (7 - dmachan); break; } ppc4xx_dma_update_irq_states(); int64_t numdata = dmaregs[DCR4XX_DMACT0]; if (numdata == 0) numdata = 65536; int64_t time = (numdata * 1000000) / m_buffered_dma_rate[dmachan]; m_buffered_dma_timer[dmachan]->adjust(attotime::from_usec(time), dmachan); } else { /* set the complete bit and handle interrupts */ m_dcr[DCR4XX_DMASR] |= 1 << (31 - dmachan); // m_dcr[DCR4XX_DMASR] |= 1 << (27 - dmachan); ppc4xx_dma_update_irq_states(); m_buffered_dma_timer[dmachan]->adjust(attotime::never, false); } return true; } /*------------------------------------------------- buffered_dma_callback - callback that fires when buffered DMA transfer is ready -------------------------------------------------*/ TIMER_CALLBACK_MEMBER( ppc_device::ppc4xx_buffered_dma_callback ) { int dmachan = param; static const uint8_t dma_transfer_width[4] = { 1, 2, 4, 16 }; uint32_t *dmaregs = &m_dcr[8 * dmachan]; int32_t destinc; uint8_t width; width = dma_transfer_width[(dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_PW_MASK) >> 26]; destinc = (dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_DAI) ? width : 0; if (dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_TD) { /* peripheral to memory */ switch (width) { /* byte transfer */ case 1: do { uint8_t data = 0; if (!m_ext_dma_read_cb[dmachan].isnull()) data = (m_ext_dma_read_cb[dmachan])(*m_program, 1, 0xffffffff); m_program->write_byte(dmaregs[DCR4XX_DMADA0], data); dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* word transfer */ case 2: do { uint16_t data = 0; if (!m_ext_dma_read_cb[dmachan].isnull()) data = (m_ext_dma_read_cb[dmachan])(*m_program, 2, 0xffffffff); m_program->write_word(dmaregs[DCR4XX_DMADA0], data); dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* dword transfer */ case 4: do { uint32_t data = 0; if (!m_ext_dma_read_cb[dmachan].isnull()) data = (m_ext_dma_read_cb[dmachan])(*m_program, 4, 0xffffffff); m_program->write_dword(dmaregs[DCR4XX_DMADA0], data); dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; } } else { /* memory to peripheral */ // data is read from destination address! switch (width) { /* byte transfer */ case 1: do { uint8_t data = m_program->read_byte(dmaregs[DCR4XX_DMADA0]); if (!m_ext_dma_write_cb[dmachan].isnull()) (m_ext_dma_write_cb[dmachan])(*m_program, 1, data, 0xffffffff); dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* word transfer */ case 2: do { uint16_t data = m_program->read_word(dmaregs[DCR4XX_DMADA0]); if (!m_ext_dma_write_cb[dmachan].isnull()) (m_ext_dma_write_cb[dmachan])(*m_program, 2, data, 0xffffffff); dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* dword transfer */ case 4: do { uint32_t data = m_program->read_dword(dmaregs[DCR4XX_DMADA0]); if (!m_ext_dma_write_cb[dmachan].isnull()) (m_ext_dma_write_cb[dmachan])(*m_program, 4, data, 0xffffffff); dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; } } } /*------------------------------------------------- ppc4xx_dma_fetch_transmit_byte - fetch a byte to send to a peripheral -------------------------------------------------*/ bool ppc_device::ppc4xx_dma_fetch_transmit_byte(int dmachan, uint8_t *byte) { uint32_t *dmaregs = &m_dcr[8 * dmachan]; /* if the channel is not enabled, fail */ if (!(dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_CE)) return false; /* if no transfers remaining, fail */ if ((dmaregs[DCR4XX_DMACT0] & 0xffff) == 0) return false; /* fetch the data */ *byte = m_program->read_byte(dmaregs[DCR4XX_DMADA0]++); ppc4xx_dma_decrement_count(dmachan); return true; } /*------------------------------------------------- ppc4xx_dma_handle_receive_byte - receive a byte transmitted by a peripheral -------------------------------------------------*/ bool ppc_device::ppc4xx_dma_handle_receive_byte(int dmachan, uint8_t byte) { uint32_t *dmaregs = &m_dcr[8 * dmachan]; /* if the channel is not enabled, fail */ if (!(dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_CE)) return false; /* if no transfers remaining, fail */ if ((dmaregs[DCR4XX_DMACT0] & 0xffff) == 0) return false; /* store the data */ m_program->write_byte(dmaregs[DCR4XX_DMADA0]++, byte); ppc4xx_dma_decrement_count(dmachan); return true; } /*------------------------------------------------- ppc4xx_dma_execute - execute a DMA operation if one is pending -------------------------------------------------*/ void ppc_device::ppc4xx_dma_exec(int dmachan) { static const uint8_t dma_transfer_width[4] = { 1, 2, 4, 16 }; uint32_t *dmaregs = &m_dcr[8 * dmachan]; int32_t destinc, srcinc; uint8_t width; /* skip if not enabled */ if (!(dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_CE)) return; /* check for unsupported features */ if (!(dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_TCE)) fatalerror("ppc4xx_dma_exec: DMA_TCE == 0\n"); /* transfer mode */ switch ((dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_TM_MASK) >> 21) { /* buffered mode DMA */ case 0: if (((dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_PL) >> 28) == 0) { /* buffered DMA with external peripheral */ int64_t numdata = dmaregs[DCR4XX_DMACT0]; if (numdata == 0) numdata = 65536; int64_t time; if (numdata > 100) { time = (numdata * 1000000) / m_buffered_dma_rate[dmachan]; } else { time = 0; // let very short transfers occur instantly } m_buffered_dma_timer[dmachan]->adjust(attotime::from_usec(time), dmachan); } else /* buffered DMA with internal peripheral (SPU) */ { /* nothing to do; this happens asynchronously and is driven by the SPU */ } break; /* fly-by mode DMA */ case 1: fatalerror("ppc4xx_dma_exec: fly-by DMA not implemented\n"); /* software initiated memory-to-memory mode DMA */ case 2: width = dma_transfer_width[(dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_PW_MASK) >> 26]; srcinc = (dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_SAI) ? width : 0; destinc = (dmaregs[DCR4XX_DMACR0] & PPC4XX_DMACR_DAI) ? width : 0; switch (width) { /* byte transfer */ case 1: do { m_program->write_byte(dmaregs[DCR4XX_DMADA0], m_program->read_byte(dmaregs[DCR4XX_DMASA0])); dmaregs[DCR4XX_DMASA0] += srcinc; dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* word transfer */ case 2: do { m_program->write_word(dmaregs[DCR4XX_DMADA0], m_program->read_word(dmaregs[DCR4XX_DMASA0])); dmaregs[DCR4XX_DMASA0] += srcinc; dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* dword transfer */ case 4: do { m_program->write_dword(dmaregs[DCR4XX_DMADA0], m_program->read_dword(dmaregs[DCR4XX_DMASA0])); dmaregs[DCR4XX_DMASA0] += srcinc; dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; /* 16-byte transfer */ case 16: do { m_program->write_qword(dmaregs[DCR4XX_DMADA0], m_program->read_qword(dmaregs[DCR4XX_DMASA0])); m_program->write_qword(dmaregs[DCR4XX_DMADA0] + 8, m_program->read_qword(dmaregs[DCR4XX_DMASA0] + 8)); dmaregs[DCR4XX_DMASA0] += srcinc; dmaregs[DCR4XX_DMADA0] += destinc; } while (!ppc4xx_dma_decrement_count(dmachan)); break; } break; /* hardware initiated memory-to-memory mode DMA */ case 3: fatalerror("ppc4xx_dma_exec: HW mem-to-mem DMA not implemented\n"); } } /*------------------------------------------------- ppc4xx_fit_callback - FIT timer callback -------------------------------------------------*/ TIMER_CALLBACK_MEMBER( ppc_device::ppc4xx_fit_callback ) { /* if this is a real callback and we are enabled, signal an interrupt */ if (param) { m_core->spr[SPR4XX_TSR] |= PPC4XX_TSR_FIS; ppc4xx_set_irq_line(0, 0); } /* update ourself for the next interval if we are enabled */ if (m_core->spr[SPR4XX_TCR] & PPC4XX_TCR_FIE) { uint32_t timebase = get_timebase(); uint32_t interval = 0x200 << (4 * ((m_core->spr[SPR4XX_TCR] & PPC4XX_TCR_FP_MASK) >> 24)); uint32_t target = (timebase + interval) & ~(interval - 1); m_fit_timer->adjust(cycles_to_attotime((target + 1 - timebase) / m_tb_divisor), true); } /* otherwise, turn ourself off */ else m_fit_timer->adjust(attotime::never, false); } /*------------------------------------------------- ppc4xx_pit_callback - PIT timer callback -------------------------------------------------*/ TIMER_CALLBACK_MEMBER( ppc_device::ppc4xx_pit_callback ) { /* if this is a real callback and we are enabled, signal an interrupt */ if (param) { m_core->spr[SPR4XX_TSR] |= PPC4XX_TSR_PIS; ppc4xx_set_irq_line(0, 0); } /* update ourself for the next interval if we are enabled and we are either being forced to update, or we are in auto-reload mode */ if ((m_core->spr[SPR4XX_TCR] & PPC4XX_TCR_PIE) && m_pit_reload != 0 && (!param || (m_core->spr[SPR4XX_TCR] & PPC4XX_TCR_ARE))) { uint32_t timebase = get_timebase(); uint32_t interval = m_pit_reload; uint32_t target = timebase + interval; m_pit_timer->adjust(cycles_to_attotime((target + 1 - timebase) / m_tb_divisor), true); } /* otherwise, turn ourself off */ else m_pit_timer->adjust(attotime::never, false); } /*------------------------------------------------- ppc4xx_spu_update_irq_states - update the IRQ state for the SPU -------------------------------------------------*/ void ppc_device::ppc4xx_spu_update_irq_states() { /* check for receive buffer full interrupt */ if ((m_spu.regs[SPU4XX_RX_COMMAND] & 0x60) == 0x20 && (m_spu.regs[SPU4XX_LINE_STATUS] & 0x80)) ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_SPUR, ASSERT_LINE); /* check for receive error interrupt */ else if ((m_spu.regs[SPU4XX_RX_COMMAND] & 0x10) && (m_spu.regs[SPU4XX_LINE_STATUS] & 0x78)) ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_SPUR, ASSERT_LINE); /* clear otherwise */ else ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_SPUR, CLEAR_LINE); /* check for transmit buffer empty interrupt */ if ((m_spu.regs[SPU4XX_TX_COMMAND] & 0x60) == 0x20 && (m_spu.regs[SPU4XX_LINE_STATUS] & 0x04)) ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_SPUT, ASSERT_LINE); /* check for shift register empty interrupt */ else if ((m_spu.regs[SPU4XX_TX_COMMAND] & 0x10) && (m_spu.regs[SPU4XX_LINE_STATUS] & 0x02)) ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_SPUT, ASSERT_LINE); /* clear otherwise */ else ppc4xx_set_irq_line(PPC4XX_IRQ_BIT_SPUT, CLEAR_LINE); } /*------------------------------------------------- ppc4xx_spu_rx_data - serial port data receive -------------------------------------------------*/ void ppc_device::ppc4xx_spu_rx_data(uint8_t data) { uint32_t new_rxin; /* fail if we are going to overflow */ new_rxin = (m_spu.rxin + 1) % ARRAY_LENGTH(m_spu.rxbuffer); if (new_rxin == m_spu.rxout) fatalerror("ppc4xx_spu_rx_data: buffer overrun!\n"); /* store the data and accept the new in index */ m_spu.rxbuffer[m_spu.rxin] = data; m_spu.rxin = new_rxin; } /*------------------------------------------------- ppc4xx_spu_timer_reset - reset and recompute the transmit/receive timer -------------------------------------------------*/ void ppc_device::ppc4xx_spu_timer_reset() { uint8_t enabled = (m_spu.regs[SPU4XX_RX_COMMAND] | m_spu.regs[SPU4XX_TX_COMMAND]) & 0x80; /* if we're enabled, reset at the current baud rate */ if (enabled) { attotime clockperiod = attotime::from_hz((m_dcr[DCR4XX_IOCR] & 0x02) ? 3686400 : 33333333); int divisor = ((m_spu.regs[SPU4XX_BAUD_DIVISOR_H] * 256 + m_spu.regs[SPU4XX_BAUD_DIVISOR_L]) & 0xfff) + 1; int bpc = 7 + ((m_spu.regs[SPU4XX_CONTROL] & 8) >> 3) + 1 + (m_spu.regs[SPU4XX_CONTROL] & 1); attotime charperiod = clockperiod * (divisor * 16 * bpc); m_spu.timer->adjust(charperiod, 0, charperiod); if (PRINTF_SPU) printf("ppc4xx_spu_timer_reset: baud rate = %.0f\n", ATTOSECONDS_TO_HZ(charperiod.attoseconds()) * bpc); } /* otherwise, disable the timer */ else m_spu.timer->adjust(attotime::never); } /*------------------------------------------------- ppc4xx_spu_callback - serial port send/receive timer -------------------------------------------------*/ TIMER_CALLBACK_MEMBER( ppc_device::ppc4xx_spu_callback ) { /* transmit enabled? */ if (m_spu.regs[SPU4XX_TX_COMMAND] & 0x80) { int operation = (m_spu.regs[SPU4XX_TX_COMMAND] >> 5) & 3; /* if we have data to transmit, do it now */ if (!(m_spu.regs[SPU4XX_LINE_STATUS] & 0x04)) { /* if we have a transmit handler, send it that way */ if (!m_spu.tx_cb.isnull()) (m_spu.tx_cb)(*m_program, 0, m_spu.txbuf, 0xff); /* indicate that we have moved it to the shift register */ m_spu.regs[SPU4XX_LINE_STATUS] |= 0x04; m_spu.regs[SPU4XX_LINE_STATUS] &= ~0x02; } /* otherwise, clear the shift register */ else if (!(m_spu.regs[SPU4XX_LINE_STATUS] & 0x02)) m_spu.regs[SPU4XX_LINE_STATUS] |= 0x02; /* handle DMA */ if (operation >= 2 && ppc4xx_dma_fetch_transmit_byte(operation, &m_spu.txbuf)) m_spu.regs[SPU4XX_LINE_STATUS] &= ~0x04; } /* receive enabled? */ if (m_spu.regs[SPU4XX_RX_COMMAND] & 0x80) if (m_spu.rxout != m_spu.rxin) { int operation = (m_spu.regs[SPU4XX_RX_COMMAND] >> 5) & 3; uint8_t rxbyte; /* consume the byte and advance the out pointer */ rxbyte = m_spu.rxbuffer[m_spu.rxout]; m_spu.rxout = (m_spu.rxout + 1) % ARRAY_LENGTH(m_spu.rxbuffer); /* if we're not full, copy data to the buffer and update the line status */ if (!(m_spu.regs[SPU4XX_LINE_STATUS] & 0x80)) { m_spu.rxbuf = rxbyte; m_spu.regs[SPU4XX_LINE_STATUS] |= 0x80; } /* otherwise signal an overrun */ else { m_spu.regs[SPU4XX_LINE_STATUS] |= 0x20; goto updateirq; } /* handle DMA */ if (operation >= 2 && ppc4xx_dma_handle_receive_byte(operation, m_spu.rxbuf)) m_spu.regs[SPU4XX_LINE_STATUS] &= ~0x80; } /* update the final IRQ states */ updateirq: ppc4xx_spu_update_irq_states(); } /*------------------------------------------------- ppc4xx_spu_r - serial port read handler -------------------------------------------------*/ READ8_MEMBER( ppc4xx_device::ppc4xx_spu_r ) { uint8_t result = 0xff; switch (offset) { case SPU4XX_BUFFER: result = m_spu.rxbuf; m_spu.regs[SPU4XX_LINE_STATUS] &= ~0x80; break; default: if (offset < ARRAY_LENGTH(m_spu.regs)) result = m_spu.regs[offset]; break; } if (PRINTF_SPU) printf("spu_r(%d) = %02X\n", offset, result); return result; } /*------------------------------------------------- ppc4xx_spu_w - serial port write handler -------------------------------------------------*/ WRITE8_MEMBER( ppc4xx_device::ppc4xx_spu_w ) { uint8_t oldstate, newstate; if (PRINTF_SPU) printf("spu_w(%d) = %02X\n", offset, data); switch (offset) { /* clear error bits */ case SPU4XX_LINE_STATUS: m_spu.regs[SPU4XX_LINE_STATUS] &= ~(data & 0xf8); ppc4xx_spu_update_irq_states(); break; /* enable/disable the timer if one of these is enabled */ case SPU4XX_RX_COMMAND: case SPU4XX_TX_COMMAND: oldstate = m_spu.regs[SPU4XX_RX_COMMAND] | m_spu.regs[SPU4XX_TX_COMMAND]; m_spu.regs[offset] = data; newstate = m_spu.regs[SPU4XX_RX_COMMAND] | m_spu.regs[SPU4XX_TX_COMMAND]; if ((oldstate ^ newstate) & 0x80) ppc4xx_spu_timer_reset(); ppc4xx_spu_update_irq_states(); break; /* if the divisor changes, we need to update the timer */ case SPU4XX_BAUD_DIVISOR_H: case SPU4XX_BAUD_DIVISOR_L: if (data != m_spu.regs[offset]) { m_spu.regs[offset] = data; ppc4xx_spu_timer_reset(); } break; /* if the number of data bits or stop bits changes, we need to update the timer */ case SPU4XX_CONTROL: oldstate = m_spu.regs[offset]; m_spu.regs[offset] = data; if ((oldstate ^ data) & 0x09) ppc4xx_spu_timer_reset(); break; case SPU4XX_BUFFER: /* write to the transmit buffer and mark it full */ m_spu.txbuf = data; m_spu.regs[SPU4XX_LINE_STATUS] &= ~0x04; break; default: if (offset < ARRAY_LENGTH(m_spu.regs)) m_spu.regs[offset] = data; break; } } /*------------------------------------------------- ppc4xx_spu_set_tx_handler - PowerPC 4XX- specific TX handler configuration -------------------------------------------------*/ void ppc4xx_device::ppc4xx_spu_set_tx_handler(write8_delegate callback) { m_spu.tx_cb = callback; } /*------------------------------------------------- ppc4xx_spu_receive_byte - PowerPC 4XX- specific serial byte receive -------------------------------------------------*/ void ppc4xx_device::ppc4xx_spu_receive_byte(uint8_t byteval) { ppc4xx_spu_rx_data(byteval); } /*------------------------------------------------- ppc4xx_set_dma_read_handler - PowerPC 4XX- specific external DMA read handler configuration -------------------------------------------------*/ void ppc4xx_device::ppc4xx_set_dma_read_handler(int channel, read32_delegate callback, int rate) { m_ext_dma_read_cb[channel] = callback; m_buffered_dma_rate[channel] = rate; } /*------------------------------------------------- ppc4xx_set_dma_write_handler - PowerPC 4XX- specific external DMA write handler configuration -------------------------------------------------*/ void ppc4xx_device::ppc4xx_set_dma_write_handler(int channel, write32_delegate callback, int rate) { m_ext_dma_write_cb[channel] = callback; m_buffered_dma_rate[channel] = rate; } /*------------------------------------------------- ppc4xx_set_dcr_read_handler -------------------------------------------------*/ void ppc4xx_device::ppc4xx_set_dcr_read_handler(read32_delegate dcr_read_func) { m_dcr_read_func = dcr_read_func; } /*------------------------------------------------- ppc4xx_set_dcr_write_handler -------------------------------------------------*/ void ppc4xx_device::ppc4xx_set_dcr_write_handler(write32_delegate dcr_write_func) { m_dcr_write_func = dcr_write_func; }
27.817958
250
0.611711
rjw57
1e094e2118b8258d7b7588c3de488b00eea31286
248
cc
C++
tests/day12_tests.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
tests/day12_tests.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
tests/day12_tests.cc
LesnyRumcajs/advent-of-cpp-2015
3301f31fdcca3aeddae6691ce15b0eb712a7c867
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include <catch2/catch.hpp> #include "../src/day12.h" TEST_CASE("Day12::part1", "[]") { REQUIRE(6 == day12::sumAllNumbers("{\"a\":2,\"b\":4}")); REQUIRE(3 == day12::sumAllNumbers("{\"a\":{\"b\":4},\"c\":-1}")); }
27.555556
69
0.564516
LesnyRumcajs
1f6117402c993c00fa7ca45af41be702e691c75e
6,080
cpp
C++
examples/promps_hsmm_ball_viterbi.cpp
DiegoAE/BOSD
a7ce88462c64c540ba2922d16eb6f7eba8055b47
[ "MIT" ]
19
2019-05-03T05:31:43.000Z
2022-01-08T18:14:31.000Z
examples/promps_hsmm_ball_viterbi.cpp
DiegoAE/BOSD
a7ce88462c64c540ba2922d16eb6f7eba8055b47
[ "MIT" ]
2
2019-02-14T15:29:34.000Z
2020-06-04T10:14:54.000Z
examples/promps_hsmm_ball_viterbi.cpp
DiegoAE/BOSD
a7ce88462c64c540ba2922d16eb6f7eba8055b47
[ "MIT" ]
1
2019-07-01T07:44:09.000Z
2019-07-01T07:44:09.000Z
#include <armadillo> #include <boost/program_options.hpp> #include <HSMM.hpp> #include <json.hpp> #include <ProMPs_emission.hpp> using namespace arma; using namespace hsmm; using namespace robotics; using namespace std; using json = nlohmann::json; namespace po = boost::program_options; field<mat> fromMatToField(const mat& obs) { field<mat> ret(obs.n_cols); for(int i = 0; i < obs.n_cols; i++) ret(i) = obs.col(i); return ret; } // Running the Viterbi algorithm. void ViterbiAlgorithm(HSMM& promp_hsmm, const field<field<mat>>& seq_obs, string filename) { int nseq = seq_obs.n_elem; for(int s = 0; s < nseq; s++) { const field<mat>& obs = seq_obs(s); int nstates = promp_hsmm.nstates_; int nobs = obs.n_elem; imat psi_duration(nstates, nobs, fill::zeros); imat psi_state(nstates, nobs, fill::zeros); mat delta(nstates, nobs, fill::zeros); cout << "Before pdf" << endl; cube log_pdf = promp_hsmm.computeEmissionsLogLikelihood(obs); cout << "After pdf" << endl; Viterbi(promp_hsmm.transition_, promp_hsmm.pi_, promp_hsmm.duration_, log_pdf, delta, psi_duration, psi_state, promp_hsmm.min_duration_, nobs); cout << "Delta last column" << endl; cout << delta.col(nobs - 1) << endl; ivec viterbiStates, viterbiDurations; viterbiPath(psi_duration, psi_state, delta, viterbiStates, viterbiDurations); cout << "Viterbi states and durations" << endl; imat states_and_durations = join_horiz(viterbiStates, viterbiDurations); cout << states_and_durations << endl; cout << "Python states list representation" << endl; cout << "["; for(int i = 0; i < viterbiStates.n_elem; i++) cout << viterbiStates[i] << ((i + 1 == viterbiStates.n_elem)? "]" : ","); cout << endl; cout << "Python duration list representation" << endl; cout << "["; for(int i = 0; i < viterbiDurations.n_elem; i++) cout << viterbiDurations[i] << ((i + 1 == viterbiDurations.n_elem)? "]" : ","); cout << endl; // Saving the matrix of joint states and durations. string viterbi_filename(filename); if (nseq > 1) viterbi_filename += string(".") + to_string(s); states_and_durations.save(viterbi_filename, raw_ascii); } } int main(int argc, char *argv[]) { po::options_description desc("Options"); desc.add_options() ("help,h", "Produce help message") ("input,i", po::value<string>(), "Path to the input obs") ("params,p", po::value<string>(), "Path to the json input params") ("output,o", po::value<string>(), "Path to the output viterbi file(s)") ("polybasisfun", po::value<int>()->default_value(1), "Order of the " "poly basis functions") ("norbf", "Flag to deactivate the radial basis functions") ("nsequences,n", po::value<int>()->default_value(1), "Number of sequences used for training"); po::variables_map vm; po::store(po::parse_command_line(argc, argv, desc), vm); po::notify(vm); if (vm.count("help")) { cout << desc << endl; return 0; } if (!vm.count("input") || !vm.count("output") || !vm.count("params")) { cerr << "Error: You should provide input and output files" << endl; return 1; } string input_filename = vm["input"].as<string>(); string output_filename = vm["output"].as<string>(); string params = vm["params"].as<string>(); int nseq = vm["nsequences"].as<int>(); field<field<mat>> seq_obs(nseq); int njoints; for(int i = 0; i < nseq; i++) { string name = input_filename; if (nseq != 1) name += string(".") + to_string(i); mat obs; obs.load(name, raw_ascii); ifstream input_params_file(params); json input_params; input_params_file >> input_params; njoints = obs.n_rows; int nobs = obs.n_cols; cout << "Time series shape: (" << njoints << ", " << nobs << ")." << endl; seq_obs(i) = fromMatToField(obs); } ifstream input_params_file(params); json input_params; input_params_file >> input_params; int min_duration = input_params["min_duration"]; int nstates = input_params["nstates"]; int ndurations = input_params["ndurations"]; mat transition(nstates, nstates); transition.fill(1.0 / (nstates - 1)); transition.diag().zeros(); // No self-transitions. vec pi(nstates); pi.fill(1.0/nstates); mat durations(nstates, ndurations); durations.fill(1.0 / ndurations); // Setting a combination of polynomial and rbf basis functions. auto rbf = shared_ptr<ScalarGaussBasis>(new ScalarGaussBasis( {0.25,0.5,0.75},0.25)); auto poly = make_shared<ScalarPolyBasis>(vm["polybasisfun"].as<int>()); auto comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({rbf, poly})); if (vm.count("norbf")) comb = shared_ptr<ScalarCombBasis>(new ScalarCombBasis({poly})); int n_basis_functions = comb->dim(); // Instantiating as many ProMPs as hidden states. vector<FullProMP> promps; for(int i = 0; i < nstates; i++) { vec mu_w(n_basis_functions * njoints); mu_w.randn(); mat Sigma_w = eye<mat>(n_basis_functions * njoints, n_basis_functions * njoints); mat Sigma_y = 0.01*eye<mat>(njoints, njoints); ProMP promp(mu_w, Sigma_w, Sigma_y); FullProMP poly(comb, promp, njoints); promps.push_back(poly); } // Creating the ProMP emission and parsing the model parameters as json. shared_ptr<AbstractEmission> ptr_emission(new ProMPsEmission(promps)); HSMM promp_hsmm(ptr_emission, transition, pi, durations, min_duration); promp_hsmm.from_stream(input_params); ViterbiAlgorithm(promp_hsmm, seq_obs, output_filename); return 0; }
38.974359
82
0.611678
DiegoAE
1f6454f565597e0119c7cd9f0cf864933bb9bc52
833
cpp
C++
215-Kth-Largest-Element-in-an-Array/solution_test.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
3
2019-05-27T06:47:32.000Z
2020-12-22T05:57:10.000Z
215-Kth-Largest-Element-in-an-Array/solution_test.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
null
null
null
215-Kth-Largest-Element-in-an-Array/solution_test.cpp
johnhany/leetcode
453a86ac16360e44893262e04f77fd350d1e80f2
[ "Apache-2.0" ]
5
2020-04-01T10:26:04.000Z
2022-02-05T18:21:01.000Z
#define BOOST_TEST_MODULE SolutionTest #include "solution.hpp" //#define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE(SolutionSuite) BOOST_AUTO_TEST_CASE(PlainTest1) { vector<int> nums{3,2,1,5,6,4}; int k = 2; int results = Solution().findKthLargest(nums, k); int expected = 5; BOOST_CHECK_EQUAL(results, expected); } BOOST_AUTO_TEST_CASE(PlainTest2) { vector<int> nums{3,2,3,1,2,4,5,5,6}; int k = 4; int results = Solution().findKthLargest(nums, k); int expected = 4; BOOST_CHECK_EQUAL(results, expected); } BOOST_AUTO_TEST_CASE(PlainTest3) { vector<int> nums{3,2,3,1,2,4,5,5,6}; int k = 7; int results = Solution().findKthLargest(nums, k); int expected = 2; BOOST_CHECK_EQUAL(results, expected); } BOOST_AUTO_TEST_SUITE_END()
19.372093
53
0.691477
johnhany
1f6509939218c9fbbc869ee57a6dfa41d37e8fd9
2,797
cpp
C++
10-graphs-dfs/D-condensation.cpp
GimmeDanger/made-algo-2020-hw
701db679a927f70ee5265ef35038e4a47daf52df
[ "MIT" ]
null
null
null
10-graphs-dfs/D-condensation.cpp
GimmeDanger/made-algo-2020-hw
701db679a927f70ee5265ef35038e4a47daf52df
[ "MIT" ]
null
null
null
10-graphs-dfs/D-condensation.cpp
GimmeDanger/made-algo-2020-hw
701db679a927f70ee5265ef35038e4a47daf52df
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define dbg 0 #if dbg #define INPUT_SOURCE() ifstream cin("input.txt") #else #define INPUT_SOURCE() #endif #define FAST_IO() \ ios::sync_with_stdio(false); \ cout.tie(nullptr); \ cin.tie(nullptr) using graph = vector<unordered_set<int>>; ////////////////////// Toposort implementation ////////////////////// void dfs_topo(const graph &adj, vector<bool> &visited, vector<int> &postorder, int v) { visited[v] = true; for (int u : adj[v]) { if (!visited[u]) { dfs_topo(adj, visited, postorder, u); } } postorder.push_back(v); } vector<int> toposort(const graph &adj) { vector<int> postorder; postorder.reserve(adj.size()); vector<bool> visited(adj.size(), false); for (int v = 0; v < adj.size(); v++) { if (!visited[v]) { dfs_topo(adj, visited, postorder, v); } } reverse(begin(postorder), end(postorder)); return postorder; } ////////////////////// Kosaraju–Sharir algorithm implementation ////////////////////// graph reverse(const graph &adj) { graph r_adj(adj.size()); for (int v = 0; v < adj.size(); v++) { for (int u : adj[v]) { r_adj[u].insert(v); } } return r_adj; } static constexpr int INVALID_COMPONENT = -1; bool not_visited(int c) { return c == INVALID_COMPONENT; } void dfs_cc(const graph &adj, vector<int> &cc, int cc_curr, int v) { cc[v] = cc_curr; for (int u : adj[v]) { if (not_visited(cc[u])) { dfs_cc(adj, cc, cc_curr, u); } } } pair<int, vector<int>> get_strong_components(const graph &adj) { int cc_num = 0; vector<int> cc(adj.size(), INVALID_COMPONENT); for (int v : toposort(reverse(adj))) { if (not_visited(cc[v])) { dfs_cc(adj, cc, cc_num++, v); } } return {cc_num, cc}; } ////////////////////// Solver ////////////////////// void solve(istream &is, ostream &os) { int n, m, u, v; is >> n >> m; graph adj(n); for (int i = 0; i < m; i++) { is >> u >> v; if (u == v) { continue; } u--; v--; adj[u].insert(v); } auto res = get_strong_components(adj); graph cond_adj(res.first); auto &cc = res.second; size_t edges_in_condensation = 0; for (int v = 0; v < n; v++) { for (int u : adj[v]) { if (cc[v] != cc[u]) { auto [it, success] = cond_adj[cc[v]].insert(cc[u]); if (success) { edges_in_condensation++; } } } } os << edges_in_condensation << endl; } int main() { FAST_IO(); INPUT_SOURCE(); solve(cin, cout); return 0; }
22.198413
87
0.504469
GimmeDanger
1f6b282c287f4b512b2321af5a36faa2bb891294
9,097
cpp
C++
DrunkEngine/GameObject.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
null
null
null
DrunkEngine/GameObject.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
3
2018-09-27T17:00:14.000Z
2018-12-19T13:30:25.000Z
DrunkEngine/GameObject.cpp
MarcFly/Fly3D-Engine
e8da09a63c7c3d991b8f25c346798ee230593e78
[ "Unlicense" ]
null
null
null
#include "GameObject.h" #include "Application.h" #include "ComponentMaterial.h" #include "ComponentMesh.h" #include "ComponentCamera.h" #include "ResourceMesh.h" #include "ComponentBillboard.h" #include "ComponentSkeleton.h" #include "ComponentAnimation.h" // Creation of Root Node from a file GameObject::GameObject() { GetTransform(); App->gameObj->objects_in_scene.push_back(this); App->gameObj->non_static_objects_in_scene.push_back(this); Start(); UUID = GetUUID(); } GameObject::GameObject(const char* name, GameObject * par) { this->name = name; this->root = this; if (par != nullptr) { this->parent = par; root = par->root; } GetTransform(); App->gameObj->objects_in_scene.push_back(this); App->gameObj->non_static_objects_in_scene.push_back(this); UUID = GetUUID(); Start(); } void GameObject::Start() { for (int i = 0; i < this->components.size(); i++) this->components[i]->Start(); for (int i = 0; i < this->children.size(); i++) this->children[i]->Start(); } void GameObject::Update(float dt) { for (int i = 0; i < this->components.size(); i++) { if (this->components[i]->active) { this->components[i]->Update(dt); } } for (int i = 0; i < this->children.size(); i++) { if(this->children[i]->active) { this->children[i]->Update(dt); } } Draw(); } void GameObject::Draw() { for (int i = 0; i < this->components.size(); i++) { if (this->components[i]->active) { this->components[i]->Draw(); } } if (this->BoundingBox != nullptr && (App->renderer3D->bounding_box || this->sv_active)) this->DrawBB(); } void GameObject::DrawBB() const { glDisable(GL_LIGHTING); glBegin(GL_LINES); glColor3f(0.f, 1.f, 0.f); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->minPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->maxPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->maxPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->maxPoint.z); glVertex3f(this->BoundingBox->minPoint.x, this->BoundingBox->minPoint.y, this->BoundingBox->minPoint.z); glColor3f(0, 1, 0); glEnd(); if (App->renderer3D->lighting) glEnable(GL_LIGHTING); } vec GameObject::getObjectCenter() { if (BoundingBox != nullptr) { float aux_x = (BoundingBox->maxPoint.x + BoundingBox->minPoint.x) / 2; float aux_y = (BoundingBox->maxPoint.y + BoundingBox->minPoint.y) / 2; float aux_z = (BoundingBox->maxPoint.z + BoundingBox->minPoint.z) / 2; return vec(aux_x, aux_y, aux_z); } return vec(0, 0, 0); } void GameObject::OrderChildren() { for (int i = 0; i < this->children.size(); i++) { if (this->children[i]->par_UUID != UINT_FAST32_MAX && this->children[i]->par_UUID != this->children[i]->parent->UUID) { GameObject* obj = this->children[i]; this->children[i]->to_pop = true; this->AdjustObjects(); obj->to_pop = false; GameObject* get = this->GetChild(obj->par_UUID); obj->parent = get; if (get != nullptr) get->children.push_back(obj); i--; } } } void GameObject::AdjustObjects() { int i = 0; for (; i < this->children.size(); i++) { if (this->children[i]->to_pop == true) { //delete this->children[i]; //this->children[i] = nullptr; break; } } for (int j = i; j < this->children.size() - 1; j++) { this->children[j] = this->children[j + 1]; } this->children.pop_back(); } void GameObject::AdjustComponents() { int i = 0; for (; i < this->components.size(); i++) { if (this->components[i]->to_pop == true) { delete this->components[i]; this->components[i] = nullptr; break; } } for (int j = i; j < this->components.size() - 1; j++) { this->components[j] = this->components[j + 1]; } this->components.pop_back(); } void GameObject::RecursiveSetStatic(GameObject * obj, const bool bool_static) { obj->is_static = bool_static; for (int i = 0; i < obj->children.size(); i++) RecursiveSetStatic(obj->children[i], bool_static); } void GameObject::CleanUp() { for (int i = 0; i < this->components.size(); i++) { this->components[i]->CleanUp(); delete this->components[i]; this->components[i] = nullptr; } this->components.clear(); if (this->BoundingBox != nullptr) { delete this->BoundingBox; this->BoundingBox = nullptr; } for (int i = 0; i < this->children.size(); i++) this->children[i]->CleanUp(); this->children.clear(); this->parent = nullptr; this->root = nullptr; this->name.clear(); } void GameObject::DestroyThisObject() { this->CleanUp(); this->to_pop = true; if (parent != nullptr) parent->AdjustObjects(); } void GameObject::DestroyComponent() { } void GameObject::RecursiveSetNewUUID() { if (this->parent == nullptr) par_UUID = UINT_FAST32_MAX; else par_UUID = parent->UUID; UUID = GetUUID(); for (int i = 0; i < children.size(); i++) children[i]->RecursiveSetNewUUID(); } void GameObject::Load(const JSON_Value* go, const char* file) { bool ret = true; } void GameObject::Save(JSON_Array* go) { JSON_Value* append = json_value_init_object(); JSON_Object* curr = json_value_get_object(append); std::string obj = "gameobject."; std::string set_val; set_val = obj + "UUID"; json_object_dotset_number(curr, set_val.c_str(), UUID); set_val = obj + "par_UUID"; json_object_dotset_number(curr, set_val.c_str(), par_UUID); set_val = obj + "name"; json_object_dotset_string(curr, set_val.c_str(), name.c_str()); JSON_Value* set_array = json_value_init_array(); JSON_Array* comps = json_value_get_array(set_array); for (int i = 0; i < this->components.size(); i++) this->components[i]->Save(comps); set_val = obj + "components"; json_object_dotset_value(curr,set_val.c_str(), set_array); json_array_append_value(go, append); for(int i = 0; i < this->children.size(); i++) this->children[i]->Save(go); } std::vector<uint> GameObject::GetMeshProps() { uint ret[2] = { 0,0 }; std::vector<Component*> meshes; meshes = GetComponents(CT_Mesh); for (int i = 0; i < meshes.size(); i++) { ComponentMesh* aux = meshes[i]->AsMesh(); ret[0] += aux->r_mesh->num_vertex; ret[1] += aux->r_mesh->num_faces; } for (int i = 0; i < children.size(); i++) { std::vector<uint> child = children[i]->GetMeshProps(); ret[0] += child[0]; ret[1] += child[1]; } std::vector<uint> ret_v; ret_v.push_back(ret[0]); ret_v.push_back(ret[1]); return ret_v; } Component* GameObject::NewComponent(const CTypes type) { if (type == CT_Mesh) return new ComponentMesh(this); else if (type == CT_Material) return new ComponentMaterial(this); else if (type == CT_Camera) return new ComponentCamera(this); else if (type == CT_Transform) return new ComponentTransform(this); /*else if (type == CT_Billboard) return new ComponentBillboard(this);*/ else if (type == CT_Skeleton) return new ComponentSkeleton(this); else if (type == CT_Animation) return new ComponentAnimation(this); return nullptr; }
25.410615
119
0.68616
MarcFly
1f6d36c2e537f1d9ec41d98de0578c5e6520cc65
321
cpp
C++
src/ResLoader/data_mgr.cpp
wu1274704958/vulkan_demo
545e00a1fae98e0ff179115887dfa7669b56ccde
[ "MIT" ]
null
null
null
src/ResLoader/data_mgr.cpp
wu1274704958/vulkan_demo
545e00a1fae98e0ff179115887dfa7669b56ccde
[ "MIT" ]
null
null
null
src/ResLoader/data_mgr.cpp
wu1274704958/vulkan_demo
545e00a1fae98e0ff179115887dfa7669b56ccde
[ "MIT" ]
1
2021-12-27T08:40:07.000Z
2021-12-27T08:40:07.000Z
#include <data_mgr.hpp> #include <resource_mgr.hpp> #include <log.hpp> #include <sundry.hpp> #include <serialization.hpp> #include <assimp/scene.h> #include <fileop.hpp> using namespace dbg::literal; //---------------------------------------------------------------------------------------------------------------------
29.181818
119
0.470405
wu1274704958
1f7a927960bc887ab2d4ce231969c4fced9ede59
7,672
cxx
C++
main/dbaccess/source/ui/control/marktree.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/dbaccess/source/ui/control/marktree.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/dbaccess/source/ui/control/marktree.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_dbui.hxx" #ifndef _DBAUI_MARKTREE_HXX_ #include "marktree.hxx" #endif #ifndef _DBU_CONTROL_HRC_ #include "dbu_control.hrc" #endif #ifndef _SV_SVAPP_HXX #include <vcl/svapp.hxx> #endif //......................................................................... namespace dbaui { using namespace ::com::sun::star::uno; using namespace ::com::sun::star::lang; //......................................................................... #define SPACEBETWEENENTRIES 4 //======================================================================== //= OMarkableTreeListBox //======================================================================== DBG_NAME(OMarkableTreeListBox) //------------------------------------------------------------------------ OMarkableTreeListBox::OMarkableTreeListBox( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, WinBits nWinStyle ) : DBTreeListBox(pParent,_rxORB,nWinStyle) { DBG_CTOR(OMarkableTreeListBox,NULL); InitButtonData(); } //------------------------------------------------------------------------ OMarkableTreeListBox::OMarkableTreeListBox( Window* pParent, const Reference< XMultiServiceFactory >& _rxORB, const ResId& rResId) : DBTreeListBox(pParent,_rxORB,rResId) { DBG_CTOR(OMarkableTreeListBox,NULL); InitButtonData(); } //------------------------------------------------------------------------ OMarkableTreeListBox::~OMarkableTreeListBox() { delete m_pCheckButton; DBG_DTOR(OMarkableTreeListBox,NULL); } //------------------------------------------------------------------------ void OMarkableTreeListBox::Paint(const Rectangle& _rRect) { if (!IsEnabled()) { Font aOldFont = GetFont(); Font aNewFont(aOldFont); StyleSettings aSystemStyle = Application::GetSettings().GetStyleSettings(); aNewFont.SetColor(aSystemStyle.GetDisableColor()); SetFont(aNewFont); DBTreeListBox::Paint(_rRect); SetFont(aOldFont); } else DBTreeListBox::Paint(_rRect); } //------------------------------------------------------------------------ void OMarkableTreeListBox::InitButtonData() { m_pCheckButton = new SvLBoxButtonData( this ); EnableCheckButton( m_pCheckButton ); } //------------------------------------------------------------------------ void OMarkableTreeListBox::KeyInput( const KeyEvent& rKEvt ) { // nur wenn space if (rKEvt.GetKeyCode().GetCode() == KEY_SPACE && !rKEvt.GetKeyCode().IsShift() && !rKEvt.GetKeyCode().IsMod1()) { SvLBoxEntry* pCurrentHandlerEntry = GetHdlEntry(); if(pCurrentHandlerEntry) { SvButtonState eState = GetCheckButtonState( pCurrentHandlerEntry); if(eState == SV_BUTTON_CHECKED) SetCheckButtonState( pCurrentHandlerEntry, SV_BUTTON_UNCHECKED); else SetCheckButtonState( pCurrentHandlerEntry, SV_BUTTON_CHECKED); CheckButtonHdl(); } else DBTreeListBox::KeyInput(rKEvt); } else DBTreeListBox::KeyInput(rKEvt); } //------------------------------------------------------------------------ SvButtonState OMarkableTreeListBox::implDetermineState(SvLBoxEntry* _pEntry) { SvButtonState eState = GetCheckButtonState(_pEntry); if (!GetModel()->HasChilds(_pEntry)) // nothing to do in this bottom-up routine if there are no children ... return eState; #ifdef DBG_UTIL String sEntryText =GetEntryText(_pEntry); #endif // loop through the children and check their states sal_uInt16 nCheckedChildren = 0; sal_uInt16 nChildrenOverall = 0; SvLBoxEntry* pChildLoop = GetModel()->FirstChild(_pEntry); while (pChildLoop) { #ifdef DBG_UTIL String sChildText =GetEntryText(pChildLoop); #endif SvButtonState eChildState = implDetermineState(pChildLoop); if (SV_BUTTON_TRISTATE == eChildState) break; if (SV_BUTTON_CHECKED == eChildState) ++nCheckedChildren; ++nChildrenOverall; pChildLoop = GetModel()->NextSibling(pChildLoop); } if (pChildLoop) { // we did not finish the loop because at least one of the children is in tristate eState = SV_BUTTON_TRISTATE; // but this means that we did not finish all the siblings of pChildLoop, so their checking may be // incorrect at the moment // -> correct this // 88485 - 20.06.2001 - frank.schoenheit@sun.com while (pChildLoop) { implDetermineState(pChildLoop); pChildLoop = GetModel()->NextSibling(pChildLoop); } } else // none if the children is in tristate if (nCheckedChildren) // we have at least one chil checked if (nCheckedChildren != nChildrenOverall) // not all children are checked eState = SV_BUTTON_TRISTATE; else // all children are checked eState = SV_BUTTON_CHECKED; else // no children are checked eState = SV_BUTTON_UNCHECKED; // finally set the entry to the state we just determined SetCheckButtonState(_pEntry, eState); // outta here return eState; } //------------------------------------------------------------------------ void OMarkableTreeListBox::CheckButtons() { SvLBoxEntry* pEntry = GetModel()->First(); while (pEntry) { implDetermineState(pEntry); pEntry = GetModel()->NextSibling(pEntry); } } //------------------------------------------------------------------------ void OMarkableTreeListBox::CheckButtonHdl() { checkedButton_noBroadcast(GetHdlEntry()); if (m_aCheckButtonHandler.IsSet()) m_aCheckButtonHandler.Call(this); } //------------------------------------------------------------------------ void OMarkableTreeListBox::checkedButton_noBroadcast(SvLBoxEntry* _pEntry) { SvButtonState eState = GetCheckButtonState( _pEntry); if (GetModel()->HasChilds(_pEntry)) // Falls Kinder, dann diese auch checken { SvLBoxEntry* pChildEntry = GetModel()->Next(_pEntry); SvLBoxEntry* pSiblingEntry = GetModel()->NextSibling(_pEntry); while(pChildEntry && pChildEntry != pSiblingEntry) { SetCheckButtonState(pChildEntry, eState); pChildEntry = GetModel()->Next(pChildEntry); } } SvLBoxEntry* pEntry = IsSelected(_pEntry) ? FirstSelected() : NULL; while(pEntry) { SetCheckButtonState(pEntry,eState); if(GetModel()->HasChilds(pEntry)) // Falls Kinder, dann diese auch checken { SvLBoxEntry* pChildEntry = GetModel()->Next(pEntry); SvLBoxEntry* pSiblingEntry = GetModel()->NextSibling(pEntry); while(pChildEntry && pChildEntry != pSiblingEntry) { SetCheckButtonState(pChildEntry,eState); pChildEntry = GetModel()->Next(pChildEntry); } } pEntry = NextSelected(pEntry); } CheckButtons(); } //------------------------------------------------------------------------ //......................................................................... } // namespace dbaui //.........................................................................
31.442623
131
0.609489
Grosskopf
1f7b0bfdd5712791868cee25dc91ae687f6177ed
5,023
cpp
C++
testing_environmen/testing_environmen/src/shadows/shadow.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
testing_environmen/testing_environmen/src/shadows/shadow.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
4
2018-12-24T11:16:53.000Z
2018-12-24T11:20:29.000Z
testing_environmen/testing_environmen/src/shadows/shadow.cpp
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
/*#include "shadow.h" auto shadow_handler::get_projection(void) -> glm::mat4 & { return projection_matrix; } auto shadow_handler::get_depth_map(void) -> texture & { return depth_map; } auto shadow_handler::get_fbo(void) -> framebuffer & { return depth_fbo; } auto shadow_handler::get_shaders(void) -> program & { return shaders; } auto shadow_handler::get_light_view(void) -> glm::mat4 & { return light_view_matrix; } auto shadow_handler::get_shadow_bias(void) -> glm::mat4 & { return shadow_bias; } auto shadow_handler::create(glm::vec3 const & light_pos) -> void { create_fbo(); create_shaders(); create_shadow_bias_matrix(); create_light_view_matrix(glm::normalize(glm::vec3(light_pos.x, -light_pos.y, light_pos.z))); } auto shadow_handler::update(f32 far, f32 near, f32 aspect, f32 fov, glm::vec3 const & pos, glm::vec3 const & dir) -> void { std::array<glm::vec4, 8> corners; calculate_frustum_dimensions(far, near, aspect, fov); calculate_ortho_corners(pos, dir, far, near, corners); find_min_max_values(corners); projection_matrix = glm::ortho<f32>(x_min, x_max, y_min, y_max, z_min, z_max); } auto shadow_handler::update_light_view(glm::vec3 const & light_pos) -> void { create_light_view_matrix(glm::normalize(glm::vec3(light_pos.x, -light_pos.y, light_pos.z))); } auto shadow_handler::calculate_frustum_dimensions(f32 far, f32 near, f32 aspect, f32 fov) -> void { far_width = 2.0f * far * tan(glm::radians(fov)); near_width = 2.0f * near * tan(glm::radians(fov)); far_height = far_width / aspect; near_height = near_width / aspect; } auto shadow_handler::calculate_ortho_corners(glm::vec3 const & pos, glm::vec3 const & dir, f32 far, f32 near, std::array<glm::vec4, 8> & corners) -> void { glm::vec3 right_view = glm::normalize(glm::cross(dir, detail::up)); glm::vec3 up_view = glm::normalize(glm::cross(dir, right_view)); f32 far_width_half = far_width / 2.0f; f32 near_width_half = near_width / 2.0f; f32 far_height_half = far_height / 2.0f; f32 near_height_half = near_height / 2.0f; corners[flt] = light_view_matrix * glm::vec4(pos + dir * far - right_view * far_width_half + up_view * far_height_half, 1.0f); corners[flb] = light_view_matrix * glm::vec4(pos + dir * far - right_view * far_width_half - up_view * far_height_half, 1.0f); corners[frt] = light_view_matrix * glm::vec4(pos + dir * far + right_view * far_width_half + up_view * far_height_half, 1.0f); corners[frb] = light_view_matrix * glm::vec4(pos + dir * far + right_view * far_width_half - up_view * far_height_half, 1.0f); corners[nlt] = light_view_matrix * glm::vec4(pos + dir * near - right_view * near_width_half + up_view * near_height_half, 1.0f); corners[nlb] = light_view_matrix * glm::vec4(pos + dir * near - right_view * near_width_half - up_view * near_height_half, 1.0f); corners[nrt] = light_view_matrix * glm::vec4(pos + dir * near + right_view * near_width_half + up_view * near_height_half, 1.0f); corners[nrb] = light_view_matrix * glm::vec4(pos + dir * near + right_view * near_width_half - up_view * near_height_half, 1.0f); } auto shadow_handler::find_min_max_values(std::array<glm::vec4, 8> & corners) -> void { x_min = x_max = corners[0].x; y_min = y_max = corners[0].y; z_min = z_max = corners[0].z; for (u32 i = 1; i < 8; ++i) { if (x_min > corners[i].x) x_min = corners[i].x; if (x_max < corners[i].x) x_max = corners[i].x; if (y_min > corners[i].y) y_min = corners[i].y; if (y_max < corners[i].y) y_max = corners[i].y; if (z_min > corners[i].z) z_min = corners[i].z; if (z_max < corners[i].z) z_max = corners[i].z; } } auto shadow_handler::create_fbo(void) -> void { depth_fbo.create(shadow_map_size, shadow_map_size); depth_fbo.bind(); create_depth_texture(); depth_fbo.attach(depth_map, GL_DEPTH_ATTACHMENT, 0); depth_fbo.select_color_buffer(GL_NONE); } auto shadow_handler::create_depth_texture(void) -> void { depth_map.create(); depth_map.bind(GL_TEXTURE_2D); depth_map.fill(GL_TEXTURE_2D, GL_DEPTH_COMPONENT, GL_DEPTH_COMPONENT, GL_FLOAT, nullptr, shadow_map_size, shadow_map_size); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); depth_map.int_param(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } auto shadow_handler::create_shaders(void) -> void { shaders.create_shader(GL_VERTEX_SHADER, "shadow/shadow_vsh.shader"); shaders.create_shader(GL_FRAGMENT_SHADER, "shadow/shadow_fsh.shader"); shaders.link_shaders("vertex_position"); shaders.get_uniform_locations("vp", "model"); } auto shadow_handler::create_light_view_matrix(glm::vec3 const & light_dir) -> void { light_view_matrix = glm::lookAt(glm::normalize(-light_dir), glm::vec3(0), detail::up); } auto shadow_handler::create_shadow_bias_matrix(void) -> void { shadow_bias = glm::mat4 ( 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0, 0.0, 0.5, 0.0, 0.5, 0.5, 0.5, 1.0 ); }*/
39.865079
153
0.724069
llGuy
1f7d8456c5838e79e62387209e49b4c930680972
8,434
cpp
C++
examples/ex30p.cpp
ajithvallabai/mfem
5920fbf645f328c29a9d6489f2474d989f808451
[ "BSD-3-Clause" ]
null
null
null
examples/ex30p.cpp
ajithvallabai/mfem
5920fbf645f328c29a9d6489f2474d989f808451
[ "BSD-3-Clause" ]
null
null
null
examples/ex30p.cpp
ajithvallabai/mfem
5920fbf645f328c29a9d6489f2474d989f808451
[ "BSD-3-Clause" ]
1
2019-07-09T20:41:56.000Z
2019-07-09T20:41:56.000Z
// MFEM Example 30 - Parallel Version // // Compile with: make ex30p // // Sample runs: mpirun -np 4 ex30p -m ../data/square-disc.mesh -o 1 // mpirun -np 4 ex30p -m ../data/square-disc.mesh -o 2 // mpirun -np 4 ex30p -m ../data/square-disc.mesh -o 2 -me 1e3 // mpirun -np 4 ex30p -m ../data/square-disc-nurbs.mesh -o 2 // mpirun -np 4 ex30p -m ../data/star.mesh -o 2 -eo 4 // mpirun -np 4 oscp -m ../data/fichera.mesh -o 2 -me 1e4 // mpirun -np 4 ex30p -m ../data/disc-nurbs.mesh -o 2 // mpirun -np 4 ex30p -m ../data/ball-nurbs.mesh -o 2 -eo 3 -e 1e-2 // mpirun -np 4 ex30p -m ../data/star-surf.mesh -o 2 // mpirun -np 4 ex30p -m ../data/square-disc-surf.mesh -o 2 // mpirun -np 4 ex30p -m ../data/amr-quad.mesh -l 2 // // Description: This is an example of adaptive mesh refinement preprocessing // which lowers the data oscillation [1] to a user-defined // relative threshold. There is no PDE being solved. // // MFEM's capability to work with both conforming and // nonconforming meshes is demonstrated in example 6. In some // problems, the material data or loading data is not sufficiently // resolved on the initial mesh. This missing fine scale data // reduces the accuracy of the solution as well as the accuracy // of some local error estimators. By preprocessing the mesh // before solving the PDE, many issues can be avoided. // // [1] Morin, P., Nochetto, R. H., & Siebert, K. G. (2000). // Data oscillation and convergence of adaptive FEM. SIAM // Journal on Numerical Analysis, 38(2), 466-488. // // [2] Mitchell, W. F. (2013). A collection of 2D elliptic // problems for testing adaptive grid refinement algorithms. // Applied mathematics and computation, 220, 350-364. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; // Piecewise-affine function which is sometimes mesh-conforming double affine_function(const Vector &p) { double x = p(0), y = p(1); if (x < 0.0) { return 1.0 + x + y; } else { return 1.0; } } // Piecewise-constant function which is never mesh-conforming double jump_function(const Vector &p) { if (p.Normlp(2.0) > 0.4 && p.Normlp(2.0) < 0.6) { return 1.0; } return 5.0; } // Singular function derived from the Laplacian of the "steep wavefront" // problem in [2]. double singular_function(const Vector &p) { double x = p(0), y = p(1); double alpha = 1000.0; double xc = 0.75, yc = 0.5; double r0 = 0.7; double r = sqrt(pow(x - xc,2.0) + pow(y - yc,2.0)); double num = - ( alpha - pow(alpha,3) * (pow(r,2) - pow(r0,2)) ); double denom = pow(r * ( pow(alpha,2) * pow(r0,2) + pow(alpha,2) * pow(r,2) \ - 2 * pow(alpha,2) * r0 * r + 1.0 ),2); denom = max(denom,1e-8); return num / denom; } int main(int argc, char *argv[]) { // 0. Initialize MPI. int num_procs, myid; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); // 1. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; int nc_limit = 1; int max_elems = 1e5; double double_max_elems = double(max_elems); bool visualization = true; bool nc_simplices = true; double osc_threshold = 1e-3; int enriched_order = 5; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree)."); args.AddOption(&nc_limit, "-l", "--nc-limit", "Maximum level of hanging nodes."); args.AddOption(&double_max_elems, "-me", "--max-elems", "Stop after reaching this many elements."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.AddOption(&osc_threshold, "-e", "--error", "relative data oscillation threshold."); args.AddOption(&enriched_order, "-eo", "--enriched_order", "Enriched quadrature order."); args.AddOption(&nc_simplices, "-ns", "--nonconforming-simplices", "-cs", "--conforming-simplices", "For simplicial meshes, enable/disable nonconforming" " refinement"); args.Parse(); if (!args.Good()) { if (myid == 0) { args.PrintUsage(cout); } MPI_Finalize(); return 1; } if (myid == 0) { args.PrintOptions(cout); } max_elems = int(double_max_elems); Mesh mesh(mesh_file, 1, 1); // 2. Since a NURBS mesh can currently only be refined uniformly, we need to // convert it to a piecewise-polynomial curved mesh. First we refine the // NURBS mesh a bit more and then project the curvature to quadratic Nodes. if (mesh.NURBSext) { for (int i = 0; i < 2; i++) { mesh.UniformRefinement(); } mesh.SetCurvature(2); } // 3. Make sure the mesh is in the non-conforming mode to enable local // refinement of quadrilaterals/hexahedra. Simplices can be refined // either in conforming or in non-conforming mode. The conforming // mode however does not support dynamic partitioning. mesh.EnsureNCMesh(nc_simplices); // 4. Define a parallel mesh by partitioning the serial mesh. // Once the parallel mesh is defined, the serial mesh can be deleted. ParMesh pmesh(MPI_COMM_WORLD, mesh); mesh.Clear(); // 5. Define functions and refiner. FunctionCoefficient affine_coeff(affine_function); FunctionCoefficient jump_coeff(jump_function); FunctionCoefficient singular_coeff(singular_function); CoefficientRefiner coeffrefiner(affine_coeff,order); // 6. Connect to GLVis. char vishost[] = "localhost"; int visport = 19916; socketstream sol_sock; if (visualization) { sol_sock.open(vishost, visport); } // 7. Define custom integration rule (optional). const IntegrationRule *irs[Geometry::NumGeom]; int order_quad = 2*order + enriched_order; for (int i=0; i < Geometry::NumGeom; ++i) { irs[i] = &(IntRules.Get(i, order_quad)); } // 8. Apply custom refiner settings. coeffrefiner.SetIntRule(irs); coeffrefiner.SetMaxElements(max_elems); coeffrefiner.SetThreshold(osc_threshold); coeffrefiner.SetNCLimit(nc_limit); coeffrefiner.PrintWarnings(); // 9. Preprocess mesh to control osc (piecewise-affine function). // This is mostly just a verification check. The oscillation should // be zero if the function is mesh-conforming and order > 0. coeffrefiner.PreprocessMesh(pmesh); int globalNE = pmesh.GetGlobalNE(); double osc = coeffrefiner.GetOsc(); if (myid == 0) { mfem::out << "\n"; mfem::out << "Function 0 (affine) \n"; mfem::out << "Number of Elements " << globalNE << "\n"; mfem::out << "Osc error " << osc << "\n"; } // 10. Preprocess mesh to control osc (jump function). coeffrefiner.ResetCoefficient(jump_coeff); coeffrefiner.PreprocessMesh(pmesh); globalNE = pmesh.GetGlobalNE(); osc = coeffrefiner.GetOsc(); if (myid == 0) { mfem::out << "\n"; mfem::out << "Function 1 (discontinuous) \n"; mfem::out << "Number of Elements " << globalNE << "\n"; mfem::out << "Osc error " << osc << "\n"; } // 11. Preprocess mesh to control osc (singular function). coeffrefiner.ResetCoefficient(singular_coeff); coeffrefiner.PreprocessMesh(pmesh); globalNE = pmesh.GetGlobalNE(); osc = coeffrefiner.GetOsc(); if (myid == 0) { mfem::out << "\n"; mfem::out << "Function 2 (singular) \n"; mfem::out << "Number of Elements " << globalNE << "\n"; mfem::out << "Osc error " << osc << "\n"; } sol_sock.precision(8); sol_sock << "parallel " << num_procs << " " << myid << "\n"; sol_sock << "mesh\n" << pmesh << flush; MPI_Finalize(); return 0; }
34.85124
81
0.600901
ajithvallabai
1f84165a95592b9dcb4054bcf07a11a16389cc2b
3,590
cpp
C++
src/scenes/SFPC/yosukeJohnWhitneyMatrix/yosukeJohnWhitneyMatrix.cpp
roymacdonald/ReCoded
3bcb3d579cdd17381e54a508a1e4ef9e3d5bc4f1
[ "MIT" ]
64
2017-06-12T19:24:08.000Z
2022-01-27T19:14:48.000Z
src/scenes/yosukeJohnWhitneyMatrix/yosukeJohnWhitneyMatrix.cpp
colaplate/recoded
934e1184c7502d192435c406e56b8a2106e9b6b4
[ "MIT" ]
10
2017-06-13T10:38:39.000Z
2017-11-15T11:21:05.000Z
src/scenes/yosukeJohnWhitneyMatrix/yosukeJohnWhitneyMatrix.cpp
colaplate/recoded
934e1184c7502d192435c406e56b8a2106e9b6b4
[ "MIT" ]
24
2017-06-11T08:14:46.000Z
2020-04-16T20:28:46.000Z
#include "yosukeJohnWhitneyMatrix.h" void yosukeJohnWhitneyMatrix::setup(){ // setup pramaters numOfGroup.set("number-of-group", 4, 1, MAXNUMOFGROPU); parameters.add(numOfGroup); numOfBall.set("number-of-ball", 6, 1, MAXNUMOFBALL); parameters.add(numOfBall); radius.set("rotation-radius", 150, 1, 1000 ); parameters.add(radius); speed.set("speed", 0.1, 0.0, 1.0 ); parameters.add(speed); ballRadius.set("ball-radius", 4, 0, 10); parameters.add(ballRadius); setAuthor("Yosuke Sakai"); setOriginalArtist("John Whitney"); loadCode("scenes/yosukeJohnWhitneyMatrix/exampleCode.cpp"); //ofSetVerticalSync(true); //ofBackground(0,0,0); ofSetCircleResolution(150); //transform the origin to the center of the screen. xorigin = dimensions.width/2.0; yorigin = dimensions.height/2.0; //the radius of the lissajus //radius = ; //set the initial positon of the ball for (int j=0; j<numOfGroup; j++) { for (int i = 0; i < numOfBall; i++) { t = ofGetElapsedTimef() / 10.0; angleofangle[j][i] = - (i-1)*PI/15; if(j==0 || j==1){ angle[j][i] = 5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i]; } else { angle[j][i] = 5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i]; } x[j][i] = xorigin + radius * sin(angle[j][i] * 1.0); y[j][i] = yorigin + radius * -sin(angle[j][i] * 1.5); } } lastTime = 0; integratedTime = 0; } void yosukeJohnWhitneyMatrix::reset() { lastTime = 0; integratedTime = 0; } void yosukeJohnWhitneyMatrix::update(){ float now = getElapsedTimef(); if (lastTime == 0) { lastTime = now; } float dt = now - lastTime; lastTime = now; integratedTime += dt * speed; t = integratedTime; for (int j=0; j<numOfGroup; j++) { for (int i = 0; i < numOfBall; i++) { angleofangle[j][i] = - (i-1)*PI/20; //the argument of sin if(j==0 || j==1){ angle[j][i] = (5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i]); } else { angle[j][i] = (5.0*sin((t-0.1) * PI/2.0 - PI/2.0) + 3.0*angleofangle[j][i]); } } } } void yosukeJohnWhitneyMatrix::draw(){ for (int j=0; j<numOfGroup; j++) { for (int i = 0; i < numOfBall; i++) { if(j==0){ x[j][i] = xorigin + radius * -sin(1.0 * (angle[j][i] - PI/2.0)); y[j][i] = yorigin + radius * sin(1.5 * (angle[j][i] - PI/2.0)); } else if(j==1){ x[j][i] = xorigin + radius * sin(1.0 * (angle[j][i] - PI/2.0)); y[j][i] = yorigin + radius * sin(1.5 * (angle[j][i] - PI/2.0)); } else if(j==2){ x[j][i] = xorigin + radius * cos(1.0 * (angle[j][i] - PI/4.5)); y[j][i] = yorigin + radius * cos(1.5 * (angle[j][i] - PI/4.5)); } else { x[j][i] = xorigin + radius * -cos(1.0 * (angle[j][i] - PI/4.5)); y[j][i] = yorigin + radius * cos(1.5 * (angle[j][i] - PI/4.5)); } } } ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(255); ofFill(); for (int j=0; j<numOfGroup; j++) { for (int i = 0; i < numOfBall; i++) { ofDrawCircle(x[j][i], y[j][i], ballRadius); } } }
29.916667
92
0.479109
roymacdonald
1f84cb7fd11acc3baba1edb3272eb6c8a9146224
740
hpp
C++
libs/renderer/include/Renderer.hpp
Sharpyfile/WARdrobe
7842d486f65c7a045771f9ef78c0655eda2d346a
[ "DOC" ]
null
null
null
libs/renderer/include/Renderer.hpp
Sharpyfile/WARdrobe
7842d486f65c7a045771f9ef78c0655eda2d346a
[ "DOC" ]
null
null
null
libs/renderer/include/Renderer.hpp
Sharpyfile/WARdrobe
7842d486f65c7a045771f9ef78c0655eda2d346a
[ "DOC" ]
1
2021-03-21T16:52:22.000Z
2021-03-21T16:52:22.000Z
#pragma once #include "Camera.hpp" #include "Model.hpp" #include "Shader.hpp" #include "Skybox.hpp" #include "glm/gtc/type_ptr.hpp" #include "glm/glm.hpp" class Renderer { public: Renderer(); Renderer(unsigned int); Renderer(bool, float[], int, unsigned int[], int, std::string); void Draw(Shader*, Model*, Camera*, glm::vec3, glm::vec3, glm::vec3, int, int); void DrawToShadowMap(Shader*, Model*, glm::vec3, glm::vec3, glm::vec3); void Draw(Shader *); void DrawRefractiveObject(Shader*, Model*, Camera*, Skybox* , glm::vec3, glm::vec3, glm::vec3, int, int); void DrawSkybox(Shader*, Skybox*, Camera*, int, int); void Init(); unsigned int drawingType; glm::vec3 newColor = glm::vec3(1.0f, 1.0f, 1.0f); private: };
25.517241
106
0.674324
Sharpyfile
1f87813d03db483268f6c0b4feff429c8da9dc29
7,651
cpp
C++
glass/src/libnt/native/cpp/NTField2D.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
null
null
null
glass/src/libnt/native/cpp/NTField2D.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
null
null
null
glass/src/libnt/native/cpp/NTField2D.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2020 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "glass/networktables/NTField2D.h" #include <algorithm> #include <ntcore_cpp.h> #include <wpi/SmallVector.h> #include "glass/DataSource.h" using namespace glass; class NTField2DModel::GroupModel : public FieldObjectGroupModel { public: GroupModel(wpi::StringRef name, NT_Entry entry) : m_name{name}, m_entry{entry} {} wpi::StringRef GetName() const { return m_name; } NT_Entry GetEntry() const { return m_entry; } void NTUpdate(const nt::Value& value); void Update() override { if (auto value = nt::GetEntryValue(m_entry)) NTUpdate(*value); } bool Exists() override { return nt::GetEntryType(m_entry) != NT_UNASSIGNED; } bool IsReadOnly() override { return false; } void ForEachFieldObject( wpi::function_ref<void(FieldObjectModel& model)> func) override; private: std::string m_name; NT_Entry m_entry; // keep count of objects rather than resizing vector, as there is a fair // amount of overhead associated with the latter (DataSource record keeping) size_t m_count = 0; class ObjectModel; std::vector<std::unique_ptr<ObjectModel>> m_objects; }; class NTField2DModel::GroupModel::ObjectModel : public FieldObjectModel { public: ObjectModel(wpi::StringRef name, NT_Entry entry, int index) : m_entry{entry}, m_index{index}, m_x{name + "[" + wpi::Twine{index} + "]/x"}, m_y{name + "[" + wpi::Twine{index} + "]/y"}, m_rot{name + "[" + wpi::Twine{index} + "]/rot"} {} void SetExists(bool exists) { m_exists = exists; } void Update() override {} bool Exists() override { return m_exists; } bool IsReadOnly() override { return false; } DataSource* GetXData() override { return &m_x; } DataSource* GetYData() override { return &m_y; } DataSource* GetRotationData() override { return &m_rot; } void SetPose(double x, double y, double rot) override; void SetPosition(double x, double y) override; void SetRotation(double rot) override; private: void SetPoseImpl(double x, double y, double rot, bool setX, bool setY, bool setRot); NT_Entry m_entry; int m_index; bool m_exists = true; public: DataSource m_x; DataSource m_y; DataSource m_rot; }; void NTField2DModel::GroupModel::NTUpdate(const nt::Value& value) { if (!value.IsDoubleArray()) { m_count = 0; return; } auto arr = value.GetDoubleArray(); // must be triples if ((arr.size() % 3) != 0) { m_count = 0; return; } m_count = arr.size() / 3; if (m_count > m_objects.size()) { m_objects.reserve(m_count); for (size_t i = m_objects.size(); i < m_count; ++i) m_objects.emplace_back(std::make_unique<ObjectModel>(m_name, m_entry, i)); } if (m_count < m_objects.size()) { for (size_t i = m_count; i < m_objects.size(); ++i) m_objects[i]->SetExists(false); } for (size_t i = 0; i < m_count; ++i) { auto& obj = m_objects[i]; obj->SetExists(true); obj->m_x.SetValue(arr[i * 3], value.last_change()); obj->m_y.SetValue(arr[i * 3 + 1], value.last_change()); obj->m_rot.SetValue(arr[i * 3 + 2], value.last_change()); } } void NTField2DModel::GroupModel::ForEachFieldObject( wpi::function_ref<void(FieldObjectModel& model)> func) { for (size_t i = 0; i < m_count; ++i) { func(*m_objects[i]); } } void NTField2DModel::GroupModel::ObjectModel::SetPose(double x, double y, double rot) { SetPoseImpl(x, y, rot, true, true, true); } void NTField2DModel::GroupModel::ObjectModel::SetPosition(double x, double y) { SetPoseImpl(x, y, 0, true, true, false); } void NTField2DModel::GroupModel::ObjectModel::SetRotation(double rot) { SetPoseImpl(0, 0, rot, false, false, true); } void NTField2DModel::GroupModel::ObjectModel::SetPoseImpl(double x, double y, double rot, bool setX, bool setY, bool setRot) { // get from NT, validate type and size auto value = nt::GetEntryValue(m_entry); if (!value || !value->IsDoubleArray()) return; auto origArr = value->GetDoubleArray(); if (origArr.size() < static_cast<size_t>((m_index + 1) * 3)) return; // copy existing array wpi::SmallVector<double, 8> arr; arr.reserve(origArr.size()); for (auto&& elem : origArr) arr.emplace_back(elem); // update value if (setX) arr[m_index * 3 + 0] = x; if (setY) arr[m_index * 3 + 1] = y; if (setRot) arr[m_index * 3 + 2] = rot; // set back to NT nt::SetEntryValue(m_entry, nt::Value::MakeDoubleArray(arr)); } NTField2DModel::NTField2DModel(wpi::StringRef path) : NTField2DModel{nt::GetDefaultInstance(), path} {} NTField2DModel::NTField2DModel(NT_Inst inst, wpi::StringRef path) : m_nt{inst}, m_path{(path + "/").str()}, m_name{m_nt.GetEntry(path + "/.name")} { m_nt.AddListener(m_path, NT_NOTIFY_LOCAL | NT_NOTIFY_NEW | NT_NOTIFY_DELETE | NT_NOTIFY_UPDATE | NT_NOTIFY_IMMEDIATE); } NTField2DModel::~NTField2DModel() {} void NTField2DModel::Update() { for (auto&& event : m_nt.PollListener()) { // .name if (event.entry == m_name) { if (event.value && event.value->IsString()) { m_nameValue = event.value->GetString(); } continue; } // common case: update of existing entry; search by entry if (event.flags & NT_NOTIFY_UPDATE) { auto it = std::find_if( m_groups.begin(), m_groups.end(), [&](const auto& e) { return e->GetEntry() == event.entry; }); if (it != m_groups.end()) { (*it)->NTUpdate(*event.value); continue; } } // handle create/delete if (wpi::StringRef{event.name}.startswith(m_path)) { auto name = wpi::StringRef{event.name}.drop_front(m_path.size()); if (name.empty() || name[0] == '.') continue; auto it = std::lower_bound(m_groups.begin(), m_groups.end(), name, [](const auto& e, wpi::StringRef name) { return e->GetName() < name; }); bool match = (it != m_groups.end() && (*it)->GetName() == name); if (event.flags & NT_NOTIFY_DELETE) { if (match) m_groups.erase(it); continue; } else if (event.flags & NT_NOTIFY_NEW) { if (!match) it = m_groups.emplace( it, std::make_unique<GroupModel>(event.name, event.entry)); } else if (!match) { continue; } if (event.flags & (NT_NOTIFY_NEW | NT_NOTIFY_UPDATE)) { (*it)->NTUpdate(*event.value); } } } } bool NTField2DModel::Exists() { return m_nt.IsConnected() && nt::GetEntryType(m_name) != NT_UNASSIGNED; } bool NTField2DModel::IsReadOnly() { return false; } void NTField2DModel::ForEachFieldObjectGroup( wpi::function_ref<void(FieldObjectGroupModel& model, wpi::StringRef name)> func) { for (auto&& group : m_groups) { if (group->Exists()) func(*group, wpi::StringRef{group->GetName()}.drop_front(m_path.size())); } }
32.2827
80
0.597177
bvisness
1f87e3622d8dda2ecceae07634359ee921097ad3
52
cc
C++
bazel/examples/cc__linking_mock_vs_real/a-real.cc
laszlocsomor/projects
fb0f8b62046c0c420dc409d2e44c10728028ea1a
[ "Apache-2.0" ]
2
2018-02-21T13:51:38.000Z
2019-09-10T19:35:15.000Z
bazel/examples/cc__linking_mock_vs_real/a-real.cc
laszlocsomor/projects
fb0f8b62046c0c420dc409d2e44c10728028ea1a
[ "Apache-2.0" ]
null
null
null
bazel/examples/cc__linking_mock_vs_real/a-real.cc
laszlocsomor/projects
fb0f8b62046c0c420dc409d2e44c10728028ea1a
[ "Apache-2.0" ]
2
2018-08-14T11:31:21.000Z
2020-01-10T15:47:49.000Z
#include "a.h" int foo(int x) { return x * 2; }
8.666667
16
0.519231
laszlocsomor
1f8c75b508745d5ae510a58cbd68f0557da2a304
11,506
cpp
C++
source/RenderSystem.cpp
theacodes/PhoenixCore
3953384f9cd84c5775dd23bd60b25ac8d6b6405b
[ "Zlib", "MIT" ]
2
2019-09-09T08:56:18.000Z
2020-12-28T03:52:54.000Z
source/RenderSystem.cpp
theacodes/PhoenixCore
3953384f9cd84c5775dd23bd60b25ac8d6b6405b
[ "Zlib", "MIT" ]
null
null
null
source/RenderSystem.cpp
theacodes/PhoenixCore
3953384f9cd84c5775dd23bd60b25ac8d6b6405b
[ "Zlib", "MIT" ]
1
2022-01-03T23:27:07.000Z
2022-01-03T23:27:07.000Z
/* Copyright (c) 2010, Jonathan Wayne Parrott Please see the license.txt file included with this source distribution for more information. */ #include "config.h" #include "glew/GL/glew.h" #include "RenderSystem.h" #include "DroidSansMono.h" #include "BitmapFont.h" #include "BMFontLoader.h" #include "GLFWWindowManager.h" #include "soil/SOIL.h" using namespace phoenix; //////////////////////////////////////////////////////////////////////////////// //Static Members //////////////////////////////////////////////////////////////////////////////// int RenderSystem::src_blend = GL_SRC_ALPHA; int RenderSystem::dst_blend = GL_ONE_MINUS_SRC_ALPHA; //////////////////////////////////////////////////////////////////////////////// //Construct & Destruct //////////////////////////////////////////////////////////////////////////////// void RenderSystem::initialize( const Vector2d& _sz , bool _fs, bool _resize, bool _reint ) { if( _reint ){ // Re-initialization requires us to dump everything. resources.clear(); if( console ) console = boost::shared_ptr<DebugConsole>(); if( font ) font = FontPtr(); try{ WindowManager::Instance()->close(); // close any open window. }catch( WindowManager::BadInstance ){ } } WindowManagerPtr windowManager; // Does a window manager already exist? if so, use it try { windowManager = WindowManager::Instance(); } // If not, attempt to create one. catch( WindowManager::BadInstance ){ #if PH_USE_GLFW // GLFW Window Manager windowManager = GLFWWindowManager::Instance(); #endif //PH_USE_GLFW } if(!windowManager) { throw std::runtime_error("Phoenix has no Window Manager. This is bad."); } // Create our window if( !windowManager->open( _sz, _fs, _resize ) ) { throw std::runtime_error("Failed to open a window."); } // Initialize GLEW if( glewInit() != GLEW_OK ){ throw std::runtime_error("GLEW Failed to init, what are you trying to run me on?"); } // Listen to events. event_connection = windowManager->listen( boost::bind( &RenderSystem::onWindowEvent, this, _1 ) ); // viewport the same as the window size. renderer.getView().setSize(); // Orthogonal projection. glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, _sz.getX(), _sz.getY(), 0.0f, 1000.0f, -1000.0f); // load up identity for the modelview matrix. glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Set up depth buffer #ifdef DISABLE_DEPTHBUFFER // No need for depth buffer. glDisable(GL_DEPTH_TEST); #else // Enable depth testing and set the function glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LEQUAL); #endif // Smoooth shading, Nicest Hinting. glShadeModel(GL_SMOOTH); glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Enable blending and set our blending mode. glEnable(GL_BLEND); setBlendMode(); // Default is for 2d transluceny with RGBA textures. //! Default material is white. GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 }; GLfloat mat_shininess[] = { 50.0 }; glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular); glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess); // Material mode glColorMaterial( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ); glEnable(GL_COLOR_MATERIAL); //load our default font BitmapFontPtr bmfont = new BitmapFont( *this ); BMFontLoader ldr( *this, bmfont ); ldr.loadFromString( get_droid_sans_mono_fnt_file() ); const unsigned char* data = get_droid_sans_mono_file_data(); bmfont->setPage( 0, loadTexture( get_droid_sans_mono_file_data(), get_droid_sans_mono_file_size(), std::string("Droid Sans Mono") ) ); font = bmfont; //! Make a console console = boost::shared_ptr<DebugConsole>( new DebugConsole( *this ) ); //! Report version information (*console)<<"PhoenixCore initialized.\n"<<"Using GLEW "<<glewGetString(GLEW_VERSION)<<"\n"; if( GLEW_VERSION_2_0 ){ (*console)<<"OpenGL Version 2.0 available\n"; } if( GLEW_VERSION_3_0 ){ (*console)<<"OpenGL Version 3.0 available\n"; } // Clear the screen to black renderer.setClearing(true); renderer.clearScreen( Color(0,0,0) ); //!start the timer fpstimer.start(); } RenderSystem::~RenderSystem() { event_connection.disconnect(); WindowManager::Instance()->close(); } //////////////////////////////////////////////////////////////////////////////// //run function, should be called once every loop, it makes things ready for //a render. //////////////////////////////////////////////////////////////////////////////// bool RenderSystem::run() { //Render the Debug Console. console->draw(); //Call our own draw function renderer.draw(); //flip the screen (this also polls events). WindowManager::Instance()->update(); //Clean resources resources.clean(); //store the new framerate double newframerate = 1.0f / fpstimer.getTime(); framerate = (0.6f * newframerate) + (0.4f * framerate); //Start our fps timer fpstimer.reset(); return !_quit; // Quit is set to true when the window manager has signaled to close. } //////////////////////////////////////////////////////////////////////////////// // Window Events //////////////////////////////////////////////////////////////////////////////// void RenderSystem::onWindowEvent( const WindowEvent& e ) { switch( e.type ) { case WET_CLOSE: _quit = true; break; case WET_KEY: if( e.bool_data == true && e.int_data == PHK_ESC ){ _quit = true; } break; case WET_RESIZE: switch( resize_behavior ) { case RZB_EXPAND: renderer.getView().setSize( e.vector_data ); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0.0f, e.vector_data.getX(), e.vector_data.getY(), 0.0f, 1000.0f, -1000.0f); break; case RZB_SCALE: renderer.getView().setSize( e.vector_data ); break; case RZB_REVERT: WindowManager::Instance()->setWindowSize( renderer.getView().getSize() ); break; case RZB_NOTHING: default: break; } break; default: break; }; } //////////////////////////////////////////////////////////////////////////////// //Load texture function //////////////////////////////////////////////////////////////////////////////// TexturePtr RenderSystem::loadTexture( const std::string& _fn, bool _l ) { //This is the class that will hold our texture TexturePtr ctext = new Texture( resources ); int width=0,height=0; GLuint newtextid = SOIL_load_OGL_texture ( _fn.c_str(), SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, SOIL_FLAG_TEXTURE_REPEATS, &width, &height ); if( newtextid != 0 ) { //Load the texture glBindTexture(GL_TEXTURE_2D, newtextid); //use linear filtering if ( _l == true) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { //Use nearest filter glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } //Set up the Texture class ctext->setTextureId(newtextid); ctext->setWidth(width); ctext->setHeight(height); ctext->setName( _fn ); //Return our texture return ctext; } else { TexturePtr ctext = new Texture( resources ); ctext->setTextureId(0); ctext->setWidth(0); ctext->setHeight(0); ctext->setName("FAILED TO LOAD"); //Return our texture return ctext; } //should never happen return TexturePtr(); assert(true); } // Load texture from memory. TexturePtr RenderSystem::loadTexture( const unsigned char* const _d, const unsigned int _len, const std::string& _name, bool _lin ) { //This is the class that will hold our texture TexturePtr ctext = new Texture( resources ); GLuint newtextid = SOIL_load_OGL_texture_from_memory( _d, _len, SOIL_LOAD_RGBA, SOIL_CREATE_NEW_ID, SOIL_FLAG_TEXTURE_REPEATS ); if( newtextid != 0 ) { //Load the texture glBindTexture(GL_TEXTURE_2D, newtextid); //use linear filtering if ( _lin == true) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { //Use nearest filter glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); } //Set up the Texture class ctext->setTextureId(newtextid); //Get the size from the buffer int _w = 0; int _h = 0; int _c = 4; unsigned char* tmp = SOIL_load_image_from_memory(_d, _len, &_w, &_h, &_c , SOIL_LOAD_AUTO); //Set the sizes in the Texture object ctext->setWidth( _w ); ctext->setHeight( _h ); if(!_name.size()) ctext->setName( "Loaded From Memory" ); else ctext->setName( _name ); //Return our texture return ctext; } else { TexturePtr ctext = new Texture( resources ); ctext->setTextureId(0); ctext->setWidth(0); ctext->setHeight(0); ctext->setName("FAILED TO LOAD"); //Return our texture return ctext; } //should never happen return TexturePtr(); assert(true); } //////////////////////////////////////////////////////////////////////////////// // Find texture functions. //////////////////////////////////////////////////////////////////////////////// //! Find texture. TexturePtr RenderSystem::findTexture(const std::string& _i) { ResourcePtr findtexture = resources.find(_i); if( findtexture ) { return findtexture->grab< Texture >(); } else { return TexturePtr(); } } //! Find texture. TexturePtr RenderSystem::findTexture(const GLuint& _n) { boost::recursive_mutex::scoped_lock( resources.getMutex() ); for (unsigned int i=0;i<resources.count();i++) { if( resources.get(i)->getType() == ERT_TEXTURE ) { if ( resources.get(i)->grab<Texture>()->getTextureId() == _n ) { return resources.get(i)->grab<Texture>(); } } } return TexturePtr(); } //////////////////////////////////////////////////////////////////////////////// //Draw text on the screen //////////////////////////////////////////////////////////////////////////////// BatchGeometryPtr RenderSystem::drawText( const std::string& s, const Vector2d& p, const Color& _c, const Vector2d& _scale ) { font->setDepth( factory.getDepth() ); font->setGroup( factory.getGroup() ); return font->drawText( s, p, _c, _scale ); }
26.572748
132
0.557274
theacodes
1f9063857c2c84d167630d091341e8270899d63c
1,820
cpp
C++
data_structures/Tree/c++/treap.cpp
CarbonDDR/al-go-rithms
8e65affbe812931b7dde0e2933eb06c0f44b4130
[ "CC0-1.0" ]
1,253
2017-06-06T07:19:25.000Z
2022-03-30T17:07:58.000Z
data_structures/Tree/c++/treap.cpp
rishabh99-rc/al-go-rithms
4df20d7ef7598fda4bc89101f9a99aac94cdd794
[ "CC0-1.0" ]
554
2017-09-29T18:56:01.000Z
2022-02-21T15:48:13.000Z
data_structures/Tree/c++/treap.cpp
rishabh99-rc/al-go-rithms
4df20d7ef7598fda4bc89101f9a99aac94cdd794
[ "CC0-1.0" ]
2,226
2017-09-29T19:59:59.000Z
2022-03-25T08:59:55.000Z
#include <cstdlib> #include <iostream> #include <string> #include <utility> #include <vector> using namespace std; // Treap has 2 main operations that are O(log(n)): // - split(t, k) -> split t into 2 trees, one with all keys <= k, the other with the rest // - merge(t1, t2) -> merge 2 trees where keys of t1 are smaller than any key in t2 struct Tree { Tree* left; Tree* right; int key; int value; int priority; Tree(int k, int v) { left = right = 0; key = k; value = v; priority = rand(); } }; pair<Tree*, Tree*> split(Tree* t, int k) { if (t == 0) return make_pair(nullptr, nullptr); if (t->key <= k) { auto p = split(t->right, k); t->right = p.first; return make_pair(t, p.second); } auto p = split(t->left, k); t->left = p.second; return make_pair(p.first, t); } Tree* merge(Tree* t1, Tree* t2) { if (t1 == 0) return t2; if (t2 == 0) return t1; if (t1->priority >= t2->priority) { t1->right = merge(t1->right, t2); return t1; } t2->left = merge(t1, t2->left); return t2; } // More complex operations can be implemented using only merge and split. See for example insert. Tree* insert(Tree* t, int k, int v) { Tree* n = new Tree(k, v); auto p = split(t, k); return merge(p.first, merge(n, p.second)); } void print(Tree* t, int level = 0) { if (t->right) print(t->right, level + 1); cout << string(4 * level, ' ') << "key: " << t->key << ", value: " << t->value << ", priority:" << t->priority << endl; if (t->left) print(t->left, level + 1); } void destroy(Tree* t) { if (t->left) destroy(t->left); if (t->right) destroy(t->right); delete t; } int main() { Tree* root = nullptr; for (int i = 0; i < 10; ++i) { int k = rand() % 10; root = insert(root, k, i); } print(root); destroy(root); }
23.037975
97
0.576923
CarbonDDR
1f90d9fb6690212280330dcb10894212c38a3465
4,338
cpp
C++
src/algorithm/IsomorphSpace.cpp
ehzawad/HyperGraphLib
a1424437a01ad5a9e0efa71d723d32fd58ca589c
[ "MIT" ]
22
2016-05-25T06:25:14.000Z
2022-01-12T09:15:38.000Z
src/algorithm/IsomorphSpace.cpp
ehzawad/HyperGraphLib
a1424437a01ad5a9e0efa71d723d32fd58ca589c
[ "MIT" ]
12
2016-05-08T15:02:48.000Z
2021-03-24T07:25:19.000Z
src/algorithm/IsomorphSpace.cpp
ehzawad/HyperGraphLib
a1424437a01ad5a9e0efa71d723d32fd58ca589c
[ "MIT" ]
6
2017-02-12T23:12:07.000Z
2021-06-28T06:34:55.000Z
/* * MIT License * * Copyright (c) 2015 Alexis LE GOADEC * * 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 "include/IsomorphSpace.hh" #include <iostream> #include <gecode/driver.hh> #include <gecode/minimodel.hh> IsomorphSpace::IsomorphSpace( const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstraitA, const boost::shared_ptr<HypergrapheAbstrait>& ptrHypergrapheAbstraitB) : _varEdge( *this, ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() + 1, 0, ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() ), _bVarEdge( *this, ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() + 1, 0, ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() ), _bVarEdge2( *this, ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() + 1, 0, ptrHypergrapheAbstraitA->getHyperEdgeList().size() * ptrHypergrapheAbstraitA->getHyperVertexList().size() ), _ptrHypergrapheA (ptrHypergrapheAbstraitA), _ptrHypergrapheB (ptrHypergrapheAbstraitB) { } void IsomorphSpace::postConstraints() { LibType::ListHyperVertex vertexA( _ptrHypergrapheA->getHyperVertexList() ); LibType::ListHyperEdge edgeA ( _ptrHypergrapheA->getHyperEdgeList() ); LibType::ListHyperVertex vertexB( _ptrHypergrapheB->getHyperVertexList() ); LibType::ListHyperEdge edgeB ( _ptrHypergrapheB->getHyperEdgeList() ); int j( 1 ); for(boost::shared_ptr<HyperEdge>& e : edgeA ) { for(boost::shared_ptr<HyperVertex>& v : vertexA ) { if( e->containVertex(v) ) { Gecode::rel(*this, _bVarEdge[ j ], Gecode::IRT_EQ, j); } else { Gecode::rel(*this, _bVarEdge[ j ], Gecode::IRT_EQ, 0); } j++; } } j = 1; for(boost::shared_ptr<HyperEdge>& e : edgeB ) { for(boost::shared_ptr<HyperVertex>& v : vertexB ) { if( e->containVertex(v) ) { Gecode::rel(*this, _bVarEdge2[ j ], Gecode::IRT_EQ, j); } else { Gecode::rel(*this, _bVarEdge2[ j ], Gecode::IRT_EQ, 0); } j++; } } int u( 0 ); for(int g=0; g < edgeA.size(); g++) { for(int h=0; h < vertexA.size(); h++) { Gecode::element(*this, _bVarEdge, _varEdge[u], _bVarEdge2[u]); u++; } } Gecode::distinct(*this, _varEdge ); Gecode::branch(*this, _varEdge, Gecode::INT_VAR_SIZE_MIN(), Gecode::INT_VAL_SPLIT_MIN()); } #if GECODE_VERSION_NUMBER > 500100 Gecode::Space* IsomorphSpace::copy() { return new IsomorphSpace(*this); } IsomorphSpace::IsomorphSpace(IsomorphSpace& p) : Gecode::Space(p) { _varEdge.update(*this, p._varEdge); } #else Gecode::Space* IsomorphSpace::copy(bool share) { return new IsomorphSpace(share, *this); } IsomorphSpace::IsomorphSpace(bool share, IsomorphSpace& p) : Gecode::Space(share, p) { _varEdge.update(*this, share, p._varEdge); } #endif
33.114504
118
0.665514
ehzawad
1f9ab6767cb247484030b35aa5911d7aab15c084
777
cpp
C++
bolt/server/src/mhttppost.cpp
gamunu/bolt
c1a2956f02656f3ec2c244486a816337126905ae
[ "Apache-2.0" ]
1
2022-03-06T09:23:56.000Z
2022-03-06T09:23:56.000Z
bolt/server/src/mhttppost.cpp
gamunu/bolt
c1a2956f02656f3ec2c244486a816337126905ae
[ "Apache-2.0" ]
3
2021-04-23T18:12:20.000Z
2021-04-23T18:12:47.000Z
bolt/server/src/mhttppost.cpp
gamunu/bolt
c1a2956f02656f3ec2c244486a816337126905ae
[ "Apache-2.0" ]
null
null
null
#include<mhttppost.hpp> #include<regex> #include<boost/scoped_ptr.hpp> #include <mysql_table.h> #include <metadata.hpp> using namespace std; using namespace bolt::storage::mysql; json::value MHttpPost::createTable(json::value object) { //TODO:Check if we are in windows or unix wregex name_regx(U("^[A-Za-z][A-Za-z0-9]{2,62}$")); json::value table_metadata; if (!object.is_null()) { if (object.has_field(U("TableName"))) { auto iter = object.as_object().find(U("TableName")); string_t tableName = iter->second.as_string(); if (regex_match(tableName, name_regx)) { MysqlTable table = MysqlTable(); if (table.createTable(tableName)) { table_metadata = Metadata::getMysqlTable(tableName); } } } } return table_metadata; }
22.2
57
0.680824
gamunu
1f9b955121445f1fb7046fb0d6d4ddf4552fdfc2
1,570
cc
C++
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/22_locale/money_get/get/char/39168.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
7
2020-05-02T17:34:05.000Z
2021-10-17T10:15:18.000Z
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/22_locale/money_get/get/char/39168.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
null
null
null
gcc-gcc-7_3_0-release/libstdc++-v3/testsuite/22_locale/money_get/get/char/39168.cc
best08618/asylo
5a520a9f5c461ede0f32acc284017b737a43898c
[ "Apache-2.0" ]
2
2020-07-27T00:22:36.000Z
2021-04-01T09:41:02.000Z
// Copyright (C) 2009-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // 22.2.6.1.1 money_get members #include <sstream> #include <locale> #include <climits> #include <testsuite_hooks.h> class my_moneypunct: public std::moneypunct<char> { protected: std::string do_grouping() const { return std::string(1, CHAR_MAX); } }; // libstdc++/39168 void test01() { using namespace std; typedef istreambuf_iterator<char> iterator_type; istringstream iss; iss.imbue(locale(iss.getloc(), new my_moneypunct)); const money_get<char>& mg = use_facet<money_get<char> >(iss.getloc()); string digits; ios_base::iostate err = ios_base::goodbit; iss.str("123,456"); iterator_type end = mg.get(iss.rdbuf(), 0, false, iss, err, digits); VERIFY( err == ios_base::goodbit ); VERIFY( digits == "123" ); VERIFY( *end == ',' ); } int main() { test01(); return 0; }
28.035714
74
0.708917
best08618
1f9ceca10c7920f9b0c1b921829cf18a9ee37b75
16,916
cpp
C++
wxWidgets-2.9.1/src/osx/carbon/combobox.cpp
gamekit-developers/gamekit
74c896af5826ebe8fb72f2911015738f38ab7bb2
[ "Zlib", "MIT" ]
241
2015-01-04T00:36:58.000Z
2022-01-06T19:19:23.000Z
wxWidgets-2.9.1/src/osx/carbon/combobox.cpp
gamekit-developers/gamekit
74c896af5826ebe8fb72f2911015738f38ab7bb2
[ "Zlib", "MIT" ]
10
2015-07-10T18:27:17.000Z
2019-06-26T20:59:59.000Z
wxWidgets-2.9.1/src/osx/carbon/combobox.cpp
gamekit-developers/gamekit
74c896af5826ebe8fb72f2911015738f38ab7bb2
[ "Zlib", "MIT" ]
82
2015-01-25T18:02:35.000Z
2022-03-05T12:28:17.000Z
///////////////////////////////////////////////////////////////////////////// // Name: src/osx/carbon/combobox.cpp // Purpose: wxComboBox class // Author: Stefan Csomor, Dan "Bud" Keith (composite combobox) // Modified by: // Created: 1998-01-01 // RCS-ID: $Id$ // Copyright: (c) Stefan Csomor // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #include "wx/wxprec.h" #if wxUSE_COMBOBOX && wxOSX_USE_CARBON #include "wx/combobox.h" #ifndef WX_PRECOMP #include "wx/button.h" #include "wx/menu.h" #include "wx/containr.h" #include "wx/toplevel.h" #include "wx/textctrl.h" #endif #include "wx/osx/private.h" IMPLEMENT_DYNAMIC_CLASS(wxComboBox, wxControl) WX_DELEGATE_TO_CONTROL_CONTAINER(wxComboBox, wxControl) BEGIN_EVENT_TABLE(wxComboBox, wxControl) WX_EVENT_TABLE_CONTROL_CONTAINER(wxComboBox) END_EVENT_TABLE() // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // the margin between the text control and the choice // margin should be bigger on OS X due to blue highlight // around text control. static const wxCoord MARGIN = 4; // this is the border a focus rect on OSX is needing static const int TEXTFOCUSBORDER = 3 ; // ---------------------------------------------------------------------------- // wxComboBoxText: text control forwards events to combobox // ---------------------------------------------------------------------------- class wxComboBoxText : public wxTextCtrl { public: wxComboBoxText( wxComboBox * cb ) : wxTextCtrl( cb , 1 ) { m_cb = cb; } protected: void OnChar( wxKeyEvent& event ) { // Allows processing the tab key to go to the next control if (event.GetKeyCode() == WXK_TAB) { wxNavigationKeyEvent NavEvent; NavEvent.SetEventObject(this); NavEvent.SetDirection(true); NavEvent.SetWindowChange(false); // Get the parent of the combo and have it process the navigation? if (m_cb->GetParent()->HandleWindowEvent(NavEvent)) return; } // send the event to the combobox class in case the user has bound EVT_CHAR wxKeyEvent kevt(event); kevt.SetEventObject(m_cb); if (m_cb->HandleWindowEvent(kevt)) // If the event was handled and not skipped then we're done return; if ( event.GetKeyCode() == WXK_RETURN ) { wxCommandEvent event(wxEVT_COMMAND_TEXT_ENTER, m_cb->GetId()); event.SetString( GetValue() ); event.SetInt( m_cb->GetSelection() ); event.SetEventObject( m_cb ); // This will invoke the dialog default action, // such as the clicking the default button. if (!m_cb->HandleWindowEvent( event )) { wxTopLevelWindow *tlw = wxDynamicCast(wxGetTopLevelParent(this), wxTopLevelWindow); if ( tlw && tlw->GetDefaultItem() ) { wxButton *def = wxDynamicCast(tlw->GetDefaultItem(), wxButton); if ( def && def->IsEnabled() ) { wxCommandEvent event( wxEVT_COMMAND_BUTTON_CLICKED, def->GetId() ); event.SetEventObject(def); def->Command(event); } } return; } } event.Skip(); } void OnKeyUp( wxKeyEvent& event ) { event.SetEventObject(m_cb); event.SetId(m_cb->GetId()); if (! m_cb->HandleWindowEvent(event)) event.Skip(); } void OnKeyDown( wxKeyEvent& event ) { event.SetEventObject(m_cb); event.SetId(m_cb->GetId()); if (! m_cb->HandleWindowEvent(event)) event.Skip(); } void OnText( wxCommandEvent& event ) { event.SetEventObject(m_cb); event.SetId(m_cb->GetId()); if (! m_cb->HandleWindowEvent(event)) event.Skip(); } void OnFocus( wxFocusEvent& event ) { // in case the textcontrol gets the focus we propagate // it to the parent's handlers. wxFocusEvent evt2(event.GetEventType(),m_cb->GetId()); evt2.SetEventObject(m_cb); m_cb->GetEventHandler()->ProcessEvent(evt2); event.Skip(); } private: wxComboBox *m_cb; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxComboBoxText, wxTextCtrl) EVT_KEY_DOWN(wxComboBoxText::OnKeyDown) EVT_CHAR(wxComboBoxText::OnChar) EVT_KEY_UP(wxComboBoxText::OnKeyUp) EVT_SET_FOCUS(wxComboBoxText::OnFocus) EVT_KILL_FOCUS(wxComboBoxText::OnFocus) EVT_TEXT(wxID_ANY, wxComboBoxText::OnText) END_EVENT_TABLE() class wxComboBoxChoice : public wxChoice { public: wxComboBoxChoice( wxComboBox *cb, int style ) : wxChoice( cb , 1 , wxDefaultPosition , wxDefaultSize , 0 , NULL , style & (wxCB_SORT) ) { m_cb = cb; } int GetPopupWidth() const { switch ( GetWindowVariant() ) { case wxWINDOW_VARIANT_NORMAL : case wxWINDOW_VARIANT_LARGE : return 24 ; default : return 21 ; } } protected: void OnChoice( wxCommandEvent& e ) { wxString s = e.GetString(); m_cb->DelegateChoice( s ); wxCommandEvent event2(wxEVT_COMMAND_COMBOBOX_SELECTED, m_cb->GetId() ); event2.SetInt(m_cb->GetSelection()); event2.SetEventObject(m_cb); event2.SetString(m_cb->GetStringSelection()); m_cb->ProcessCommand(event2); // For consistency with MSW and GTK, also send a text updated event // After all, the text is updated when a selection is made wxCommandEvent TextEvent( wxEVT_COMMAND_TEXT_UPDATED, m_cb->GetId() ); TextEvent.SetString( m_cb->GetStringSelection() ); TextEvent.SetEventObject( m_cb ); m_cb->ProcessCommand( TextEvent ); } virtual wxSize DoGetBestSize() const { wxSize sz = wxChoice::DoGetBestSize() ; if (! m_cb->HasFlag(wxCB_READONLY) ) sz.x = GetPopupWidth() ; return sz ; } private: wxComboBox *m_cb; friend class wxComboBox; DECLARE_EVENT_TABLE() }; BEGIN_EVENT_TABLE(wxComboBoxChoice, wxChoice) EVT_CHOICE(wxID_ANY, wxComboBoxChoice::OnChoice) END_EVENT_TABLE() wxComboBox::~wxComboBox() { // delete the controls now, don't leave them alive even though they would // still be eventually deleted by our parent - but it will be too late, the // user code expects them to be gone now wxDELETE(m_text); wxDELETE(m_choice); } // ---------------------------------------------------------------------------- // geometry // ---------------------------------------------------------------------------- wxSize wxComboBox::DoGetBestSize() const { if (!m_choice && !m_text) return GetSize(); wxSize size = m_choice->GetBestSize(); if ( m_text != NULL ) { wxSize sizeText = m_text->GetBestSize(); if (sizeText.y + 2 * TEXTFOCUSBORDER > size.y) size.y = sizeText.y + 2 * TEXTFOCUSBORDER; size.x = m_choice->GetPopupWidth() + sizeText.x + MARGIN; size.x += TEXTFOCUSBORDER ; } else { // clipping is too tight size.y += 1 ; } return size; } void wxComboBox::DoMoveWindow(int x, int y, int width, int height) { wxControl::DoMoveWindow( x, y, width , height ); if ( m_text == NULL ) { // we might not be fully constructed yet, therefore watch out... if ( m_choice ) m_choice->SetSize(0, 0 , width, -1); } else { wxCoord wText = width - m_choice->GetPopupWidth() - MARGIN; m_text->SetSize(TEXTFOCUSBORDER, TEXTFOCUSBORDER, wText, -1); wxSize tSize = m_text->GetSize(); wxSize cSize = m_choice->GetSize(); int yOffset = ( tSize.y + 2 * TEXTFOCUSBORDER - cSize.y ) / 2; // put it at an inset of 1 to have outer area shadows drawn as well m_choice->SetSize(TEXTFOCUSBORDER + wText + MARGIN - 1 , yOffset, m_choice->GetPopupWidth() , -1); } } // ---------------------------------------------------------------------------- // operations forwarded to the subcontrols // ---------------------------------------------------------------------------- bool wxComboBox::Enable(bool enable) { if ( !wxControl::Enable(enable) ) return false; if (m_text) m_text->Enable(enable); return true; } bool wxComboBox::Show(bool show) { if ( !wxControl::Show(show) ) return false; return true; } void wxComboBox::DelegateTextChanged( const wxString& value ) { SetStringSelection( value ); } void wxComboBox::DelegateChoice( const wxString& value ) { SetStringSelection( value ); } void wxComboBox::Init() { WX_INIT_CONTROL_CONTAINER(); } bool wxComboBox::Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, const wxArrayString& choices, long style, const wxValidator& validator, const wxString& name) { if ( !Create( parent, id, value, pos, size, 0, NULL, style, validator, name ) ) return false; Append(choices); return true; } bool wxComboBox::Create(wxWindow *parent, wxWindowID id, const wxString& value, const wxPoint& pos, const wxSize& size, int n, const wxString choices[], long style, const wxValidator& validator, const wxString& name) { if ( !wxControl::Create(parent, id, wxDefaultPosition, wxDefaultSize, style , validator, name) ) { return false; } wxSize csize = size; if ( style & wxCB_READONLY ) { m_text = NULL; } else { m_text = new wxComboBoxText(this); if ( size.y == -1 ) { csize.y = m_text->GetSize().y ; csize.y += 2 * TEXTFOCUSBORDER ; } } m_choice = new wxComboBoxChoice(this, style ); DoSetSize(pos.x, pos.y, csize.x, csize.y); Append( n, choices ); // Needed because it is a wxControlWithItems SetInitialSize(size); SetStringSelection(value); return true; } void wxComboBox::EnableTextChangedEvents(bool enable) { if ( m_text ) m_text->ForwardEnableTextChangedEvents(enable); } wxString wxComboBox::DoGetValue() const { wxCHECK_MSG( m_text, wxString(), "can't be called for read-only combobox" ); return m_text->GetValue(); } wxString wxComboBox::GetValue() const { wxString result; if ( m_text == NULL ) result = m_choice->GetString( m_choice->GetSelection() ); else result = m_text->GetValue(); return result; } unsigned int wxComboBox::GetCount() const { return m_choice->GetCount() ; } void wxComboBox::SetValue(const wxString& value) { if ( HasFlag(wxCB_READONLY) ) SetStringSelection( value ) ; else m_text->SetValue( value ); } void wxComboBox::WriteText(const wxString& text) { m_text->WriteText(text); } void wxComboBox::GetSelection(long *from, long *to) const { m_text->GetSelection(from, to); } // Clipboard operations void wxComboBox::Copy() { if ( m_text != NULL ) m_text->Copy(); } void wxComboBox::Cut() { if ( m_text != NULL ) m_text->Cut(); } void wxComboBox::Paste() { if ( m_text != NULL ) m_text->Paste(); } void wxComboBox::SetEditable(bool editable) { if ( ( m_text == NULL ) && editable ) { m_text = new wxComboBoxText( this ); } else if ( !editable ) { wxDELETE(m_text); } int currentX, currentY; GetPosition( &currentX, &currentY ); int currentW, currentH; GetSize( &currentW, &currentH ); DoMoveWindow( currentX, currentY, currentW, currentH ); } void wxComboBox::SetInsertionPoint(long pos) { if ( m_text ) m_text->SetInsertionPoint(pos); } void wxComboBox::SetInsertionPointEnd() { if ( m_text ) m_text->SetInsertionPointEnd(); } long wxComboBox::GetInsertionPoint() const { if ( m_text ) return m_text->GetInsertionPoint(); return 0; } wxTextPos wxComboBox::GetLastPosition() const { if ( m_text ) return m_text->GetLastPosition(); return 0; } void wxComboBox::Replace(long from, long to, const wxString& value) { if ( m_text ) m_text->Replace(from,to,value); } void wxComboBox::Remove(long from, long to) { if ( m_text ) m_text->Remove(from,to); } void wxComboBox::SetSelection(long from, long to) { if ( m_text ) m_text->SetSelection(from,to); } int wxComboBox::DoInsertItems(const wxArrayStringsAdapter& items, unsigned int pos, void **clientData, wxClientDataType type) { return m_choice->DoInsertItems(items, pos, clientData, type); } void wxComboBox::DoSetItemClientData(unsigned int n, void* clientData) { return m_choice->DoSetItemClientData( n , clientData ) ; } void* wxComboBox::DoGetItemClientData(unsigned int n) const { return m_choice->DoGetItemClientData( n ) ; } wxClientDataType wxComboBox::GetClientDataType() const { return m_choice->GetClientDataType(); } void wxComboBox::SetClientDataType(wxClientDataType clientDataItemsType) { m_choice->SetClientDataType(clientDataItemsType); } void wxComboBox::DoDeleteOneItem(unsigned int n) { m_choice->DoDeleteOneItem( n ); } void wxComboBox::DoClear() { m_choice->DoClear(); } int wxComboBox::GetSelection() const { return m_choice->GetSelection(); } void wxComboBox::SetSelection(int n) { m_choice->SetSelection( n ); if ( m_text != NULL ) m_text->SetValue(n != wxNOT_FOUND ? GetString(n) : wxString(wxEmptyString)); } int wxComboBox::FindString(const wxString& s, bool bCase) const { return m_choice->FindString( s, bCase ); } wxString wxComboBox::GetString(unsigned int n) const { return m_choice->GetString( n ); } wxString wxComboBox::GetStringSelection() const { int sel = GetSelection(); if (sel != wxNOT_FOUND) return wxString(this->GetString((unsigned int)sel)); else return wxEmptyString; } void wxComboBox::SetString(unsigned int n, const wxString& s) { m_choice->SetString( n , s ); } bool wxComboBox::IsEditable() const { return m_text != NULL && !HasFlag(wxCB_READONLY); } void wxComboBox::Undo() { if (m_text != NULL) m_text->Undo(); } void wxComboBox::Redo() { if (m_text != NULL) m_text->Redo(); } void wxComboBox::SelectAll() { if (m_text != NULL) m_text->SelectAll(); } bool wxComboBox::CanCopy() const { if (m_text != NULL) return m_text->CanCopy(); else return false; } bool wxComboBox::CanCut() const { if (m_text != NULL) return m_text->CanCut(); else return false; } bool wxComboBox::CanPaste() const { if (m_text != NULL) return m_text->CanPaste(); else return false; } bool wxComboBox::CanUndo() const { if (m_text != NULL) return m_text->CanUndo(); else return false; } bool wxComboBox::CanRedo() const { if (m_text != NULL) return m_text->CanRedo(); else return false; } bool wxComboBox::OSXHandleClicked( double WXUNUSED(timestampsec) ) { /* For consistency with other platforms, clicking in the text area does not constitute a selection wxCommandEvent event(wxEVT_COMMAND_COMBOBOX_SELECTED, m_windowId ); event.SetInt(GetSelection()); event.SetEventObject(this); event.SetString(GetStringSelection()); ProcessCommand(event); */ return true ; } wxTextWidgetImpl* wxComboBox::GetTextPeer() const { if (m_text) return m_text->GetTextPeer(); return NULL; } #endif // wxUSE_COMBOBOX && wxOSX_USE_CARBON
24.730994
107
0.565855
gamekit-developers
1f9d47ab42c6c618df449777e23c5a474dbed1ac
4,203
cpp
C++
src/FresponzeListener.cpp
suirless/fresponze
2c8f9204c8ba4b734d7885cc1fe51f31c89d22ef
[ "Apache-2.0" ]
8
2020-09-26T20:38:26.000Z
2021-05-16T18:13:48.000Z
src/FresponzeListener.cpp
Vertver/Fresponze
ca45738a2c06474fb6f45b627f8b1c8b85e69cd1
[ "Apache-2.0" ]
23
2022-01-23T04:57:32.000Z
2022-01-23T04:59:32.000Z
src/FresponzeListener.cpp
suirless/fresponze
2c8f9204c8ba4b734d7885cc1fe51f31c89d22ef
[ "Apache-2.0" ]
1
2020-12-07T13:48:15.000Z
2020-12-07T13:48:15.000Z
/********************************************************************* * Copyright (C) Anton Kovalev (vertver), 2020. All rights reserved. * Fresponze - fast, simple and modern multimedia sound library * Apache-2 License ********************************************************************** * 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 "FresponzeListener.h" CMediaListener::CMediaListener(IMediaResource* pInitialResource) { AddRef(); pInitialResource->Clone((void**)&pLocalResource); pLocalResource->GetFormat(ResourceFormat); ListenerFormat = ResourceFormat; } CMediaListener::~CMediaListener() { _RELEASE(pLocalResource); FreeStuff(); } void CMediaListener::FreeStuff() { EmittersNode* pNode = pFirstEmitter; EmittersNode* pThisNode = nullptr; while (pNode) { pThisNode = pNode->pNext; _RELEASE(pNode->pEmitter); delete pNode; pNode = pThisNode; } } bool CMediaListener::AddEmitter(IBaseEmitter* pNewEmitter) { if (!pLastEmitter) { pFirstEmitter = new EmittersNode; memset(pFirstEmitter, 0, sizeof(EmittersNode)); pLastEmitter = pFirstEmitter; pNewEmitter->Clone((void**)&pLastEmitter->pEmitter); } else { EmittersNode* pTemp = new EmittersNode; memset(pFirstEmitter, 0, sizeof(EmittersNode)); pNewEmitter->Clone((void**)&pTemp->pEmitter); pLastEmitter->pNext = pTemp; pTemp->pPrev = pLastEmitter; pLastEmitter = pTemp; } return true; } bool CMediaListener::DeleteEmitter(IBaseEmitter* pEmitter) { EmittersNode* pNode = nullptr; GetFirstEmitter(&pNode); while (pNode) { if (pNode->pEmitter == pEmitter) { pNode->pPrev->pNext = pNode->pNext; pNode->pNext->pPrev = pNode->pPrev; _RELEASE(pNode->pEmitter); delete pNode; return true; } } return false; } bool CMediaListener::GetFirstEmitter(EmittersNode** pFirstEmitter) { *pFirstEmitter = this->pFirstEmitter; return true; } bool CMediaListener::SetResource(IMediaResource* pInitialResource) { _RELEASE(pLocalResource); return pInitialResource->Clone((void**)&pLocalResource); } fr_i32 CMediaListener::SetPosition(fr_f32 FloatPosition) { return SetPosition(fr_i64(((fr_f64)ResourceFormat.Frames * fabs(FloatPosition)))); } fr_i32 CMediaListener::SetPosition(fr_i64 FramePosition) { fr_i64 outputFrames = 0; CalculateFrames64(FramePosition, ListenerFormat.SampleRate, ResourceFormat.SampleRate, outputFrames); fr_i32 ret = pLocalResource->SetPosition(outputFrames); CalculateFrames64(ret, ResourceFormat.SampleRate, ListenerFormat.SampleRate, outputFrames); return outputFrames; } fr_i64 CMediaListener::GetPosition() { fr_i64 outputFrames = pLocalResource->GetPosition(); CalculateFrames64(outputFrames, ResourceFormat.SampleRate, ListenerFormat.SampleRate, outputFrames); return outputFrames; } fr_i32 CMediaListener::GetFullFrames() { fr_i64 outputFrames = 0; CalculateFrames64(ResourceFormat.Frames, ResourceFormat.SampleRate, ListenerFormat.SampleRate, outputFrames); return (fr_i32)outputFrames; } fr_i32 CMediaListener::GetFormat(PcmFormat& fmt) { fmt = ListenerFormat; return 0; } fr_i32 CMediaListener::SetFormat(PcmFormat fmt) { EmittersNode* pProcessEmitter = pFirstEmitter; ListenerFormat = fmt; pLocalResource->SetFormat(ListenerFormat); pLocalResource->GetFormat(ResourceFormat); while (pProcessEmitter) { pProcessEmitter->pEmitter->SetFormat(&ListenerFormat); pProcessEmitter = pProcessEmitter->pNext; } return 0; } fr_i32 CMediaListener::Process(fr_f32** ppOutputFloatData, fr_i32 frames) { fr_i32 inFrames = 0; inFrames = (fr_i32)pLocalResource->Read(frames, ppOutputFloatData); framesPos = pLocalResource->GetPosition(); return inFrames; }
26.26875
110
0.730193
suirless
1fa10edad2574c55eaacb70ccf1e426684a9be6a
109
cpp
C++
SteamAPIWrap/Helper.cpp
HoggeL/Ludosity-s-Steamworks-Wrapper
5cd8f5740829a20af23343865895ceb782f9b0b4
[ "MIT" ]
null
null
null
SteamAPIWrap/Helper.cpp
HoggeL/Ludosity-s-Steamworks-Wrapper
5cd8f5740829a20af23343865895ceb782f9b0b4
[ "MIT" ]
null
null
null
SteamAPIWrap/Helper.cpp
HoggeL/Ludosity-s-Steamworks-Wrapper
5cd8f5740829a20af23343865895ceb782f9b0b4
[ "MIT" ]
null
null
null
#include "Precompiled.hpp" #include "Helper.hpp" using namespace SteamAPIWrap; namespace SteamAPIWrap { }
10.9
29
0.770642
HoggeL
1fa36e00dac9162fc1247dc4c105e61ce28dacfb
1,926
cpp
C++
Krack_X_Core_Test/core.cpp
Bensuperpc/Krack_Core_Test
2b17f6b81087b7b234ce4f2776283a43175b9fae
[ "MIT" ]
1
2019-11-14T17:42:31.000Z
2019-11-14T17:42:31.000Z
Krack_X_Core_Test/core.cpp
Bensuperpc/Krack_Core_Test
2b17f6b81087b7b234ce4f2776283a43175b9fae
[ "MIT" ]
null
null
null
Krack_X_Core_Test/core.cpp
Bensuperpc/Krack_Core_Test
2b17f6b81087b7b234ce4f2776283a43175b9fae
[ "MIT" ]
null
null
null
/* * * git.py - for git clone and pull in local * * Created by Benoît(Bensuperpc@gmail.com) 04th June 2019 * Updated by X for C++11 * * Released into the Public domain with MIT licence * https://opensource.org/licenses/MIT * * Written with QtCreator and C++11 * Script compatibility : Windows, Linux * Script requirement : C++11 and above, GCC 7.X and above * * ============================================================================== */ #include "core.h" #include <iostream> #include <thread> #include<qprocess.h> #include<QtDebug> #include <iostream> #include <mutex> #include <chrono> static std::mutex g_display_mutex; static std::atomic_uint tt; core::core() { core::exec("t"); } void core::exec(QString LauncedP){ std::thread *tt = new std::thread[CoreProcessingCount];//On créer les Threads for (unsigned int i = 0; i < CoreProcessingCount; ++i) { tt[i] = std::thread(&core::call_from_thread,this,i,CoreProcessingCount, LauncedP); } for (unsigned int i = 0; i < CoreProcessingCount; ++i){ if(tt[i].joinable()){ tt[i].join(); qDebug() << "Join thread :" << i; } } delete [] tt;//On nettoie la Memoire qDebug() << "ffff "; } void core::call_from_thread(int tid, int ThreadsCount, QString _LauncedP) { tt = tt + 1; std::thread::id this_id = std::this_thread::get_id(); g_display_mutex.lock(); std::cout << "thread " << this_id << " sleeping...\n"; qDebug() << "Launched by thread " << tid; qDebug() << "tt " << tt; g_display_mutex.unlock(); qDebug() << "==========="; std::vector<int> arr; for(unsigned long long i = 64 ; i<=75; i++){ arr.emplace_back(i); //std::cout << arr[i].ggg; qDebug() << "I =" << i <<char(arr[i]); } qDebug() << "==========="; std::this_thread::sleep_for(std::chrono::seconds(5)); } core::~core() { }
22.658824
90
0.565421
Bensuperpc
1fa38e014ca5f85754d715b90f8c8c6bd411d65c
4,557
cpp
C++
src/teleop_dummy/main_teleop_dummy_sigma.cpp
neemoh/ART
3f990b9d3c4b58558adf97866faf4eea553ba71b
[ "Unlicense" ]
11
2018-06-29T19:08:08.000Z
2021-12-30T07:13:00.000Z
src/teleop_dummy/main_teleop_dummy_sigma.cpp
liuxia-zju/ATAR
3f990b9d3c4b58558adf97866faf4eea553ba71b
[ "Unlicense" ]
1
2020-05-09T23:44:55.000Z
2020-05-09T23:44:55.000Z
src/teleop_dummy/main_teleop_dummy_sigma.cpp
liuxia-zju/ATAR
3f990b9d3c4b58558adf97866faf4eea553ba71b
[ "Unlicense" ]
6
2017-11-28T14:26:18.000Z
2019-11-29T01:57:14.000Z
// // Created by nima on 12/10/17. // #include <ros/ros.h> #include <geometry_msgs/PoseStamped.h> #include <sensor_msgs/Joy.h> #include <kdl/frames.hpp> #include <kdl_conversions/kdl_msg.h> #include <std_msgs/String.h> #include <std_msgs/Int8.h> #include <src/ar_core/ControlEvents.h> // This node simulates the slaves of the dvrk in a teleop mode and controls the // behavior of the master console to mock that of the dvrk teleoperation mode. // At the moment the dvrk does not publish the foot pedals status if the // dvrk-console is not run in teleop mode. That's why we run the dvrk-console // in a normal teleop mode, but Home the arms through this node (instead of // the user interface) so that we can power up only the masters and not the // slaves that are not needed here. // ------------------------------------- global variables --------------------------- int buttons[2]; bool new_buttons_msg; bool new_master_pose; KDL::Frame master_pose; // ------------------------------------- callback functions --------------------------- void ButtonsCallback(const sensor_msgs::JoyConstPtr & msg){ for (int i = 0; i < msg->buttons.size(); ++i) { buttons[i] = msg->buttons[i]; } new_buttons_msg = true; } void MasterPoseCurrentCallback( const geometry_msgs::PoseStamped::ConstPtr &msg){ geometry_msgs::Pose pose = msg->pose; tf::poseMsgToKDL(msg->pose, master_pose); new_master_pose = true; } void ControlEventsCallback(const std_msgs::Int8ConstPtr &msg) { int8_t control_event = msg->data; ROS_DEBUG("Received control event %d", control_event); switch(control_event){ case CE_HOME_MASTERS: break; default: break; } } // ------------------------------------- Main --------------------------- int main(int argc, char * argv[]) { ros::init(argc, argv, "teleop_dummy"); ros::NodeHandle n(ros::this_node::getName()); if( ros::console::set_logger_level( ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Info) ) ros::console::notifyLoggerLevelsChanged(); // ------------------------------------- Buttons--------------------------- ros::Subscriber sub_clutch_clutch = n.subscribe( "/sigma/sigma0/buttons", 1, ButtonsCallback); // ------------ MATERS POSE ros::Subscriber sub_master_current_pose = n.subscribe("/sigma/sigma0/pose", 1, MasterPoseCurrentCallback); // ------------ SLAVE PUBLISH POSE std::string pose_topic = std::string("/sigma/sigma0/dummy_slave_pose"); ros::Publisher pub_slave_pose = n.advertise<geometry_msgs::PoseStamped>(pose_topic, 1); // ------------ subscribe to control events that come from the GUI ros::Subscriber sub_control_events = n.subscribe("/atar/control_events", 1, ControlEventsCallback); double scaling = 0.2; n.getParam("scaling", scaling); ROS_INFO(" Master to slave position scaling: %f", scaling); // spinning freq, publishing freq will be according to the freq of master poses received ros::Rate loop_rate(1000); KDL::Vector master_position_at_clutch_instance; KDL::Vector slave_position_at_clutch_instance; KDL::Frame slave_pose; // get initial tool position std::vector<double> init_tool_position= {0., 0., 0.}; n.getParam("initial_slave_position", init_tool_position); slave_pose.p = KDL::Vector(init_tool_position[0], init_tool_position[1], init_tool_position[2]); while(ros::ok()){ if(new_buttons_msg){ new_buttons_msg = false; master_position_at_clutch_instance = master_pose.p; slave_position_at_clutch_instance = slave_pose.p; } // Incremental slave position if(new_master_pose) { new_master_pose = false; // if operator present increment the slave position if(buttons[1]==1){ slave_pose.p = slave_position_at_clutch_instance + scaling * (master_pose.p - master_position_at_clutch_instance); slave_pose.M = master_pose.M; } //publish pose geometry_msgs::PoseStamped pose; tf::poseKDLToMsg( slave_pose, pose.pose); pub_slave_pose.publish(pose); } ros::spinOnce(); loop_rate.sleep(); } }
33.507353
94
0.595128
neemoh
1fa4a5d0f424620062898e3dc6efb45278b2af22
13,519
cpp
C++
Sources/Engine/External/OpenALSoft/alc/converter.cpp
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
null
null
null
Sources/Engine/External/OpenALSoft/alc/converter.cpp
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
null
null
null
Sources/Engine/External/OpenALSoft/alc/converter.cpp
intensifier/NeoAxisEngine
5c3d6d853c1d420e332aa31c73840f7cf3fd3eef
[ "IJG" ]
null
null
null
#include "config.h" #include "converter.h" #include <algorithm> #include <cstdint> #include <iterator> #include "AL/al.h" #include "albyte.h" #include "fpu_modes.h" #include "mixer/defs.h" namespace { /* Base template left undefined. Should be marked =delete, but Clang 3.8.1 * chokes on that given the inline specializations. */ template<DevFmtType T> inline ALfloat LoadSample(typename DevFmtTypeTraits<T>::Type val) noexcept; template<> inline ALfloat LoadSample<DevFmtByte>(DevFmtTypeTraits<DevFmtByte>::Type val) noexcept { return val * (1.0f/128.0f); } template<> inline ALfloat LoadSample<DevFmtShort>(DevFmtTypeTraits<DevFmtShort>::Type val) noexcept { return val * (1.0f/32768.0f); } template<> inline ALfloat LoadSample<DevFmtInt>(DevFmtTypeTraits<DevFmtInt>::Type val) noexcept { return val * (1.0f/2147483648.0f); } template<> inline ALfloat LoadSample<DevFmtFloat>(DevFmtTypeTraits<DevFmtFloat>::Type val) noexcept { return val; } template<> inline ALfloat LoadSample<DevFmtUByte>(DevFmtTypeTraits<DevFmtUByte>::Type val) noexcept { return LoadSample<DevFmtByte>(val - 128); } template<> inline ALfloat LoadSample<DevFmtUShort>(DevFmtTypeTraits<DevFmtUShort>::Type val) noexcept { return LoadSample<DevFmtShort>(val - 32768); } template<> inline ALfloat LoadSample<DevFmtUInt>(DevFmtTypeTraits<DevFmtUInt>::Type val) noexcept { return LoadSample<DevFmtInt>(val - 2147483648u); } template<DevFmtType T> inline void LoadSampleArray(ALfloat *RESTRICT dst, const void *src, const size_t srcstep, const ALsizei samples) noexcept { using SampleType = typename DevFmtTypeTraits<T>::Type; const SampleType *ssrc = static_cast<const SampleType*>(src); for(ALsizei i{0};i < samples;i++) dst[i] = LoadSample<T>(ssrc[i*srcstep]); } void LoadSamples(ALfloat *dst, const ALvoid *src, const size_t srcstep, const DevFmtType srctype, const ALsizei samples) noexcept { #define HANDLE_FMT(T) \ case T: LoadSampleArray<T>(dst, src, srcstep, samples); break switch(srctype) { HANDLE_FMT(DevFmtByte); HANDLE_FMT(DevFmtUByte); HANDLE_FMT(DevFmtShort); HANDLE_FMT(DevFmtUShort); HANDLE_FMT(DevFmtInt); HANDLE_FMT(DevFmtUInt); HANDLE_FMT(DevFmtFloat); } #undef HANDLE_FMT } template<DevFmtType T> inline typename DevFmtTypeTraits<T>::Type StoreSample(ALfloat) noexcept; template<> inline ALfloat StoreSample<DevFmtFloat>(ALfloat val) noexcept { return val; } template<> inline ALint StoreSample<DevFmtInt>(ALfloat val) noexcept { return fastf2i(clampf(val*2147483648.0f, -2147483648.0f, 2147483520.0f)); } template<> inline ALshort StoreSample<DevFmtShort>(ALfloat val) noexcept { return fastf2i(clampf(val*32768.0f, -32768.0f, 32767.0f)); } template<> inline ALbyte StoreSample<DevFmtByte>(ALfloat val) noexcept { return fastf2i(clampf(val*128.0f, -128.0f, 127.0f)); } /* Define unsigned output variations. */ template<> inline ALuint StoreSample<DevFmtUInt>(ALfloat val) noexcept { return StoreSample<DevFmtInt>(val) + 2147483648u; } template<> inline ALushort StoreSample<DevFmtUShort>(ALfloat val) noexcept { return StoreSample<DevFmtShort>(val) + 32768; } template<> inline ALubyte StoreSample<DevFmtUByte>(ALfloat val) noexcept { return StoreSample<DevFmtByte>(val) + 128; } template<DevFmtType T> inline void StoreSampleArray(void *dst, const ALfloat *RESTRICT src, const size_t dststep, const ALsizei samples) noexcept { using SampleType = typename DevFmtTypeTraits<T>::Type; SampleType *sdst = static_cast<SampleType*>(dst); for(ALsizei i{0};i < samples;i++) sdst[i*dststep] = StoreSample<T>(src[i]); } void StoreSamples(ALvoid *dst, const ALfloat *src, const size_t dststep, const DevFmtType dsttype, const ALsizei samples) noexcept { #define HANDLE_FMT(T) \ case T: StoreSampleArray<T>(dst, src, dststep, samples); break switch(dsttype) { HANDLE_FMT(DevFmtByte); HANDLE_FMT(DevFmtUByte); HANDLE_FMT(DevFmtShort); HANDLE_FMT(DevFmtUShort); HANDLE_FMT(DevFmtInt); HANDLE_FMT(DevFmtUInt); HANDLE_FMT(DevFmtFloat); } #undef HANDLE_FMT } template<DevFmtType T> void Mono2Stereo(ALfloat *RESTRICT dst, const void *src, const ALsizei frames) noexcept { using SampleType = typename DevFmtTypeTraits<T>::Type; const SampleType *ssrc = static_cast<const SampleType*>(src); for(ALsizei i{0};i < frames;i++) dst[i*2 + 1] = dst[i*2 + 0] = LoadSample<T>(ssrc[i]) * 0.707106781187f; } template<DevFmtType T> void Stereo2Mono(ALfloat *RESTRICT dst, const void *src, const ALsizei frames) noexcept { using SampleType = typename DevFmtTypeTraits<T>::Type; const SampleType *ssrc = static_cast<const SampleType*>(src); for(ALsizei i{0};i < frames;i++) dst[i] = (LoadSample<T>(ssrc[i*2 + 0])+LoadSample<T>(ssrc[i*2 + 1])) * 0.707106781187f; } } // namespace SampleConverterPtr CreateSampleConverter(DevFmtType srcType, DevFmtType dstType, ALsizei numchans, ALsizei srcRate, ALsizei dstRate, Resampler resampler) { if(numchans <= 0 || srcRate <= 0 || dstRate <= 0) return nullptr; void *ptr{al_calloc(16, SampleConverter::Sizeof(numchans))}; SampleConverterPtr converter{new (ptr) SampleConverter{static_cast<size_t>(numchans)}}; converter->mSrcType = srcType; converter->mDstType = dstType; converter->mSrcTypeSize = BytesFromDevFmt(srcType); converter->mDstTypeSize = BytesFromDevFmt(dstType); converter->mSrcPrepCount = 0; converter->mFracOffset = 0; /* Have to set the mixer FPU mode since that's what the resampler code expects. */ FPUCtl mixer_mode{}; auto step = static_cast<ALsizei>( mind(static_cast<ALdouble>(srcRate)/dstRate*FRACTIONONE + 0.5, MAX_PITCH*FRACTIONONE)); converter->mIncrement = maxi(step, 1); if(converter->mIncrement == FRACTIONONE) converter->mResample = Resample_<CopyTag,CTag>; else { if(resampler == BSinc24Resampler) BsincPrepare(converter->mIncrement, &converter->mState.bsinc, &bsinc24); else if(resampler == BSinc12Resampler) BsincPrepare(converter->mIncrement, &converter->mState.bsinc, &bsinc12); converter->mResample = SelectResampler(resampler); } return converter; } ALsizei SampleConverter::availableOut(ALsizei srcframes) const { ALint prepcount{mSrcPrepCount}; if(prepcount < 0) { /* Negative prepcount means we need to skip that many input samples. */ if(-prepcount >= srcframes) return 0; srcframes += prepcount; prepcount = 0; } if(srcframes < 1) { /* No output samples if there's no input samples. */ return 0; } if(prepcount < MAX_RESAMPLE_PADDING*2 && MAX_RESAMPLE_PADDING*2 - prepcount >= srcframes) { /* Not enough input samples to generate an output sample. */ return 0; } auto DataSize64 = static_cast<uint64_t>(prepcount); DataSize64 += srcframes; DataSize64 -= MAX_RESAMPLE_PADDING*2; DataSize64 <<= FRACTIONBITS; DataSize64 -= mFracOffset; /* If we have a full prep, we can generate at least one sample. */ return static_cast<ALsizei>(clampu64((DataSize64 + mIncrement-1)/mIncrement, 1, BUFFERSIZE)); } ALsizei SampleConverter::convert(const ALvoid **src, ALsizei *srcframes, ALvoid *dst, ALsizei dstframes) { const ALsizei SrcFrameSize{static_cast<ALsizei>(mChan.size()) * mSrcTypeSize}; const ALsizei DstFrameSize{static_cast<ALsizei>(mChan.size()) * mDstTypeSize}; const ALsizei increment{mIncrement}; auto SamplesIn = static_cast<const al::byte*>(*src); ALsizei NumSrcSamples{*srcframes}; FPUCtl mixer_mode{}; ALsizei pos{0}; while(pos < dstframes && NumSrcSamples > 0) { ALint prepcount{mSrcPrepCount}; if(prepcount < 0) { /* Negative prepcount means we need to skip that many input samples. */ if(-prepcount >= NumSrcSamples) { mSrcPrepCount = prepcount + NumSrcSamples; NumSrcSamples = 0; break; } SamplesIn += SrcFrameSize*-prepcount; NumSrcSamples += prepcount; mSrcPrepCount = 0; continue; } ALint toread{mini(NumSrcSamples, BUFFERSIZE - MAX_RESAMPLE_PADDING*2)}; if(prepcount < MAX_RESAMPLE_PADDING*2 && MAX_RESAMPLE_PADDING*2 - prepcount >= toread) { /* Not enough input samples to generate an output sample. Store * what we're given for later. */ for(size_t chan{0u};chan < mChan.size();chan++) LoadSamples(&mChan[chan].PrevSamples[prepcount], SamplesIn + mSrcTypeSize*chan, mChan.size(), mSrcType, toread); mSrcPrepCount = prepcount + toread; NumSrcSamples = 0; break; } ALfloat *RESTRICT SrcData{mSrcSamples}; ALfloat *RESTRICT DstData{mDstSamples}; ALsizei DataPosFrac{mFracOffset}; auto DataSize64 = static_cast<uint64_t>(prepcount); DataSize64 += toread; DataSize64 -= MAX_RESAMPLE_PADDING*2; DataSize64 <<= FRACTIONBITS; DataSize64 -= DataPosFrac; /* If we have a full prep, we can generate at least one sample. */ auto DstSize = static_cast<ALsizei>( clampu64((DataSize64 + increment-1)/increment, 1, BUFFERSIZE)); DstSize = mini(DstSize, dstframes-pos); for(size_t chan{0u};chan < mChan.size();chan++) { const al::byte *SrcSamples{SamplesIn + mSrcTypeSize*chan}; al::byte *DstSamples = static_cast<al::byte*>(dst) + mDstTypeSize*chan; /* Load the previous samples into the source data first, then the * new samples from the input buffer. */ std::copy_n(mChan[chan].PrevSamples, prepcount, SrcData); LoadSamples(SrcData + prepcount, SrcSamples, mChan.size(), mSrcType, toread); /* Store as many prep samples for next time as possible, given the * number of output samples being generated. */ ALsizei SrcDataEnd{(DstSize*increment + DataPosFrac)>>FRACTIONBITS}; if(SrcDataEnd >= prepcount+toread) std::fill(std::begin(mChan[chan].PrevSamples), std::end(mChan[chan].PrevSamples), 0.0f); else { size_t len = mini(MAX_RESAMPLE_PADDING*2, prepcount+toread-SrcDataEnd); std::copy_n(SrcData+SrcDataEnd, len, mChan[chan].PrevSamples); std::fill(std::begin(mChan[chan].PrevSamples)+len, std::end(mChan[chan].PrevSamples), 0.0f); } /* Now resample, and store the result in the output buffer. */ const ALfloat *ResampledData{mResample(&mState, SrcData+MAX_RESAMPLE_PADDING, DataPosFrac, increment, DstData, DstSize)}; StoreSamples(DstSamples, ResampledData, mChan.size(), mDstType, DstSize); } /* Update the number of prep samples still available, as well as the * fractional offset. */ DataPosFrac += increment*DstSize; mSrcPrepCount = mini(prepcount + toread - (DataPosFrac>>FRACTIONBITS), MAX_RESAMPLE_PADDING*2); mFracOffset = DataPosFrac & FRACTIONMASK; /* Update the src and dst pointers in case there's still more to do. */ SamplesIn += SrcFrameSize*(DataPosFrac>>FRACTIONBITS); NumSrcSamples -= mini(NumSrcSamples, (DataPosFrac>>FRACTIONBITS)); dst = static_cast<al::byte*>(dst) + DstFrameSize*DstSize; pos += DstSize; } *src = SamplesIn; *srcframes = NumSrcSamples; return pos; } ChannelConverterPtr CreateChannelConverter(DevFmtType srcType, DevFmtChannels srcChans, DevFmtChannels dstChans) { if(srcChans != dstChans && !((srcChans == DevFmtMono && dstChans == DevFmtStereo) || (srcChans == DevFmtStereo && dstChans == DevFmtMono))) return nullptr; return al::make_unique<ChannelConverter>(srcType, srcChans, dstChans); } void ChannelConverter::convert(const ALvoid *src, ALfloat *dst, ALsizei frames) const { if(mSrcChans == DevFmtStereo && mDstChans == DevFmtMono) { switch(mSrcType) { #define HANDLE_FMT(T) case T: Stereo2Mono<T>(dst, src, frames); break HANDLE_FMT(DevFmtByte); HANDLE_FMT(DevFmtUByte); HANDLE_FMT(DevFmtShort); HANDLE_FMT(DevFmtUShort); HANDLE_FMT(DevFmtInt); HANDLE_FMT(DevFmtUInt); HANDLE_FMT(DevFmtFloat); #undef HANDLE_FMT } } else if(mSrcChans == DevFmtMono && mDstChans == DevFmtStereo) { switch(mSrcType) { #define HANDLE_FMT(T) case T: Mono2Stereo<T>(dst, src, frames); break HANDLE_FMT(DevFmtByte); HANDLE_FMT(DevFmtUByte); HANDLE_FMT(DevFmtShort); HANDLE_FMT(DevFmtUShort); HANDLE_FMT(DevFmtInt); HANDLE_FMT(DevFmtUInt); HANDLE_FMT(DevFmtFloat); #undef HANDLE_FMT } } else LoadSamples(dst, src, 1u, mSrcType, frames*ChannelsFromDevFmt(mSrcChans, 0)); }
36.243968
112
0.6553
intensifier
1fa651fd76841758e078bce56db748f2b9794d19
901
cpp
C++
OJ/vol127/UVa12709.cpp
jennygaz/competitive
2807b0fbd2eaaca8ba618f03b1e62c0241849e6c
[ "MIT" ]
null
null
null
OJ/vol127/UVa12709.cpp
jennygaz/competitive
2807b0fbd2eaaca8ba618f03b1e62c0241849e6c
[ "MIT" ]
null
null
null
OJ/vol127/UVa12709.cpp
jennygaz/competitive
2807b0fbd2eaaca8ba618f03b1e62c0241849e6c
[ "MIT" ]
null
null
null
/* UVa 12709 - Falling Ants */ /* Solution: Sort by H then by the product LW */ /* by jennyga */ #include <iostream> #include <vector> #include <algorithm> #include <tuple> #include <functional> using namespace std; constexpr int MAXN = 110; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n {}; vector<tuple<int, int, int>> data( MAXN ); while( cin >> n, n ){ int L {}, W {}, H {}; for( int i = 0; i < n; ++ i ){ cin >> L >> W >> H; data[i] = { L, W, H }; } sort( data.begin(), data.begin() + n, []( tuple<int, int, int>& lhs, tuple<int, int, int>& rhs ) -> bool { if( get<2>( lhs ) != get<2>( rhs ) ) return get<2>( lhs ) > get<2>( rhs ); else return get<0>( lhs ) * get<1>( lhs ) > get<0>( rhs ) * get<1>( rhs ); } ); cout << get<0>( data[0] ) * get<1>( data[0] ) * get<2>( data[0] ) << '\n'; } return 0; }
25.027778
79
0.513873
jennygaz
1fa78f043c98ebdfff8814f34733c311bc583b2a
8,334
cpp
C++
demos/cocos2d-x-3.2/Classes/HelloWorldScene.cpp
silwings/DragonBonesCPP
8c1003875f78d8feba49fd30ada3196db9afdff1
[ "MIT" ]
null
null
null
demos/cocos2d-x-3.2/Classes/HelloWorldScene.cpp
silwings/DragonBonesCPP
8c1003875f78d8feba49fd30ada3196db9afdff1
[ "MIT" ]
null
null
null
demos/cocos2d-x-3.2/Classes/HelloWorldScene.cpp
silwings/DragonBonesCPP
8c1003875f78d8feba49fd30ada3196db9afdff1
[ "MIT" ]
null
null
null
#include "HelloWorldScene.h" USING_NS_CC; using namespace dragonBones; Scene* HelloWorld::createScene() { // 'scene' is an autorelease object auto scene = Scene::create(); // 'layer' is an autorelease object auto layer = HelloWorld::create(); // add layer as a child to scene scene->addChild(layer); // return the scene return scene; } void HelloWorld::updateHandler(float passTime) { dragonBones::WorldClock::clock.advanceTime(passTime); Rect rect = _armature->getBoundingBox(); Vec2 vec2s[4]; vec2s[0].x = rect.getMidX(); vec2s[0].y = rect.getMidY(); vec2s[1].x = rect.getMidX(); vec2s[1].y = rect.getMaxY(); vec2s[2].x = rect.getMaxX(); vec2s[2].y = rect.getMaxY(); vec2s[3].x = rect.getMaxX(); vec2s[3].y = rect.getMidY(); // log("rect = x=%f, y=%f, w=%f, h=%f", rect.origin.x, rect.origin.y, rect.size.width, rect.size.height); // log("rect: left=%f, right=%f, top=%f, bottom=%f", rect.getMinX(), rect.getMaxX(), rect.getMaxY(), rect.getMinY()); drawnode->clear(); drawnode->drawPolygon(vec2s, 4, Color4F::WHITE, 1, Color4F::RED); } // on "init" you need to initialize your instance void HelloWorld::demoInit() { ////////////////////////////// Size visibleSize = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); ///////////////////////////// // 2. add a menu item with "X" image, which is clicked to quit the program // you may modify it. // add a "close" icon to exit the progress. it's an autorelease object auto closeItem = MenuItemImage::create( "CloseNormal.png", "CloseSelected.png", CC_CALLBACK_1(HelloWorld::menuCloseCallback, this)); closeItem->setPosition(origin.x + visibleSize.width - closeItem->getContentSize().width/2 , origin.y + closeItem->getContentSize().height/2); // create menu, it's an autorelease object auto menu = Menu::create(closeItem, NULL); menu->setPosition(Vec2::ZERO); this->addChild(menu, 1); ///////////////////////////// // 3. add your codes below... // add a label shows "Hello World" // create and initialize a label auto label = LabelTTF::create("Hello World", "Arial", 24); // position the label on the center of the screen label->setPosition(origin.x + visibleSize.width/2, origin.y + visibleSize.height - label->getContentSize().height); // add the label as a child to this layer this->addChild(label, 1); // factory DBCCFactory::getInstance()->loadDragonBonesData("armatures/Knight/skeleton.xml"); DBCCFactory::getInstance()->loadTextureAtlas("armatures/Knight/texture.xml"); // DBCCFactory::getInstance()->loadDragonBonesData("leiyanfentian/leiyanfentian_skeleton.xml"); // DBCCFactory::getInstance()->loadTextureAtlas("leiyanfentian/leiyanfentian.xml"); // armature auto armature = (dragonBones::DBCCArmature *)(dragonBones::DBCCFactory::factory.buildArmature("main", "zhugeliang")); _armature = dragonBones::DBCCArmatureNode::create(armature); drawnode = DrawNode::create(); //_armature->addChild(drawnode, -1); this->addChild(drawnode); _armature->getAnimation()->gotoAndPlay("walk"); _armature->setPosition(480.f, 200.f); this->addChild(_armature); // armature event auto movementHandler = std::bind(&HelloWorld::armAnimationHandler, this, std::placeholders::_1); auto frameHandler = std::bind(&HelloWorld::armAnimationHandler, this, std::placeholders::_1); _armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::START, movementHandler); _armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::FADE_IN, movementHandler); _armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::COMPLETE, movementHandler); _armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::LOOP_COMPLETE, movementHandler); _armature->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::ANIMATION_FRAME_EVENT, frameHandler); // update dragonBones::WorldClock::clock.add(_armature->getArmature()); // key cocos2d::EventListenerKeyboard *listener = cocos2d::EventListenerKeyboard::create(); listener->onKeyPressed = [&](cocos2d::EventKeyboard::KeyCode keyCode, cocos2d::Event *event){ log("key pressed code=%d", keyCode); switch (keyCode) { case cocos2d::EventKeyboard::KeyCode::KEY_A: //_armature->getAnimation()->gotoAndPlay("wait"); _armature->getAnimation()->gotoAndPlay("skill1"); break; case cocos2d::EventKeyboard::KeyCode::KEY_S: _armature->getAnimation()->gotoAndPlay("wait"); break; case cocos2d::EventKeyboard::KeyCode::KEY_D: _armature->getAnimation()->gotoAndPlay("atk"); _curAction = "atk"; _jump2Wait = true; break; case cocos2d::EventKeyboard::KeyCode::KEY_F: _armature->getAnimation()->gotoAndPlay("beAtk"); _curAction = "beAtk"; _jump2Wait = true; break; case cocos2d::EventKeyboard::KeyCode::KEY_W: _armature->getAnimation()->gotoAndPlay("skill3"); _curAction = "skill3"; auto node = createEffect("leiyanfentian", "skill_self_1"); _armature->addChild(node); _jump2Wait = true; break; } }; //listener->onKeyReleased = std::bind(&DemoKnight::keyReleaseHandler, this, std::placeholders::_1, std::placeholders::_2); this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this); } void HelloWorld::armAnimationHandler(cocos2d::EventCustom *event) { dragonBones::EventData *eventData = (dragonBones::EventData *)(event->getUserData()); switch (eventData->getType()) { case dragonBones::EventData::EventType::START: cocos2d::log("animation start: %s %f", eventData->animationState->name.c_str(), utils::gettime()); break; case dragonBones::EventData::EventType::FADE_IN: cocos2d::log("animation fade in: %s %f", eventData->animationState->name.c_str(), utils::gettime()); break; case dragonBones::EventData::EventType::COMPLETE: cocos2d::log("animation complete: %s %f", eventData->animationState->name.c_str(), utils::gettime()); if(_jump2Wait && eventData->animationState->name == _curAction) { _jump2Wait = false; _armature->getAnimation()->gotoAndPlay("wait"); } break; case dragonBones::EventData::EventType::LOOP_COMPLETE: cocos2d::log("animation loop complete: %s %f", eventData->animationState->name.c_str(), utils::gettime()); if(_jump2Wait && eventData->animationState->name == _curAction) { _jump2Wait = false; _armature->getAnimation()->gotoAndPlay("wait"); } break; case dragonBones::EventData::EventType::ANIMATION_FRAME_EVENT: cocos2d::log("animation frame event: %s %s %f", eventData->animationState->name.c_str(), eventData->frameLabel, utils::gettime()); break; } } dragonBones::DBCCArmatureNode* HelloWorld::createEffect(std::string dragonbones, std::string armature) { auto effect = (dragonBones::DBCCArmature *)(dragonBones::DBCCFactory::factory.buildArmature(armature, "", "", dragonbones, dragonbones)); effect->getAnimation()->gotoAndPlay("mv"); auto node = dragonBones::DBCCArmatureNode::create(effect); dragonBones::WorldClock::clock.add(effect); auto handler = [](cocos2d::EventCustom *event){ dragonBones::EventData *eventData = (dragonBones::EventData *)(event->getUserData()); dragonBones::WorldClock::clock.remove(eventData->armature); auto node1 = static_cast<Node*>(eventData->armature->getDisplay()); //node1->getParent()->removeFromParent(); node1->setVisible(false); eventData->armature->getAnimation()->stop(); }; node->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::COMPLETE, handler); node->getCCEventDispatcher()->addCustomEventListener(dragonBones::EventData::LOOP_COMPLETE, handler); return node; } void HelloWorld::menuCloseCallback(Ref* pSender) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) MessageBox("You pressed the close button. Windows Store Apps do not implement a close button.","Alert"); return; #endif Director::getInstance()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif }
37.881818
138
0.695944
silwings
1fa7c79894bde96bf431ecc48a8e66be03076186
4,899
cpp
C++
Core/third_party/JavaScriptCore/bytecode/ArithProfile.cpp
InfiniteSynthesis/lynx-native
022e277ee6767f5b668269a17b1679072cf7c3d6
[ "MIT" ]
677
2017-09-23T16:03:12.000Z
2022-03-26T08:32:10.000Z
Core/third_party/JavaScriptCore/bytecode/ArithProfile.cpp
InfiniteSynthesis/lynx-native
022e277ee6767f5b668269a17b1679072cf7c3d6
[ "MIT" ]
9
2020-04-18T18:47:18.000Z
2020-04-18T18:52:41.000Z
Core/third_party/JavaScriptCore/bytecode/ArithProfile.cpp
InfiniteSynthesis/lynx-native
022e277ee6767f5b668269a17b1679072cf7c3d6
[ "MIT" ]
92
2017-09-21T14:21:27.000Z
2022-03-25T13:29:42.000Z
/* * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ArithProfile.h" #include "CCallHelpers.h" #include "JSCInlines.h" namespace JSC { #if ENABLE(JIT) void ArithProfile::emitObserveResult(CCallHelpers& jit, JSValueRegs regs, TagRegistersMode mode) { if (!shouldEmitSetDouble() && !shouldEmitSetNonNumber()) return; CCallHelpers::Jump isInt32 = jit.branchIfInt32(regs, mode); CCallHelpers::Jump notDouble = jit.branchIfNotDoubleKnownNotInt32(regs, mode); emitSetDouble(jit); CCallHelpers::Jump done = jit.jump(); notDouble.link(&jit); emitSetNonNumber(jit); done.link(&jit); isInt32.link(&jit); } bool ArithProfile::shouldEmitSetDouble() const { uint32_t mask = ArithProfile::Int32Overflow | ArithProfile::Int52Overflow | ArithProfile::NegZeroDouble | ArithProfile::NonNegZeroDouble; return (m_bits & mask) != mask; } void ArithProfile::emitSetDouble(CCallHelpers& jit) const { if (shouldEmitSetDouble()) jit.or32(CCallHelpers::TrustedImm32(ArithProfile::Int32Overflow | ArithProfile::Int52Overflow | ArithProfile::NegZeroDouble | ArithProfile::NonNegZeroDouble), CCallHelpers::AbsoluteAddress(addressOfBits())); } bool ArithProfile::shouldEmitSetNonNumber() const { uint32_t mask = ArithProfile::NonNumber; return (m_bits & mask) != mask; } void ArithProfile::emitSetNonNumber(CCallHelpers& jit) const { if (shouldEmitSetNonNumber()) jit.or32(CCallHelpers::TrustedImm32(ArithProfile::NonNumber), CCallHelpers::AbsoluteAddress(addressOfBits())); } #endif // ENABLE(JIT) } // namespace JSC namespace WTF { using namespace JSC; void printInternal(PrintStream& out, const ArithProfile& profile) { const char* separator = ""; out.print("Result:<"); if (!profile.didObserveNonInt32()) { out.print("Int32"); separator = "|"; } else { if (profile.didObserveNegZeroDouble()) { out.print(separator, "NegZeroDouble"); separator = "|"; } if (profile.didObserveNonNegZeroDouble()) { out.print(separator, "NonNegZeroDouble"); separator = "|"; } if (profile.didObserveNonNumber()) { out.print(separator, "NonNumber"); separator = "|"; } if (profile.didObserveInt32Overflow()) { out.print(separator, "Int32Overflow"); separator = "|"; } if (profile.didObserveInt52Overflow()) { out.print(separator, "Int52Overflow"); separator = "|"; } } if (profile.tookSpecialFastPath()) out.print(separator, "Took special fast path."); out.print(">"); out.print(" LHS ObservedType:<"); out.print(profile.lhsObservedType()); out.print("> RHS ObservedType:<"); out.print(profile.rhsObservedType()); out.print(">"); out.print(" LHS ResultType:<", RawPointer(bitwise_cast<void*>(static_cast<uintptr_t>(profile.lhsResultType().bits())))); out.print("> RHS ResultType:<", RawPointer(bitwise_cast<void*>(static_cast<uintptr_t>(profile.rhsResultType().bits())))); out.print(">"); } void printInternal(PrintStream& out, const JSC::ObservedType& observedType) { const char* separator = ""; if (observedType.sawInt32()) { out.print(separator, "Int32"); separator = "|"; } if (observedType.sawNumber()) { out.print(separator, "Number"); separator = "|"; } if (observedType.sawNonNumber()) { out.print(separator, "NonNumber"); separator = "|"; } } } // namespace WTF
34.020833
215
0.679118
InfiniteSynthesis
1fabacd0fa188edfceda3c63aa7473133957177a
414
cpp
C++
Sail/src/Sail/api/GraphicsAPI.cpp
Piratkopia13/MasterThesisIntersectionVisualizer
08b802a3b3fe3761c9ba7ac5a650cbca89887df8
[ "MIT" ]
1
2020-09-03T09:53:45.000Z
2020-09-03T09:53:45.000Z
Sail/src/Sail/api/GraphicsAPI.cpp
aaron-foster-wallace/MasterThesisIntersectionVisualizer
08b802a3b3fe3761c9ba7ac5a650cbca89887df8
[ "MIT" ]
null
null
null
Sail/src/Sail/api/GraphicsAPI.cpp
aaron-foster-wallace/MasterThesisIntersectionVisualizer
08b802a3b3fe3761c9ba7ac5a650cbca89887df8
[ "MIT" ]
1
2021-01-31T05:27:36.000Z
2021-01-31T05:27:36.000Z
#include "pch.h" #include "GraphicsAPI.h" GraphicsAPI::GraphicsAPI() { EventSystem::getInstance()->subscribeToEvent(Event::WINDOW_RESIZE, this); } GraphicsAPI::~GraphicsAPI() { EventSystem::getInstance()->unsubscribeFromEvent(Event::WINDOW_RESIZE, this); } bool GraphicsAPI::onEvent(Event& event) { EventHandler::HandleType<WindowResizeEvent>(event, SAIL_BIND_EVENT(&GraphicsAPI::onResize)); return true; }
25.875
93
0.768116
Piratkopia13
1fabbc6ab4875b5d144177f4fbb4d30025b60936
23,874
hpp
C++
graehl/shared/tree.hpp
graehl/carmel
4a5d0990a17d0d853621348272b2f05a0dab3450
[ "Apache-2.0" ]
29
2015-01-05T16:52:53.000Z
2022-02-14T07:36:10.000Z
graehl/shared/tree.hpp
graehl/carmel
4a5d0990a17d0d853621348272b2f05a0dab3450
[ "Apache-2.0" ]
1
2016-04-18T17:20:37.000Z
2016-04-23T07:36:38.000Z
graehl/shared/tree.hpp
graehl/carmel
4a5d0990a17d0d853621348272b2f05a0dab3450
[ "Apache-2.0" ]
7
2015-06-11T14:48:13.000Z
2017-08-12T16:06:19.000Z
// Copyright 2014 Jonathan Graehl - http://graehl.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. // the usual recursive label+list of children trees #ifndef GRAEHL_SHARED__TREE_HPP #define GRAEHL_SHARED__TREE_HPP #define GRAEHL_TREE_UNARY_OPTIMIZATION namespace graehl { typedef short rank_type; // (rank=#children) -1 = any rank, -2 = any tree ... (can't be unsigned type) } #ifndef SATISFY_VALGRIND //FIXME: make SATISFY_VALGRIND + GRAEHL_TREE_UNARY_OPTIMIZATION compile // program is still correct w/o this defined, but you get bogus valgrind warnings if not //# define SATISFY_VALGRIND #endif #include <iostream> #include <graehl/shared/myassert.h> #include <graehl/shared/genio.h> #include <graehl/shared/word_spacer.hpp> //#include <vector> #include <graehl/shared/dynamic_array.hpp> #include <algorithm> #ifdef USE_LAMBDA #include <boost/lambda/lambda.hpp> namespace lambda = boost::lambda; #endif #include <functional> //#include <graehl/shared/config.h> #include <graehl/shared/graphviz.hpp> //#include "symbol.hpp" #include <graehl/shared/byref.hpp> #include <graehl/shared/stream_util.hpp> #ifdef GRAEHL_TEST #include <graehl/shared/test.hpp> #include <graehl/shared/string_to.hpp> #endif //template <class L, class A> struct Tree; // Tree owns its own child pointers list but not trees it points to! - routines for creating trees through new and recurisvely deleting are provided outside the class. Reading from a stream does create children using new. finish with dealloc_recursive() // alloc builds child vectors on heap. // FIXME: need two allocators (or always rebind/copy from one) instead of just new/deleting self_type ... that is, shared_tree nodes are coming off usual heap, but we act interested in how we get the child pointer vectors. really, if you care about one, you probably care about the other. namespace graehl { template <class L, class Alloc = std::allocator<void *> > struct shared_tree : private Alloc { typedef shared_tree self_type; typedef L Label; Label label; rank_type rank; friend inline void swap(self_type &a, self_type &b) { using namespace std; swap(a.label, b.label); rank_type r = b.rank; b.rank = a.rank; a.rank = r; self_type **children = b.c.children; b.c.children = a.c.children; a.c.children = children; // swap(a.rank,b.rank); // swap(a.c.children,b.c.children); //FIXME: diff pointer types? then detect based on rank } protected: //shared_tree(const self_type &t) : {} union children_or_child { self_type **children; self_type *child; }; children_or_child c; public: bool is_leaf() const { return rank==0; } template <class T> struct related_child { self_type dummy; T data; related_child() {} }; template<class T> T &leaf_data() { Assert(rank==0); Assert(sizeof(T) <= sizeof(c.children)); // return *(reinterpret_cast<T*>(&children)); return *(T *)(related_child<T>*)&c.child; // C99 aliasing is ok with this because we cast to a struct that relates T* and self_type*, or so I'm told } template<class T> const T &leaf_data() const { return const_cast<self_type *>(this)->leaf_data<T>(); } /* int &leaf_data_int() { Assert(rank==0); return *(reinterpret_cast<int *>(&children)); } void * leaf_data() const { return const_cast<self_type *>(this)->leaf_data(); } int leaf_data_int() const { return const_cast<self_type *>(this)->leaf_data(); } */ rank_type size() const { return rank; } shared_tree() : rank(0) #ifdef SATISFY_VALGRIND , children(0) #endif {} explicit shared_tree (const Label &l) : label(l), rank(0) #ifdef SATISFY_VALGRIND , children(0) #endif { } shared_tree (const Label &l, rank_type n) : label(l) { alloc(n); } explicit shared_tree (std::string const& s) : rank(0) #ifdef SATISFY_VALGRIND , children(0) #endif { std::istringstream ic(s); ic >> *this; } void alloc(rank_type _rank) { rank = _rank; #ifdef GRAEHL_TREE_UNARY_OPTIMIZATION if (rank>1) #else if (rank) #endif c.children = (self_type **)this->allocate(rank); #ifdef SATISFY_VALGRIND else children = 0; #endif } template <class to_type> void copy_deep(to_type &to) const { to.clear(); to.label = label; to.alloc(rank); iterator t = to.begin(); for (const_iterator i = begin(), e = end(); i!=e; ++i, ++t) { (*i)->copy_deep(*(*t = new to_type)); } } shared_tree(rank_type _rank) { alloc(_rank); } void dump_children() { dealloc(); } void create_children(unsigned n) { alloc(n); } void set_rank(unsigned n) { dealloc(); alloc(n); } void clear() { dealloc(); } void dealloc() { #ifdef GRAEHL_TREE_UNARY_OPTIMIZATION if (rank>1) #else if (rank) #endif this->deallocate((void **)c.children, rank); rank = 0; } void dealloc_recursive(); ~shared_tree() { dealloc(); } // STL container stuff typedef self_type *value_type; typedef value_type *iterator; typedef const self_type *const_value_type; typedef const const_value_type *const_iterator; value_type & child(rank_type i) { #ifdef GRAEHL_TREE_UNARY_OPTIMIZATION if (rank == 1) { Assert(i==0); return c.child; } #endif return c.children[i]; } value_type & child(rank_type i) const { return const_cast<self_type*>(this)->child(i); } value_type & operator [](rank_type i) { return child(i); } value_type & operator [](rank_type i) const { return child(i); } iterator begin() { #ifdef GRAEHL_TREE_UNARY_OPTIMIZATION if (rank == 1) return &c.child; else #endif return c.children; } iterator end() { #ifdef GRAEHL_TREE_UNARY_OPTIMIZATION if (rank == 1) return &c.child+1; else #endif return c.children+rank; } const_iterator begin() const { return const_cast<self_type *>(this)->begin(); } const_iterator end() const { return const_cast<self_type *>(this)->end(); } template <class T> friend size_t tree_count(const T *t); template <class T> friend size_t tree_height(const T *t); //height = maximum length path from root size_t height() const { return tree_height(this); } size_t count_nodes() const { return tree_count(this); } template <class charT, class Traits> std::ios_base::iostate print(std::basic_ostream<charT, Traits>& o, bool lisp_style = true) const { if (!lisp_style || !rank) o << label; if (rank) { o << '('; word_spacer sp; if (lisp_style) o << sp << label; for (const_iterator i = begin(), e = end(); i!=e; ++i) { o << sp; (*i)->print(o, lisp_style); } o << ')'; } return GENIOGOOD; } template <class O, class Writer> void print_writer(O& o, Writer const& w, bool lisp_style = true) const { if (!lisp_style || !rank) w(o, label); if (rank) { o << '('; word_spacer sp; if (lisp_style) { o << sp; w(o, label); } for (const_iterator i = begin(), e = end(); i!=e; ++i) { o << sp; (*i)->print_writer(o, w, lisp_style); } o << ')'; } } /* template <class charT, class Traits, class Writer> std::ios_base::iostate print_graphviz(std::basic_ostream<charT,Traits>& o,Writer writer, const char *treename="T") const { o << "digraph "; out_quote(o,treename); o << "{\n"; print_graphviz_rec(o,writer,0); o << "}\n"; return GENIOGOOD; } template <class charT, class Traits, class Writer> void print_graphviz_rec(std::basic_ostream<charT,Traits>& o,Writer writer,unsigned node_no) const { for (const_iterator i=begin(),e=end();i!=e;++i) { i->print_graphviz_rec(o,writer,++node_no); } } */ typedef int style_type; BOOST_STATIC_CONSTANT(style_type, UNKNOWN = 0); BOOST_STATIC_CONSTANT(style_type, PAREN_FIRST = 1); BOOST_STATIC_CONSTANT(style_type, HEAD_FIRST = 2); //template <class T, class charT, class Traits> friend template <class charT, class Traits, class Reader> static self_type *read_tree(std::basic_istream<charT, Traits>& in, Reader r, style_type style = UNKNOWN) { self_type *ret = new self_type; std::ios_base::iostate err = std::ios_base::goodbit; if (ret->read(in, r, style)) in.setstate(err); if (!in.good()) { ret->dealloc_recursive(); return NULL; } return ret; } template <class charT, class Traits> static self_type *read_tree(std::basic_istream<charT, Traits>& in) { return read_tree(in, DefaultReader<Label>()); } // template <class T> friend void delete_tree(T *); #ifdef DEBUG_TREEIO #define DBTREEIO(a) DBP(a) #else #define DBTREEIO(a) #endif // this method is supposed to recognize two types of trees: one where the initial is (head ....) and the other which is head(...) ... (1 (2 3)) vs. 1(2 3) - note that this is shorthand for (1 ((2) (3))) vs. 1(2() 3()) (leaves have 0 children). also, comma is allowed a separator as well as space. this means that labels can't contain '(),' ... also, we don't like 1 (2 3) ... this would parse as the tree 1, not 1(2 3) (i.e. no space between label and '(') // Reader passed by value, so can't be stateful (unless itself is a pointer to shared state) template <class charT, class Traits, class Reader> std::ios_base::iostate read(std::basic_istream<charT, Traits>& in, Reader read, style_type style = UNKNOWN) { char c; rank = 0; dynamic_array<self_type *> in_children; try { EXPECTI_COMMENT_FIRST(in>>c); if (c == '(') { if (style==HEAD_FIRST) return GENIOBAD; style = PAREN_FIRST; EXPECTI_COMMENT_FIRST(deref(read)(in, label)); DBTREEIO(label); } else { in.unget(); EXPECTI_COMMENT_FIRST(deref(read)(in, label)); DBTREEIO(label); if (style==PAREN_FIRST) { // then must be leaf goto good; } else style = HEAD_FIRST; I_COMMENT(in.get(c)); // to disambiguate (1 (2) 3 (4)) vs. 1( 2 3(4)) ... should be (1 2 3 4) and not (1 2 (3 4)) ... in other words open paren must follow root label. but now we allow space by fixing style at root if (in.eof()) // since c!='(' before in>>c, can almost not test for this - but don't want to unget() if nothing was read. goto good; if (!in) goto fail; if (c!='(') { in.unget(); goto good; } } //POST: read a '(' and a label (in either order) DBTREEIO('('); for (;;) { EXPECTI_COMMENT(in>>c); if (c == ',') EXPECTI_COMMENT(in>>c); if (c==')') { DBTREEIO(')'); break; } in.unget(); self_type *in_child = read_tree(in, read, style); if (in_child) { DBTREEIO('!'); in_children.push_back(in_child); } else goto fail; } dealloc(); alloc((rank_type)in_children.size()); //copy(in_children.begin(),in_children.end(),begin()); in_children.moveto(begin()); goto good; } catch(...) { goto fail; } fail: for (typename dynamic_array<self_type *>::iterator i = in_children.begin(), end = in_children.end(); i!=end; ++i) (*i)->dealloc_recursive(); return GENIOBAD; good: DBTREEIO(*this); return GENIOGOOD; } TO_OSTREAM_PRINT template <class charT, class Traits> std::ios_base::iostate read(std::basic_istream<charT, Traits>& in) { return read(in, DefaultReader<L>()); } void set_no_children() { for (iterator i = begin(), e = end(); i!=e; ++i) *i = NULL; } FROM_ISTREAM_READ }; template <class L, class Alloc = std::allocator<void *> > struct tree : public shared_tree<L, Alloc> { typedef tree self_type; typedef shared_tree<L, Alloc> shared; tree() {} explicit tree(L const& l) : shared(l) {} explicit tree(std::string const& c) : shared(c) {} tree(shared const& o) { o.copy_deep(*this); } tree(shared const& o, bool /*move construct*/) { swap(*(shared *)this, o); } tree(self_type const& o) { o.copy_deep(*this); } tree(rank_type rank) : shared(rank) { this->set_no_children(); } tree(L const&l, rank_type r) : shared(l, r) { this->set_no_children(); } ~tree() { clear(); } typedef self_type *value_type; typedef value_type *iterator; typedef const self_type *const_value_type; typedef const const_value_type *const_iterator; void operator = (self_type &o) { o.clear(); this->copy_deep(o); } value_type &child(rank_type i) { return (value_type &)shared::child(i); } value_type const&child(rank_type i) const { return (value_type const&)shared::child(i); } iterator begin() { return (iterator)shared::begin(); } iterator end() { return (iterator)shared::end(); } const_iterator begin() const { return (const_iterator)shared::begin(); } const_iterator end() const { return (const_iterator)shared::end(); } void clear() { for (iterator i = begin(), e = end(); i!=e; ++i) if (*i) delete *i; this->dealloc(); } TO_OSTREAM_PRINT template <class charT, class Traits, class Reader> std::ios_base::iostate read(std::basic_istream<charT, Traits>& in, Reader read) { clear(); return shared::read(in, read); } template <class charT, class Traits> std::ios_base::iostate read(std::basic_istream<charT, Traits>& in) { return read(in, DefaultReader<L>()); } FROM_ISTREAM_READ }; template <class C> void delete_arg(C #ifndef DEBUG const #endif &c) { delete c; #ifdef DEBUG c = NULL; #endif } template <class T, class F> bool tree_visit(T *tree, F func) { if (!deref(func).discover(tree)) return false; for (typename T::iterator i = tree->begin(), end = tree->end(); i!=end; ++i) if (!tree_visit(*i, func)) break; return deref(func).finish(tree); } template <class T, class F> void tree_leaf_visit(T *tree, F func) { if (tree->size()) { for (T *child = tree->begin(), *end = tree->end(); child!=end; ++child) { tree_leaf_visit(child, func); } } else { deref(func)(tree); } } template <class Label, class Labeler = DefaultNodeLabeler<Label> > struct TreeVizPrinter : public GraphvizPrinter { Labeler labeler; typedef shared_tree<Label> T; unsigned samerank; enum make_not_anon_24 {ANY_ORDER = 0, CHILD_ORDER = 1, CHILD_SAMERANK = 2}; TreeVizPrinter(std::ostream &o_, unsigned samerank_ = CHILD_SAMERANK, const std::string &prelude="", const Labeler &labeler_ = Labeler(), const char *graphname="tree") : GraphvizPrinter(o_, prelude, graphname), labeler(labeler_), samerank(samerank_) {} void print(const T &t) { print(t, next_node++); o << std::endl; } void print(const T &t, unsigned parent) { o << " " << parent << " ["; labeler.print(o, t.label); o << "]\n"; if (t.rank) { unsigned child_start = next_node; next_node += t.rank; unsigned child_end = next_node; unsigned child = child_start+1; if (samerank!=ANY_ORDER) if (t.rank > 1) { // ensure left->right order o << "{"; if (samerank==CHILD_SAMERANK) o << "rank=same "; o << child_start; for (; child != child_end; ++child) o << " -> " << child; o << " [style=invis,weight=0.01]}\n"; } child = child_start; for (typename T::const_iterator i = t.begin(), e = t.end(); i!=e; ++i, ++child) { o << " " << parent << " -> " << child; if (samerank==ANY_ORDER) { // o << "[label=" << i-t.begin() << "]"; } o << "\n"; } child = child_start; for (typename T::const_iterator i = t.begin(), e = t.end(); i!=e; ++i, ++child) { print(**i, child); } } } }; struct TreePrinter { std::ostream &o; bool first; TreePrinter(std::ostream &o_):o(o_), first(true) {} template <class T> bool discover(T *t) { if (!first) o<<' '; o<<t->label; if (t->size()) { o << '('; first = true; } return true; } template <class T> bool finish(T *t) { if (t->size()) o << ')'; first = false; return true; } }; template <class T, class F> void postorder(T *tree, F func) { Assert(tree); for (typename T::iterator i = tree->begin(), end = tree->end(); i!=end; ++i) postorder(*i, func); deref(func)(tree); } template <class T, class F> void postorder(const T *tree, F func) { Assert(tree); for (typename T::const_iterator i = tree->begin(), end = tree->end(); i!=end; ++i) postorder(*i, func); deref(func)(tree); } template <class L, class A> void delete_tree(shared_tree<L, A> *tree) { Assert(tree); tree->dealloc_recursive(); // postorder(tree,delete_arg<shared_tree<L,A> *>); } template <class L, class A> void shared_tree<L, A>::dealloc_recursive() { for (iterator i = begin(), e = end(); i!=e; ++i) (*i)->dealloc_recursive(); //delete_tree(*i); //foreach (begin(),end(),delete_tree<self_type>); dealloc(); } template <class T1, class T2> bool tree_equal(const T1& a, const T2& b) { if (a.size() != b.size() || !(a.label == b.label)) return false; typename T2::const_iterator b_i = b.begin(); for (typename T1::const_iterator a_i = a.begin(), a_end = a.end(); a_i!=a_end; ++a_i, ++b_i) if (!(tree_equal(**a_i, **b_i))) return false; return true; } template <class T1, class T2, class P> bool tree_equal(const T1& a, const T2& b, P equal) { if ( (a.size()!=b.size()) || !equal(a, b) ) return false; typename T2::const_iterator b_i = b.begin(); for (typename T1::const_iterator a_i = a.begin(), a_end = a.end(); a_i!=a_end; ++a_i, ++b_i) if (!(tree_equal(**a_i, **b_i, equal))) return false; return true; } template <class T1, class T2> struct label_equal_to { bool operator()(const T1&a, const T2&b) const { return a.label == b.label; } }; template <class T1, class T2> bool tree_contains(const T1& a, const T2& b) { return tree_contains(a, b, label_equal_to<T1, T2>()); } template <class T1, class T2, class P> bool tree_contains(const T1& a, const T2& b, P equal) { if ( !equal(a, b) ) return false; // leaves of b can match interior nodes of a if (!b.size()) return true; if ( a.size()!=b.size()) return false; typename T1::const_iterator a_i = a.begin(); for (typename T2::const_iterator b_end = b.end(), b_i = b.begin(); b_i!=b_end; ++a_i, ++b_i) if (!(tree_contains(**a_i, **b_i, equal))) return false; return true; } template <class L, class A> inline bool operator !=(const shared_tree<L, A> &a, const shared_tree<L, A> &b) { return !(a==b); } template <class L, class A> inline bool operator ==(const shared_tree<L, A> &a, const shared_tree<L, A> &b) { return tree_equal(a, b); } template <class T> struct TreeCount { size_t count; void operator()(const T * tree) { ++count; } TreeCount() : count(0) {} }; #include <boost/ref.hpp> template <class T> size_t tree_count(const T *t) { TreeCount<T> n; postorder(t, boost::ref(n)); return n.count; } //height = maximum length path from root template <class T> size_t tree_height(const T *tree) { Assert(tree); if (!tree->size()) return 0; size_t max_h = 0; for (typename T::const_iterator i = tree->begin(), end = tree->end(); i!=end; ++i) { size_t h = tree_height(*i); if (h>=max_h) max_h = h; } return max_h+1; } template <class T, class O> struct Emitter { O &out; Emitter(O &o) : out(o) {} void operator()(T * tree) { out << tree; } }; template <class T, class O> void emit_postorder(const T *t, O out) { #ifndef USE_LAMBDA Emitter<T, O &> e(out); postorder(t, e); #else postorder(t, o << boost::lambda::_1); #endif } template <class L> tree<L> *new_tree(const L &l) { return new tree<L> (l, 0); } template <class L> tree<L> *new_tree(const L &l, tree<L> *c1) { tree<L> *ret = new tree<L>(l, 1); (*ret)[0] = c1; return ret; } template <class L> tree<L> *new_tree(const L &l, tree<L> *c1, tree<L> *c2) { tree<L> *ret = new tree<L>(l, 2); (*ret)[0] = c1; (*ret)[1] = c2; return ret; } template <class L> tree<L> *new_tree(const L &l, tree<L> *c1, tree<L> *c2, tree<L> *c3) { tree<L> *ret = new tree<L>(l, 3); (*ret)[0] = c1; (*ret)[1] = c2; (*ret)[2] = c3; return ret; } template <class L, class charT, class Traits> tree<L> *read_tree(std::basic_istream<charT, Traits>& in) { tree<L> *ret = new tree<L>; in >> *ret; return ret; //return tree<L>::read_tree(in,DefaultReader<L>()); //return tree<L>::read_tree(in); } #ifdef GRAEHL_TEST template<class T> bool always_equal(const T& a, const T& b) { return true; } BOOST_AUTO_TEST_CASE( test_tree ) { using namespace std; tree<int> a, b, *c, *d, *g = new_tree(1), *h; //string sa="%asdf\n1(%asdf\n 2 %asdf\n,%asdf\n3 (4\n ()\n,\t 5,6))"; string sa="%asdf\n1%asdf\n(%asdf\n 2 %asdf\n,%asdf\n3 (4\n ()\n,\t 5,6))"; //string sa="1(2 3(4 5 6))"; string streeprint="1(2 3(4 5 6))"; string sb="(1 2 (3 4 5 6))"; stringstream o; istringstream isa(sa); isa >> a; o << a; BOOST_CHECK_EQUAL(o.str(), sb); o >> b; ostringstream o2; TreePrinter tp(o2); tree_visit(&a, boost::ref(tp)); BOOST_CHECK_EQUAL(streeprint, o2.str()); c = new_tree(1, new_tree(2), new_tree(3, new_tree(4), new_tree(5), new_tree(6))); d = new_tree(1, new_tree(2), new_tree(3)); istringstream isb(sb); h = read_tree<int>(isb); //h=Tree<int>::read_tree(istringstream(sb),DefaultReader<int>()); BOOST_CHECK(a == a); BOOST_CHECK_EQUAL(a, b); BOOST_CHECK_EQUAL(a, *c); BOOST_CHECK_EQUAL(a, *h); BOOST_CHECK_EQUAL(a.count_nodes(), 6); BOOST_CHECK(tree_equal(a, *c, always_equal<tree<int> >)); BOOST_CHECK(tree_contains(a, *c, always_equal<tree<int> >)); BOOST_CHECK(tree_contains(a, *d, always_equal<tree<int> >)); BOOST_CHECK(tree_contains(a, *d)); BOOST_CHECK(tree_contains(a, b)); BOOST_CHECK(!tree_contains(*d, a)); tree<int> e("1(1(1) 1(1,1,1))"), f("1(1(1()),1)"); BOOST_CHECK(!tree_contains(a, e, always_equal<tree<int> >)); BOOST_CHECK(tree_contains(e, a, always_equal<tree<int> >)); BOOST_CHECK(!tree_contains(f, e)); BOOST_CHECK(tree_contains(e, f)); BOOST_CHECK(tree_contains(a, *g)); BOOST_CHECK(e.height()==2); BOOST_CHECK(f.height()==2); BOOST_CHECK_EQUAL(a.height(), 2); BOOST_CHECK(g->height()==0); delete c; delete d; delete h; delete g; // delete_tree(c); // delete_tree(d); // delete_tree(g); // delete_tree(h); tree<int> k("1"); tree<int> l("1()"); BOOST_CHECK(tree_equal(k, l)); BOOST_CHECK(k.rank==0); BOOST_CHECK(l.rank==0); BOOST_CHECK(l.label==1); string s1="(1 2 (3))"; string s2="(1 2 3)"; tree<int> t1, t2; string_to(s1, t1); string_to(s2, t2); BOOST_CHECK_EQUAL(s2, to_string(t2)); BOOST_CHECK_EQUAL(t1, t2); BOOST_CHECK(tree_equal(t1, t2)); } #endif } #endif
26.206367
460
0.614895
graehl
1faca97e265772e544205831e22d13e0894b3339
83
cpp
C++
cloud9_root/src/third_party/stp/src/main/versionString.cpp
DanielGuoVT/symsc
95b705bd1f4d2863d79866c84fc7ee90aba743cb
[ "Apache-2.0" ]
3
2019-02-12T04:14:39.000Z
2020-11-05T08:46:20.000Z
cloud9_root/src/third_party/stp/src/main/versionString.cpp
DanielGuoVT/symsc
95b705bd1f4d2863d79866c84fc7ee90aba743cb
[ "Apache-2.0" ]
null
null
null
cloud9_root/src/third_party/stp/src/main/versionString.cpp
DanielGuoVT/symsc
95b705bd1f4d2863d79866c84fc7ee90aba743cb
[ "Apache-2.0" ]
null
null
null
#include <string> namespace BEEV{extern const std::string version = " exported ";}
27.666667
64
0.73494
DanielGuoVT
1fb06c4cfc4d1e9dada028d300608be949e698f5
24,451
cc
C++
iree/hal/string_util.cc
OliverScherf/iree
f2d74fd832fa412ce4375661f0c8607a1985b61a
[ "Apache-2.0" ]
null
null
null
iree/hal/string_util.cc
OliverScherf/iree
f2d74fd832fa412ce4375661f0c8607a1985b61a
[ "Apache-2.0" ]
null
null
null
iree/hal/string_util.cc
OliverScherf/iree
f2d74fd832fa412ce4375661f0c8607a1985b61a
[ "Apache-2.0" ]
null
null
null
// Copyright 2019 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "iree/hal/string_util.h" #include <cctype> #include <cinttypes> #include <cstdio> #include <vector> #include "absl/strings/ascii.h" #include "absl/strings/match.h" #include "absl/strings/numbers.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/strip.h" #include "absl/types/span.h" #include "iree/base/api.h" #include "iree/base/tracing.h" #include "iree/hal/buffer.h" #include "iree/hal/buffer_view.h" #include "third_party/half/half.hpp" IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_shape( iree_string_view_t value, iree_host_size_t shape_capacity, iree_hal_dim_t* out_shape, iree_host_size_t* out_shape_rank) { IREE_ASSERT_ARGUMENT(out_shape_rank); *out_shape_rank = 0; auto str_value = absl::string_view(value.data, value.size); if (str_value.empty()) { return iree_ok_status(); // empty shape } std::vector<iree_hal_dim_t> dims; for (auto dim_str : absl::StrSplit(str_value, 'x')) { int dim_value = 0; if (!absl::SimpleAtoi(dim_str, &dim_value)) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "shape[%zu] invalid value '%.*s' of '%.*s'", dims.size(), (int)dim_str.size(), dim_str.data(), (int)value.size, value.data); } if (dim_value < 0) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "shape[%zu] unsupported value %d of '%.*s'", dims.size(), dim_value, (int)value.size, value.data); } dims.push_back(dim_value); } if (out_shape_rank) { *out_shape_rank = dims.size(); } if (dims.size() > shape_capacity) { return iree_status_from_code(IREE_STATUS_OUT_OF_RANGE); } if (out_shape) { std::memcpy(out_shape, dims.data(), dims.size() * sizeof(*out_shape)); } return iree_ok_status(); } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_shape(const iree_hal_dim_t* shape, iree_host_size_t shape_rank, iree_host_size_t buffer_capacity, char* buffer, iree_host_size_t* out_buffer_length) { if (out_buffer_length) { *out_buffer_length = 0; } iree_host_size_t buffer_length = 0; for (iree_host_size_t i = 0; i < shape_rank; ++i) { int n = std::snprintf(buffer ? buffer + buffer_length : nullptr, buffer ? buffer_capacity - buffer_length : 0, (i < shape_rank - 1) ? "%dx" : "%d", shape[i]); if (n < 0) { return iree_make_status(IREE_STATUS_FAILED_PRECONDITION, "snprintf failed to write dimension %zu", i); } else if (buffer && n >= buffer_capacity - buffer_length) { buffer = nullptr; } buffer_length += n; } if (out_buffer_length) { *out_buffer_length = buffer_length; } return buffer ? iree_ok_status() : iree_status_from_code(IREE_STATUS_OUT_OF_RANGE); } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_element_type( iree_string_view_t value, iree_hal_element_type_t* out_element_type) { IREE_ASSERT_ARGUMENT(out_element_type); *out_element_type = IREE_HAL_ELEMENT_TYPE_NONE; auto str_value = absl::string_view(value.data, value.size); iree_hal_numerical_type_t numerical_type = IREE_HAL_NUMERICAL_TYPE_UNKNOWN; if (absl::StartsWith(str_value, "i")) { numerical_type = IREE_HAL_NUMERICAL_TYPE_INTEGER_SIGNED; str_value.remove_prefix(1); } else if (absl::StartsWith(str_value, "u")) { numerical_type = IREE_HAL_NUMERICAL_TYPE_INTEGER_UNSIGNED; str_value.remove_prefix(1); } else if (absl::StartsWith(str_value, "f")) { numerical_type = IREE_HAL_NUMERICAL_TYPE_FLOAT_IEEE; str_value.remove_prefix(1); } else if (absl::StartsWith(str_value, "x") || absl::StartsWith(str_value, "*")) { numerical_type = IREE_HAL_NUMERICAL_TYPE_UNKNOWN; str_value.remove_prefix(1); } else { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "unhandled element type prefix in '%.*s'", (int)value.size, value.data); } uint32_t bit_count = 0; if (!absl::SimpleAtoi(str_value, &bit_count) || bit_count > 0xFFu) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "out of range bit count in '%.*s'", (int)value.size, value.data); } *out_element_type = iree_hal_make_element_type(numerical_type, bit_count); return iree_ok_status(); } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_element_type( iree_hal_element_type_t element_type, iree_host_size_t buffer_capacity, char* buffer, iree_host_size_t* out_buffer_length) { if (out_buffer_length) { *out_buffer_length = 0; } const char* prefix; switch (iree_hal_element_numerical_type(element_type)) { case IREE_HAL_NUMERICAL_TYPE_INTEGER_SIGNED: prefix = "i"; break; case IREE_HAL_NUMERICAL_TYPE_INTEGER_UNSIGNED: prefix = "u"; break; case IREE_HAL_NUMERICAL_TYPE_FLOAT_IEEE: prefix = "f"; break; default: prefix = "*"; break; } int n = std::snprintf( buffer, buffer_capacity, "%s%d", prefix, static_cast<int32_t>(iree_hal_element_bit_count(element_type))); if (n < 0) { return iree_make_status(IREE_STATUS_FAILED_PRECONDITION, "snprintf failed"); } if (out_buffer_length) { *out_buffer_length = n; } return n >= buffer_capacity ? iree_status_from_code(IREE_STATUS_OUT_OF_RANGE) : iree_ok_status(); } // Parses a string of two character pairs representing hex numbers into bytes. static void iree_hal_hex_string_to_bytes(const char* from, uint8_t* to, ptrdiff_t num) { /* clang-format off */ static constexpr char kHexValue[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, // '0'..'9' 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'A'..'F' 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 'a'..'f' 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; /* clang-format on */ for (int i = 0; i < num; i++) { to[i] = (kHexValue[from[i * 2] & 0xFF] << 4) + (kHexValue[from[i * 2 + 1] & 0xFF]); } } // Parses a signal element string, assuming that the caller has validated that // |out_data| has enough storage space for the parsed element data. static iree_status_t iree_hal_parse_element_unsafe( iree_string_view_t data_str, iree_hal_element_type_t element_type, uint8_t* out_data) { switch (element_type) { case IREE_HAL_ELEMENT_TYPE_SINT_8: { int32_t temp = 0; if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), &temp) || temp > INT8_MAX) { return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); } *reinterpret_cast<int8_t*>(out_data) = static_cast<int8_t>(temp); return iree_ok_status(); } case IREE_HAL_ELEMENT_TYPE_UINT_8: { uint32_t temp = 0; if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), &temp) || temp > UINT8_MAX) { return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); } *reinterpret_cast<uint8_t*>(out_data) = static_cast<uint8_t>(temp); return iree_ok_status(); } case IREE_HAL_ELEMENT_TYPE_SINT_16: { int32_t temp = 0; if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), &temp) || temp > INT16_MAX) { return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); } *reinterpret_cast<int16_t*>(out_data) = static_cast<int16_t>(temp); return iree_ok_status(); } case IREE_HAL_ELEMENT_TYPE_UINT_16: { uint32_t temp = 0; if (!absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), &temp) || temp > UINT16_MAX) { return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); } *reinterpret_cast<uint16_t*>(out_data) = static_cast<uint16_t>(temp); return iree_ok_status(); } case IREE_HAL_ELEMENT_TYPE_SINT_32: return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), reinterpret_cast<int32_t*>(out_data)) ? iree_ok_status() : iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); case IREE_HAL_ELEMENT_TYPE_UINT_32: return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), reinterpret_cast<uint32_t*>(out_data)) ? iree_ok_status() : iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); case IREE_HAL_ELEMENT_TYPE_SINT_64: return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), reinterpret_cast<int64_t*>(out_data)) ? iree_ok_status() : iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); case IREE_HAL_ELEMENT_TYPE_UINT_64: return absl::SimpleAtoi(absl::string_view(data_str.data, data_str.size), reinterpret_cast<uint64_t*>(out_data)) ? iree_ok_status() : iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); case IREE_HAL_ELEMENT_TYPE_FLOAT_16: { float temp = 0; if (!absl::SimpleAtof(absl::string_view(data_str.data, data_str.size), &temp)) { return iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); } *reinterpret_cast<uint16_t*>(out_data) = half_float::detail::float2half<std::round_to_nearest>(temp); return iree_ok_status(); } case IREE_HAL_ELEMENT_TYPE_FLOAT_32: return absl::SimpleAtof(absl::string_view(data_str.data, data_str.size), reinterpret_cast<float*>(out_data)) ? iree_ok_status() : iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); case IREE_HAL_ELEMENT_TYPE_FLOAT_64: return absl::SimpleAtod(absl::string_view(data_str.data, data_str.size), reinterpret_cast<double*>(out_data)) ? iree_ok_status() : iree_status_from_code(IREE_STATUS_INVALID_ARGUMENT); default: { // Treat any unknown format as binary. iree_host_size_t element_size = iree_hal_element_byte_count(element_type); if (data_str.size != element_size * 2) { return iree_make_status(IREE_STATUS_INVALID_ARGUMENT, "binary hex element count mismatch: buffer " "length=%zu < expected=%zu", data_str.size, element_size * 2); } iree_hal_hex_string_to_bytes(data_str.data, out_data, element_size); return iree_ok_status(); } } } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_element( iree_string_view_t data_str, iree_hal_element_type_t element_type, iree_byte_span_t data_ptr) { iree_host_size_t element_size = iree_hal_element_byte_count(element_type); if (data_ptr.data_length < element_size) { return iree_make_status( IREE_STATUS_INVALID_ARGUMENT, "output data buffer overflow: data_length=%zu < element_size=%zu", data_ptr.data_length, element_size); } return iree_hal_parse_element_unsafe(data_str, element_type, data_ptr.data); } // Converts a sequence of bytes into hex number strings. static void iree_hal_bytes_to_hex_string(const uint8_t* src, char* dest, ptrdiff_t num) { static constexpr char kHexTable[513] = "000102030405060708090A0B0C0D0E0F" "101112131415161718191A1B1C1D1E1F" "202122232425262728292A2B2C2D2E2F" "303132333435363738393A3B3C3D3E3F" "404142434445464748494A4B4C4D4E4F" "505152535455565758595A5B5C5D5E5F" "606162636465666768696A6B6C6D6E6F" "707172737475767778797A7B7C7D7E7F" "808182838485868788898A8B8C8D8E8F" "909192939495969798999A9B9C9D9E9F" "A0A1A2A3A4A5A6A7A8A9AAABACADAEAF" "B0B1B2B3B4B5B6B7B8B9BABBBCBDBEBF" "C0C1C2C3C4C5C6C7C8C9CACBCCCDCECF" "D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF" "E0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF"; for (auto src_ptr = src; src_ptr != (src + num); ++src_ptr, dest += 2) { const char* hex_p = &kHexTable[*src_ptr * 2]; std::copy(hex_p, hex_p + 2, dest); } } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_element( iree_const_byte_span_t data, iree_hal_element_type_t element_type, iree_host_size_t buffer_capacity, char* buffer, iree_host_size_t* out_buffer_length) { iree_host_size_t element_size = iree_hal_element_byte_count(element_type); if (data.data_length < element_size) { return iree_make_status( IREE_STATUS_OUT_OF_RANGE, "data buffer underflow: data_length=%zu < element_size=%zu", data.data_length, element_size); } int n = 0; switch (element_type) { case IREE_HAL_ELEMENT_TYPE_SINT_8: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi8, *reinterpret_cast<const int8_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_UINT_8: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu8, *reinterpret_cast<const uint8_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_SINT_16: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi16, *reinterpret_cast<const int16_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_UINT_16: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu16, *reinterpret_cast<const uint16_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_SINT_32: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi32, *reinterpret_cast<const int32_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_UINT_32: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu32, *reinterpret_cast<const uint32_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_SINT_64: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIi64, *reinterpret_cast<const int64_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_UINT_64: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%" PRIu64, *reinterpret_cast<const uint64_t*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_FLOAT_16: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%G", half_float::detail::half2float<float>( *reinterpret_cast<const uint16_t*>(data.data))); break; case IREE_HAL_ELEMENT_TYPE_FLOAT_32: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%G", *reinterpret_cast<const float*>(data.data)); break; case IREE_HAL_ELEMENT_TYPE_FLOAT_64: n = std::snprintf(buffer, buffer ? buffer_capacity : 0, "%G", *reinterpret_cast<const double*>(data.data)); break; default: { // Treat any unknown format as binary. n = 2 * (int)element_size; if (buffer && buffer_capacity > n) { iree_hal_bytes_to_hex_string(data.data, buffer, element_size); buffer[n] = 0; } } } if (n < 0) { return iree_make_status(IREE_STATUS_FAILED_PRECONDITION, "snprintf failed"); } else if (buffer && n >= buffer_capacity) { buffer = nullptr; } if (out_buffer_length) { *out_buffer_length = n; } return buffer ? iree_ok_status() : iree_status_from_code(IREE_STATUS_OUT_OF_RANGE); } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_parse_buffer_elements( iree_string_view_t data_str, iree_hal_element_type_t element_type, iree_byte_span_t data_ptr) { IREE_TRACE_SCOPE0("iree_hal_parse_buffer_elements"); iree_host_size_t element_size = iree_hal_element_byte_count(element_type); iree_host_size_t element_capacity = data_ptr.data_length / element_size; if (iree_string_view_is_empty(data_str)) { memset(data_ptr.data, 0, data_ptr.data_length); return iree_ok_status(); } size_t src_i = 0; size_t dst_i = 0; size_t token_start = std::string::npos; while (src_i < data_str.size) { char c = data_str.data[src_i++]; bool is_separator = absl::ascii_isspace(c) || c == ',' || c == '[' || c == ']'; if (token_start == std::string::npos) { if (!is_separator) { token_start = src_i - 1; } continue; } else if (token_start != std::string::npos && !is_separator) { continue; } if (dst_i >= element_capacity) { return iree_make_status( IREE_STATUS_OUT_OF_RANGE, "output data buffer overflow: element_capacity=%zu < dst_i=%zu+", element_capacity, dst_i); } IREE_RETURN_IF_ERROR(iree_hal_parse_element_unsafe( iree_string_view_t{data_str.data + token_start, src_i - 2 - token_start + 1}, element_type, data_ptr.data + dst_i * element_size)); ++dst_i; token_start = std::string::npos; } if (token_start != std::string::npos) { if (dst_i >= element_capacity) { return iree_make_status( IREE_STATUS_OUT_OF_RANGE, "output data overflow: element_capacity=%zu < dst_i=%zu", element_capacity, dst_i); } IREE_RETURN_IF_ERROR(iree_hal_parse_element_unsafe( iree_string_view_t{data_str.data + token_start, data_str.size - token_start}, element_type, data_ptr.data + dst_i * element_size)); ++dst_i; } if (dst_i == 1 && element_capacity > 1) { // Splat the single value we got to the entire buffer. uint8_t* p = data_ptr.data + element_size; for (int i = 1; i < element_capacity; ++i, p += element_size) { memcpy(p, data_ptr.data, element_size); } } else if (dst_i < element_capacity) { return iree_make_status( IREE_STATUS_OUT_OF_RANGE, "input data string underflow: dst_i=%zu < element_capacity=%zu", dst_i, element_capacity); } return iree_ok_status(); } static iree_status_t iree_hal_format_buffer_elements_recursive( iree_const_byte_span_t data, const iree_hal_dim_t* shape, iree_host_size_t shape_rank, iree_hal_element_type_t element_type, iree_host_size_t* max_element_count, iree_host_size_t buffer_capacity, char* buffer, iree_host_size_t* out_buffer_length) { iree_host_size_t buffer_length = 0; auto append_char = [&](char c) { if (buffer) { if (buffer_length < buffer_capacity - 1) { buffer[buffer_length] = c; buffer[buffer_length + 1] = '\0'; } else { buffer = nullptr; } } ++buffer_length; }; if (shape_rank == 0) { // Scalar value; recurse to get on to the leaf dimension path. const iree_hal_dim_t one = 1; return iree_hal_format_buffer_elements_recursive( data, &one, 1, element_type, max_element_count, buffer_capacity, buffer, out_buffer_length); } else if (shape_rank > 1) { // Nested dimension; recurse into the next innermost dimension. iree_hal_dim_t dim_length = 1; for (iree_host_size_t i = 1; i < shape_rank; ++i) { dim_length *= shape[i]; } iree_device_size_t dim_stride = dim_length * iree_hal_element_byte_count(element_type); if (data.data_length < dim_stride * shape[0]) { return iree_make_status( IREE_STATUS_OUT_OF_RANGE, "input data underflow: data_length=%zu < expected=%zu", data.data_length, static_cast<iree_host_size_t>(dim_stride * shape[0])); } iree_const_byte_span_t subdata; subdata.data = data.data; subdata.data_length = dim_stride; for (iree_hal_dim_t i = 0; i < shape[0]; ++i) { append_char('['); iree_host_size_t actual_length = 0; iree_status_t status = iree_hal_format_buffer_elements_recursive( subdata, shape + 1, shape_rank - 1, element_type, max_element_count, buffer ? buffer_capacity - buffer_length : 0, buffer ? buffer + buffer_length : nullptr, &actual_length); buffer_length += actual_length; if (iree_status_is_out_of_range(status)) { buffer = nullptr; } else if (!iree_status_is_ok(status)) { return status; } subdata.data += dim_stride; append_char(']'); } } else { // Leaf dimension; output data. iree_host_size_t max_count = std::min(*max_element_count, static_cast<iree_host_size_t>(shape[0])); iree_device_size_t element_stride = iree_hal_element_byte_count(element_type); if (data.data_length < max_count * element_stride) { return iree_make_status( IREE_STATUS_OUT_OF_RANGE, "input data underflow; data_length=%zu < expected=%zu", data.data_length, static_cast<iree_host_size_t>(max_count * element_stride)); } *max_element_count -= max_count; iree_const_byte_span_t subdata; subdata.data = data.data; subdata.data_length = element_stride; for (iree_hal_dim_t i = 0; i < max_count; ++i) { if (i > 0) append_char(' '); iree_host_size_t actual_length = 0; iree_status_t status = iree_hal_format_element( subdata, element_type, buffer ? buffer_capacity - buffer_length : 0, buffer ? buffer + buffer_length : nullptr, &actual_length); subdata.data += element_stride; buffer_length += actual_length; if (iree_status_is_out_of_range(status)) { buffer = nullptr; } else if (!iree_status_is_ok(status)) { return status; } } if (max_count < shape[0]) { append_char('.'); append_char('.'); append_char('.'); } } if (out_buffer_length) { *out_buffer_length = buffer_length; } return buffer ? iree_ok_status() : iree_status_from_code(IREE_STATUS_OUT_OF_RANGE); } IREE_API_EXPORT iree_status_t IREE_API_CALL iree_hal_format_buffer_elements( iree_const_byte_span_t data, const iree_hal_dim_t* shape, iree_host_size_t shape_rank, iree_hal_element_type_t element_type, iree_host_size_t max_element_count, iree_host_size_t buffer_capacity, char* buffer, iree_host_size_t* out_buffer_length) { IREE_TRACE_SCOPE0("iree_hal_format_buffer_elements"); if (out_buffer_length) { *out_buffer_length = 0; } if (buffer && buffer_capacity) { buffer[0] = '\0'; } return iree_hal_format_buffer_elements_recursive( data, shape, shape_rank, element_type, &max_element_count, buffer_capacity, buffer, out_buffer_length); }
40.281713
80
0.644391
OliverScherf
1fb39dd7f9862d543aab8948f2a3838d9b93fe3e
2,058
cpp
C++
src/Generic/common/Decompressor.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
1
2022-03-24T19:57:00.000Z
2022-03-24T19:57:00.000Z
src/Generic/common/Decompressor.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
src/Generic/common/Decompressor.cpp
BBN-E/serif
1e2662d82fb1c377ec3c79355a5a9b0644606cb4
[ "Apache-2.0" ]
null
null
null
#include "Generic/common/leak_detection.h" #include "Decompressor.h" #include <sstream> #include <utility> #include "Generic/common/BoostUtil.h" #include "Generic/common/SessionLogger.h" #include "Generic/common/UnexpectedInputException.h" Decompressor::ImplMap Decompressor::_implementations; std::string extension(const std::string& filename) { return BOOST_FILESYSTEM_PATH_GET_EXTENSION(boost::filesystem::path(filename)); } bool Decompressor::canDecompress(const std::string& filename) { std::string ext = extension(filename); if (!ext.empty()) { return _implementations.find(ext) != _implementations.end(); } return false; } unsigned char* Decompressor::decompressIntoMemory(const std::string& filename, size_t& size, const std::string& overrideExtension) { std::string ext; if (overrideExtension.empty()) { ext = extension(filename); } else { ext = overrideExtension; } if (!ext.empty()) { ImplMap::iterator probe = _implementations.find(ext); if (probe != _implementations.end()) { return probe->second->decompressIntoMemory(filename, size); } else { std::stringstream err; err << "Cannot decompress file " << filename << " because SERIF " << "doesn't know how to compress files with extension " << ext; throw UnexpectedInputException("Decompressor::decompressIntoMemory", err.str().c_str()); } } else { std::stringstream err; err << "Cannot decompress file " << filename << " because it has no " << "extension and no extension override was specified."; throw UnexpectedInputException("Decompressor::decompressIntoMemory", err.str().c_str()); } } void Decompressor::registerImplementation(const std::string& ext, DecompressorImplementation* impl) { if (_implementations.find(ext) != _implementations.end()) { SessionLogger::warn("duplicate_decompressor") << "Attempting to register decompressor for extension " << ext << ", but a decompressor is already registered for it." << " Ignoring."; } else { _implementations.insert(std::make_pair(ext, impl)); } }
29.4
79
0.720117
BBN-E
1fb4d9fcf28e13e998a55d4723163ca30a407d8c
589
cpp
C++
deque.cpp
AbhiRepository/algorithm_codes
723b9a660084a701b468f98f1c184f9573856521
[ "MIT" ]
2
2018-09-05T17:12:37.000Z
2018-09-18T09:27:40.000Z
deque.cpp
AbhiRepository/algorithm_codes
723b9a660084a701b468f98f1c184f9573856521
[ "MIT" ]
8
2018-03-24T20:41:25.000Z
2018-10-19T15:04:20.000Z
deque.cpp
AbhiRepository/algorithm_codes
723b9a660084a701b468f98f1c184f9573856521
[ "MIT" ]
5
2018-09-05T17:12:43.000Z
2018-10-01T09:13:52.000Z
//Program to implement deque for finding the maximum of all suaarays of size k #include <iostream> #include <deque> using namespace std; int main() { int a[]={1,43,23,11,46,22,81,22}; int n=sizeof(a)/sizeof(a[0]); int k=3; deque<int> d; int i; for (i = 0; i < k; ++i) { while(!d.empty() && a[i]>=a[d.back()]) d.pop_back(); d.push_back(i); } for (; i < n; ++i) { cout<<a[d.front()]<<" "; while(!d.empty() && d.front()<=i-k) d.pop_front(); while(!d.empty() && a[i]>=a[d.back()]) d.pop_back(); d.push_back(i); } cout<<a[d.front()]<<endl; return 0; }
15.5
78
0.550085
AbhiRepository
1fb570c46f48c50828febe33a93d107e0d4ab239
1,124
cpp
C++
c++/422.cpp
AkashChandrakar/UVA
b90535c998ecdffe0f30e56fec89411f456b16a5
[ "Apache-2.0" ]
2
2016-10-23T14:35:13.000Z
2018-09-16T05:38:47.000Z
c++/422.cpp
AkashChandrakar/UVA
b90535c998ecdffe0f30e56fec89411f456b16a5
[ "Apache-2.0" ]
null
null
null
c++/422.cpp
AkashChandrakar/UVA
b90535c998ecdffe0f30e56fec89411f456b16a5
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<ll, ll> ii; vector<int> v; map<char, ii> hash; char s[500]; ll process() { int len = strlen(s); ll res = 0; char chr = 'a'; ii a, b, c; stack<char> S; map<char, ii> temphash; for (int i = 0; i < len; ++i) { if (s[i] == '(') S.push('('); else if (s[i] == ')') { if (hash.find(S.top()) != hash.end()) b = hash[S.top()]; else b = temphash[S.top()]; S.pop(); if (hash.find(S.top()) != hash.end()) a = hash[S.top()]; else a = temphash[S.top()]; S.pop(); if (a.second != b.first) return -1; c.first = a.first, c.second = b.second; res += (a.first * a.second * b.second); S.pop(); temphash[chr] = c; S.push(chr); ++chr; } else { S.push(s[i]); } } return res; } int main() { int n, row, col; ll res; char c; scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("\n%c %d %d", &c, &row, &col); hash[c] = ii(row, col); } while (scanf("%s", s) != EOF) { res = process(); if (res == -1) printf("error\n"); else printf("%lld\n", res); } return 0; }
18.129032
42
0.495552
AkashChandrakar
1fb880944f4e0dbf8b6354a2d62b8e9ce3e3727a
5,736
cpp
C++
src/mpi/matrix/MatrixCSR.cpp
jgurhem/TBSLA
ef4e14fe033f179e1accdea09813962322431b88
[ "MIT" ]
null
null
null
src/mpi/matrix/MatrixCSR.cpp
jgurhem/TBSLA
ef4e14fe033f179e1accdea09813962322431b88
[ "MIT" ]
null
null
null
src/mpi/matrix/MatrixCSR.cpp
jgurhem/TBSLA
ef4e14fe033f179e1accdea09813962322431b88
[ "MIT" ]
null
null
null
#include <tbsla/mpi/MatrixCSR.hpp> #include <tbsla/cpp/utils/range.hpp> #include <vector> #include <algorithm> #include <mpi.h> #define TBSLA_MATRIX_CSR_READLINES 2048 int tbsla::mpi::MatrixCSR::read_bin_mpiio(MPI_Comm comm, std::string filename, int pr, int pc, int NR, int NC) { int world, rank; MPI_Comm_size(comm, &world); MPI_Comm_rank(comm, &rank); MPI_File fh; MPI_Status status; MPI_File_open(comm, filename.c_str(), MPI_MODE_RDONLY, MPI_INFO_NULL, &fh); MPI_File_read_all(fh, &this->n_row, 1, MPI_INT, &status); MPI_File_read_all(fh, &this->n_col, 1, MPI_INT, &status); MPI_File_read_at_all(fh, 6 * sizeof(int), &this->gnnz, 1, MPI_LONG, &status); size_t vec_size, depla_general, values_start; depla_general = 10 * sizeof(int) + sizeof(long int); this->pr = pr; this->pc = pc; this->NR = NR; this->NC = NC; this->ln_row = tbsla::utils::range::lnv(n_row, pr, NR); this->f_row = tbsla::utils::range::pflv(n_row, pr, NR); this->ln_col = tbsla::utils::range::lnv(n_col, pc, NC); this->f_col = tbsla::utils::range::pflv(n_col, pc, NC); // skip values vector for now int values_size = vec_size; MPI_File_read_at_all(fh, depla_general, &vec_size, 1, MPI_UNSIGNED_LONG, &status); depla_general += sizeof(size_t); values_start = depla_general; depla_general += vec_size * sizeof(double); MPI_File_read_at_all(fh, depla_general, &vec_size, 1, MPI_UNSIGNED_LONG, &status); depla_general += sizeof(size_t); this->rowptr.resize(this->ln_row + 1); int rowptr_start = depla_general + this->f_row * sizeof(int); depla_general += vec_size * sizeof(int); MPI_File_read_at_all(fh, depla_general, &vec_size, 1, MPI_UNSIGNED_LONG, &status); depla_general += sizeof(size_t); int colidx_start = depla_general; this->rowptr[0] = 0; this->nnz = 0; this->colidx.reserve(this->ln_row * 10); this->values.reserve(this->ln_row * 10); int mod = this->ln_row % TBSLA_MATRIX_CSR_READLINES; tbsla::mpi::MatrixCSR::mpiio_read_lines(fh, 0, mod, rowptr_start, colidx_start, values_start); for(int i = mod; i < this->ln_row; i += TBSLA_MATRIX_CSR_READLINES) { tbsla::mpi::MatrixCSR::mpiio_read_lines(fh, i, TBSLA_MATRIX_CSR_READLINES, rowptr_start, colidx_start, values_start); } this->colidx.shrink_to_fit(); this->rowptr.shrink_to_fit(); MPI_File_close(&fh); return 0; } void tbsla::mpi::MatrixCSR::mpiio_read_lines(MPI_File &fh, int s, int n, int rowptr_start, int colidx_start, int values_start) { MPI_Status status; std::vector<int> jtmp(n + 1); int idx, jmin, jmax, nv; MPI_File_read_at(fh, rowptr_start + s * sizeof(int), jtmp.data(), n + 1, MPI_INT, &status); jmin = jtmp[0]; jmax = jtmp[n]; nv = jmax - jmin; std::cout << nv << std::endl; std::vector<int> ctmp(nv); std::vector<double> vtmp(nv); MPI_File_read_at(fh, colidx_start + jmin * sizeof(int), ctmp.data(), nv, MPI_INT, &status); MPI_File_read_at(fh, values_start + jmin * sizeof(double), vtmp.data(), nv, MPI_DOUBLE, &status); int incr = 0; for(int i = 0; i < n; i++) { jmin = jtmp[i]; jmax = jtmp[i + 1]; nv = jmax - jmin; for(int j = incr; j < incr + nv; j++) { idx = ctmp[j]; if(idx >= this->f_col && idx < this->f_col + this->ln_col) { this->colidx.push_back(idx); this->values.push_back(vtmp[j]); this->nnz++; } } incr += nv; this->rowptr[s + i + 1] = this->nnz; } } std::vector<double> tbsla::mpi::MatrixCSR::spmv(MPI_Comm comm, const std::vector<double> &v, int vect_incr) { std::vector<double> send = this->spmv(v, vect_incr); if(this->NC == 1 && this->NR == 1) { return send; } else if(this->NC == 1 && this->NR > 1) { std::vector<int> recvcounts(this->NR); std::vector<int> displs(this->NR, 0); for(int i = 0; i < this->NR; i++) { recvcounts[i] = tbsla::utils::range::lnv(this->get_n_row(), i, this->NR); } for(int i = 1; i < this->NR; i++) { displs[i] = displs[i - 1] + recvcounts[i - 1]; } std::vector<double> recv(this->get_n_row()); MPI_Allgatherv(send.data(), send.size(), MPI_DOUBLE, recv.data(), recvcounts.data(), displs.data(), MPI_DOUBLE, comm); return recv; } else if(this->NC > 1 && this->NR == 1) { std::vector<double> recv(this->get_n_row()); MPI_Allreduce(send.data(), recv.data(), send.size(), MPI_DOUBLE, MPI_SUM, comm); return recv; } else { MPI_Comm row_comm; MPI_Comm_split(comm, this->pr, this->pc, &row_comm); std::vector<double> recv(send.size()); MPI_Allreduce(send.data(), recv.data(), send.size(), MPI_DOUBLE, MPI_SUM, row_comm); std::vector<double> recv2(this->get_n_row()); std::vector<int> recvcounts(this->NR); std::vector<int> displs(this->NR, 0); for(int i = 0; i < this->NR; i++) { recvcounts[i] = tbsla::utils::range::lnv(this->get_n_row(), i, this->NR); } for(int i = 1; i < this->NR; i++) { displs[i] = displs[i - 1] + recvcounts[i - 1]; } MPI_Comm col_comm; MPI_Comm_split(comm, this->pc, this->pr, &col_comm); MPI_Allgatherv(recv.data(), recv.size(), MPI_DOUBLE, recv2.data(), recvcounts.data(), displs.data(), MPI_DOUBLE, col_comm); MPI_Comm_free(&col_comm); MPI_Comm_free(&row_comm); return recv2; } } std::vector<double> tbsla::mpi::MatrixCSR::a_axpx_(MPI_Comm comm, const std::vector<double> &v, int vect_incr) { std::vector<double> vs(v.begin() + this->f_col, v.begin() + this->f_col + this->ln_col); std::vector<double> r = this->spmv(comm, vs, vect_incr); std::transform (r.begin(), r.end(), v.begin(), r.begin(), std::plus<double>()); std::vector<double> l(r.begin() + this->f_col, r.begin() + this->f_col + this->ln_col); return this->spmv(comm, l, vect_incr); }
38.24
128
0.647838
jgurhem
1fb98b7fd35e9148e4f4c70f0541f2c9a05e17b5
1,562
cpp
C++
enduser/troubleshoot/launcher/client/tsmfc.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/troubleshoot/launcher/client/tsmfc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/troubleshoot/launcher/client/tsmfc.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // MODULE: tsmfc.cpp // // PURPOSE: Imitate the MFC string resource functions that are not available // in Win32 programs. // // PROJECT: Local Troubleshooter Launcher for the Device Manager // // COMPANY: Saltmine Creative, Inc. (206)-633-4743 support@saltmine.com // // AUTHOR: Richard Meadows // // ORIGINAL DATE: 2-26-98 // // // Version Date By Comments //-------------------------------------------------------------------- // V0.1 - RM Original /////////////////////// #include <windows.h> #include "tsmfc.h" int AfxLoadStringA(UINT nID, LPSTR lpszBuf, UINT nMaxBuf) { LPCSTR lpszName = MAKEINTRESOURCEA((nID>>4)+1); HINSTANCE hInst; int nLen = 0; // Unlike MFC, this function call is guarenteed to work. // AfxGetResourceHandle gets the handle that was passed // to DllMain(). hInst = AfxGetResourceHandle(); if (::FindResourceA(hInst, lpszName, (LPCSTR)RT_STRING) != NULL) nLen = ::LoadStringA(hInst, nID, lpszBuf, nMaxBuf); return nLen; } int AfxLoadStringW(UINT nID, LPWSTR lpszBuf, UINT nMaxBuf) { LPCWSTR lpszName = MAKEINTRESOURCEW((nID>>4)+1); HINSTANCE hInst; int nLen = 0; // Unlike MFC, this function call is guarenteed to work. // AfxGetResourceHandle gets the handle that was passed // to DllMain(). hInst = AfxGetResourceHandle(); if (::FindResourceW(hInst, lpszName, (LPCWSTR)RT_STRING) != NULL) nLen = ::LoadStringW(hInst, nID, lpszBuf, nMaxBuf); return nLen; } HINSTANCE AfxGetResourceHandle() { extern HINSTANCE g_hInst; return g_hInst; }
27.403509
78
0.644046
npocmaka
1fba7a152c610fc21125775f6fc104d260a08888
1,895
cpp
C++
GeneticAlgorithm/GeneticAlgorithm.cpp
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
2
2019-11-04T15:09:52.000Z
2022-01-12T05:41:16.000Z
GeneticAlgorithm/GeneticAlgorithm.cpp
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
null
null
null
GeneticAlgorithm/GeneticAlgorithm.cpp
TomaszRewak/BMCP
99e94b11f70658d9b8de792b36af7ecbb215d665
[ "MIT" ]
1
2020-09-09T12:24:35.000Z
2020-09-09T12:24:35.000Z
// ======================================== // ======= Created by Tomasz Rewak ======== // ======================================== // ==== https://github.com/TomaszRewak ==== // ======================================== #include <memory> #include <vector> #include <algorithm> #include "GeneticAlgorithm.h" #include "InitialPopulation.h" #include "StopCondition.h" #include "Fitness.h" #include "Specimen.h" #include "Component.h" namespace GA { void GeneticAlgorithm::start() { startTime = std::chrono::steady_clock::now(); for (auto spec : initialPopulation->generate()) population.push_back(std::move(spec)); for (auto& specimen : population) if (specimen.fitness <= globalBest.fitness) globalBest = specimen; while(true) { for (auto stopCondition : stopConditions) if (stopCondition->checkCondition(*this)) return; for (auto chainGenerator : chainGenerators) { ComponentChainBuilder builder; chainGenerator(builder); builder.chain->get(*this); } for (auto& specimen : population) if (specimen.fitness <= globalBest.fitness) globalBest = specimen; generation++; } } int GeneticAlgorithm::currentGeneration() { return generation; } void GeneticAlgorithm::addLog(std::string category, std::string log) { logs[category].push_back(log); } #pragma region Initialization GeneticAlgorithm& GeneticAlgorithm::withInitialPopulation(std::shared_ptr<InitialPopulation> initialPopulation) { this->initialPopulation = initialPopulation; return *this; } GeneticAlgorithm& GeneticAlgorithm::withStopCondition(std::shared_ptr<StopCondition> stopCondition) { stopConditions.push_back(stopCondition); return *this; } GeneticAlgorithm& GeneticAlgorithm::with(std::function<void(ComponentChainBuilder& builder)> chain) { chainGenerators.push_back(chain); return *this; } #pragma endregion }
22.294118
112
0.668602
TomaszRewak
1fbcd45bf47b41749f66033657b69cdb0ff6a0c8
8,032
cc
C++
node_modules/@parcel/watcher/src/watchman/BSER.cc
hamsall/hamsall.github.io
dc21c8037c9cd13641c61628ef1ed04c306c7701
[ "MIT" ]
346
2019-04-08T01:30:31.000Z
2022-03-24T01:49:04.000Z
node_modules/@parcel/watcher/src/watchman/BSER.cc
hamsall/hamsall.github.io
dc21c8037c9cd13641c61628ef1ed04c306c7701
[ "MIT" ]
79
2019-04-20T08:00:07.000Z
2022-03-30T17:24:22.000Z
node_modules/@parcel/watcher/src/watchman/BSER.cc
hamsall/hamsall.github.io
dc21c8037c9cd13641c61628ef1ed04c306c7701
[ "MIT" ]
12
2019-04-08T08:02:10.000Z
2022-02-03T05:18:53.000Z
#include <stdint.h> #include "./BSER.hh" BSERType decodeType(std::istream &iss) { int8_t type; iss.read(reinterpret_cast<char*>(&type), sizeof(type)); return (BSERType) type; } void expectType(std::istream &iss, BSERType expected) { BSERType got = decodeType(iss); if (got != expected) { throw std::runtime_error("Unexpected BSER type"); } } void encodeType(std::ostream &oss, BSERType type) { int8_t t = (int8_t)type; oss.write(reinterpret_cast<char*>(&t), sizeof(t)); } template<typename T> class Value : public BSERValue { public: T value; Value(T val) { value = val; } Value() {} }; class BSERInteger : public Value<int64_t> { public: BSERInteger(int64_t value) : Value(value) {} BSERInteger(std::istream &iss) { int8_t int8; int16_t int16; int32_t int32; int64_t int64; BSERType type = decodeType(iss); switch (type) { case BSER_INT8: iss.read(reinterpret_cast<char*>(&int8), sizeof(int8)); value = int8; break; case BSER_INT16: iss.read(reinterpret_cast<char*>(&int16), sizeof(int16)); value = int16; break; case BSER_INT32: iss.read(reinterpret_cast<char*>(&int32), sizeof(int32)); value = int32; break; case BSER_INT64: iss.read(reinterpret_cast<char*>(&int64), sizeof(int64)); value = int64; break; default: throw std::runtime_error("Invalid BSER int type"); } } int64_t intValue() override { return value; } void encode(std::ostream &oss) override { if (value <= INT8_MAX) { encodeType(oss, BSER_INT8); int8_t v = (int8_t)value; oss.write(reinterpret_cast<char*>(&v), sizeof(v)); } else if (value <= INT16_MAX) { encodeType(oss, BSER_INT16); int16_t v = (int16_t)value; oss.write(reinterpret_cast<char*>(&v), sizeof(v)); } else if (value <= INT32_MAX) { encodeType(oss, BSER_INT32); int32_t v = (int32_t)value; oss.write(reinterpret_cast<char*>(&v), sizeof(v)); } else { encodeType(oss, BSER_INT64); oss.write(reinterpret_cast<char*>(&value), sizeof(value)); } } }; class BSERArray : public Value<BSER::Array> { public: BSERArray() : Value() {} BSERArray(BSER::Array value) : Value(value) {} BSERArray(std::istream &iss) { expectType(iss, BSER_ARRAY); int64_t len = BSERInteger(iss).intValue(); for (int64_t i = 0; i < len; i++) { value.push_back(BSER(iss)); } } BSER::Array arrayValue() override { return value; } void encode(std::ostream &oss) override { encodeType(oss, BSER_ARRAY); BSERInteger(value.size()).encode(oss); for (auto it = value.begin(); it != value.end(); it++) { it->encode(oss); } } }; class BSERString : public Value<std::string> { public: BSERString(std::string value) : Value(value) {} BSERString(std::istream &iss) { expectType(iss, BSER_STRING); int64_t len = BSERInteger(iss).intValue(); value.resize(len); iss.read(&value[0], len); } std::string stringValue() override { return value; } void encode(std::ostream &oss) override { encodeType(oss, BSER_STRING); BSERInteger(value.size()).encode(oss); oss << value; } }; class BSERObject : public Value<BSER::Object> { public: BSERObject() : Value() {} BSERObject(BSER::Object value) : Value(value) {} BSERObject(std::istream &iss) { expectType(iss, BSER_OBJECT); int64_t len = BSERInteger(iss).intValue(); for (int64_t i = 0; i < len; i++) { auto key = BSERString(iss).stringValue(); auto val = BSER(iss); value.emplace(key, val); } } BSER::Object objectValue() override { return value; } void encode(std::ostream &oss) override { encodeType(oss, BSER_OBJECT); BSERInteger(value.size()).encode(oss); for (auto it = value.begin(); it != value.end(); it++) { BSERString(it->first).encode(oss); it->second.encode(oss); } } }; class BSERDouble : public Value<double> { public: BSERDouble(double value) : Value(value) {} BSERDouble(std::istream &iss) { expectType(iss, BSER_REAL); iss.read(reinterpret_cast<char*>(&value), sizeof(value)); } double doubleValue() override { return value; } void encode(std::ostream &oss) override { encodeType(oss, BSER_REAL); oss.write(reinterpret_cast<char*>(&value), sizeof(value)); } }; class BSERBoolean : public Value<bool> { public: BSERBoolean(bool value) : Value(value) {} bool boolValue() override { return value; } void encode(std::ostream &oss) override { int8_t t = value == true ? BSER_BOOL_TRUE : BSER_BOOL_FALSE; oss.write(reinterpret_cast<char*>(&t), sizeof(t)); } }; class BSERNull : public Value<bool> { public: BSERNull() : Value(false) {} void encode(std::ostream &oss) override { encodeType(oss, BSER_NULL); } }; std::shared_ptr<BSERArray> decodeTemplate(std::istream &iss) { expectType(iss, BSER_TEMPLATE); auto keys = BSERArray(iss).arrayValue(); auto len = BSERInteger(iss).intValue(); std::shared_ptr<BSERArray> arr = std::make_shared<BSERArray>(); for (int64_t i = 0; i < len; i++) { BSER::Object obj; for (auto it = keys.begin(); it != keys.end(); it++) { if (iss.peek() == 0x0c) { iss.ignore(1); continue; } auto val = BSER(iss); obj.emplace(it->stringValue(), val); } arr->value.push_back(obj); } return arr; } BSER::BSER(std::istream &iss) { BSERType type = decodeType(iss); iss.unget(); switch (type) { case BSER_ARRAY: m_ptr = std::make_shared<BSERArray>(iss); break; case BSER_OBJECT: m_ptr = std::make_shared<BSERObject>(iss); break; case BSER_STRING: m_ptr = std::make_shared<BSERString>(iss); break; case BSER_INT8: case BSER_INT16: case BSER_INT32: case BSER_INT64: m_ptr = std::make_shared<BSERInteger>(iss); break; case BSER_REAL: m_ptr = std::make_shared<BSERDouble>(iss); break; case BSER_BOOL_TRUE: iss.ignore(1); m_ptr = std::make_shared<BSERBoolean>(true); break; case BSER_BOOL_FALSE: iss.ignore(1); m_ptr = std::make_shared<BSERBoolean>(false); break; case BSER_NULL: iss.ignore(1); m_ptr = std::make_shared<BSERNull>(); break; case BSER_TEMPLATE: m_ptr = decodeTemplate(iss); break; default: throw std::runtime_error("unknown BSER type"); } } BSER::BSER() : m_ptr(std::make_shared<BSERNull>()) {} BSER::BSER(BSER::Array value) : m_ptr(std::make_shared<BSERArray>(value)) {} BSER::BSER(BSER::Object value) : m_ptr(std::make_shared<BSERObject>(value)) {} BSER::BSER(const char *value) : m_ptr(std::make_shared<BSERString>(value)) {} BSER::BSER(std::string value) : m_ptr(std::make_shared<BSERString>(value)) {} BSER::BSER(int64_t value) : m_ptr(std::make_shared<BSERInteger>(value)) {} BSER::BSER(double value) : m_ptr(std::make_shared<BSERDouble>(value)) {} BSER::BSER(bool value) : m_ptr(std::make_shared<BSERBoolean>(value)) {} BSER::Array BSER::arrayValue() { return m_ptr->arrayValue(); } BSER::Object BSER::objectValue() { return m_ptr->objectValue(); } std::string BSER::stringValue() { return m_ptr->stringValue(); } int64_t BSER::intValue() { return m_ptr->intValue(); } double BSER::doubleValue() { return m_ptr->doubleValue(); } bool BSER::boolValue() { return m_ptr->boolValue(); } void BSER::encode(std::ostream &oss) { m_ptr->encode(oss); } int64_t BSER::decodeLength(std::istream &iss) { char pdu[2]; if (!iss.read(pdu, 2) || pdu[0] != 0 || pdu[1] != 1) { throw std::runtime_error("Invalid BSER"); } return BSERInteger(iss).intValue(); } std::string BSER::encode() { std::ostringstream oss(std::ios_base::binary); encode(oss); std::ostringstream res(std::ios_base::binary); res.write("\x00\x01", 2); BSERInteger(oss.str().size()).encode(res); res << oss.str(); return res.str(); }
26.508251
78
0.631225
hamsall
1fbd2a4e5c43d018d88dc7f3bb0039973f32725b
47
cpp
C++
Unreal/CtaCpp/Runtime/Scripts/Combat/IItem.cpp
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
3
2021-06-02T16:44:02.000Z
2022-01-24T20:20:10.000Z
Unreal/CtaCpp/Runtime/Scripts/Combat/IItem.cpp
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
null
null
null
Unreal/CtaCpp/Runtime/Scripts/Combat/IItem.cpp
areilly711/CtaApi
8c7a80c48f2a6d02fb6680a5d8f62e6ff7da8d4c
[ "MIT" ]
null
null
null
#include "IItem.h" namespace Cta::Combat { }
7.833333
21
0.659574
areilly711
1fbdb69e6030ee670f300c97ca10550e3effd251
8,052
cpp
C++
JLITOSL_Liczba_na_slowo/main.cpp
MichalWilczek/spoj-tasks
6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3
[ "Unlicense" ]
null
null
null
JLITOSL_Liczba_na_slowo/main.cpp
MichalWilczek/spoj-tasks
6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3
[ "Unlicense" ]
null
null
null
JLITOSL_Liczba_na_slowo/main.cpp
MichalWilczek/spoj-tasks
6d5d77d750747ecb162c76a2b7eb4b8e8f2c4fc3
[ "Unlicense" ]
null
null
null
#include <iostream> #include <map> #include <vector> #include <string> #include <bits/stdc++.h> using namespace std; void defineNumberNames(map<int, string> &numbers) { numbers[1] = "jeden"; numbers[2] = "dwa"; numbers[3] = "trzy"; numbers[4] = "cztery"; numbers[5] = "piec"; numbers[6] = "szesc"; numbers[7] = "siedem"; numbers[8] = "osiem"; numbers[9] = "dziewiec"; numbers[10] = "dziesiec"; numbers[11] = "jedenascie"; numbers[12] = "dwanascie"; numbers[13] = "trzynascie"; numbers[14] = "czternascie"; numbers[15] = "pietnascie"; numbers[16] = "szesnascie"; numbers[17] = "siedemnascie"; numbers[18] = "osiemnascie"; numbers[19] = "dziewietnascie"; numbers[20] = "dwadziescia"; numbers[30] = "trzydziesci"; numbers[40] = "czterdziesci"; numbers[50] = "piecdziesiat"; numbers[60] = "szescdziesiat"; numbers[70] = "siedemdziesiat"; numbers[80] = "osiemdziesiat"; numbers[90] = "dziewiecdziesiat"; numbers[100] = "sto"; numbers[200] = "dwiescie"; numbers[300] = "trzysta"; numbers[400] = "czterysta"; numbers[500] = "piecset"; numbers[600] = "szescset"; numbers[700] = "siedemset"; numbers[800] = "osiemset"; numbers[900] = "dziewiecset"; numbers[1000] = "tys."; numbers[1000000] = "mln."; numbers[1000000000] = "mld."; numbers[1000000000000] = "bln."; } int uploadNumbers(vector<string> &numbers) { int numbersAmount; string number; cin >> numbersAmount; for (int i=0; i<numbersAmount; i++) { cin >> number; numbers.push_back(number); } return numbersAmount; } void printDigitUnities(char digit, map<int, string> &numberNames) { switch (digit) { case '1': cout << numberNames[1]; break; case '2': cout << numberNames[2]; break; case '3': cout << numberNames[3]; break; case '4': cout << numberNames[4]; break; case '5': cout << numberNames[5]; break; case '6': cout << numberNames[6]; break; case '7': cout << numberNames[7]; break; case '8': cout << numberNames[8]; break; case '9': cout << numberNames[9]; break; } cout << " "; } void printDigitTens(char digitTens, char digitUnities, map<int, string> &numberNames) { switch (digitTens) { case '0': break; case '1': switch(digitUnities) { case '0': cout << numberNames[10]; break; case '1': cout << numberNames[11]; break; case '2': cout << numberNames[12]; break; case '3': cout << numberNames[13]; break; case '4': cout << numberNames[14]; break; case '5': cout << numberNames[15]; break; case '6': cout << numberNames[16]; break; case '7': cout << numberNames[17]; break; case '8': cout << numberNames[18]; break; case '9': cout << numberNames[19]; break; } break; case '2': cout << numberNames[20]; break; case '3': cout << numberNames[30]; break; case '4': cout << numberNames[40]; break; case '5': cout << numberNames[50]; break; case '6': cout << numberNames[60]; break; case '7': cout << numberNames[70]; break; case '8': cout << numberNames[80]; break; case '9': cout << numberNames[90]; break; } cout << " "; } void printDigitHundreds(char digit, map<int, string> &numberNames){ switch(digit) { case '1': cout << numberNames[100]; break; case '2': cout << numberNames[200]; break; case '3': cout << numberNames[300]; break; case '4': cout << numberNames[400]; break; case '5': cout << numberNames[500]; break; case '6': cout << numberNames[600]; break; case '7': cout << numberNames[700]; break; case '8': cout << numberNames[800]; break; case '9': cout << numberNames[900]; break; } cout << " "; } bool defineNumberFromThreeDigitsSet(string DigitsSet, map<int, string> &numberNames){ int numberUnities; int numberTens; int numberHundreds; int DigitsSetLength = DigitsSet.length(); bool threeZeros = false; switch (DigitsSetLength) { // case when 3 digits occur case 3: numberUnities = DigitsSet[2]; numberTens = DigitsSet[1]; numberHundreds = DigitsSet[0]; if (numberUnities == '0' && numberTens == '0' && numberHundreds == '0'){ threeZeros = true; } printDigitHundreds(numberHundreds, numberNames); printDigitTens(numberTens, numberUnities, numberNames); if (numberTens != '1') { printDigitUnities(numberUnities, numberNames); } break; // case when 2 digits occur case 2: numberUnities = DigitsSet[1]; numberTens = DigitsSet[0]; printDigitTens(numberTens, numberUnities, numberNames); if (numberTens != '1') { printDigitUnities(numberUnities, numberNames); } break; // case when 1 digit occurs case 1: numberUnities = DigitsSet[0]; printDigitUnities(numberUnities, numberNames); break; } return threeZeros; } void printNumber(vector<string> &setDigits, map<int, string> &numberNames){ bool threeZeros; vector<string> thousandElements; thousandElements.push_back(numberNames[1000000000000]); thousandElements.push_back(numberNames[1000000000]); thousandElements.push_back(numberNames[1000000]); thousandElements.push_back(numberNames[1000]); int numberThreeDigitsSetsAmount = setDigits.size(); int thousandElementsIterator; switch (numberThreeDigitsSetsAmount){ case 2: thousandElementsIterator = 3; break; case 3: thousandElementsIterator = 2; break; case 4: thousandElementsIterator = 1; break; case 5: thousandElementsIterator = 0; break; } for (int i=0; i< numberThreeDigitsSetsAmount; i++){ threeZeros = defineNumberFromThreeDigitsSet(setDigits[i], numberNames); if (i < numberThreeDigitsSetsAmount-1){ // take the case when only zeros occur into account if ((threeZeros == false) || (threeZeros == true && i == 0)) { cout << thousandElements[thousandElementsIterator] << " "; } thousandElementsIterator++; } } } vector<string> divideNumberToSubsets(vector<string> &numbers, int numberPosition) { vector<string> setDigits; string number = numbers[numberPosition]; reverse(number.begin(), number.end()); int numberLength = number.length(); string numberSet; for (int i = 0; i < numberLength; i += 3){ if (i+3 < numberLength){ numberSet = number.substr(i, 3); } else{ numberSet = number.substr(i, numberLength-i); } reverse(numberSet.begin(), numberSet.end()); setDigits.insert(setDigits.begin(), numberSet); // add numberSet to the front in the vector } return setDigits; } int main() { map<int, string> numberNames; defineNumberNames(numberNames); vector<string> numbers; int numbersAmount = uploadNumbers(numbers); for (int i=0; i<numbersAmount; i++){ vector<string> setDigits = divideNumberToSubsets(numbers, i); printNumber(setDigits, numberNames); cout << endl; } return 0; }
25.241379
99
0.551788
MichalWilczek
1fbeacbdb7e67d4301c5dba000e07850199a0087
1,707
cpp
C++
examples/google-code-jam/bcurcio/codejamA.cpp
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
examples/google-code-jam/bcurcio/codejamA.cpp
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
examples/google-code-jam/bcurcio/codejamA.cpp
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; int in(){int r=0,c;for(c=getchar_unlocked();c<=32;c=getchar_unlocked());if(c=='-') return -in();for(;c>32;r=(r<<1)+(r<<3)+c-'0',c=getchar_unlocked());return r;} string ans[]={"X won", "O won","Draw","Game has not completed"}; char bd[20]; void solve(){ int state = 2; int i; int tx=0,to=0; for(i=0;i<16;i++){ bd[i]=0; while(bd[i]<'!')scanf("%c",bd+i); if(bd[i]=='.') state=3; if(bd[i]=='X') tx++; if(bd[i]=='O') to++; } //puts("leyo"); //for(i=0;i<16;i++) putchar(bd[i]); //puts("leyo"); int j; bool vale; for(i=0;i<4;i++){ vale=true; for(j=0;j<4;j++) if(bd[i*4+j]=='X' || bd[i*4+j]=='.') vale=false; if(vale) state = 1; vale=true; for(j=0;j<4;j++) if(bd[j*4+i]=='X' || bd[j*4+i]=='.') vale=false; if(vale) state = 1; } vale=true; for(j=0;j<4;j++) if(bd[j*4+j]=='X' || bd[j*4+j]=='.') vale=false; if(vale) state = 1; vale=true; for(j=0;j<4;j++) if(bd[j*4+(3-j)]=='X' || bd[j*4+(3-j)]=='.') vale=false; if(vale) state = 1; for(i=0;i<4;i++){ vale=true; for(j=0;j<4;j++) if(bd[i*4+j]=='O' || bd[i*4+j]=='.') vale=false; if(vale) state = 0; vale=true; for(j=0;j<4;j++) if(bd[j*4+i]=='O' || bd[j*4+i]=='.') vale=false; if(vale) state = 0; } vale=true; for(j=0;j<4;j++) if(bd[j*4+j]=='O' || bd[j*4+j]=='.') vale=false; if(vale) state = 0; vale=true; for(j=0;j<4;j++) if(bd[j*4+(3-j)]=='O' || bd[j*4+(3-j)]=='.') vale=false; if(vale) state = 0; cout << ans[state] << endl; } int main(){ for(int i=0,T=in();i<T;i++){ cout << "Case #"<<i+1<<": "; solve(); } }
25.102941
160
0.485647
rbenic-fer
1fbf35864c65425ffcd01c5ce0f7aa92d11ea696
13,780
cpp
C++
Samples/Animation/Character.cpp
Ravbug/RavEngine-Samples
e9763cfb00758caaed430f38a5c99c0d44f701a7
[ "Apache-2.0" ]
4
2021-03-05T05:49:34.000Z
2022-03-30T15:30:46.000Z
Samples/Animation/Character.cpp
Ravbug/RavEngine-Samples
e9763cfb00758caaed430f38a5c99c0d44f701a7
[ "Apache-2.0" ]
null
null
null
Samples/Animation/Character.cpp
Ravbug/RavEngine-Samples
e9763cfb00758caaed430f38a5c99c0d44f701a7
[ "Apache-2.0" ]
null
null
null
#include "Character.hpp" #include <RavEngine/AnimationAsset.hpp> #include <RavEngine/MeshAssetSkinned.hpp> #include <RavEngine/BuiltinMaterials.hpp> #include <RavEngine/SkinnedMeshComponent.hpp> #include <RavEngine/ScriptComponent.hpp> #include <RavEngine/ChildEntityComponent.hpp> #include <RavEngine/StaticMesh.hpp> using namespace RavEngine; using namespace std; enum CharAnims { Idle, Walk, Run, Fall, Jump, PoundBegin, InPound, PoundEnd }; struct CharacterScript : public ScriptComponent, public RavEngine::IPhysicsActor { Ref<AnimatorComponent> animator; Ref<RigidBodyDynamicComponent> rigidBody; bool controlsEnabled = true; constexpr static decimalType sprintSpeed = 2.5, walkSpeed = 2; int16_t groundCounter = 0; CharacterScript(const decltype(animator)& a, const decltype(rigidBody)& r) : animator(a), rigidBody(r) {} inline bool OnGround() const { return groundCounter > 0; } void Tick(float fpsScale) final { switch (animator->GetCurrentState()) { case CharAnims::PoundBegin: case CharAnims::InPound: case CharAnims::PoundEnd: // hit the ground? go to poundEnd if (OnGround() && animator->GetCurrentState() != PoundEnd) { animator->Goto(PoundEnd); } break; default: { auto velocity = rigidBody->GetLinearVelocity(); auto movementVel = velocity; movementVel.y = 0; auto xzspeed = glm::length(movementVel); if (OnGround()) { if (xzspeed > 0.4 && xzspeed < 2.2) { animator->Goto(CharAnims::Walk); } else if (xzspeed >= 2.2) { animator->Goto(CharAnims::Run); } // not jumping? else if (velocity.y < 0.3) { animator->Goto(CharAnims::Idle); } } else { // falling and not in pound animation? if (velocity.y < -0.05) { switch (animator->GetCurrentState()) { case CharAnims::PoundBegin: case CharAnims::PoundEnd: case CharAnims::InPound: break; default: animator->Goto(CharAnims::Fall); } } } // jumping? if (velocity.y > 5) { animator->Goto(CharAnims::Jump); } } } if (GetTransform()->GetWorldPosition().y < -10) { GetTransform()->SetWorldPosition(vector3(0, 5, 0)); } } inline void Move(const vector3& dir, decimalType speedMultiplier) { if (controlsEnabled) { // apply movement only if touching the ground if (OnGround()) { // move in direction auto vec = dir * walkSpeed + dir * (speedMultiplier * sprintSpeed); vec.y = rigidBody->GetLinearVelocity().y; rigidBody->SetLinearVelocity(vec, false); rigidBody->SetAngularVelocity(vector3(0, 0, 0), false); } else { // in the air, you can slightly nudge your character in a direction rigidBody->AddForce(dir * 5.0); } // face direction auto rot = glm::quatLookAt(dir, GetTransform()->WorldUp()); GetTransform()->SetWorldRotation(glm::slerp(GetTransform()->GetWorldRotation(), rot, 0.2)); } } inline void Jump() { if (controlsEnabled) { if (OnGround()) { auto vel = rigidBody->GetLinearVelocity(); vel.y = 10; rigidBody->SetLinearVelocity(vel, false); } } } inline void Pound() { // we can pound if we are jumping or falling switch (animator->GetCurrentState()) { case CharAnims::Fall: case CharAnims::Jump: animator->Goto(CharAnims::PoundBegin); rigidBody->ClearAllForces(); rigidBody->SetLinearVelocity(vector3(0,0,0), false); break; default: break; } } void OnColliderEnter(const WeakRef<RavEngine::PhysicsBodyComponent>& other, const ContactPairPoint* contactPoints, size_t numContactPoints) final { if (other.lock()->filterGroup & FilterLayers::L0) { // we use filter layer 0 to mark ground auto worldpos = GetTransform()->GetWorldPosition(); // is this contact point underneath the character? for (int i = 0; i < numContactPoints; i++) { auto diff = worldpos.y - contactPoints[i].position.y; if (diff > -0.3) { groundCounter++; break; } } } } void OnColliderExit(const WeakRef<RavEngine::PhysicsBodyComponent>& other, const ContactPairPoint* contactPoints, size_t numContactPoints) final { if (other.lock()->filterGroup & FilterLayers::L0) { groundCounter--; } } inline void StartPounding() { rigidBody->SetGravityEnabled(true); rigidBody->SetLinearVelocity(vector3(0,-5,0),false); } }; Character::Character() { // setup animation // note: if you are loading multiple instances // of an animated character, you will want to load and store // the assets separately to avoid unnecessary disk i/o and parsing. auto skeleton = make_shared<SkeletonAsset>("character_anims.fbx"); auto all_clips = make_shared<AnimationAsset>("character_anims.fbx", skeleton); auto walk_anim = make_shared<AnimationAssetSegment>(all_clips, 0, 47); auto idle_anim = make_shared<AnimationAssetSegment>(all_clips, 60,120); auto run_anim = make_shared<AnimationAssetSegment>(all_clips, 131, 149); auto jump_anim = make_shared<AnimationAssetSegment>(all_clips, 160, 163); auto fall_anim = make_shared<AnimationAssetSegment>(all_clips, 171, 177); auto pound_begin_anim = make_shared<AnimationAssetSegment>(all_clips, 180, 195); auto pound_do_anim = make_shared<AnimationAssetSegment>(all_clips, 196, 200); auto pound_end_anim = make_shared<AnimationAssetSegment>(all_clips, 201, 207); auto mesh = make_shared<MeshAssetSkinned>("character_anims.fbx", skeleton); auto material = make_shared<PBRMaterialInstance>(Material::Manager::Get<PBRMaterial>()); material->SetAlbedoColor({1,0.4,0.2,1}); auto childEntity = make_shared<Entity>(); // I made the animation facing the wrong way GetTransform()->AddChild(childEntity->GetTransform()); // so I need a child entity to rotate it back childEntity->GetTransform()->LocalRotateDelta(vector3(0, glm::radians(180.f), 0)); // if your animations are the correct orientation you don't need this EmplaceComponent<ChildEntityComponent>(childEntity); // load the mesh and material onto the character auto cubemesh = childEntity->EmplaceComponent<SkinnedMeshComponent>(skeleton, mesh); cubemesh->SetMaterial(material); // load the collider and physics settings rigidBody = EmplaceComponent<RigidBodyDynamicComponent>(FilterLayers::L0, FilterLayers::L0 | FilterLayers::L1); EmplaceComponent<CapsuleCollider>(0.6, 1.3, make_shared<PhysicsMaterial>(0.0, 0.5, 0.0),vector3(0,1.7,0),vector3(0,0,glm::radians(90.0))); rigidBody->SetAxisLock(RigidBodyDynamicComponent::AxisLock::Angular_X | RigidBodyDynamicComponent::AxisLock::Angular_Z); rigidBody->SetWantsContactData(true); // load the animation auto animcomp = childEntity->EmplaceComponent<AnimatorComponent>(skeleton); // the Sockets feature allows you to expose transforms at bones on an animated skeleton as though they were their own entities. // this is useful for attaching an object to a character's hand, as shown below. auto handEntity = make_shared<Entity>(); MeshAssetOptions opt; opt.scale = 0.4f; handEntity->EmplaceComponent<StaticMesh>(MeshAsset::Manager::Get("cone.obj", opt),make_shared<PBRMaterialInstance>(Material::Manager::Get<PBRMaterial>())); auto handChildEntity = EmplaceComponent<ChildEntityComponent>(handEntity); auto handsocket = animcomp->AddSocket("character:hand_r"); // you must use the name from the importer. To see imported names, have your debugger print animcomp->skeleton->skeleton->joint_names_.data_+n handsocket->AddChild(handEntity->GetTransform()); // since this is just a normal transform, we can add an additional transformation handEntity->GetTransform()->LocalTranslateDelta(vector3(0,-0.5,0)); // create the animation state machine AnimatorComponent::State idle_state{ CharAnims::Idle, idle_anim }, walk_state{ CharAnims::Walk, walk_anim }, run_state{ CharAnims::Run, run_anim }, fall_state{ CharAnims::Fall, fall_anim }, jump_state{ CharAnims::Jump, jump_anim }, pound_begin_state{ CharAnims::PoundBegin, pound_begin_anim }, pound_do_state{ CharAnims::InPound, pound_do_anim }, pound_end_state{ CharAnims::PoundEnd, pound_end_anim }; // some states should not loop jump_state.isLooping = false; fall_state.isLooping = false; pound_begin_state.isLooping = false; pound_end_state.isLooping = false; pound_do_state.isLooping = false; // adjust the speed of clips walk_state.speed = 2.0; // create transitions // if a transition between A -> B does not exist, the animation will switch instantly. idle_state.SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew); walk_state.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.5, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::Blended) .SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.5, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew); run_state.SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::Blended) .SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.5, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew); jump_state.SetTransition(CharAnims::Fall, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::PoundBegin, TweenCurves::LinearCurve, 0.1, AnimatorComponent::State::Transition::TimeMode::BeginNew) ; pound_begin_state.SetTransition(CharAnims::InPound, TweenCurves::LinearCurve, 0.1, AnimatorComponent::State::Transition::TimeMode::BeginNew); pound_begin_state.SetAutoTransition(CharAnims::InPound); pound_do_state.SetTransition(CharAnims::PoundEnd, TweenCurves::LinearCurve, 0.1, AnimatorComponent::State::Transition::TimeMode::BeginNew); pound_end_state.SetAutoTransition(CharAnims::Idle); pound_end_state.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew); fall_state.SetTransition(CharAnims::Idle, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Walk, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Run, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::Jump, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) .SetTransition(CharAnims::PoundBegin, TweenCurves::LinearCurve, 0.2, AnimatorComponent::State::Transition::TimeMode::BeginNew) ; // this script controls the animation script = EmplaceComponent<CharacterScript>(animcomp, rigidBody); rigidBody->AddReceiver(script); // need to avoid a cyclical reference here WeakRef<CharacterScript> scriptref(script); pound_begin_state.SetBeginCallback([scriptref](uint16_t nextState) { auto ref = scriptref.lock(); ref->rigidBody->SetGravityEnabled(false); ref->controlsEnabled = false; }); pound_do_state.SetBeginCallback([=] (uint16_t nextState) { scriptref.lock()->StartPounding(); }); pound_end_state.SetEndCallback([=] (uint16_t nextState) { scriptref.lock()->controlsEnabled = true; }); // add transitions to the animator component // note that these are copied into the component, so making changes // to states after insertion will not work! animcomp->InsertState(walk_state); animcomp->InsertState(idle_state); animcomp->InsertState(run_state); animcomp->InsertState(jump_state); animcomp->InsertState(fall_state); animcomp->InsertState(pound_begin_state); animcomp->InsertState(pound_end_state); animcomp->InsertState(pound_do_state); // initialize the state machine // if an entry state is not set before play, your game will crash. animcomp->Goto(CharAnims::Idle, true); // begin playing the animator controller. // animator controllers are asynchronous to your other code // so play and pause simply signal the controller to perform an action animcomp->Play(); animcomp->debugEnabled = true; } void Character::Move(const vector3& dir, decimalType speedMultiplier){ script->Move(dir, speedMultiplier); } void Character::Jump() { script->Jump(); } void Character::Pound() { script->Pound(); }
42.269939
204
0.726633
Ravbug
1fc001e78659d76aa089e84c6fb9c70ecdce8d35
771
hxx
C++
src/core/include/ivy/log/ostream_sink.hxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
src/core/include/ivy/log/ostream_sink.hxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
src/core/include/ivy/log/ostream_sink.hxx
sikol/ivy
6365b8783353cf0c79c633bbc7110be95a55225c
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019, 2020, 2021 SiKol Ltd. * Distributed under the Boost Software License, Version 1.0. */ #ifndef IVY_LOG_OSTREAM_SINK_HXX_INCLUDED #define IVY_LOG_OSTREAM_SINK_HXX_INCLUDED #include <iosfwd> #include <ivy/log.hxx> namespace ivy::log { class ostream_sink final : public sink { std::ostream &_stream; public: ostream_sink(std::ostream &strm); auto log_message(std::chrono::system_clock::time_point timestamp, severity_code severity, std::string_view message) -> void final; }; auto make_ostream_sink(std::ostream &) -> std::unique_ptr<ostream_sink>; } // namespace ivy::log #endif // IVY_LOG_OSTREAM_SINK_HXX_INCLUDED
24.870968
77
0.64332
sikol
1fc4d55393aa617d1b67178c945ac0af91c30c99
1,410
hpp
C++
3rdparty/stout/include/stout/os/windows/dup.hpp
ruhip/mesos1.2.0
6f6d6786a91ee96fcd7cd435eee8933496c9903e
[ "Apache-2.0" ]
null
null
null
3rdparty/stout/include/stout/os/windows/dup.hpp
ruhip/mesos1.2.0
6f6d6786a91ee96fcd7cd435eee8933496c9903e
[ "Apache-2.0" ]
null
null
null
3rdparty/stout/include/stout/os/windows/dup.hpp
ruhip/mesos1.2.0
6f6d6786a91ee96fcd7cd435eee8933496c9903e
[ "Apache-2.0" ]
null
null
null
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef __STOUT_OS_WINDOWS_DUP_HPP__ #define __STOUT_OS_WINDOWS_DUP_HPP__ #include <io.h> #include <Winsock2.h> #include <stout/error.hpp> #include <stout/try.hpp> #include <stout/unreachable.hpp> #include <stout/os/windows/fd.hpp> namespace os { inline Try<WindowsFD> dup(const WindowsFD& fd) { switch (fd.type()) { case WindowsFD::FD_CRT: case WindowsFD::FD_HANDLE: { int result = ::_dup(fd.crt()); if (result == -1) { return ErrnoError(); } return result; } case WindowsFD::FD_SOCKET: { WSAPROTOCOL_INFO protInfo; if (::WSADuplicateSocket(fd, GetCurrentProcessId(), &protInfo) != INVALID_SOCKET) { return WSASocket(0, 0, 0, &protInfo, 0, 0); }; return SocketError(); } } UNREACHABLE(); } } // namespace os { #endif // __STOUT_OS_WINDOWS_DUP_HPP__
26.603774
75
0.684397
ruhip
1fc902b20a360f4ecad706065ade6472eb397ddb
752
hpp
C++
apps/openmw/mwgui/trainingwindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/trainingwindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/trainingwindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef MWGUI_TRAININGWINDOW_H #define MWGUI_TRAININGWINDOW_H #include "windowbase.hpp" #include "referenceinterface.hpp" namespace MWGui { class TrainingWindow : public WindowBase, public ReferenceInterface { public: TrainingWindow(); virtual void open(); virtual void exit(); void startTraining(MWWorld::Ptr actor); void onFrame(float dt); protected: virtual void onReferenceUnavailable (); void onCancelButtonClicked (MyGUI::Widget* sender); void onTrainingSelected(MyGUI::Widget* sender); MyGUI::Widget* mTrainingOptions; MyGUI::Button* mCancelButton; MyGUI::TextBox* mPlayerGold; float mFadeTimeRemaining; }; } #endif
19.282051
71
0.667553
Bodillium
1fc95ac4f843a7d18f0cc7d79d75d2890dab8756
9,315
cc
C++
codec/L2/demos/pikEnc/host/pik/chroma_from_luma_test.cc
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
855
2017-07-24T16:54:42.000Z
2022-03-11T01:33:14.000Z
codec/L2/demos/pikEnc/host/pik/chroma_from_luma_test.cc
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
59
2017-07-25T10:34:57.000Z
2019-11-28T15:16:58.000Z
codec/L2/demos/pikEnc/host/pik/chroma_from_luma_test.cc
vmayoral/Vitis_Libraries
2323dc5036041e18242718287aee4ce66ba071ef
[ "Apache-2.0" ]
60
2017-07-24T17:58:59.000Z
2022-03-11T01:33:22.000Z
// Copyright 2019 Google LLC // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #include "pik/chroma_from_luma.h" #include "gtest/gtest.h" #include "pik/block.h" #include "pik/butteraugli_distance.h" #include "pik/codec.h" #include "pik/common.h" #include "pik/dct_util.h" #include "pik/descriptive_statistics.h" #include "pik/image.h" #include "pik/opsin_image.h" #include "pik/opsin_inverse.h" #include "pik/quantizer.h" #include "pik/testdata_path.h" namespace pik { namespace { void RoundtripDC(const Image3F& in, Image3F* PIK_RESTRICT residuals, Image3F* PIK_RESTRICT restored) { const Rect rect(in); DequantMatrices dequant(/*need_inv_matrices=*/true); Quantizer quantizer(&dequant, in.xsize(), in.ysize()); quantizer.SetQuant(5.0f); CFL_Stats stats; *residuals = Image3F(in.xsize(), in.ysize()); *restored = Image3F(in.xsize(), in.ysize()); DecorrelateDC(in.Plane(1), in, rect, quantizer, 0, residuals, restored, &stats); Image3F restored2(restored->xsize(), restored->ysize()); RestoreDC(in.Plane(1), *residuals, rect, &restored2, &stats); // Restored images also need a Y channel for comparisons below. for (size_t by = 0; by < in.ysize(); ++by) { memcpy(restored->PlaneRow(1, by), in.ConstPlaneRow(1, by), in.xsize() * 4); memcpy(restored2.PlaneRow(1, by), in.ConstPlaneRow(1, by), in.xsize() * 4); } VerifyRelativeError(*restored, restored2, 1E-6, 1E-6); } TEST(ColorCorrelationTest, RoundtripFlatDC) { const size_t xsize_blocks = 5; const size_t ysize_blocks = 3; Image3F in(xsize_blocks, ysize_blocks); // Different values in each channel GenerateImage( [](size_t x, size_t y, int c) { return 2 * c + 0.5; // 0.5, 2.5, 4.5 }, &in); Image3F residuals, restored; RoundtripDC(in, &residuals, &restored); // Residuals are zero for (size_t c = 0; c < 3; c += 2) { for (size_t by = 0; by < ysize_blocks; ++by) { const float* PIK_RESTRICT row_res = residuals.ConstPlaneRow(c, by); for (size_t bx = 0; bx < xsize_blocks; ++bx) { if (bx == 0 && by == 0) continue; if (std::abs(row_res[bx]) > 1E-6f) { PIK_ABORT("c=%zu %zu %zu: %f\n", c, bx, by, row_res[bx]); } } } } // Near-exact reconstruction VerifyRelativeError(in, restored, 1E-5, 1E-4); } TEST(ColorCorrelationTest, RoundtripVertGradientDC) { const size_t xsize_blocks = 5; const size_t ysize_blocks = 3; Image3F in(xsize_blocks, ysize_blocks); // Different values in each channel GenerateImage([](size_t x, size_t y, int c) { return 0.5 * y + 1; }, &in); Image3F residuals, restored; RoundtripDC(in, &residuals, &restored); // Residuals are nearly zero double sum_abs_res = 0.0; for (size_t c = 0; c < 3; c += 2) { for (size_t by = 0; by < ysize_blocks; ++by) { const float* PIK_RESTRICT row_res = residuals.ConstPlaneRow(c, by); for (size_t bx = 0; bx < xsize_blocks; ++bx) { if (bx == 0 && by == 0) continue; sum_abs_res += std::abs(row_res[bx]); } } } PIK_CHECK(sum_abs_res < 3E-3); // Near-exact reconstruction VerifyRelativeError(in, restored, 5E-4, 5E-4); } TEST(ColorCorrelationTest, RoundtripRandomDC) { const size_t xsize_blocks = 9; const size_t ysize_blocks = 7; Image3F in(xsize_blocks, ysize_blocks); RandomFillImage(&in, 255.0f); Image3F residuals, restored; RoundtripDC(in, &residuals, &restored); // Nonzero residuals double sum_residuals = 0.0; for (size_t c = 0; c < 3; c += 2) { for (size_t by = 0; by < ysize_blocks; ++by) { const float* PIK_RESTRICT row_res = residuals.ConstPlaneRow(c, by); for (size_t bx = 0; bx < xsize_blocks; ++bx) { if (bx == 0 && by == 0) continue; sum_residuals += std::abs(row_res[bx]); } } } PIK_ASSERT(sum_residuals > xsize_blocks * ysize_blocks * 255 / 2); // Reasonable reconstruction VerifyRelativeError(in, restored, 5E-4, 6E-5); } void QuantizeBlock(const size_t c, const Quantizer& quantizer, const int32_t quant_ac, const float* PIK_RESTRICT from, const size_t from_stride, float* PIK_RESTRICT to, const size_t to_stride) { const AcStrategy acs(AcStrategy::Type::DCT, 0); PIK_ASSERT(acs.IsFirstBlock()); quantizer.QuantizeRoundtripBlockAC( c, 0, quant_ac, acs.GetQuantKind(), acs.covered_blocks_x(), acs.covered_blocks_y(), from, from_stride, to, to_stride); // Always use DCT8 quantization kind for DC const float mul = quantizer.DequantMatrix(0, kQuantKindDCT8, c)[0] * quantizer.inv_quant_dc(); to[0] = quantizer.QuantizeDC(c, from[0]) * mul; } void QuantizePlaneRow(const Image3F& from, const size_t c, const size_t by, const Quantizer& quantizer, Image3F* PIK_RESTRICT to) { PIK_ASSERT(SameSize(from, *to)); const size_t xsize = from.xsize(); PIK_ASSERT(xsize % kDCTBlockSize == 0); const float* row_from = from.ConstPlaneRow(c, by); float* row_to = to->PlaneRow(c, by); const int32_t* PIK_RESTRICT row_quant = quantizer.RawQuantField().Row(by); for (size_t bx = 0; bx < xsize / kDCTBlockSize; ++bx) { QuantizeBlock(c, quantizer, row_quant[bx], row_from + bx * kDCTBlockSize, from.PixelsPerRow(), row_to + bx * kDCTBlockSize, to->PixelsPerRow()); } } TEST(ColorCorrelationTest, RoundtripQuantized) { const std::string pathname = GetTestDataPath("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecContext codec_context; CodecInOut io_in(&codec_context); PIK_CHECK(io_in.SetFromFile(pathname, /*pool=*/nullptr)); io_in.ShrinkTo(io_in.xsize() & ~(kBlockDim - 1), io_in.ysize() & ~(kBlockDim - 1)); const size_t xsize_blocks = io_in.xsize() / kBlockDim; const size_t ysize_blocks = io_in.ysize() / kBlockDim; const Rect rect(0, 0, xsize_blocks, ysize_blocks); Image3F opsin = OpsinDynamicsImage(&io_in, Rect(io_in.color())); DequantMatrices dequant(/*need_inv_matrices=*/true); Quantizer quantizer(&dequant, xsize_blocks, ysize_blocks); quantizer.SetQuant(5.0f); Image3F dct(xsize_blocks * kDCTBlockSize, ysize_blocks); TransposedScaledDCT(opsin, &dct); const size_t cY = 1; // Input Y must be pre-quantized. Image3F quantized(dct.xsize(), dct.ysize()); for (size_t c = 0; c < 3; ++c) { for (size_t by = 0; by < ysize_blocks; ++by) { QuantizePlaneRow(dct, c, by, quantizer, &quantized); } } VerifyRelativeError(dct.Plane(cY), quantized.Plane(cY), 2.2E-2, 1E-3); // ------------------ DC const Image3F dc = DCImage(dct); const Image3F qdc = DCImage(quantized); Image3F residuals_dc(xsize_blocks, ysize_blocks); Image3F restored_dc(xsize_blocks, ysize_blocks); CFL_Stats stats_dc; DecorrelateDC(qdc.Plane(cY), dc, rect, quantizer, 0, &residuals_dc, &restored_dc, &stats_dc); printf("DC:\n"); stats_dc.Print(); Image3F restored2_dc(xsize_blocks, ysize_blocks); CFL_Stats stats2_dc; RestoreDC(qdc.Plane(cY), residuals_dc, rect, &restored2_dc, &stats2_dc); // Restored images also need a Y channel for comparisons below. for (size_t by = 0; by < ysize_blocks; ++by) { memcpy(restored_dc.PlaneRow(cY, by), qdc.ConstPlaneRow(cY, by), qdc.xsize() * sizeof(float)); memcpy(restored2_dc.PlaneRow(cY, by), qdc.ConstPlaneRow(cY, by), qdc.xsize() * sizeof(float)); } VerifyRelativeError(restored_dc, restored2_dc, 3E-4, 1E-5); VerifyRelativeError(dc, restored_dc, 2E-2, 1E-3); // ------------------ AC Image3F residuals(dct.xsize(), dct.ysize()); Image3F restored(dct.xsize(), dct.ysize()); CFL_Stats stats; DecorrelateAC(quantized.Plane(cY), dct, rect, quantizer, 0, &residuals, &restored, &stats); printf("AC:\n"); stats.Print(); FillDC(restored_dc, &restored); Image3F restored2(dct.xsize(), dct.ysize()); CFL_Stats stats2; RestoreAC(quantized.Plane(cY), residuals, rect, &restored2, &stats2); FillDC(restored_dc, &restored2); // Restored images also need a Y channel for comparisons below. for (size_t by = 0; by < ysize_blocks; ++by) { memcpy(restored.PlaneRow(cY, by), quantized.ConstPlaneRow(cY, by), dct.xsize() * sizeof(float)); memcpy(restored2.PlaneRow(cY, by), quantized.ConstPlaneRow(cY, by), dct.xsize() * sizeof(float)); } VerifyRelativeError(restored, restored2, 3E-4, 1E-5); VerifyRelativeError(dct, restored, 2E-2, 1E-3); Image3F idct_restored(xsize_blocks * kBlockDim, ysize_blocks * kBlockDim); TransposedScaledIDCT(restored, &idct_restored); OpsinToLinear(&idct_restored, /*pool=*/nullptr); CodecInOut io_restored(&codec_context); io_restored.SetFromImage(std::move(idct_restored), codec_context.c_linear_srgb[0]); (void)io_restored.EncodeToFile(codec_context.c_srgb[0], 8, "/tmp/dct_idct.png"); const float dist_restored = ButteraugliDistance(&io_in, &io_restored, 1.0f, /*distmap=*/nullptr, /*pool=*/nullptr); printf("dist restored %.2f\n", dist_restored); } } // namespace } // namespace pik
34.120879
79
0.658937
vmayoral
1fcadab0db2c8335c2dd90aa29cf8d131edce2e2
2,184
hpp
C++
SbgatGui/include/LCVisualizer.hpp
bbercovici/SBGAT
93e935baff49eb742470d7d593931f0573f0c062
[ "MIT" ]
6
2017-11-29T02:47:00.000Z
2021-09-26T05:25:44.000Z
SbgatGui/include/LCVisualizer.hpp
bbercovici/SBGAT
93e935baff49eb742470d7d593931f0573f0c062
[ "MIT" ]
34
2017-02-09T15:38:35.000Z
2019-04-25T20:53:37.000Z
SbgatGui/include/LCVisualizer.hpp
bbercovici/SBGAT
93e935baff49eb742470d7d593931f0573f0c062
[ "MIT" ]
1
2019-03-12T12:20:25.000Z
2019-03-12T12:20:25.000Z
/** MIT License Copyright (c) 2018 Benjamin Bercovici and Jay McMahon 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. */ #ifndef HEADER_LC_VIZUALIZER #define HEADER_LC_VIZUALIZER #include "LCWindow.hpp" #include <QVTKOpenGLWidget.h> #include <vtkRenderer.h> #include <vtkImageData.h> #include <QPushButton> #include <vtkContextView.h> #include <QVTKWidget.h> namespace SBGAT_GUI { class RadarWindow; /*! @class LCVisualizer \author Benjamin Bercovici \date March, 2018 \brief LCVisualizer class defining a window where a user can visualize previously computed lightcurves \details TODO */ class LCVisualizer : public QDialog { Q_OBJECT public: /** Creates the settings window @param parent pointer to parent window. @param measurements reference to vector of arrays of (time,luminosity) */ LCVisualizer(LCWindow * parent,const std::vector<std::array<double, 2> > & measurements) ; /** Initializes the visualizer window */ void init(const std::vector<std::array<double, 2> > & measurements); private slots: protected: QVTKOpenGLWidget * qvtkWidget; LCWindow * parent; vtkSmartPointer<vtkContextView> view; QDialogButtonBox * button_box; }; } #endif
25.395349
102
0.771978
bbercovici
1fcbf5611c831db23504fb8b66e189f045a46705
1,358
cpp
C++
src/toolchain/core/Misc/Location.cpp
layerzero/cc0
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
[ "BSD-2-Clause" ]
null
null
null
src/toolchain/core/Misc/Location.cpp
layerzero/cc0
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
[ "BSD-2-Clause" ]
null
null
null
src/toolchain/core/Misc/Location.cpp
layerzero/cc0
fa3f8f1f7bbc38ca5b6b8864c80223191b3b1f09
[ "BSD-2-Clause" ]
2
2015-03-03T04:36:51.000Z
2018-10-01T03:04:11.000Z
#include "Location.h" Location::Location() { this->FileName = ""; this->Line = 0; this->Column = 0; } /* int Location::ComparesTo(const Location& other) const { if (this->FileName != other.FileName) { return 0; } int diff = this->Line - other.Line; if (diff != 0) { return diff; } diff = this->Column - other.Column; return diff; } Location& Location::operator=(const Location & other) { this->Line = other.Line; this->Column = other.Column; return *this; } bool Location::operator==(const Location& other) const { return (this->ComparesTo(other) == 0); } bool Location::operator!=(const Location& other) const { return (this->ComparesTo(other) != 0) || (this->FileName != other.FileName); } bool Location::operator>(const Location& other) const { return (this->FileName == other.FileName) &&(this->ComparesTo(other) > 0); } bool Location::operator>=(const Location& other) const { return (this->FileName == other.FileName) &&(this->ComparesTo(other) >= 0); } bool Location::operator<(const Location& other) const { return (this->FileName == other.FileName) &&(this->ComparesTo(other) < 0); } bool Location::operator<=(const Location& other) const { return (this->FileName == other.FileName) &&(this->ComparesTo(other) <= 0); }*/
20.892308
81
0.623711
layerzero
1fccc513104b82f2e92b77eb0c65c400e5ced3f2
3,461
cpp
C++
src/main.cpp
khskarl/tori
52e07e7b8bdbab7b46c4565a6be9353c0ce59422
[ "MIT" ]
2
2018-07-05T23:50:20.000Z
2020-02-07T12:34:05.000Z
src/main.cpp
khskarl/tori
52e07e7b8bdbab7b46c4565a6be9353c0ce59422
[ "MIT" ]
null
null
null
src/main.cpp
khskarl/tori
52e07e7b8bdbab7b46c4565a6be9353c0ce59422
[ "MIT" ]
null
null
null
// 3rdparty Headers #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> // Standard Headers #include <cstdio> #include <cstdlib> #include <iostream> // Local Headers #include <ImGui.hpp> #include <Assets/AssetManager.hpp> #include "Graphics/Renderer.hpp" #include "Graphics/Context.hpp" #include "Graphics/Program.hpp" #include "Graphics/Mesh.hpp" #include "Graphics/Camera.hpp" #include "Graphics/Material.hpp" #include "GameObject.hpp" // General variables const float dt = 1.f / 60.f; glm::vec2 mLastCursorPosition(0, 0); glm::ivec2 mWindowSize(1280, 800); // Camera Camera mCamera(glm::vec3(0, 5, -5), glm::vec3(0, -1, 1), mWindowSize.x, mWindowSize.y); static void CursorPositionCallback(GLFWwindow* window, double xpos, double ypos) { int state = glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_RIGHT); if (state == GLFW_PRESS && !ImGui::IsMouseHoveringAnyWindow()) { float dx = xpos - mLastCursorPosition.x; float dy = ypos - mLastCursorPosition.y; mCamera.RotatePitch(-dy * 10.f * dt); mCamera.RotateYaw ( dx * 10.f * dt); glfwSetCursorPos(window, mWindowSize.x / 2, mWindowSize.y / 2); } glfwGetCursorPos(window, &xpos, &ypos); mLastCursorPosition = { xpos, ypos }; } int main(int argc, char * argv[]) { Context::Initialize(); Context::SetCursorPositionCallback(CursorPositionCallback); // AssetManager::Get().Setup(); Renderer renderer; renderer.SetActiveCamera(&mCamera); renderer.Setup(); GameObject* sphere = new GameObject(); sphere->m_model = Model("sphere.obj", "woodfloor.mat"); sphere->m_position = glm::vec3(0, 0, 0); renderer.Submit(sphere); // GameObject* bamboo = new GameObject(); // bamboo->m_model = Model("sphere.obj", // "rusted_albedo.png", // "rusted_normal.png", // "rusted_roughness.png", // "rusted_metalness.png", // "rusted_ao.png"); // bamboo->m_position = glm::vec3(5, 0, 5); // renderer.Submit(bamboo); // Game Loop while ((Context::ShouldClose() || Context::IsKeyDown(GLFW_KEY_ESCAPE)) == false) { Context::PollEvents(); { static bool show_renderer_window = false; static bool show_texture_window = false; static bool show_material_window = false; if (ImGui::BeginMainMenuBar()) { if (ImGui::BeginMenu("Renderer")) { ImGui::MenuItem("Settings", NULL, &show_renderer_window); ImGui::EndMenu(); } if (ImGui::BeginMenu("Assets")) { ImGui::MenuItem("Textures", NULL, &show_texture_window); ImGui::MenuItem("Materials", NULL, &show_material_window); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } if (show_renderer_window) { renderer.RendererWindow(&show_renderer_window); } if (show_texture_window) { AssetManager::Get().TexturesWindow(&show_texture_window); } if (show_material_window) { AssetManager::Get().MaterialsWindow(&show_material_window); } } if (Context::IsKeyDown(GLFW_KEY_W)) mCamera.MoveForward( 10 * dt); if (Context::IsKeyDown(GLFW_KEY_A)) mCamera.MoveRight (-10 * dt); if (Context::IsKeyDown(GLFW_KEY_S)) mCamera.MoveForward(-10 * dt); if (Context::IsKeyDown(GLFW_KEY_D)) mCamera.MoveRight ( 10 * dt); if (Context::IsKeyDown(GLFW_KEY_R)) renderer.m_mainProgram->Reload(); renderer.RenderFrame(); Context::SwapBuffers(); } Context::Destroy(); return 0; }
28.841667
87
0.672349
khskarl
1fd066c758fcecb9c26be0249bce8b5f92170893
2,484
cpp
C++
src/pca9685_motors.cpp
Mailamaca/motors_interface
c7062e5e6f1de36cfbe8904fa578d6f2bfc3d506
[ "MIT" ]
null
null
null
src/pca9685_motors.cpp
Mailamaca/motors_interface
c7062e5e6f1de36cfbe8904fa578d6f2bfc3d506
[ "MIT" ]
null
null
null
src/pca9685_motors.cpp
Mailamaca/motors_interface
c7062e5e6f1de36cfbe8904fa578d6f2bfc3d506
[ "MIT" ]
1
2021-12-03T16:01:31.000Z
2021-12-03T16:01:31.000Z
#include "motors_interface/pca9685_motors.h" // Constructor PCA9685Motors::PCA9685Motors() { } bool PCA9685Motors::setupPCA9685(bool real_hardware) { m_real_hardware = real_hardware; if (m_real_hardware) { // Calling wiringPi setup first. wiringPiSetup(); // Setup with pinbase 300 and i2c location 0x40 int fd0 = pca9685Setup(PCA9685_PIN_BASE , PCA9685_ADDRESS, PCA9685_HERTZ); if (fd0 < 0) { return false; } pca9685PWMReset(fd0); } return true; } void PCA9685Motors::setPwmMotorParams( PWMMotor **motor, float output_half_range, float output_half_dead_range, float output_center_value) { *motor = new PWMMotor( output_half_range, output_half_dead_range, output_center_value, PCA9685_MAX_PWM ); } /** * @brief trim value between -1 and 1 * * @param value * @return float value trimmed [-1,1] */ float PCA9685Motors::trim(float value){ if(value > 1.) { return 1.0; } else if(value < -1.) { return -1.0; } else { return value; } } void PCA9685Motors::setSteeringParams( float input_max_value, float output_half_range, float output_half_dead_range, float output_center_value) { m_max_steering = input_max_value; setPwmMotorParams( &m_steering_pwm, output_half_range, output_half_dead_range, output_center_value); } void PCA9685Motors::setThrottleParams( float input_max_value, float output_half_range, float output_half_dead_range, float output_center_value) { m_max_throttle = input_max_value; setPwmMotorParams( &m_throttle_pwm, output_half_range, output_half_dead_range, output_center_value); } float PCA9685Motors::setThrottle(float throttle) { throttle = trim(throttle/m_max_throttle); int th = m_throttle_pwm->calculate(throttle); if (m_real_hardware) { pwmWrite(PCA9685_PIN_BASE + PCA9685_THROTTLE_CH, th); } return throttle; } float PCA9685Motors::setSteering(float steering) { steering = trim(steering/m_max_steering); int st = m_steering_pwm->calculate(steering); if (m_real_hardware) { pwmWrite(PCA9685_PIN_BASE + PCA9685_STEERING_DX_CH, st); pwmWrite(PCA9685_PIN_BASE + PCA9685_STEERING_SX_CH, st); } return steering; }
22.788991
82
0.651369
Mailamaca
1fd8bc11becb581a448e8784dd7166e27bfe1912
1,466
hpp
C++
src/coin/coin.hpp
datavetaren/epilog
7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820
[ "MIT" ]
null
null
null
src/coin/coin.hpp
datavetaren/epilog
7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820
[ "MIT" ]
null
null
null
src/coin/coin.hpp
datavetaren/epilog
7067a4cf5b62dd8eca3ab9395fbb1b85d95a9820
[ "MIT" ]
null
null
null
#pragma once #ifndef _epilog_coin_coin_hpp #define _epilog_coin_coin_hpp #include "../interp/interpreter_base.hpp" namespace epilog { namespace coin { // Any term that has arity >= 2 and whose functor's name starts with '$' // is a coin. // The first argument must be an integer telling its value, // The second argument is either unbound (unspent) or not (spent.) static inline bool is_coin(interp::interpreter_base &interp, common::term t) { if (t.tag() != common::tag_t::STR) { return false; } auto f = interp.functor(t); if (f.arity() < 2) { return false; } return interp.is_dollar_atom_name(f); } static inline bool is_native_coin(interp::interpreter_base &interp, common::term t) { return interp.is_functor(t, common::con_cell("$coin",2)); } static inline bool is_coin_spent(interp::interpreter_base &interp, common::term t) { assert(is_coin(interp, t)); return !interp.arg(t, 1).tag().is_ref(); } static inline bool spend_coin(interp::interpreter_base &interp, common::term t) { assert(is_coin(interp, t)); assert(!is_coin_spent(interp, t)); return interp.unify(interp.arg(t, 1), common::term_env::EMPTY_LIST); } static inline int64_t coin_value(interp::interpreter_base &interp, common::term t) { assert(is_coin(interp, t)); common::term v = interp.arg(t, 0); assert(v.tag() == common::tag_t::INT); return reinterpret_cast<common::int_cell &>(v).value(); } }} #endif
29.32
85
0.688267
datavetaren
1fd8d06dc16a83647d55c6c0b1dd1777716d0efb
2,361
cpp
C++
SUAI/C1/LabOP4/sources/seeker_cpp/main.cpp
mersinvald/SUAI-1441
0ad15112aa8794e501fd6794db795e3312ae538c
[ "MIT" ]
1
2017-01-23T17:38:59.000Z
2017-01-23T17:38:59.000Z
SUAI/C1/LabOP4/sources/seeker_cpp/main.cpp
mersinvald/SUAI-1441
0ad15112aa8794e501fd6794db795e3312ae538c
[ "MIT" ]
null
null
null
SUAI/C1/LabOP4/sources/seeker_cpp/main.cpp
mersinvald/SUAI-1441
0ad15112aa8794e501fd6794db795e3312ae538c
[ "MIT" ]
1
2016-05-28T05:18:04.000Z
2016-05-28T05:18:04.000Z
#include <stdio.h> void getInput(int &width, int &heigth, int** &bitmap, //array[w][h], initializing in function; int* &exitPoint, //array[2], 0 - x, 1 - y; int* &startPoint); void printBitmap(int **bitmap, int w, int h); int main() { int width, heigth; int* startPoint; int* exitPoint; int** bitmap; getInput(width, heigth, bitmap, exitPoint, startPoint); //передаем ссылки на массивы и переменные, чтобы ф-я могла в них писать printBitmap(bitmap, width, heigth); return 0; } void getInput(int &width, int &heigth, int** &bitmap, int* &exitPoint, int* &startPoint) //получаем указатели на переданные переменные { unsigned int i, j, x, y, bit, valid = 0; //unsigned, чтобы не было отрицательного ввода. Знаю, сурово, ибо сегфолт. printf("Enter labyrinth width: "); scanf("%i", &width); printf("Enter labyrinth heigth: "); scanf("%i", &heigth); //get WxH bitmam printf("Enter labyrinth bitmap:\n"); bitmap = new int*[heigth]; //резервируем память для $heigth строк for(i = 0; i < heigth; i++) { bitmap[i] = new int[width]; //резервируем память для width ячеек в строке i for(j = 0; j < width; j++) scanf("%i", &bitmap[i][j]); } while(!valid) //ввод выходной точки { printf("\nEnter labyrinth exit point x y: "); scanf("%i%i", &x, &y); bit = bitmap[x][y]; if(x <= width && y <= heigth && bit != 0) valid = 1; else printf("Point is out of map bounds or wall!\n"); } //резервируем 2 ячейки по размеру int и пишем в них xy exitPoint = new int[2]; exitPoint[0] = x; exitPoint[1] = y; valid = 0; while(!valid) //ввод стартовой позиции { printf("\nEnter labyrinth start point x y: "); scanf("%i%i", &x, &y); bit = bitmap[x][y]; if(x <= width && y <= heigth && bit != 0) valid = 1; else printf("Point is out of map bounds or wall!\n"); } //резервируем и пишем xy startPoint = new int[2]; startPoint[0] = x; startPoint[1] = y; } void printBitmap(int **bitmap, int w, int h) { int i, j; for(i = 0; i < h; i++){ for(j = 0; j < w; j++) printf("%i", bitmap[i][j]); printf("\n"); } }
27.776471
134
0.545108
mersinvald
1fd91438fd7dece051485f2ca4a07d1bdca660be
3,442
hpp
C++
mineworld/terminal.hpp
Lollipop-Studio/mineworld
539897831ddc5e669bdff62f54a29a5d01358aa1
[ "MIT" ]
18
2019-09-26T16:38:02.000Z
2022-03-09T06:44:59.000Z
mineworld/terminal.hpp
Lollipop-Studio/mineworld
539897831ddc5e669bdff62f54a29a5d01358aa1
[ "MIT" ]
2
2019-12-05T02:15:07.000Z
2021-11-22T08:33:30.000Z
mineworld/terminal.hpp
Lollipop-Studio/mineworld
539897831ddc5e669bdff62f54a29a5d01358aa1
[ "MIT" ]
7
2020-01-13T21:18:37.000Z
2021-09-07T00:31:33.000Z
#ifndef terminal_hpp #define terminal_hpp #include <iostream> #include <string> #include <vector> #include <deque> #include <GL/glew.h> #include <GLFW/glfw3.h> #include <glm/glm.hpp> #include "shape.hpp" #include "util.hpp" #include "cell.hpp" #include "handler.hpp" #include "block.hpp" #include "types.hpp" namespace mineworld { struct font_loc_t { int x, y; font_loc_t(int x, int y) : x(x), y(y) {} }; font_loc_t getFontLoc(char c); rect2D createCharRect(const font_loc_t & fl); /* * font */ class Font { rect2D fontset[16 * 6]; public: GLuint textureID, program; void load(); rect2D getCharRect(char c) { if (c <= 32) return fontset[0]; else return fontset[c - 32]; } ~Font() { glDeleteTextures(1, &textureID); } }; /* * view the screen content as 2D array * draw again if contents being updated */ class Screen { protected: int width, height; int capcity; glRect2DBuffer * glbuffer; std::string screencontent; Font font; float fontw, fonth; public: void init(); int getWidth() { return width; } int getHeight() { return height; } void resize(); void putc(int pos, char c); void print(int start, int size, const char * str); void clear(); void flush(); void show(); }; /* * print message to screen "line by line" * execute command */ class Terminal : public Screen { std::deque<std::string> lines; int cursor, tail; bool edited = false; public: Terminal() {} void init() { Screen::init(); lines.push_back(std::string("> ")); edited = true; } void flush(); void resize() { Screen::resize(); edited = true; } void inputc(unsigned int c) { // input a character lines.rbegin()->push_back((char)c); edited = true; } void del() { // delete a character if (lines.rbegin()->size() > 2) lines.rbegin()->pop_back(); edited = true; } void execute(); // execute command void println(const std::string & str) { // print one line to screen lines.push_back(str); std::cout << str << std::endl; edited = true; } }; /* * display a single line */ class Board : public Screen { std::string displayline; bool edited = false; public: void init() { Screen::init(); display(std::string(MW_VERSION)); } void resize() { Screen::resize(); edited = true; } void display(const std::string & str) { displayline = str; clear(); print(0, displayline.size(), displayline.c_str()); edited = true; } void flush() { if (edited) Screen::flush(); } }; extern Terminal gterminal; extern Board gboard; } #endif /* terminal_hpp */
22.496732
75
0.478501
Lollipop-Studio
1fd985113702245f49b83fee1405a750b52fb3d3
1,314
cpp
C++
src/Parse/BasicTreeVisitor.cpp
Naios/swy
c48f7eb4322aa7fd44a3bb82259787b89292733b
[ "Apache-2.0" ]
19
2017-06-04T09:39:51.000Z
2021-11-16T10:14:45.000Z
src/Parse/BasicTreeVisitor.cpp
Naios/swy
c48f7eb4322aa7fd44a3bb82259787b89292733b
[ "Apache-2.0" ]
null
null
null
src/Parse/BasicTreeVisitor.cpp
Naios/swy
c48f7eb4322aa7fd44a3bb82259787b89292733b
[ "Apache-2.0" ]
1
2019-03-19T02:24:40.000Z
2019-03-19T02:24:40.000Z
/** Copyright(c) 2016 - 2017 Denis Blank <denis.blank at outlook dot com> 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 "BasicTreeVisitor.hpp" SourceRange BasicTreeVisitor::sourceRangeOf(antlr4::tree::TerminalNode* token) const { return sourceLocationOf(token).extend(token->getText().length()); /* TODO FIXME interval is returned with { 0, 0 } from antlr. auto interval = token->getSourceInterval(); auto lower = sourceLocationOf(tokenStream_->get(interval.a)); auto upper = sourceLocationOf(tokenStream_->get(interval.b)); return { lower, upper }; */ } SourceRange BasicTreeVisitor::sourceRangeOf(antlr4::tree::TerminalNode* begin, antlr4::tree::TerminalNode* end) const { return SourceRange::concat(sourceRangeOf(begin), sourceRangeOf(end)); }
34.578947
74
0.732116
Naios
1fe1e26fa6c9490778dc7dde89ad97b152ba5129
1,524
cpp
C++
cpp/algorithm_ranges_inplace_merge.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/algorithm_ranges_inplace_merge.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
cpp/algorithm_ranges_inplace_merge.cpp
rpuntaie/c-examples
385b3c792e5b39f81a187870100ed6401520a404
[ "MIT" ]
null
null
null
/* g++ --std=c++20 -pthread -o ../_build/cpp/algorithm_ranges_inplace_merge.exe ./cpp/algorithm_ranges_inplace_merge.cpp && (cd ../_build/cpp/;./algorithm_ranges_inplace_merge.exe) https://en.cppreference.com/w/cpp/algorithm/ranges/inplace_merge */ #include <algorithm> #include <complex> #include <functional> #include <iostream> #include <iterator> #include <vector> void print(auto const& v, auto const& rem, int middle = -1) { for (int i{}; auto n : v) std::cout << (i++ == middle ? "│ " : "") << n << ' '; std::cout << rem << '\n'; } template <std::random_access_iterator I, std::sentinel_for<I> S> requires std::sortable<I> void merge_sort(I first, S last) { if (last - first > 1) { I middle {first + (last - first) / 2}; merge_sort(first, middle); merge_sort(middle, last); std::ranges::inplace_merge(first, middle, last); } } int main() { // custom merge-sort demo std::vector v {8, 2, 0, 4, 9, 8, 1, 7, 3}; print(v, ": before sort"); merge_sort(v.begin(), v.end()); print(v, ": after sort\n"); // merging with comparison function object and projection using CI = std::complex<int>; std::vector<CI> r { {0,1}, {0,2}, {0,3}, {1,1}, {1,2} }; const auto middle { std::ranges::next(r.begin(), 3) }; auto comp { std::ranges::less{} }; auto proj { [](CI z) { return z.imag(); } }; print(r, ": before merge", middle - r.begin()); std::ranges::inplace_merge(r, middle, comp, proj); print(r, ": after merge"); }
33.130435
177
0.60105
rpuntaie
1fe1e8a508a7b089e04781df67f510873ae5e21f
885
cpp
C++
LightOj/1053 - Higher Math.cpp
MhmdRyhn/Programming-Sloution
be189cbf81b14ac7c10d387e259aa23992ba1016
[ "MIT" ]
1
2019-07-29T04:05:34.000Z
2019-07-29T04:05:34.000Z
LightOj/1053 - Higher Math.cpp
MhmdRyhn/Programming-Sloution
be189cbf81b14ac7c10d387e259aa23992ba1016
[ "MIT" ]
null
null
null
LightOj/1053 - Higher Math.cpp
MhmdRyhn/Programming-Sloution
be189cbf81b14ac7c10d387e259aa23992ba1016
[ "MIT" ]
null
null
null
#include<cstdio> #include<cmath> using namespace std; int main() { int t,a=5,b=10,c; scanf("%d",&t); for(int i=0; i<t; i++) { scanf("%d%d%d",&a,&b,&c); /*printf("Direct: %s\n",(a>b and a>c and a*a==(b*b+c*c))? "yes": ((b>a and b>c and b*b==(a*a+c*c))? "yes":((c*c==(a*a+b*b))? "yes":"no"))); */ printf("Case %d: ",i+1); if(a>b and a>c) { if(a*a==(b*b+c*c)) printf("yes"); else printf("no"); } else if(b>c and b>a) { if(b*b==(a*a+c*c)) printf("yes"); else printf("no"); } else { if(c*c==(a*a+b*b)) printf("yes"); else printf("no"); } printf("\n"); } return 0; }
19.666667
89
0.328814
MhmdRyhn
1fe1ede3b6795ed7de178573fa3a5d4db6736875
2,798
cpp
C++
src/gui/icons/small_up_icon.cpp
jojoelfe/cisTEM
6d5bc5803fd726022c381e65a721a24661b48639
[ "BSD-3-Clause" ]
7
2020-09-09T10:59:59.000Z
2020-11-19T15:26:53.000Z
src/gui/icons/small_up_icon.cpp
jojoelfe/cisTEM
6d5bc5803fd726022c381e65a721a24661b48639
[ "BSD-3-Clause" ]
85
2020-09-11T15:07:02.000Z
2021-02-08T20:38:13.000Z
src/gui/icons/small_up_icon.cpp
jojoelfe/cisTEM
6d5bc5803fd726022c381e65a721a24661b48639
[ "BSD-3-Clause" ]
6
2021-03-26T13:04:10.000Z
2021-11-18T19:28:16.000Z
static const unsigned char small_up_icon_png[] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x07, 0x08, 0x06, 0x00, 0x00, 0x00, 0x3c, 0xb2, 0xac, 0x24, 0x00, 0x00, 0x00, 0x06, 0x62, 0x4b, 0x47, 0x44, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xa0, 0xbd, 0xa7, 0x93, 0x00, 0x00, 0x00, 0x09, 0x70, 0x48, 0x59, 0x73, 0x00, 0x00, 0x0b, 0x13, 0x00, 0x00, 0x0b, 0x13, 0x01, 0x00, 0x9a, 0x9c, 0x18, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45, 0x07, 0xe1, 0x09, 0x08, 0x16, 0x1e, 0x0d, 0x6b, 0x33, 0xb4, 0xb9, 0x00, 0x00, 0x01, 0x50, 0x49, 0x44, 0x41, 0x54, 0x18, 0xd3, 0x63, 0x60, 0x90, 0xaa, 0x63, 0x60, 0x60, 0x60, 0x60, 0x60, 0x68, 0xf8, 0xcf, 0xc0, 0xc0, 0xc0, 0xc0, 0xc0, 0x29, 0x95, 0xa6, 0x29, 0xe1, 0xb7, 0xf8, 0xa0, 0x62, 0xc8, 0xc2, 0x75, 0x0c, 0x0c, 0xbc, 0x12, 0x0c, 0x0c, 0x0c, 0x0c, 0x39, 0x5f, 0xff, 0x33, 0x32, 0x30, 0x30, 0x30, 0x88, 0xea, 0xfb, 0x30, 0xa0, 0x00, 0x56, 0x06, 0x37, 0x4d, 0x26, 0xc7, 0x79, 0x8f, 0xe4, 0xab, 0x2f, 0xfc, 0x77, 0xec, 0xbe, 0xfe, 0x5f, 0x3b, 0x61, 0xdd, 0x11, 0x06, 0x46, 0x16, 0x31, 0x64, 0x35, 0x4c, 0x0c, 0x33, 0xff, 0x43, 0x99, 0x6a, 0x2a, 0xbf, 0xad, 0x82, 0xf6, 0xfc, 0x53, 0xd3, 0x94, 0x65, 0xfb, 0xf7, 0x8b, 0xc1, 0x4a, 0x9d, 0x93, 0xc1, 0xc2, 0x52, 0xc3, 0x5a, 0x3b, 0x71, 0xed, 0x46, 0x7e, 0x7e, 0x06, 0x41, 0x06, 0x06, 0x06, 0x86, 0xbe, 0xff, 0xff, 0x19, 0x99, 0x18, 0xd2, 0x19, 0x19, 0x18, 0x18, 0xdc, 0xf4, 0x18, 0xac, 0x0a, 0x8f, 0x30, 0xe8, 0x19, 0x48, 0x31, 0xff, 0xfa, 0xc9, 0xf0, 0xf4, 0xc8, 0xf9, 0x55, 0x8f, 0xae, 0x3c, 0x3d, 0xa9, 0xaa, 0xc4, 0xcf, 0xc0, 0x2d, 0x2a, 0x6c, 0x21, 0xee, 0xbb, 0x76, 0xa7, 0xa6, 0xab, 0xb7, 0x74, 0x11, 0x23, 0xe3, 0x7f, 0x66, 0x36, 0x91, 0x54, 0xc3, 0x7f, 0xc6, 0x6e, 0xbb, 0x18, 0xf4, 0x0d, 0xc5, 0x19, 0x3f, 0x7f, 0x62, 0x60, 0xbb, 0x7a, 0x61, 0xc5, 0xf7, 0x13, 0xb9, 0x11, 0x97, 0x0e, 0x69, 0xaf, 0x92, 0x34, 0x90, 0xf0, 0x12, 0x90, 0x12, 0x94, 0x38, 0x72, 0xf9, 0x8d, 0x34, 0x27, 0xb7, 0xa6, 0xad, 0x82, 0xb6, 0xf4, 0x4e, 0x66, 0x3d, 0xe7, 0xf4, 0x4e, 0x69, 0x7b, 0x33, 0xab, 0x67, 0x77, 0x5f, 0x32, 0x30, 0x9c, 0x3d, 0xb1, 0xe4, 0xcf, 0x95, 0xaa, 0x68, 0x06, 0x06, 0x06, 0x06, 0x86, 0x7f, 0xbb, 0x7e, 0x5e, 0xfa, 0x60, 0xbf, 0xda, 0xc1, 0x4c, 0xd6, 0x59, 0x46, 0x59, 0x58, 0xea, 0xee, 0xf3, 0x9f, 0xd2, 0x9c, 0x7f, 0x39, 0x1f, 0x32, 0x31, 0xfe, 0xfc, 0xb5, 0xf6, 0xd7, 0xd5, 0xeb, 0xaf, 0x99, 0xae, 0x9c, 0x9d, 0xc1, 0x70, 0xbb, 0x21, 0x96, 0x81, 0x81, 0x81, 0x81, 0x57, 0xb7, 0x97, 0x31, 0x77, 0xd9, 0x63, 0x46, 0x86, 0x13, 0x91, 0x6f, 0xa7, 0x2c, 0x7f, 0xec, 0xa8, 0x25, 0xc6, 0x77, 0xc0, 0xc7, 0x56, 0xe9, 0xde, 0xb3, 0x1f, 0x2c, 0xfb, 0x01, 0x96, 0x73, 0x6d, 0xae, 0x21, 0x6e, 0xef, 0xf7, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82, };
68.243902
72
0.659042
jojoelfe
1fe36009b980067522a5cde822fabc2266624f9a
461
cpp
C++
X-Engine/src/XEngine/Core/Window.cpp
JohnMichaelProductions/X-Engine
218ffcf64bfe5d5aed51b483c6f6986831ceeec4
[ "Apache-2.0" ]
4
2020-02-17T07:08:26.000Z
2020-08-07T21:35:12.000Z
X-Engine/src/XEngine/Core/Window.cpp
JohnMichaelProductions/X-Engine
218ffcf64bfe5d5aed51b483c6f6986831ceeec4
[ "Apache-2.0" ]
25
2020-03-08T05:35:25.000Z
2020-07-08T01:59:52.000Z
X-Engine/src/XEngine/Core/Window.cpp
JohnMichaelProductions/X-Engine
218ffcf64bfe5d5aed51b483c6f6986831ceeec4
[ "Apache-2.0" ]
1
2020-10-15T12:39:29.000Z
2020-10-15T12:39:29.000Z
// Source file for Window class, decides to create a window based on the platform #include "Xpch.h" #include "XEngine/Core/Window.h" #ifdef XPLATFORM_WINDOWS #include "Platforms/OperatingSystems/Windows10/Win10Window.h" #endif namespace XEngine { Scope<Window> Window::Create(const WindowProps& props) { #ifdef XPLATFORM_WINDOWS return CreateScope<Win10Window>(props); #else XCORE_ASSERT(false, "Unknown Platform"); return nullptr; #endif } }
25.611111
81
0.759219
JohnMichaelProductions
1fe3b07329a19727c15b39fc56ad871b7c105468
251
cpp
C++
src/events/set_context.cpp
Damdoshi/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
38
2016-07-30T09:35:19.000Z
2022-03-04T10:13:48.000Z
src/events/set_context.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
15
2017-02-12T19:20:52.000Z
2021-06-09T09:30:52.000Z
src/events/set_context.cpp
Elania-Marvers/LibLapin
800e0f17ed8f3c47797c48feea4c280bb0e4bdc9
[ "BSD-3-Clause" ]
12
2016-10-06T09:06:59.000Z
2022-03-04T10:14:00.000Z
// Jason Brillante "Damdoshi" // Hanged Bunny Studio 2014-2018 // // Lapin Library #include <string.h> #include "lapin_private.h" void bunny_set_context(const t_bunny_context *context) { memcpy(&gl_callback, context, sizeof(gl_callback)); }
17.928571
57
0.729084
Damdoshi
1fe7df4ecd4330763d3d8f36d2bdad5419d4f07a
3,499
cpp
C++
Asteroids/src/asteroid.cpp
pscompsci/Asteroids
6e8f0eba2b8b6893ddee80779ef577e4890c947b
[ "MIT" ]
null
null
null
Asteroids/src/asteroid.cpp
pscompsci/Asteroids
6e8f0eba2b8b6893ddee80779ef577e4890c947b
[ "MIT" ]
null
null
null
Asteroids/src/asteroid.cpp
pscompsci/Asteroids
6e8f0eba2b8b6893ddee80779ef577e4890c947b
[ "MIT" ]
null
null
null
/** * Copyright (c) 2019 Peter Stacey * * 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 "asteroid.h" #include <iostream> #include "config.h" Asteroid::Asteroid(double x, double y, double angle, int size) { position.x = x; position.y = y; angle = angle; acceleration = { 0.0, 0.0 }; this->size_ = size; velocity.x = ASTEROID_BASE_SPEED * size * 0.5 * sin(angle * M_PI / 180.0f); velocity.y = ASTEROID_BASE_SPEED * size * 0.5 * -cos(angle * M_PI / 180.0f); switch (this->size_) { case(1): points_value_ = LARGE_ASTEROID_SCORE; break; case(2): points_value_ = MEDIUM_ASTEROID_SCORE; break; case(3): points_value_ = SMALL_ASTEROID_SCORE; break; default: points_value_ = 0; } } Asteroid::~Asteroid() { } void Asteroid::Update() { position.Add(velocity); if (position.y < 0.0) position.y = SCREEN_HEIGHT; if (position.y > SCREEN_HEIGHT) position.y = 0.0; if (position.x < 0.0) position.x = SCREEN_WIDTH; if (position.x > SCREEN_WIDTH) position.x = 0.0; } void Asteroid::Render(SDL_Renderer * renderer) { double x1 = position.x - (30.0 * 1 / size_); double y1 = position.y + (0.0 * 1 / size_); double x2 = position.x - (10.0 * 1 / size_); double y2 = position.y - (25.0 * 1 / size_); double x3 = position.x + (0.0 * 1 / size_); double y3 = position.y - (30.0 * 1 / size_); double x4 = position.x + (25.0 * 1 / size_); double y4 = position.y - (20.0 * 1 / size_); double x5 = position.x + (30.0 * 1 / size_); double y5 = position.y + (0.0 * 1 / size_); double x6 = position.x + (20.0 * 1 / size_); double y6 = position.y + (20.0 * 1 / size_); double x7 = position.x + (0.0 * 1 / size_); double y7 = position.y + (30.0 * 1 / size_); double x8 = position.x - (25.0 * 1 / size_); double y8 = position.y + (25.0 * 1 / size_); SDL_SetRenderDrawColor(renderer, 255, 255, 255, SDL_ALPHA_OPAQUE); SDL_RenderDrawLine(renderer, x1, y1, x2, y2); SDL_RenderDrawLine(renderer, x2, y2, x3, y3); SDL_RenderDrawLine(renderer, x3, y3, x4, y4); SDL_RenderDrawLine(renderer, x4, y4, x5, y5); SDL_RenderDrawLine(renderer, x5, y5, x6, y6); SDL_RenderDrawLine(renderer, x6, y6, x7, y7); SDL_RenderDrawLine(renderer, x7, y7, x8, y8); SDL_RenderDrawLine(renderer, x8, y8, x1, y1); SDL_SetRenderDrawColor(renderer, 0, 0, 0, SDL_ALPHA_OPAQUE); } bool Asteroid::CollidesWith(GameObject * object) { return false; } int Asteroid::GetSize() { return size_; } int Asteroid::GetPointsValue() { return points_value_; }
29.905983
81
0.68934
pscompsci
1fe9a4a014c4de1d662efc55e8903f248f620597
4,554
cpp
C++
src/Magnum/Math/Test/AngleTest.cpp
TUZIHULI/magnum
1f6ae8f359976e5b2f1b9649342434a00a6ccbe1
[ "MIT" ]
1
2019-05-09T03:31:10.000Z
2019-05-09T03:31:10.000Z
src/Magnum/Math/Test/AngleTest.cpp
TUZIHULI/magnum
1f6ae8f359976e5b2f1b9649342434a00a6ccbe1
[ "MIT" ]
null
null
null
src/Magnum/Math/Test/AngleTest.cpp
TUZIHULI/magnum
1f6ae8f359976e5b2f1b9649342434a00a6ccbe1
[ "MIT" ]
null
null
null
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/TestSuite/Tester.h> #include "Magnum/Math/Angle.h" namespace Magnum { namespace Math { namespace Test { class AngleTest: public Corrade::TestSuite::Tester { public: explicit AngleTest(); void construct(); void literals(); void conversion(); void debugDeg(); void debugRad(); }; typedef Math::Deg<Float> Deg; typedef Math::Rad<Float> Rad; #ifndef MAGNUM_TARGET_GLES typedef Math::Deg<Double> Degd; typedef Math::Rad<Double> Radd; #endif AngleTest::AngleTest() { addTests({&AngleTest::construct, &AngleTest::literals, &AngleTest::conversion, &AngleTest::debugDeg, &AngleTest::debugRad}); } void AngleTest::construct() { /* Default constructor */ constexpr Deg m; CORRADE_COMPARE(Float(m), 0.0f); #ifndef MAGNUM_TARGET_GLES constexpr Degd a; CORRADE_COMPARE(Double(a), 0.0); #else constexpr Deg a; CORRADE_COMPARE(Float(a), 0.0f); #endif /* Value constructor */ constexpr Deg b(25.0); CORRADE_COMPARE(Float(b), 25.0f); #ifndef MAGNUM_TARGET_GLES constexpr Radd n(3.14); CORRADE_COMPARE(Double(n), 3.14); #else constexpr Rad n(3.14); CORRADE_COMPARE(Float(n), 3.14f); #endif /* Copy constructor */ constexpr Deg c(b); CORRADE_COMPARE(c, b); #ifndef MAGNUM_TARGET_GLES constexpr Radd o(n); CORRADE_COMPARE(o, n); #else constexpr Rad o(n); CORRADE_COMPARE(o, n); #endif /* Conversion operator */ constexpr Rad p(n); CORRADE_COMPARE(Float(p), 3.14f); #ifndef MAGNUM_TARGET_GLES constexpr Degd d(b); CORRADE_COMPARE(Double(d), 25.0); #else constexpr Deg d(b); CORRADE_COMPARE(Float(d), 25.0f); #endif } void AngleTest::literals() { #ifndef MAGNUM_TARGET_GLES constexpr auto a = 25.0_deg; CORRADE_VERIFY((std::is_same<decltype(a), const Degd>::value)); CORRADE_COMPARE(Double(a), 25.0); #endif constexpr auto b = 25.0_degf; CORRADE_VERIFY((std::is_same<decltype(b), const Deg>::value)); CORRADE_COMPARE(Float(b), 25.0f); #ifndef MAGNUM_TARGET_GLES constexpr auto m = 3.14_rad; CORRADE_VERIFY((std::is_same<decltype(m), const Radd>::value)); CORRADE_COMPARE(Double(m), 3.14); #endif constexpr auto n = 3.14_radf; CORRADE_VERIFY((std::is_same<decltype(n), const Rad>::value)); CORRADE_COMPARE(Float(n), 3.14f); } void AngleTest::conversion() { /* Implicit conversion should be allowed */ constexpr Deg a = Rad(1.57079633f); CORRADE_COMPARE(Float(a), 90.0f); constexpr Rad b = Deg(90.0f); CORRADE_COMPARE(Float(b), 1.57079633f); } void AngleTest::debugDeg() { std::ostringstream o; Debug(&o) << Deg(90.0f); CORRADE_COMPARE(o.str(), "Deg(90)\n"); /* Verify that this compiles */ o.str({}); Debug(&o) << Deg(56.0f) - Deg(34.0f); CORRADE_COMPARE(o.str(), "Deg(22)\n"); } void AngleTest::debugRad() { std::ostringstream o; Debug(&o) << Rad(1.5708f); CORRADE_COMPARE(o.str(), "Rad(1.5708)\n"); /* Verify that this compiles */ o.str({}); Debug(&o) << Rad(1.5708f) - Rad(3.1416f); CORRADE_COMPARE(o.str(), "Rad(-1.5708)\n"); } }}} CORRADE_TEST_MAIN(Magnum::Math::Test::AngleTest)
27.93865
78
0.658981
TUZIHULI
1fee02c077825a38fb2081178083abfa0536d458
447
hpp
C++
src/Core/ECS/Systems/ManaSystem.hpp
Gegel85/THFgame
89b2508ac8564274c26db0f45f7fab4876badb5d
[ "MIT" ]
null
null
null
src/Core/ECS/Systems/ManaSystem.hpp
Gegel85/THFgame
89b2508ac8564274c26db0f45f7fab4876badb5d
[ "MIT" ]
null
null
null
src/Core/ECS/Systems/ManaSystem.hpp
Gegel85/THFgame
89b2508ac8564274c26db0f45f7fab4876badb5d
[ "MIT" ]
1
2019-11-18T22:05:10.000Z
2019-11-18T22:05:10.000Z
/* ** EPITECH PROJECT, 2019 ** THFgame ** File description: ** ManaSystem.hpp */ #ifndef THFGAME_MANASYSTEM_HPP #define THFGAME_MANASYSTEM_HPP #include "../System.hpp" namespace TouhouFanGame::ECS::Systems { //! @brief Updates Entity having a HealthComponent. class ManaSystem : public System { public: ManaSystem(Core &parent); void updateEntity(const std::shared_ptr<Entity> &entity) override; }; } #endif //THFGAME_MANASYSTEM_HPP
17.192308
68
0.740492
Gegel85
1feeef5effe80b026453b93f9abee6cc83be6c80
3,383
cpp
C++
sourceCode/dotNet4.6/vb/language/shared/pageprotect.cpp
csoap/csoap.github.io
2a8db44eb63425deff147652b65c5912f065334e
[ "Apache-2.0" ]
5
2017-03-03T02:13:16.000Z
2021-08-18T09:59:56.000Z
sourceCode/dotNet4.6/vb/language/shared/pageprotect.cpp
295007712/295007712.github.io
25241dbf774427545c3ece6534be6667848a6faf
[ "Apache-2.0" ]
null
null
null
sourceCode/dotNet4.6/vb/language/shared/pageprotect.cpp
295007712/295007712.github.io
25241dbf774427545c3ece6534be6667848a6faf
[ "Apache-2.0" ]
4
2016-11-15T05:20:12.000Z
2021-11-13T16:32:11.000Z
//------------------------------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // Page Heap management. Ruthlessly stolen from the C# team. Please notify [....] and [....] // about any changes to this file. It is likely the change will need to be mirrored in the C# // implementation // //------------------------------------------------------------------------------------------------- #include "StdAfx.h" #include "stdafx.h" #define PROTECT #ifdef DEBUGPROTECT struct ITEM { void * a; size_t sz; void * np; size_t nsz; int ts; DWORD level; DWORD origOldLevel; DWORD oldLevel; }; static ITEM items[1000]; int g_current = 0; int g_large = 0; void dumpItem(void * a, size_t sz, void * np, size_t nsz, DWORD level, DWORD origOld, DWORD oldLevel) { items[g_current].a = a; items[g_current].sz = sz; items[g_current].np = np; items[g_current].nsz = nsz; items[g_current].level = level; items[g_current].origOldLevel = origOld; items[g_current].oldLevel = oldLevel; items[g_current].ts = g_large; g_current ++; g_large ++; if (g_current == 1000) g_current = 0; } #endif // DEBUGPROTECT ProtectedEntityFlagsEnum const whatIsProtected = ProtectedEntityFlags::Nothing; void ComputePagesFromAddress(void * addr, size_t size, size_t * pageFrom, size_t * pageTo) { size_t SYSTEM_PAGE_SIZE = GetSystemPageSize(); size_t lowerByFrom = ((size_t)addr) % SYSTEM_PAGE_SIZE; size_t lowerByTo = (((size_t)addr) + size) % SYSTEM_PAGE_SIZE; *pageFrom = (size_t) addr - lowerByFrom; *pageTo = ((size_t) addr + size) - lowerByTo; } DWORD PageProtect::ToggleWrite(ProtectedEntityFlagsEnum entity, void * p, size_t sz, DWORD level) { if (!PageProtect::IsEntityProtected(entity)) return PAGE_READWRITE; ProtectionToggleLock toggleLock; size_t SYSTEM_PAGE_SIZE = GetSystemPageSize(); size_t lowerBy = ((size_t)p) % SYSTEM_PAGE_SIZE; size_t nsz = sz + lowerBy; nsz = nsz - (nsz % SYSTEM_PAGE_SIZE) + SYSTEM_PAGE_SIZE * ((nsz % SYSTEM_PAGE_SIZE) == 0 ? 0 : 1); DWORD oldFlags, origOldFlags; void * np = (void*)(((size_t)p) - lowerBy); #ifdef PROTECT BOOL succeeded = VirtualProtect(np, nsz, level, &oldFlags); VSASSERT(succeeded, "Invalid"); #ifdef DEBUGPROTECT if (level == PAGE_READWRITE) { BYTE oldValue = *(BYTE*)p; *(BYTE*)p = 0; *(BYTE*)p = oldValue; } #endif // DEBUGPROTECT #else // PROTECT oldFlags = PAGE_READWRITE; #endif // !PROTECT origOldFlags = oldFlags; if (oldFlags & (PAGE_NOACCESS | PAGE_EXECUTE)) { oldFlags = PAGE_NOACCESS; } else if (oldFlags & (PAGE_READONLY | PAGE_EXECUTE_READ)) { oldFlags = PAGE_READONLY; } else { VSASSERT(oldFlags & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY), "Invalid"); oldFlags = PAGE_READWRITE; } #ifdef DEBUGPROTECT dumpItem(p, sz, np, nsz, level, origOldFlags, oldFlags); #endif return oldFlags; } CTinyLock memoryProtectionLock; ProtectionToggleLock::ProtectionToggleLock() { locked = memoryProtectionLock.Acquire(); } ProtectionToggleLock::~ProtectionToggleLock() { if (locked) { memoryProtectionLock.Release(); } }
24.875
107
0.623116
csoap
1fef2a2de06f16ed0641dda067f59fd59ec07813
2,758
hxx
C++
gunrock/src/sssp/sssp_problem.hxx
aka-chris/mini
608751ff11f74e1ee59222399cbf6c9ee92208fb
[ "Apache-2.0" ]
17
2016-08-13T07:19:11.000Z
2021-05-05T15:19:02.000Z
gunrock/src/sssp/sssp_problem.hxx
aka-chris/mini
608751ff11f74e1ee59222399cbf6c9ee92208fb
[ "Apache-2.0" ]
6
2016-10-19T02:43:21.000Z
2020-01-05T07:10:59.000Z
gunrock/src/sssp/sssp_problem.hxx
aka-chris/mini
608751ff11f74e1ee59222399cbf6c9ee92208fb
[ "Apache-2.0" ]
7
2016-08-15T18:53:17.000Z
2021-11-02T12:05:36.000Z
#pragma once #include "problem.hxx" #include <queue> #include <utility> namespace gunrock { namespace sssp { struct sssp_problem_t : problem_t { mem_t<float> d_labels; mem_t<int> d_preds; mem_t<int> d_visited; std::vector<float> labels; std::vector<int> preds; int src; struct data_slice_t { float *d_labels; int *d_preds; float *d_weights; int *d_visited; void init(mem_t<float> &_labels, mem_t<int> &_preds, mem_t<float> &_weights, mem_t<int> &_visited) { d_labels = _labels.data(); d_preds = _preds.data(); d_weights = _weights.data(); d_visited = _visited.data(); } }; mem_t<data_slice_t> d_data_slice; std::vector<data_slice_t> data_slice; sssp_problem_t() {} sssp_problem_t(const sssp_problem_t& rhs) = delete; sssp_problem_t& operator=(const sssp_problem_t& rhs) = delete; sssp_problem_t(std::shared_ptr<graph_device_t> rhs, size_t src, standard_context_t& context) : problem_t(rhs), src(src), data_slice( std::vector<data_slice_t>(1) ) { labels = std::vector<float>(rhs->num_nodes, std::numeric_limits<float>::max()); preds = std::vector<int>(rhs->num_nodes, -1); labels[src] = 0; d_labels = to_mem(labels, context); d_preds = to_mem(preds, context); d_visited = fill(-1, rhs->num_nodes, context); data_slice[0].init(d_labels, d_preds, gslice->d_col_values, d_visited); d_data_slice = to_mem(data_slice, context); } void extract() { mgpu::dtoh(labels, d_labels.data(), gslice->num_nodes); mgpu::dtoh(preds, d_preds.data(), gslice->num_nodes); } void cpu(std::vector<int> &validation_preds, std::vector<int> &row_offsets, std::vector<int> &col_indices, std::vector<float> &col_values) { // CPU SSSP for validation (Dijkstra's algorithm) typedef std::pair<int, int> ipair; // initialize input frontier std::priority_queue<ipair, std::vector<ipair>, std::greater<ipair> > pq; std::vector<int> dist(row_offsets.size(), std::numeric_limits<int>::max()); pq.push(std::make_pair(-1, src)); validation_preds[src] = -1; dist[src] = 0; while(!pq.empty()) { int u = pq.top().second; pq.pop(); for (int i = row_offsets[u]; i < row_offsets[u+1]; ++i) { int v = col_indices[i]; int w = col_values[i]; if (dist[v] > dist[u] + w) { validation_preds[v] = u; dist[v] = dist[u] + w; pq.push(std::make_pair(dist[u], v)); } } } } }; } //end sssp } //end gunrock
29.655914
106
0.583394
aka-chris
1ff25378664e776e8db14948e7a4dad23f5604fd
449
cpp
C++
Library/Standard/Primitives/ErrorMessage.cpp
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
Library/Standard/Primitives/ErrorMessage.cpp
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
Library/Standard/Primitives/ErrorMessage.cpp
dwhobrey/MindCausalModellingLibrary
797d716e785d2dcd5c373ab385c20d3a74bbfcb0
[ "BSD-3-Clause" ]
null
null
null
#include "PlatoIncludes.h" #include "Strings.h" #include "ErrorMessage.h" namespace Plato { ErrorMessage::ErrorMessage(int errorCode, const string& errorMessage) { mErrorCode = errorCode; mErrorMessage = &errorMessage; } ErrorMessage::~ErrorMessage() { delete mErrorMessage; } string& ErrorMessage::StatusReport() { return Strings::Format("E%x:%s",mErrorCode,mErrorMessage->c_str()); } }
21.380952
75
0.659243
dwhobrey
1ff52a14c7d8ce269aa5bb4f25dad07f05db33f6
3,542
cpp
C++
HSAHRBNUOJ/P27xx/P2795.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
HSAHRBNUOJ/P27xx/P2795.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
HSAHRBNUOJ/P27xx/P2795.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <cstdio> #define MAXN 500010 #define INT_MAX 2147483647 using namespace std; struct SBT { int left_child; int right_child; int s; int key; }; SBT tree[MAXN]; int siz, root; int n, T, a, l, r, p, ans, t, pp, s; long long pre[MAXN]; void right_rotate(int &node) { int k = tree[node].left_child; tree[node].left_child = tree[k].right_child; tree[k].right_child = node; tree[k].s = tree[node].s; tree[node].s = tree[tree[node].left_child].s + tree[tree[node].right_child].s + 1; node = k; } void left_rotate(int &node) { int k = tree[node].right_child; tree[node].right_child = tree[k].left_child; tree[k].left_child = node; tree[k].s = tree[node].s; tree[node].s = tree[tree[node].left_child].s + tree[tree[node].right_child].s + 1; node = k; } void maintain(int &node, bool flag) { if (!flag) { if (tree[tree[tree[node].left_child].left_child].s > tree[tree[node].right_child].s) right_rotate(node); else if (tree[tree[tree[node].right_child].left_child].s > tree[tree[node].right_child].s) { left_rotate(node); right_rotate(node); } else return; } else { if (tree[tree[tree[node].right_child].right_child].s > tree[tree[node].left_child].s) left_rotate(node); else if (tree[tree[tree[node].left_child].right_child].s > tree[tree[node].left_child].s) { right_rotate(node); left_rotate(node); } else return; } maintain(tree[node].left_child, false); maintain(tree[node].right_child, true); maintain(node, false); maintain(node, true); } void add(int &node, int k) { if (!node) { tree[node = ++siz].s = 1; tree[node].left_child = tree[node].right_child = 0; tree[node].key = k; } else { tree[node].s++; if (tree[node].key > k) add(tree[node].left_child, k); else add(tree[node].right_child, k); maintain(node, k >= tree[node].key); } } int select(int &node, int k) { int v = tree[tree[node].left_child].s + 1; if (k == v) return tree[node].key; else if (k < v) return select(tree[node].left_child, k); else return select(tree[node].right_child, k - v); } bool exist(int &node, int v) { if (!node) return false; if (v < tree[node].key) return exist(tree[node].left_child, v); else return (tree[node].key == v) || exist(tree[node].right_child, v); } int prec(int &node, int v) { if (!node) return v; if (v <= tree[node].key) return prec(tree[node].left_child, v); else { int r = prec(tree[node].right_child, v); if (r == v) return tree[node].key; } } int succ(int &node, int v) { if (!node) return v; if (tree[node].key <= v) return succ(tree[node].right_child, v); else { int r = succ(tree[node].left_child, v); if (r == v) return tree[node].key; } } inline void read(int &x) { x = 0; int f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar(); x *= f; return ; } inline int mymin(int a, int b) { return a < b ? a : b; } int main() { //freopen("seq.in","r",stdin);freopen("seq.out","w",stdout); read(n); read(T); for (int i = 1; i <= n; i++) { read(a); pre[i] = pre[i - 1] + a; } while (T--) { read(l); read(r); read(p); if (r - l + 1 >= p) { puts("0"); continue; } root = siz = 0; ans = INT_MAX; add(root, 0); for (int i = l; i <= r; i++) { t = (pre[i] - pre[l - 1]) % p; if (exist(root, t)) { ans = 0; break; } pp = prec(root, t); ans = mymin(ans, t - pp); add(root, t); } printf("%d\n", ans); } return 0; }
19.355191
92
0.595991
HeRaNO
1ff82f38a6ab2896e55589947d3c34ae68a56b54
929
cpp
C++
Chapter2/Section2.1/sort3/sort3.cpp
suzyz/USACO
c7f58850f20693fedfc30ef462f898d20d002396
[ "MIT" ]
null
null
null
Chapter2/Section2.1/sort3/sort3.cpp
suzyz/USACO
c7f58850f20693fedfc30ef462f898d20d002396
[ "MIT" ]
null
null
null
Chapter2/Section2.1/sort3/sort3.cpp
suzyz/USACO
c7f58850f20693fedfc30ef462f898d20d002396
[ "MIT" ]
null
null
null
/* ID: suzyzha1 PROG: sort3 LANG: C++ */ #include <iostream> #include <fstream> #include <cstring> #include <cmath> #include <algorithm> using namespace std; int n; int seq[1010]; int num[4]; int main() { fstream fin("sort3.in",ios::in); fstream fout("sort3.out",ios::out); fin>>n; for(int i=1;i<=n;i++) { fin>>seq[i]; num[seq[i]]++; } int mis21=0,mis31=0,mis1=0,mis23=0,mis32=0,mis12=0,mis13=0; for(int i=1;i<=n;i++) { switch(seq[i]) { case 1: if(i>num[1]) mis1++; if(i>num[1] && i<=num[1]+num[2]) mis12++; if(i>num[1]+num[2]) mis13++; break; case 2: if(i<=num[1]) mis21++; else if(i>num[1]+num[2]) mis23++; break; case 3: if(i<=num[1]) mis31++; else if(i<=num[1]+num[2]) mis32++; break; } } int ans=mis1; if(mis12>=mis21) ans+=mis32+mis12-mis21; else ans+=mis23+mis13-mis31; fout<<ans<<endl; fin.close(); fout.close(); return 0; }
14.075758
60
0.559742
suzyz
1ffac9eb99f33b232992979ba8096bc5e088038c
1,273
hpp
C++
include/common/logging.hpp
jonas-ellert/gsaca-lyndon
b36110cb270b51f29035f8d53d798d56745deaac
[ "MIT" ]
null
null
null
include/common/logging.hpp
jonas-ellert/gsaca-lyndon
b36110cb270b51f29035f8d53d798d56745deaac
[ "MIT" ]
1
2021-10-03T23:31:07.000Z
2021-10-31T03:12:07.000Z
include/common/logging.hpp
jonas-ellert/gsaca-lyndon
b36110cb270b51f29035f8d53d798d56745deaac
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <sstream> #define LOG_VERBOSE if constexpr (false) std::cout #define LOG_STATS if constexpr (true) ::gsaca_lyndon::clog namespace gsaca_lyndon { namespace logging_internal { constexpr uint64_t LOG_LIMIT = 1ULL << 20; struct temporary_logger { std::string key; template<typename T> void operator<<(T &&); }; } struct { private: uint64_t size = logging_internal::LOG_LIMIT; std::stringstream ss; public: friend class logging_internal::temporary_logger; inline auto operator<<(std::string &&str) { return logging_internal::temporary_logger{std::move(str)}; } inline std::string get_and_clear_log() { auto result = ss.str(); size = logging_internal::LOG_LIMIT; ss = std::stringstream(); return result; } } clog; template<typename T> void logging_internal::temporary_logger::operator<<(T &&t) { std::string value = std::to_string(t); uint64_t add = 2 + key.size() + value.size(); if (clog.size + add < logging_internal::LOG_LIMIT) { clog.size += add; clog.ss << " " << std::move(key) << "=" << std::move(value); } else { clog.size = 1 + key.size() + value.size(); clog.ss = std::stringstream(); clog.ss << std::move(key) << "=" << std::move(value); } } }
21.948276
64
0.660644
jonas-ellert
1ffe7415a8705c70578a9b4516bf45825fccbeda
2,097
cc
C++
agent/php7/hook/openrasp_fileupload.cc
xuing/openrasp
9cb9ccebdd205ebd647eaf342ae6f89975b2bc72
[ "Apache-2.0" ]
2,219
2017-08-10T11:47:31.000Z
2022-03-29T08:58:56.000Z
agent/php7/hook/openrasp_fileupload.cc
xuing/openrasp
9cb9ccebdd205ebd647eaf342ae6f89975b2bc72
[ "Apache-2.0" ]
206
2017-08-14T02:37:15.000Z
2022-03-31T23:01:00.000Z
agent/php7/hook/openrasp_fileupload.cc
xuing/openrasp
9cb9ccebdd205ebd647eaf342ae6f89975b2bc72
[ "Apache-2.0" ]
551
2017-08-10T11:47:41.000Z
2022-03-30T12:29:47.000Z
/* * Copyright 2017-2021 Baidu Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "hook/data/fileupload_object.h" #include "hook/checker/v8_detector.h" #include "openrasp_hook.h" /** * fileupload相关hook点 */ PRE_HOOK_FUNCTION(move_uploaded_file, FILE_UPLOAD); void pre_global_move_uploaded_file_FILE_UPLOAD(OPENRASP_INTERNAL_FUNCTION_PARAMETERS) { zval *path = nullptr; zval *new_path = nullptr; if (!SG(rfc1867_uploaded_files)) { return; } if (zend_parse_parameters(ZEND_NUM_ARGS(), "zz", &path, &new_path) == FAILURE) { return; } if (path != nullptr && Z_TYPE_P(path) == IS_STRING && zend_hash_str_exists(SG(rfc1867_uploaded_files), Z_STRVAL_P(path), Z_STRLEN_P(path))) { std::string file_content; php_stream *stream = php_stream_open_wrapper(Z_STRVAL_P(path), "rb", 0, nullptr); if (stream) { zend_string *buffer = php_stream_copy_to_mem(stream, 4 * 1024, 0); if (buffer) { file_content = std::string(ZSTR_VAL(buffer), ZSTR_LEN(buffer)); zend_string_release(buffer); } stream->is_persistent ? php_stream_pclose(stream) : php_stream_close(stream); } openrasp::data::FileuploadObject fileupload_obj(OPENRASP_G(request).get_parameter(), path, new_path, file_content); openrasp::checker::V8Detector v8_detector(fileupload_obj, OPENRASP_HOOK_G(lru), OPENRASP_V8_G(isolate), OPENRASP_CONFIG(plugin.timeout.millis)); v8_detector.run(); } }
35.542373
152
0.680019
xuing
1ffebf01c19fc85691797133390d94c346d45410
10,017
hpp
C++
source/Switch_HIDInterface.hpp
TheGreatRambler/TOZ
2bd5851359f82489072bf1c228d58831570653cb
[ "MIT" ]
2
2021-04-26T20:50:45.000Z
2021-04-27T09:52:54.000Z
source/Switch_HIDInterface.hpp
TheGreatRambler/TOZ
2bd5851359f82489072bf1c228d58831570653cb
[ "MIT" ]
null
null
null
source/Switch_HIDInterface.hpp
TheGreatRambler/TOZ
2bd5851359f82489072bf1c228d58831570653cb
[ "MIT" ]
null
null
null
#pragma once #include <sys/ioctl.h> #include <sys/select.h> #include <sys/stat.h> #include <sys/types.h> #include <linux/types.h> #include <linux/usb/ch9.h> #include <linux/usb/gadgetfs.h> #include <fcntl.h> #include <pthread.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include "thirdParty/usbstring.h" // Descriptors #include "descriptors/Switch_Descriptors.hpp" #include "preformHandshake.hpp" // clang-format off #define FETCH(_var_) \ memcpy(cp, &_var_, _var_.bLength); \ cp += _var_.bLength; // clang-format on #define CONFIG_VALUE 2 // specific to controller #define USB_DEV "/dev/gadget/20980000.usb" #define USB_EPIN "/dev/gadget/ep1in" #define USB_EPOUT "/dev/gadget/ep2out" struct io_thread_args { unsigned stop; int fd_in, fd_out; }; static struct io_thread_args thread_args; static struct usb_endpoint_descriptor ep_descriptor_in; static struct usb_endpoint_descriptor ep_descriptor_out; /* * Respond to host requests */ static void* io_thread(void* arg) { struct io_thread_args* thread_args = (struct io_thread_args*) arg; fd_set read_set, write_set; struct timeval timeout; int ret, max_read_fd, max_write_fd; char buffer[512]; max_read_fd = max_write_fd = 0; if (thread_args->fd_in > max_write_fd) max_write_fd = thread_args->fd_in; if (thread_args->fd_out > max_read_fd) max_read_fd = thread_args->fd_out; while (!thread_args->stop) { FD_ZERO(&read_set); FD_SET(thread_args->fd_out, &read_set); timeout.tv_sec = 0; timeout.tv_usec = 10000; // 10ms memset(buffer, 0, sizeof(buffer)); ret = select(max_read_fd + 1, &read_set, NULL, NULL, &timeout); // Timeout if (ret == 0) continue; // Error if (ret < 0) break; ret = read(thread_args->fd_out, buffer, sizeof(buffer)); if (ret > 0) printf("Read %d bytes : %s\n", ret, buffer); else printf("Read error %d(%m)\n", ret); FD_ZERO(&write_set); FD_SET(thread_args->fd_in, &write_set); memset(buffer, 0, sizeof(buffer)); ret = select(max_write_fd + 1, NULL, &write_set, NULL, NULL); // Error if (ret < 0) break; strcpy(buffer, "My name is USBond !"); ret = write(thread_args->fd_in, buffer, strlen(buffer) + 1); printf("Write status %d (%m)\n", ret); } close(thread_args->fd_in); close(thread_args->fd_out); thread_args->fd_in = -1; thread_args->fd_out = -1; return NULL; } static int init_ep(int* fd_in, int* fd_out) { uint8_t init_config[2048]; uint8_t* cp; int ret = -1; uint32_t send_size; // Configure ep1 (low/full speed + high speed) *fd_in = open(USB_EPIN, O_RDWR); if (*fd_in <= 0) { printf("Unable to open %s (%m)\n", USB_EPIN); goto end; } *(uint32_t*) init_config = 1; cp = &init_config[4]; FETCH(ep_descriptor_in); FETCH(ep_descriptor_in); send_size = (uint32_t) cp - (uint32_t) init_config; ret = write(*fd_in, init_config, send_size); if (ret != send_size) { printf("Write error %d (%m)\n", ret); goto end; } printf("ep1 configured\n"); // Configure ep2 (low/full speed + high speed) *fd_out = open(USB_EPOUT, O_RDWR); if (*fd_out <= 0) { printf("Unable to open %s (%m)\n", USB_EPOUT); goto end; } *(uint32_t*) init_config = 1; cp = &init_config[4]; FETCH(ep_descriptor_out); FETCH(ep_descriptor_out); send_size = (uint32_t) cp - (uint32_t) init_config; ret = write(*fd_out, init_config, send_size); if (ret != send_size) { printf("Write error %d (%m)\n", ret); goto end; } printf("ep2 configured\n"); ret = 0; end: return ret; } static void handle_setup_request(int fd, struct usb_ctrlrequest* setup) { int status; uint8_t buffer[512]; pthread_t thread; printf("Setup request %d\n", setup->bRequest); switch (setup->bRequest) { case USB_REQ_GET_DESCRIPTOR: if (setup->bRequestType != USB_DIR_IN) goto stall; switch (setup->wValue >> 8) { case USB_DT_STRING: printf("Get string id #%d (max length %d)\n", setup->wValue & 0xff, setup->wLength); // Procontroller specific strings status = usb_gadget_get_string(&deviceStrings, setup->wValue & 0xff, buffer); // Error if (status < 0) { printf("String not found !!\n"); break; } else { printf("Found %d bytes\n", status); } write(fd, buffer, status); return; default: printf("Cannot return descriptor %d\n", (setup->wValue >> 8)); } break; case USB_REQ_SET_CONFIGURATION: if (setup->bRequestType != USB_DIR_OUT) { printf("Bad dir\n"); goto stall; } switch (setup->wValue) { case CONFIG_VALUE: printf("Set config value\n"); if (!thread_args.stop) { thread_args.stop = 1; usleep(200000); // Wait for termination } if (thread_args.fd_in <= 0) { status = init_ep(&thread_args.fd_in, &thread_args.fd_out); } else status = 0; if (!status) { thread_args.stop = 0; pthread_create(&thread, NULL, io_thread, &thread_args); } break; case 0: printf("Disable threads\n"); thread_args.stop = 1; break; default: printf("Unhandled configuration value %d\n", setup->wValue); break; } // Just ACK status = read(fd, &status, 0); return; case USB_REQ_GET_INTERFACE: printf("GET_INTERFACE\n"); buffer[0] = 0; write(fd, buffer, 1); return; case USB_REQ_SET_INTERFACE: printf("SET_INTERFACE\n"); ioctl(thread_args.fd_in, GADGETFS_CLEAR_HALT); ioctl(thread_args.fd_out, GADGETFS_CLEAR_HALT); // ACK status = read(fd, &status, 0); return; } stall: printf("Stalled\n"); // Error if (setup->bRequestType & USB_DIR_IN) read(fd, &status, 0); else write(fd, &status, 0); } static void handle_ep0(int fd) { int ret, nevents, i; fd_set read_set; struct usb_gadgetfs_event events[5]; while (1) { printf("FD_ZERO\n"); FD_ZERO(&read_set); FD_SET(fd, &read_set); printf("select\n"); select(fd + 1, &read_set, NULL, NULL, NULL); printf("read...\n"); ret = read(fd, &events, sizeof(events)); if (ret < 0) { printf("Read error %d (%m)\n", ret); goto end; } nevents = ret / sizeof(events[0]); printf("%d event(s)\n", nevents); for (i = 0; i < nevents; i++) { switch (events[i].type) { case GADGETFS_CONNECT: printf("EP0 CONNECT\n"); //startHandshake(fd); break; case GADGETFS_DISCONNECT: printf("EP0 DISCONNECT\n"); break; case GADGETFS_SETUP: printf("EP0 SETUP\n"); handle_setup_request(fd, &events[i].u.setup); break; case GADGETFS_NOP: printf("NOP\n"); break; case GADGETFS_SUSPEND: printf("SUSPEND\n"); break; } } } end: return; } bool alreadyMounted() { struct stat buffer; const std::string name = "/dev/gadget"; // Check if directory exists return (stat(name.c_str(), &buffer) == 0); // Maybe this is the reason // return false; } int StartGadget() { // Create gadgetfs in memory if (!alreadyMounted()) { puts("Mount endpoint"); system("sudo modprobe dwc2"); //system("sudo modprobe dummy_hcd"); system("sudo modprobe gadgetfs"); system("sudo mkdir /dev/gadget"); system("sudo mount -t gadgetfs none /dev/gadget"); } int fd = -1, ret, err = -1; uint32_t send_size; uint8_t init_config[2048]; uint8_t* cp; fd = open(USB_DEV, O_RDWR | O_SYNC); if (fd <= 0) { printf("Unable to open %s (%m)\n", USB_DEV); return 1; } printf("Start init\n"); *(uint32_t*) init_config = 0; cp = &init_config[4]; struct usb_config_descriptor config; struct usb_config_descriptor config_hs; config.bLength = sizeof(config); // 9 bytes config.bDescriptorType = USB_DT_CONFIG; // This is a configuration config.wTotalLength = config.bLength + procontroller_interface_descriptor.bLength + procontroller_ep_in_descriptor.bLength + procontroller_ep_out_descriptor.bLength;//usb_gadget_cpu_to_le16(0x0029), // 41 bytess config.bNumInterfaces = 0x01; // One interface config.bConfigurationValue = 0x01; // One?? config.iConfiguration = STRING_CONFIG; // I dunno what this does config.bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER;//0xA0 (Remote Wakeup), ONE and WAKEUP should be here config.bMaxPower = 0xFA; // Max power is 500 mA config_hs.bLength = sizeof(config_hs); // 9 bytes config_hs.bDescriptorType = USB_DT_CONFIG; // This is a configuration config_hs.wTotalLength = config_hs.bLength + procontroller_interface_descriptor.bLength + procontroller_ep_in_descriptor.bLength + procontroller_ep_out_descriptor.bLength;//usb_gadget_cpu_to_le16(0x0029), // 41 bytes config_hs.bNumInterfaces = 0x01; // One interface config_hs.bConfigurationValue = 0x01; // One?? config_hs.iConfiguration = STRING_CONFIG; // I dunno what this does config_hs.bmAttributes = USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER;//0xA0 (Remote Wakeup), ONE and WAKEUP should be here config_hs.bMaxPower = 0xFA; // Max power is 500 mA // Add all included descriptors // First, config FETCH(config);//FETCH(procontroller_config_descriptor); // Interface FETCH(procontroller_interface_descriptor); // HID descriptor //FETCH(procontroller_hid_descriptor) // Endpoint in FETCH(procontroller_ep_in_descriptor); // Endpoint out FETCH(procontroller_ep_out_descriptor); // Add same thing for highspeed (same config) FETCH(config_hs);//FETCH(procontroller_hs_config_descriptor); FETCH(procontroller_interface_descriptor); //FETCH(procontroller_hid_descriptor) FETCH(procontroller_ep_in_descriptor); FETCH(procontroller_ep_out_descriptor); // Finally, add device descriptor FETCH(procontroller_device_descriptor); // Configure ep0 send_size = (uint32_t) cp - (uint32_t) init_config; //printf("WRITE-TEST: %i\n",write(fd,"HI",2)); ret = write(fd, init_config, send_size); if (ret != send_size) { printf("Write error %d (%m)\n", ret); printf("Errstr: %s\n", strerror(errno)); goto end; } printf("ep0 configured\n"); handle_ep0(fd); end: if (fd != -1) close(fd); return err; }
23.793349
217
0.677349
TheGreatRambler
950717ecbe0d897e317149de011fceba5a33e00d
1,641
cpp
C++
src/gui/DeleteConfig.cpp
faroub/project-qt-cpp-cmake-IO-communication
f116b75766afce99664a6d82f4d6b10317b754a1
[ "MIT" ]
null
null
null
src/gui/DeleteConfig.cpp
faroub/project-qt-cpp-cmake-IO-communication
f116b75766afce99664a6d82f4d6b10317b754a1
[ "MIT" ]
null
null
null
src/gui/DeleteConfig.cpp
faroub/project-qt-cpp-cmake-IO-communication
f116b75766afce99664a6d82f4d6b10317b754a1
[ "MIT" ]
null
null
null
#include <QPushButton> #include <QHBoxLayout> #include <QGridLayout> #include <QListWidget> #include "DeleteConfig.h" gui::DeleteConfig::DeleteConfig(QWidget *ap_parent, utils::ConfigData *ap_ConfigData) : QDialog(ap_parent), mp_configFileList(new QListWidget(this)) { mp_configData = ap_ConfigData; QPushButton *lp_okButton = new QPushButton(tr("OK")); QPushButton *lp_cancelButton = new QPushButton(tr("Cancel")); QHBoxLayout *lp_hLayout = new QHBoxLayout(); lp_hLayout->addWidget(lp_okButton); lp_hLayout->addWidget(lp_cancelButton); QGridLayout *lp_mainGridLayout = new QGridLayout(); QStringList myStringList = QStringList() << "foo" << "bar" << "baz"; mp_configFileList->addItems(myStringList); lp_mainGridLayout->addWidget(mp_configFileList,0,0,4,2); lp_mainGridLayout->addLayout(lp_hLayout,4,1,1,1); setLayout(lp_mainGridLayout); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setFixedSize(sizeHint().width(),sizeHint().height()); setWindowTitle(tr("Delete Configuration")); } gui::DeleteConfig::~DeleteConfig() { } void gui::DeleteConfig::open() { qInfo("Open delete configuration widget"); QDialog::open(); } void gui::DeleteConfig::close() { qInfo("Close delete configuration widget"); QDialog::close(); } void gui::DeleteConfig::fillConfigFileList() { //QStringList myStringList = QStringList() << "foo" << "bar" << "baz"; mp_configFileList->addItem("farid"); mp_configFileList->addItem("farid"); mp_configFileList->addItem("farid"); }
27.813559
87
0.678854
faroub
9507d2fb345fa46173949496ff8f87b669772505
3,923
cpp
C++
Lab5/1356M_Linux/tools.cpp
HoverWings/HUST_RFID_Labs
8f824fb21b47cb92f35e1d90c7faaafe97cd38dd
[ "MIT" ]
null
null
null
Lab5/1356M_Linux/tools.cpp
HoverWings/HUST_RFID_Labs
8f824fb21b47cb92f35e1d90c7faaafe97cd38dd
[ "MIT" ]
1
2019-05-29T02:44:42.000Z
2019-05-29T02:44:42.000Z
Lab5/1356M_Windows/tools.cpp
HoverWings/HUST_RFID_Labs
8f824fb21b47cb92f35e1d90c7faaafe97cd38dd
[ "MIT" ]
null
null
null
#include "tools.h" #include <QDebug> Tools::Tools(QObject *parent) : QObject(parent) { list = new QStringList(); } //获取当前PC可用的串口名 QStringList Tools::getSerialName() { QStringList temp; foreach (const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { QSerialPort serial; serial.setPort(info); if (serial.open(QIODevice::ReadWrite)) { if(! list->contains(info.portName(),Qt::CaseSensitive)) list->insert(0,info.portName()); serial.close(); temp << info.portName(); } } for(int i = 0 ; i < list->size() ; i ++) { if(!temp.contains(list->at(i))) list->removeAt(i); } return *list; } ///获取当前日期和时间 QString Tools::CurrentDateTime() { QDateTime dt; QTime time; QDate date; dt.setTime(time.currentTime()); dt.setDate(date.currentDate()); return dt.toString("yyyy-MM-dd hh:mm:ss"); } ///获取当前的时间 QString Tools::CurrentTime() { QTime time; return time.currentTime().toString("hh:mm:ss"); } ///获取当前的时间 QString Tools::CurrentMTime() { QTime time; return time.currentTime().toString("hh:mm:ss.zzz"); } ///普通字符串转为16进制字符串 QString Tools::CharStringtoHexString(QString space, const char * src, int len) { QString hex = ""; if(space == NULL) { for(int i = 0 ; i < len ; i ++) { hex += QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0')); } return hex.toUpper(); } else { for(int i = 0 ; i < len ; i ++) { hex += space + QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0')); } return hex.right(hex.length() - space.length()).toUpper(); } } //QString 转 Hex char * quint8 Tools::StringToHex(QString string, quint8 *hex) { QString temp; quint8 len = string.length(); for(quint8 i=0; i<len; i+=2) { temp = string.mid(i, 2); hex[i/2] = (quint8)temp.toInt(0,16); } return len/2; } ///普通字符串转为16进制字符串 QString Tools::CharStringtoHexString(QString space, const char * src, int start, int end) { QString hex = ""; if(space == NULL) { for(int i = start ; i < end ; i ++) { hex += QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0')); } return hex.toUpper(); } else { for(int i = start ; i < end ; i ++) { hex += space + QString("%1").arg(src[i]&0xFF,2,16,QLatin1Char('0')); } return hex.right(hex.length() - space.length()).toUpper(); } } //用于导出数据库中的数据到文件,csv格式的文件可以用Excel打开 void Tools::export_table(const QAbstractItemModel &model) { QString fileName = QFileDialog::getSaveFileName(0, QObject::tr("保存记录"), "/", "files(*.csv)"); QFile file(fileName); if(file.open(QFile::WriteOnly|QFile::Truncate)){ QTextStream out(&file); QString str; str.clear(); for(int i=0; i<model.columnCount(); i++) str.append(model.headerData(i, Qt::Horizontal).toString()).append(","); out<<str<<"\r\n"; for(int row=0; row<model.rowCount(); row++){ str.clear(); for(int col=0; col<model.columnCount(); col++) str.append(model.data(model.index(row,col)).toString()).append(","); out<<str<<"\r\n"; } file.close(); } } //两个时间只差与天数的比较 bool Tools::isOverdue(QString borrowTime, QString returnTime, int days) { QTime start = QTime::fromString(borrowTime); QTime end = QTime::fromString(returnTime); int secs = start.secsTo(end); qDebug() << secs; if(days*24*3600 < secs)//未超时 return true; else return false; } //TODO:两个时间只差与天数的比较 //时间戳到转换为时间 //查询表项
26.328859
98
0.536324
HoverWings
950c962c5c01b79bf0009f811ca6a88348499256
2,837
cpp
C++
src/GameHostStarter.cpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
2
2015-01-07T18:36:39.000Z
2015-01-08T13:54:43.000Z
src/GameHostStarter.cpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
null
null
null
src/GameHostStarter.cpp
maximaximal/piga
54530c208e59eaaf8d44c1f8d640f5ec028d4126
[ "Zlib" ]
null
null
null
#include <pigaco/GameHostStarter.hpp> #include <QDir> #include <easylogging++.h> namespace pigaco { GameHostStarter::GameHostStarter() : QObject() { m_gameProcess = new QProcess(this); connect(m_gameProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(gameEnded(int,QProcess::ExitStatus))); connect(m_gameProcess, SIGNAL(started()), this, SLOT(gameStarted())); connect(m_gameProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(gameError(QProcess::ProcessError))); } GameHostStarter::~GameHostStarter() { if(isRunning(true)) m_gameProcess->terminate(); delete m_gameProcess; } bool GameHostStarter::isRunning(bool fsCheck) { //FS-Check can be ignored, because the boolean is getting changed by an Qt event in this implementation //instead of a temporary file check. return m_running; } void GameHostStarter::startGame(const std::string &command, const std::string &arguments) { LOG(INFO) << "Starting \"" << getConfig(ConfigValue::Name) << "\" with executable \"" << QDir::currentPath().toStdString() + "/" + command << "\"."; LOG(INFO) << "Using arguments: \"" << arguments << "\""; m_gameProcess->start(QDir::currentPath() + "/" + QString::fromStdString(command) + " " + QString::fromStdString(arguments)); } void GameHostStarter::gameEnded(int code, QProcess::ExitStatus status) { m_running = false; QString exitStatus; switch(status) { case QProcess::NormalExit: exitStatus = "Normal"; break; case QProcess::CrashExit: exitStatus = "Crashed"; break; } LOG(INFO) << "Exited \"" << getConfig(ConfigValue::Name) << "\" with exit code \"" << exitStatus.toStdString() << "\"."; } void GameHostStarter::gameStarted() { m_running = true; LOG(INFO) << "Started \"" << getConfig(ConfigValue::Name) << "\"!"; } void GameHostStarter::gameError(QProcess::ProcessError error) { LOG(WARNING) << "There was an error while starting or running \"" << getConfig(ConfigValue::Name) << "\"!"; switch(error) { case QProcess::ProcessError::FailedToStart: LOG(WARNING) << "The executable failed to start."; break; case QProcess::ProcessError::Crashed: LOG(WARNING) << "The game crashed!"; break; case QProcess::ProcessError::Timedout: LOG(WARNING) << "The game timed out!"; break; case QProcess::ProcessError::ReadError: LOG(WARNING) << "There was a read error!"; break; case QProcess::ProcessError::WriteError: LOG(WARNING) << "There was a write error!"; break; case QProcess::ProcessError::UnknownError: LOG(WARNING) << "The error was unknown!"; break; } } }
30.836957
152
0.627071
maximaximal
950dc54711be7a9eb53ace5073d65f7871dc8223
4,398
cpp
C++
tools/mull-xctest/XCTestInvocation.cpp
kateinoigakukun/mull-xctest
e7be5afa9afb64bef97dde29417c016af2a50dcc
[ "MIT" ]
43
2021-03-04T04:57:41.000Z
2022-03-03T17:16:54.000Z
tools/mull-xctest/XCTestInvocation.cpp
kateinoigakukun/mull-xctest
e7be5afa9afb64bef97dde29417c016af2a50dcc
[ "MIT" ]
2
2021-03-09T10:32:29.000Z
2021-10-19T12:01:25.000Z
tools/mull-xctest/XCTestInvocation.cpp
kateinoigakukun/mull-xctest
e7be5afa9afb64bef97dde29417c016af2a50dcc
[ "MIT" ]
1
2021-03-09T14:29:17.000Z
2021-03-09T14:29:17.000Z
#include "XCTestInvocation.h" #include "MullXCTest/MutantSerialization.h" #include <llvm/Support/Path.h> #include <mull/MutationResult.h> #include <mull/Parallelization/Parallelization.h> #include <mull/Toolchain/Runner.h> #include <sstream> using namespace llvm; using namespace mull; namespace mull_xctest { namespace { class MutantExecutionTask { public: using In = const std::vector<std::unique_ptr<Mutant>>; using Out = std::vector<std::unique_ptr<MutationResult>>; using iterator = In::const_iterator; MutantExecutionTask(const Configuration &configuration, Diagnostics &diagnostics, const std::string executable, const std::string testBundle, ExecutionResult &baseline, const std::vector<std::string> XCTestArgs) : configuration(configuration), diagnostics(diagnostics), executable(executable), testBundle(testBundle), baseline(baseline), XCTestArgs(XCTestArgs) {} void operator()(iterator begin, iterator end, Out &storage, progress_counter &counter); private: const Configuration &configuration; Diagnostics &diagnostics; const std::string executable; const std::string testBundle; const std::vector<std::string> XCTestArgs; ExecutionResult &baseline; }; void MutantExecutionTask::operator()(iterator begin, iterator end, Out &storage, progress_counter &counter) { Runner runner(diagnostics); std::vector<std::string> arguments; arguments.push_back("xctest"); arguments.insert(arguments.end(), XCTestArgs.begin(), XCTestArgs.end()); arguments.push_back(testBundle); for (auto it = begin; it != end; ++it, counter.increment()) { auto &mutant = *it; ExecutionResult result; if (mutant->isCovered()) { result = runner.runProgram(executable, arguments, {mutant->getIdentifier()}, baseline.runningTime * 10, configuration.captureMutantOutput, std::nullopt); } else { result.status = NotCovered; } if (result.status == Timedout) { std::stringstream message; message << "Timedout runningTime=" << result.runningTime << "\n"; message << " exitStatus=" << result.exitStatus << "\n"; message << " stderrOutput=" << result.stderrOutput << "\n"; message << " stdoutOutput=" << result.stdoutOutput << "\n"; } storage.push_back(std::make_unique<MutationResult>(result, mutant.get())); } } } // namespace std::unique_ptr<Result> XCTestInvocation::run() { auto xcrun = "/usr/bin/xcrun"; auto xctest = "xctest"; auto mutants = extractMutantInfo(); Runner runner(diagnostics); singleTask.execute("Warm up run", [&]() { runner.runProgram(xcrun, {xctest, testBundle.str()}, {}, config.timeout, config.captureMutantOutput, std::nullopt); }); ExecutionResult baseline; singleTask.execute("Baseline run", [&]() { baseline = runner.runProgram(xcrun, {xctest, testBundle.str()}, {}, config.timeout, config.captureMutantOutput, std::nullopt); }); std::vector<std::unique_ptr<MutationResult>> mutationResults; std::vector<MutantExecutionTask> tasks; tasks.reserve(config.parallelization.mutantExecutionWorkers); for (int i = 0; i < config.parallelization.mutantExecutionWorkers; i++) { tasks.emplace_back(config, diagnostics, xcrun, testBundle.str(), baseline, XCTestArgs); } TaskExecutor<MutantExecutionTask> mutantRunner(diagnostics, "Running mutants", mutants, mutationResults, std::move(tasks)); mutantRunner.execute(); return std::make_unique<Result>(std::move(mutants), std::move(mutationResults)); } MutantList XCTestInvocation::extractMutantInfo() { auto filename = llvm::sys::path::filename(testBundle); auto basename = filename.rsplit(".").first; SmallString<64> binaryPath(testBundle); llvm::sys::path::append(binaryPath, "Contents", "MacOS", basename); auto result = ExtractMutantInfo(binaryPath.str().str(), factory, diagnostics); if (!result) { llvm::consumeError(result.takeError()); return {}; } return std::move(result.get()); } }; // namespace mull_xctest
35.756098
80
0.649386
kateinoigakukun
950ddbd84b1db4d5ec15e309b1084abf6c670da4
981
cpp
C++
sources/Video/RenderSystem/ScopedActiveRenderContext.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
13
2017-03-21T22:46:18.000Z
2020-07-30T01:31:57.000Z
sources/Video/RenderSystem/ScopedActiveRenderContext.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
null
null
null
sources/Video/RenderSystem/ScopedActiveRenderContext.cpp
LukasBanana/ForkENGINE
8b575bd1d47741ad5025a499cb87909dbabc3492
[ "BSD-3-Clause" ]
2
2018-07-23T19:56:41.000Z
2020-07-30T01:32:01.000Z
/* * Scoped active render context file * * This file is part of the "ForkENGINE" (Copyright (c) 2014 by Lukas Hermanns) * See "LICENSE.txt" for license information. */ #include "Video/RenderSystem/ScopedActiveRenderContext.h" #include "Video/RenderSystem/RenderContext.h" #include "Core/Exception/NullPointerException.h" #include "Core/StaticConfig.h" namespace Fork { namespace Video { ScopedActiveRenderContext::ScopedActiveRenderContext(RenderContext* renderContext) : prevRenderContext_(RenderContext::Active()) { if (renderContext) renderContext->Activate(); } ScopedActiveRenderContext::ScopedActiveRenderContext(ScopedActiveRenderContext&& other) : prevRenderContext_(other.prevRenderContext_) { other.prevRenderContext_ = nullptr; } ScopedActiveRenderContext::~ScopedActiveRenderContext() { if (prevRenderContext_) prevRenderContext_->Activate(); } } // /namespace Video } // /namespace Fork // ========================
21.8
89
0.738022
LukasBanana
950ddcf01a642ac46f2a51c94f79a581ed10ec0b
160
cpp
C++
src/Updatable.cpp
Xansta/SeriousProton
f4f79d28bf292fbacb61a863a427b55da6d49774
[ "MIT" ]
62
2015-01-07T14:47:47.000Z
2021-09-06T09:52:29.000Z
src/Updatable.cpp
Xansta/SeriousProton
f4f79d28bf292fbacb61a863a427b55da6d49774
[ "MIT" ]
70
2015-03-09T07:08:00.000Z
2022-02-27T07:28:24.000Z
src/Updatable.cpp
Xansta/SeriousProton
f4f79d28bf292fbacb61a863a427b55da6d49774
[ "MIT" ]
49
2015-03-07T11:42:06.000Z
2022-02-20T11:06:05.000Z
#include "Updatable.h" PVector<Updatable> updatableList; Updatable::Updatable() { updatableList.push_back(this); } Updatable::~Updatable() { //dtor }
13.333333
35
0.7
Xansta
950e86d7af45ea905f102d29dfabadada67f7ea4
11,340
cpp
C++
Hanse/TaskXsensNavigation/taskxsensnavigation.cpp
iti-luebeck/HANSE2011
0bd5b3f1e0bc5a02516e7514b2241897337334c2
[ "BSD-3-Clause" ]
null
null
null
Hanse/TaskXsensNavigation/taskxsensnavigation.cpp
iti-luebeck/HANSE2011
0bd5b3f1e0bc5a02516e7514b2241897337334c2
[ "BSD-3-Clause" ]
null
null
null
Hanse/TaskXsensNavigation/taskxsensnavigation.cpp
iti-luebeck/HANSE2011
0bd5b3f1e0bc5a02516e7514b2241897337334c2
[ "BSD-3-Clause" ]
null
null
null
/* - Fahre zu Position Start - Falls nicht moeglich, emergencyStop - Mache x milisekunden Xsens-Following, dann einen Turn - Falls nicht moeglich, state ueberspringen - Fahre zu Position B - Falls nicht moeglich, emergencyStop - Mache Turn 180 - Falls nicht moeglich, state ueberspringen - Fahre zu Position End - Falls nicht moeglich, emergencyStop */ #include "taskxsensnavigation.h" #include "taskxsensnavigationform.h" #include <QtGui> #include <Module_Simulation/module_simulation.h> #include <Behaviour_XsensFollowing/behaviour_xsensfollowing.h> #include <Module_Navigation/module_navigation.h> #include <Behaviour_TurnOneEighty/behaviour_turnoneeighty.h> TaskXsensNavigation::TaskXsensNavigation(QString id, Module_Simulation *sim, Behaviour_XsensFollowing *xf, Module_Navigation *n, Behaviour_TurnOneEighty *o180) : RobotBehaviour(id) { this->sim = sim; this->xsensfollow = xf; this->navi = n; this->turn180 = o180; } bool TaskXsensNavigation::isActive(){ return active; } void TaskXsensNavigation::init(){ logger->debug("taskxsensnavigation init"); active = false; setEnabled(false); // Default task settings this->setDefaultValue("description", ""); this->setDefaultValue("taskStopTime",120000); this->setDefaultValue("signalTimer",1000); this->setDefaultValue("startNavigation", "a"); this->setDefaultValue("startTolerance", 2); this->setDefaultValue("bNavigation", "b"); this->setDefaultValue("bTolerance", 2); this->setDefaultValue("targetNavigation", "c"); this->setDefaultValue("targetTolerance", 2); this->setDefaultValue("timerActivated", true); this->setDefaultValue("loopActivated", true); // Default xsensfollow settings this->setDefaultValue("ffSpeed", 0.5); this->setDefaultValue("kp", 0.4); this->setDefaultValue("delta", 10); this->setDefaultValue("timer", 30); this->setDefaultValue("driveTime", 10000); this->setDefaultValue("waitTime", 10000); // Default turn180 settings this->setDefaultValue("hysteresis", 10); this->setDefaultValue("p", 0.4); this->setDefaultValue("degree", 180); taskTimer.setSingleShot(true); taskTimer.moveToThread(this); connect(this, SIGNAL(enabled(bool)), this, SLOT(controlEnabledChanged(bool))); connect(navi, SIGNAL(reachedWaypoint(QString)), this, SLOT(reachedWaypoint(QString))); connect(turn180, SIGNAL(turn180finished()), this, SLOT(turn180Finished())); connect(this, SIGNAL(setNewWaypoint(QString)), navi, SLOT(gotoWayPoint(QString))); } void TaskXsensNavigation::startBehaviour(){ if (isActive()){ logger->info("Already active!"); return; } this->reset(); logger->info("Taskxsensnavigation started" ); setHealthToOk(); // Stateoverview emit newStateOverview("Move to start"); emit newStateOverview("Do xsensfollowing"); emit newStateOverview("Move to B"); emit newStateOverview("Turn180"); emit newStateOverview("Move to end"); if(this->getSettingsValue("loopActivated").toBool()){ emit newStateOverview("...in a loop"); } active = true; if(!isEnabled()){ setEnabled(true); } emit started(this); // Enable all components if(!this->navi->isEnabled()) { this->navi->setEnabled(true); } state = XSENS_NAV_STATE_MOVE_START; addData("loop", this->getSettingsValue("loopActivated").toBool()); addData("timer", this->getSettingsValue("timerActivated").toBool()); addData("state", state); emit dataChanged(this); emit updateSettings(); if(this->getSettingsValue("timerActivated").toBool()){ logger->debug("Taskxsensnavigation with timer stop"); taskTimer.singleShot(this->getSettingsValue("taskStopTime").toInt(),this, SLOT(timeoutStop())); taskTimer.start(); } taskTimer.singleShot(0, this, SLOT(stateChanged())); } void TaskXsensNavigation::stateChanged() { if(!isActive()){ return; } if (state == XSENS_NAV_STATE_MOVE_START) { if (this->navi->getHealthStatus().isHealthOk()) { logger->debug("move to start"); emit setNewWaypoint(this->getSettingsValue("startNavigation").toString()); } else { logger->info("move to start not possible!"); emergencyStop(); } } else if (state == XSENS_NAV_STATE_FOLLOW_XSENS) { if (this->xsensfollow->getHealthStatus().isHealthOk()) { logger->debug("xsens following"); initBehaviourParameters(); if (!this->xsensfollow->isEnabled()) { logger->debug("enable xsensfollow"); QTimer::singleShot(0, xsensfollow, SLOT(startBehaviour())); } else { QTimer::singleShot(0, xsensfollow, SLOT(reset())); } // Finish state after drivetime msec and a little bit time to finish turn int tempWait = this->getSettingsValue("driveTime").toInt() + this->getSettingsValue("waitTime").toInt(); QTimer::singleShot(tempWait, this, SLOT(xsensFollowFinished())); } else { logger->info("xsens following not possible!"); state = XSENS_NAV_STATE_MOVE_B; QTimer::singleShot(0, this, SLOT(stateChanged())); } } else if (state == XSENS_NAV_STATE_MOVE_B) { if (this->navi->getHealthStatus().isHealthOk()) { logger->debug("move to B"); emit setNewWaypoint(this->getSettingsValue("bNavigation").toString()); } else { logger->info("move to B not possible!"); emergencyStop(); } } else if (state == XSENS_NAV_STATE_TURN_180) { if(this->turn180->getHealthStatus().isHealthOk()) { logger->debug("turn 180 degrees"); initBehaviourParameters(); if (!this->turn180->isEnabled()){ logger->debug("enable turn180"); QTimer::singleShot(0, turn180, SLOT(startBehaviour())); } else { QTimer::singleShot(0, turn180, SLOT(reset())); } } else { logger->info("turn 180 degrees not possible!"); state = XSENS_NAV_STATE_MOVE_END; QTimer::singleShot(0, this, SLOT(stateChanged())); } } else if (state == XSENS_NAV_STATE_MOVE_END) { if (this->navi->getHealthStatus().isHealthOk()) { logger->debug("move to end"); emit setNewWaypoint(this->getSettingsValue("targetNavigation").toString()); } else { logger->info("move to end not possible!"); emergencyStop(); } } else if (state == XSENS_NAV_STATE_DONE) { logger->debug("idle, controlNextState"); if(this->getSettingsValue("loopActivated").toBool()){ logger->debug("start again"); state = XSENS_NAV_STATE_MOVE_START; QTimer::singleShot(0, this, SLOT(stateChanged())); } else { // Task finished, stop stop(); } } addData("state", state); emit dataChanged(this); QString navstate = this->navi->getDataValue("state").toString(); QString navsubstate = this->navi->getDataValue("substate").toString(); QString stateComment = state + " - "+ navstate + " - " + navsubstate; emit newState(this->getId(),stateComment); } void TaskXsensNavigation::initBehaviourParameters() { if (state == XSENS_NAV_STATE_FOLLOW_XSENS) { this->xsensfollow->setSettingsValue("ffSpeed", this->getSettingsValue("ffSpeed").toString()); this->xsensfollow->setSettingsValue("kp", this->getSettingsValue("kp").toString()); this->xsensfollow->setSettingsValue("delta", this->getSettingsValue("delta").toString()); this->xsensfollow->setSettingsValue("timer", this->getSettingsValue("timer").toString()); this->xsensfollow->setSettingsValue("turnClockwise", true); this->xsensfollow->setSettingsValue("driveTime", this->getSettingsValue("driveTime").toString()); } else if (state == XSENS_NAV_STATE_TURN_180) { this->turn180->setSettingsValue("hysteresis", this->getSettingsValue("hysteresis").toFloat()); this->turn180->setSettingsValue("p", this->getSettingsValue("p").toFloat()); this->turn180->setSettingsValue("degree", this->getSettingsValue("degree").toFloat()); } } void TaskXsensNavigation::reachedWaypoint(QString) { if (state == XSENS_NAV_STATE_MOVE_START) { state = XSENS_NAV_STATE_FOLLOW_XSENS; } else if (state == XSENS_NAV_STATE_MOVE_B) { state = XSENS_NAV_STATE_TURN_180; } else if (state == XSENS_NAV_STATE_MOVE_END) { state = XSENS_NAV_STATE_DONE; } taskTimer.singleShot(0, this, SLOT(stateChanged())); } void TaskXsensNavigation::xsensFollowFinished() { QTimer::singleShot(0, xsensfollow, SLOT(stop())); state = XSENS_NAV_STATE_MOVE_B; taskTimer.singleShot(0, this, SLOT(stateChanged())); } void TaskXsensNavigation::turn180Finished() { QTimer::singleShot(0, turn180, SLOT(stop())); state = XSENS_NAV_STATE_MOVE_END; taskTimer.singleShot(0, this, SLOT(stateChanged())); } void TaskXsensNavigation::stop(){ if(!isActive()){ logger->info("Not active!"); return; } logger->info("Taskxsensnavigation stopped"); active = false; setEnabled(false); this->taskTimer.stop(); this->navi->setEnabled(false); this->xsensfollow->setEnabled(false); QTimer::singleShot(0, xsensfollow, SLOT(stop())); emit finished(this,true); } void TaskXsensNavigation::timeoutStop(){ if(!isActive()){ return; } logger->info("Taskxsensnavigation timeout stopped"); active = false; setEnabled(false); this->taskTimer.stop(); this->navi->setEnabled(false); this->xsensfollow->setEnabled(false); QTimer::singleShot(0, xsensfollow, SLOT(stop())); emit finished(this,false); } void TaskXsensNavigation::emergencyStop(){ if (!isActive()){ logger->info("Not active, no emergency stop needed"); return; } logger->info("Taskxsensnavigation emergency stopped"); active = false; setEnabled(false); this->taskTimer.stop(); this->navi->setEnabled(false); this->xsensfollow->setEnabled(false); QTimer::singleShot(0, xsensfollow, SLOT(stop())); emit finished(this,false); } void TaskXsensNavigation::terminate() { this->stop(); RobotModule::terminate(); } QWidget* TaskXsensNavigation::createView(QWidget *parent) { return new TaskXsensNavigationForm(this, parent); } QList<RobotModule*> TaskXsensNavigation::getDependencies() { QList<RobotModule*> ret; ret.append(xsensfollow); ret.append(sim); return ret; } void TaskXsensNavigation::controlEnabledChanged(bool enabled){ if(!enabled && isActive()){ logger->info("Disable and deactivate TaskXsensNavigation"); stop(); } else if(!enabled && !isActive()){ //logger->info("Still deactivated"); } else if(enabled && !isActive()){ //logger->info("Enable and activate TaskXsensNavigation"); //startBehaviour(); } else { //logger->info("Still activated"); } }
31.325967
159
0.645591
iti-luebeck
95120dff98db66a662c81530e469b7ea3b900831
6,616
cpp
C++
src/main.cpp
LiangGuoYu/spoa
9dbcd7aa223c1e7fa789530c39fcd143d3886d3b
[ "MIT" ]
1
2022-01-13T09:02:18.000Z
2022-01-13T09:02:18.000Z
src/main.cpp
LiangGuoYu/spoa
9dbcd7aa223c1e7fa789530c39fcd143d3886d3b
[ "MIT" ]
null
null
null
src/main.cpp
LiangGuoYu/spoa
9dbcd7aa223c1e7fa789530c39fcd143d3886d3b
[ "MIT" ]
1
2019-08-16T01:17:09.000Z
2019-08-16T01:17:09.000Z
#include <getopt.h> #include <cstdint> #include <string> #include <iostream> #include <exception> #include "sequence.hpp" #include "spoa/spoa.hpp" #include "bioparser/bioparser.hpp" static const std::string version = "v3.0.1"; static struct option options[] = { {"algorithm", required_argument, nullptr, 'l'}, {"result", required_argument, nullptr, 'r'}, {"dot", required_argument, nullptr, 'd'}, {"version", no_argument, nullptr, 'v'}, {"help", no_argument, nullptr, 'h'}, {nullptr, 0, nullptr, 0} }; void help(); int main(int argc, char** argv) { std::int8_t m = 5; std::int8_t n = -4; std::int8_t g = -8; std::int8_t e = -6; std::int8_t q = -10; std::int8_t c = -4; std::uint8_t algorithm = 0; std::uint8_t result = 0; std::string dot_path = ""; char opt; while ((opt = getopt_long(argc, argv, "m:n:g:e:q:c:l:r:d:h", options, nullptr)) != -1) { switch (opt) { case 'm': m = atoi(optarg); break; case 'n': n = atoi(optarg); break; case 'g': g = atoi(optarg); break; case 'e': e = atoi(optarg); break; case 'q': q = atoi(optarg); break; case 'c': c = atoi(optarg); break; case 'l': algorithm = atoi(optarg); break; case 'r': result = atoi(optarg); break; case 'd': dot_path = optarg; break; case 'v': std::cout << version << std::endl; return 0; case 'h': help(); return 0; default: return 1; } } if (optind >= argc) { std::cerr << "[spoa::] error: missing input file!" << std::endl; help(); return 1; } std::string sequences_path = argv[optind]; auto is_suffix = [](const std::string& src, const std::string& suffix) -> bool { if (src.size() < suffix.size()) { return false; } return src.compare(src.size() - suffix.size(), suffix.size(), suffix) == 0; }; std::unique_ptr<bioparser::Parser<spoa::Sequence>> sparser = nullptr; if (is_suffix(sequences_path, ".fasta") || is_suffix(sequences_path, ".fa") || is_suffix(sequences_path, ".fasta.gz") || is_suffix(sequences_path, ".fa.gz")) { sparser = bioparser::createParser<bioparser::FastaParser, spoa::Sequence>( sequences_path); } else if (is_suffix(sequences_path, ".fastq") || is_suffix(sequences_path, ".fq") || is_suffix(sequences_path, ".fastq.gz") || is_suffix(sequences_path, ".fq.gz")) { sparser = bioparser::createParser<bioparser::FastqParser, spoa::Sequence>( sequences_path); } else { std::cerr << "[spoa::] error: file " << sequences_path << " has unsupported format extension (valid extensions: .fasta, " ".fasta.gz, .fa, .fa.gz, .fastq, .fastq.gz, .fq, .fq.gz)!" << std::endl; return 1; } std::unique_ptr<spoa::AlignmentEngine> alignment_engine; try { alignment_engine = spoa::createAlignmentEngine( static_cast<spoa::AlignmentType>(algorithm), m, n, g, e, q, c); } catch(std::invalid_argument& exception) { std::cerr << exception.what() << std::endl; return 1; } auto graph = spoa::createGraph(); std::vector<std::unique_ptr<spoa::Sequence>> sequences; sparser->parse(sequences, -1); std::size_t max_sequence_size = 0; for (const auto& it: sequences) { max_sequence_size = std::max(max_sequence_size, it->data().size()); } alignment_engine->prealloc(max_sequence_size, 4); for (const auto& it: sequences) { auto alignment = alignment_engine->align(it->data(), graph); try { graph->add_alignment(alignment, it->data(), it->quality()); } catch(std::invalid_argument& exception) { std::cerr << exception.what() << std::endl; return 1; } } if (result == 0 || result == 2) { std::string consensus = graph->generate_consensus(); std::cout << "Consensus (" << consensus.size() << ")" << std::endl; std::cout << consensus << std::endl; } if (result == 1 || result == 2) { std::vector<std::string> msa; graph->generate_multiple_sequence_alignment(msa); std::cout << "Multiple sequence alignment" << std::endl; for (const auto& it: msa) { std::cout << it << std::endl; } } graph->print_dot(dot_path); return 0; } void help() { std::cout << "usage: spoa [options ...] <sequences>\n" "\n" " <sequences>\n" " input file in FASTA/FASTQ format (can be compressed with gzip)\n" " containing sequences\n" "\n" " options:\n" " -m <int>\n" " default: 5\n" " score for matching bases\n" " -n <int>\n" " default: -4\n" " score for mismatching bases\n" " -g <int>\n" " default: -8\n" " gap opening penalty (must be non-positive)\n" " -e <int>\n" " default: -6\n" " gap extension penalty (must be non-positive)\n" " -q <int>\n" " default: -10\n" " gap opening penalty of the second affine function\n" " (must be non-positive)\n" " -c <int>\n" " default: -4\n" " gap extension penalty of the second affine function\n" " (must be non-positive)\n" " -l, --algorithm <int>\n" " default: 0\n" " alignment mode:\n" " 0 - local (Smith-Waterman)\n" " 1 - global (Needleman-Wunsch)\n" " 2 - semi-global\n" " -r, --result <int>\n" " default: 0\n" " result mode:\n" " 0 - consensus\n" " 1 - multiple sequence alignment\n" " 2 - 0 & 1\n" " -d, --dot <file>\n" " output file for the final POA graph in DOT format\n" " --version\n" " prints the version number\n" " -h, --help\n" " prints the usage\n" "\n" " gap mode:\n" " linear if g >= e\n" " affine if g <= q or e >= c\n" " convex otherwise (default)\n"; }
34.103093
92
0.502418
LiangGuoYu
95138877d849e1b0def7a93bc119145943a2b669
947
cpp
C++
kernel/ports.cpp
shockkolate/shockk-os
1cbe2e14be6a8dd4bbe808e199284b6979dacdff
[ "Apache-2.0" ]
2
2015-11-16T07:30:38.000Z
2016-03-26T21:14:42.000Z
kernel/ports.cpp
shockkolate/shockk-os
1cbe2e14be6a8dd4bbe808e199284b6979dacdff
[ "Apache-2.0" ]
null
null
null
kernel/ports.cpp
shockkolate/shockk-os
1cbe2e14be6a8dd4bbe808e199284b6979dacdff
[ "Apache-2.0" ]
null
null
null
#include <kernel/ports.h> uint8_t ports_inb(unsigned short port) { uint8_t result; __asm__ __volatile__ ("in %1, %0" : "=a" (result) : "d" (port)); return result; } uint16_t ports_ins(unsigned short port) { uint16_t result; __asm__ __volatile__ ("in %1, %0" : "=a" (result) : "d" (port)); return result; } uint32_t ports_inl(unsigned short port) { uint32_t result; __asm__ __volatile__ ("in %1, %0" : "=a" (result) : "d" (port)); return result; } void ports_str_ins(unsigned short port, volatile uint16_t *buffer, size_t count) { __asm__ ("rep insw" : : "d" (port), "c" (count), "D" (buffer) : "memory"); } void ports_outb(unsigned short port, uint8_t data) { __asm__ ("out %0, %1" : : "a" (data), "d" (port)); } void ports_outs(unsigned short port, uint16_t data) { __asm__ ("out %0, %1" : : "a" (data), "d" (port)); } void ports_outl(unsigned short port, uint32_t data) { __asm__ ("out %0, %1" : : "a" (data), "d" (port)); }
26.305556
82
0.634636
shockkolate
95142327f8d73d2e272de7cd5d192dec4252d33d
12,654
hpp
C++
inc/Services/StorageAndRetrievalService.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
inc/Services/StorageAndRetrievalService.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
inc/Services/StorageAndRetrievalService.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
#ifndef ECSS_SERVICES_STORAGEANDRETRIEVALSERVICE_HPP #define ECSS_SERVICES_STORAGEANDRETRIEVALSERVICE_HPP #include "ECSS_Definitions.hpp" #include "Service.hpp" #include "ErrorHandler.hpp" #include "Helpers/PacketStore.hpp" #include "etl/map.h" /** * Implementation of ST[15] Storage and Retrieval Service, as defined in ECSS-E-ST-70-41C. * * This Service: * - provides the capability to select reports generated by other services and store them into packet stores. * - allows the ground system to manage the reports in the packet stores and request their downlink. * * @author Konstantinos Petridis <petridkon@gmail.com> */ class StorageAndRetrievalService : public Service { public: /** * The type of timestamps that the Storage and Retrieval Subservice assigns to each incoming packet. */ enum TimeStampType : uint8_t { StorageBased = 0, PacketBased = 1 }; /** * Different types of packet retrieval from a packet store, relative to a specified time-tag. */ enum TimeWindowType : uint8_t { FromTagToTag = 0, AfterTimeTag = 1, BeforeTimeTag = 2 }; /** * The type of timestamps that the subservice sets to each incoming telemetry packet. */ const TimeStampType timeStamping = PacketBased; private: typedef String<ECSSPacketStoreIdSize> packetStoreId; /** * All packet stores, held by the Storage and Retrieval Service. Each packet store has its ID as key. */ etl::map<packetStoreId, PacketStore, ECSSMaxPacketStores> packetStores; /** * Helper function that reads the packet store ID string from a TM[15] message */ static inline String<ECSSPacketStoreIdSize> readPacketStoreId(Message& message); /** * Helper function that, given a time-limit, deletes every packet stored in the specified packet-store, up to the * requested time. * * @param packetStoreId required to access the correct packet store. * @param timeLimit the limit until which, packets are deleted. */ void deleteContentUntil(const String<ECSSPacketStoreIdSize>& packetStoreId, uint32_t timeLimit); /** * Copies all TM packets from source packet store to the target packet-store, that fall between the two specified * time-tags as per 6.15.3.8.4.d(1) of the standard. * * @param request used to read the time-tags, the packet store IDs and to raise errors. */ void copyFromTagToTag(Message& request); /** * Copies all TM packets from source packet store to the target packet-store, whose time-stamp is after the * specified time-tag as per 6.15.3.8.4.d(2) of the standard. * * @param request used to read the time-tag, the packet store IDs and to raise errors. */ void copyAfterTimeTag(Message& request); /** * Copies all TM packets from source packet store to the target packet-store, whose time-stamp is before the * specified time-tag as per 6.15.3.8.4.d(3) of the standard. * * @param request used to raise errors. */ void copyBeforeTimeTag(Message& request); /** * Checks if the two requested packet stores exist. * * @param fromPacketStoreId the source packet store, whose content is to be copied. * @param toPacketStoreId the target packet store, which is going to receive the new content. * @param request used to raise errors. * @return true if an error has occurred. */ bool checkPacketStores(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, const String<ECSSPacketStoreIdSize>& toPacketStoreId, Message& request); /** * Checks whether the time window makes logical sense (end time should be after the start time) * * @param request used to raise errors. */ static bool checkTimeWindow(uint32_t startTime, uint32_t endTime, Message& request); /** * Checks if the destination packet store is empty, in order to proceed with the copying of packets. * * @param toPacketStoreId the target packet store, which is going to receive the new content. Needed for error * checking. * @param request used to raise errors. */ bool checkDestinationPacketStore(const String<ECSSPacketStoreIdSize>& toPacketStoreId, Message& request); /** * Checks if there are no stored timestamps that fall between the two specified time-tags. * * @param fromPacketStoreId the source packet store, whose content is to be copied. Needed for error checking. * @param request used to raise errors. * * @note * This function assumes that `startTime` and `endTime` are valid at this point, so any necessary error checking * regarding these variables, should have already occurred. */ bool noTimestampInTimeWindow(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, uint32_t startTime, uint32_t endTime, Message& request); /** * Checks if there are no stored timestamps that fall between the two specified time-tags. * * @param isAfterTimeTag true indicates that we are examining the case of AfterTimeTag. Otherwise, we are referring * to the case of BeforeTimeTag. * @param request used to raise errors. * @param fromPacketStoreId the source packet store, whose content is to be copied. */ bool noTimestampInTimeWindow(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, uint32_t timeTag, Message& request, bool isAfterTimeTag); /** * Performs all the necessary error checking for the case of FromTagToTag copying of packets. * * @param fromPacketStoreId the source packet store, whose content is to be copied. * @param toPacketStoreId the target packet store, which is going to receive the new content. * @param request used to raise errors. * @return true if an error has occurred. */ bool failedFromTagToTag(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, const String<ECSSPacketStoreIdSize>& toPacketStoreId, uint32_t startTime, uint32_t endTime, Message& request); /** * Performs all the necessary error checking for the case of AfterTimeTag copying of packets. * * @param fromPacketStoreId the source packet store, whose content is to be copied. * @param toPacketStoreId the target packet store, which is going to receive the new content. * @param request used to raise errors. * @return true if an error has occurred. */ bool failedAfterTimeTag(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, const String<ECSSPacketStoreIdSize>& toPacketStoreId, uint32_t startTime, Message& request); /** * Performs all the necessary error checking for the case of BeforeTimeTag copying of packets. * * @param fromPacketStoreId the source packet store, whose content is to be copied. * @param toPacketStoreId the target packet store, which is going to receive the new content. * @param request used to raise errors. * @return true if an error has occurred. */ bool failedBeforeTimeTag(const String<ECSSPacketStoreIdSize>& fromPacketStoreId, const String<ECSSPacketStoreIdSize>& toPacketStoreId, uint32_t endTime, Message& request); /** * Performs the necessary error checking for a request to start the by-time-range retrieval process. * * @param request used to raise errors. * @return true if an error has occurred. */ bool failedStartOfByTimeRangeRetrieval(const String<ECSSPacketStoreIdSize>& packetStoreId, Message& request); /** * Forms the content summary of the specified packet-store and appends it to a report message. */ void createContentSummary(Message& report, const String<ECSSPacketStoreIdSize>& packetStoreId); public: inline static const uint8_t ServiceType = 15; enum MessageType : uint8_t { EnableStorageInPacketStores = 1, DisableStorageInPacketStores = 2, StartByTimeRangeRetrieval = 9, DeletePacketStoreContent = 11, ReportContentSummaryOfPacketStores = 12, PacketStoreContentSummaryReport = 13, ChangeOpenRetrievalStartingTime = 14, ResumeOpenRetrievalOfPacketStores = 15, SuspendOpenRetrievalOfPacketStores = 16, AbortByTimeRangeRetrieval = 17, ReportStatusOfPacketStores = 18, PacketStoresStatusReport = 19, CreatePacketStores = 20, DeletePacketStores = 21, ReportConfigurationOfPacketStores = 22, PacketStoreConfigurationReport = 23, CopyPacketsInTimeWindow = 24, ResizePacketStores = 25, ChangeTypeToCircular = 26, ChangeTypeToBounded = 27, ChangeVirtualChannel = 28 }; StorageAndRetrievalService() = default; /** * Adds new packet store into packet stores. */ void addPacketStore(const String<ECSSPacketStoreIdSize>& packetStoreId, const PacketStore& packetStore); /** * Adds telemetry to the specified packet store and timestamps it. */ void addTelemetryToPacketStore(const String<ECSSPacketStoreIdSize>& packetStoreId, uint32_t timestamp); /** * Deletes the content from all the packet stores. */ void resetPacketStores(); /** * Returns the number of existing packet stores. */ uint16_t currentNumberOfPacketStores(); /** * Returns the packet store with the specified packet store ID. */ PacketStore& getPacketStore(const String<ECSSPacketStoreIdSize>& packetStoreId); /** * Returns true if the specified packet store is present in packet stores. */ bool packetStoreExists(const String<ECSSPacketStoreIdSize>& packetStoreId); /** * Given a request that contains a number N, followed by N packet store IDs, this method calls function on every * packet store. Implemented to reduce duplication. If N = 0, then function is applied to all packet stores. * Incorrect packet store IDs are ignored and generate an error. * @param function the job to be done after the error checking. */ void executeOnPacketStores(Message& request, const std::function<void(PacketStore&)>& function); /** * TC[15,1] request to enable the packet stores' storage function */ void enableStorageFunction(Message& request); /** * TC[15,2] request to disable the packet stores' storage function */ void disableStorageFunction(Message& request); /** * TC[15,9] start the by-time-range retrieval of packet stores */ void startByTimeRangeRetrieval(Message& request); /** * TC[15,11] delete the packet store content up to the specified time */ void deletePacketStoreContent(Message& request); /** * This function takes a TC[15,12] 'report the packet store content summary' as argument and responds with a TM[15, * 13] 'packet store content summary report' report message. */ void packetStoreContentSummaryReport(Message& request); /** * TC[15,14] change the open retrieval start time tag */ void changeOpenRetrievalStartTimeTag(Message& request); /** * TC[15,15] resume the open retrieval of packet stores */ void resumeOpenRetrievalOfPacketStores(Message& request); /** * TC[15,16] suspend the open retrieval of packet stores */ void suspendOpenRetrievalOfPacketStores(Message& request); /** * TC[15,17] abort the by-time-range retrieval of packet stores */ void abortByTimeRangeRetrieval(Message& request); /** * This function takes a TC[15,18] 'report the status of packet stores' request as argument and responds with a * TM[15,19] 'packet stores status' report message. */ void packetStoresStatusReport(Message& request); /** * TC[15,20] create packet stores */ void createPacketStores(Message& request); /** * TC[15,21] delete packet stores */ void deletePacketStores(Message& request); /** * This function takes a TC[15,22] 'report the packet store configuration' as argument and responds with a TM[15, * 23] 'packet store configuration report' report message. */ void packetStoreConfigurationReport(Message& request); /** * TC[15,24] copy the packets contained into a packet store, selected by the time window */ void copyPacketsInTimeWindow(Message& request); /** * TC[15,25] resize packet stores */ void resizePacketStores(Message& request); /** * TC[15,26] change the packet store type to circular */ void changeTypeToCircular(Message& request); /** * TC[15,27] change the packet store type to bounded */ void changeTypeToBounded(Message& request); /** * TC[15,28] change the virtual channel used by a packet store */ void changeVirtualChannel(Message& request); /** * It is responsible to call the suitable function that executes a telecommand packet. The source of that packet * is the ground station. * * @note This function is called from the main execute() that is defined in the file MessageParser.hpp * @param request Contains the necessary parameters to call the suitable subservice */ void execute(Message& request); }; #endif
35.745763
116
0.735973
ACubeSAT
951504d692ddd20a29a59fc9461cf1761fc90d10
336
hpp
C++
BlueNoise/src/Library/Sample.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
BlueNoise/src/Library/Sample.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
BlueNoise/src/Library/Sample.hpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* Sample.hpp a sample with value and coordinate Li-Yi Wei 06/28/2007 */ #ifndef _SAMPLE_HPP #define _SAMPLE_HPP #include "Coordinate.hpp" typedef CoordinateT<float> Coordinate; class Sample { public: Sample(const int dim); ~Sample(void); public: float value; Coordinate coordinate; }; #endif
11.2
38
0.669643
1iyiwei
95157ef9fb1fbb630a97dea115860697d2688c01
2,288
hpp
C++
deps/src/boost_1_65_1/boost/metaparse/v1/keyword.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
11,356
2017-12-08T19:42:32.000Z
2022-03-31T16:55:25.000Z
deps/src/boost_1_65_1/boost/metaparse/v1/keyword.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
2,402
2017-12-08T22:31:01.000Z
2022-03-28T19:25:52.000Z
deps/src/boost_1_65_1/boost/metaparse/v1/keyword.hpp
shreyasvj25/turicreate
32e84ca16aef8d04aff3d49ae9984bd49326bffd
[ "BSD-3-Clause" ]
1,343
2017-12-08T19:47:19.000Z
2022-03-26T11:31:36.000Z
#ifndef BOOST_METAPARSE_V1_KEYWORD_HPP #define BOOST_METAPARSE_V1_KEYWORD_HPP // Copyright Abel Sinkovics (abel@sinkovics.hu) 2009 - 2010. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <boost/metaparse/v1/impl/void_.hpp> #include <boost/metaparse/v1/lit.hpp> #include <boost/metaparse/v1/return_.hpp> #include <boost/metaparse/v1/is_error.hpp> #include <boost/metaparse/v1/get_remaining.hpp> #include <boost/metaparse/v1/get_position.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/empty.hpp> #include <boost/mpl/pop_front.hpp> #include <boost/mpl/front.hpp> namespace boost { namespace metaparse { namespace v1 { // Does not consume/check anything after the keyword template <class Kw, class ResultType = impl::void_> struct keyword { private: struct nonempty { private: typedef lit<typename boost::mpl::front<Kw>::type> next_char_parser; typedef keyword<typename boost::mpl::pop_front<Kw>::type, ResultType> rest_parser; template <class S, class Pos> struct apply_unchecked : rest_parser::template apply< typename get_remaining< typename next_char_parser::template apply<S, Pos> >::type, typename get_position< typename next_char_parser::template apply<S, Pos> >::type > {}; public: template <class S, class Pos> struct apply : boost::mpl::eval_if< typename is_error< typename next_char_parser::template apply<S, Pos> >::type, typename next_char_parser::template apply<S, Pos>, apply_unchecked<S, Pos> > {}; }; public: typedef keyword type; template <class S, class Pos> struct apply : boost::mpl::if_< boost::mpl::empty<Kw>, return_<ResultType>, nonempty >::type::template apply<S, Pos> {}; }; } } } #endif
27.902439
77
0.590909
shreyasvj25
95169b8f50aaad152f30a32783937523f1f907b1
16,151
hpp
C++
stream/core.hpp
alipha/cpp
0e880164e58ee8fcfe2fc818b4b9de289a4dd476
[ "MIT" ]
4
2020-10-28T21:31:30.000Z
2021-08-02T21:38:22.000Z
stream/core.hpp
alipha/cpp
0e880164e58ee8fcfe2fc818b4b9de289a4dd476
[ "MIT" ]
null
null
null
stream/core.hpp
alipha/cpp
0e880164e58ee8fcfe2fc818b4b9de289a4dd476
[ "MIT" ]
null
null
null
#ifndef LIPH_STREAM_CORE_HPP #define LIPH_STREAM_CORE_HPP #include <cstddef> #include <functional> #include <iterator> #include <memory> #include <optional> #include <stdexcept> #include <tuple> #include <type_traits> #include <utility> namespace stream { class streamer_error : public std::runtime_error { public: streamer_error(const std::string &what) : std::runtime_error(what) {} streamer_error(const char *what) : std::runtime_error(what) {} }; namespace detail { template<typename Func, typename Tuple, typename = std::void_t<>> constexpr bool can_apply_tuple = false; template<typename Func, typename... Args> constexpr bool can_apply_tuple<Func, std::tuple<Args...>, std::void_t<decltype(std::declval<Func>()(std::declval<Args&>()...))>> = true; template <typename... Args> constexpr auto make_ref_tuple_from_args(Args&... args) { return std::tuple<Args&...>(args...); } template <size_t... indices, typename T1> constexpr auto make_ref_tuple(T1&& s, std::index_sequence<indices...>) { return make_ref_tuple_from_args(std::get<indices>(std::forward<T1>(s))...); } template <typename T1> constexpr auto make_ref_tuple(T1&& s) { constexpr std::size_t N = std::tuple_size<std::remove_reference_t<T1>>::value; return make_ref_tuple(std::forward<T1>(s), std::make_index_sequence<N>()); } template<typename Func, typename Tuple, typename... Args> constexpr auto apply_first(Func &&func, Tuple &&tup, Args&&... args) { return std::apply(std::forward<Func>(func), std::tuple_cat(std::forward<Tuple>(tup), std::tuple<Args&&...>(std::forward<Args>(args)...))); } template<typename Func, typename Tuple, typename... Args> constexpr auto apply_last(Func &&func, Tuple &&tup, Args&&... args) { return std::apply(std::forward<Func>(func), std::tuple_cat(std::tuple<Args&&...>(std::forward<Args>(args)...), std::forward<Tuple>(tup))); } template<typename Op, typename... Params> constexpr auto call_stream_gen_run(Op &op, std::tuple<Params&...> &&params) { using Class = std::remove_reference_t<Op>; using Ret = decltype(op.run(std::declval<Params&>()...)); return apply_last(static_cast<Ret(Class::*)(Params&...)>(&Class::template run<Params&...>), std::move(params), op); } template<typename Op, typename Src, typename... Params> constexpr auto call_stream_op_run(Op &op, Src &src, std::tuple<Params&...> params) { using Class = std::remove_reference_t<Op>; using Ret = decltype(op.run(src, std::declval<Params&>()...)); return apply_last(static_cast<Ret(Class::*)(Src&, Params&...)>(&Class::template run<Src&, Params&...>), std::move(params), op, src); } template<typename Op, typename... Params> constexpr auto call_stream_post_init(Op &op, std::tuple<Params&...> &&params) { using Class = std::remove_reference_t<Op>; return apply_last(static_cast<void(Class::*)(Params&...)>(&Class::template post_init<Params&...>), std::move(params), op); } template<typename Pipe, typename Gen = char, typename ValueType = decltype(std::declval<Pipe>().next())> struct iterator { using value_type = ValueType; constexpr iterator() : gen(), pipe(nullptr), value() {} constexpr explicit iterator(Pipe *p) : gen(), pipe(p), value(pipe->next()) {} constexpr explicit iterator(Gen &&g) : gen(std::move(g)), pipe(&*gen), value(pipe->next()) {} constexpr iterator &operator++() { value = pipe->next(); return *this; } constexpr iterator operator++(int) { iterator it = *this; value = pipe->next(); return it; } constexpr typename ValueType::value_type &operator*() { return *value; } std::optional<Gen> gen; Pipe *pipe; ValueType value; }; template<typename Pipe, typename Gen, typename ValueType> constexpr bool operator==(const iterator<Pipe, Gen, ValueType> &left, const iterator<Pipe, Gen, ValueType> &right) { return left.value.has_value() == right.value.has_value(); } template<typename Pipe, typename Gen, typename ValueType> constexpr bool operator!=(const iterator<Pipe, Gen, ValueType> &left, const iterator<Pipe, Gen, ValueType> &right) { return !(left == right); } template<typename Src, typename Params = decltype(std::declval<Src>().init())> struct gen { constexpr explicit gen(Src s) : src(std::move(s)), params(src.init()) { call_stream_post_init(src, make_ref_tuple(params)); } constexpr auto next() { return call_stream_gen_run(src, make_ref_tuple(params)); } Src src; Params params; using iterator = detail::iterator<gen, gen>; using value_opt_type = decltype(std::declval<gen<Src>>().next()); using value_type = typename value_opt_type::value_type; constexpr iterator begin() { return iterator(this); } constexpr iterator end() { return iterator(); } }; template<typename Src, typename Dest, typename Params = decltype(std::declval<Dest>().template init(std::declval<Src&>()))> struct pipe { constexpr pipe(Src s, Dest d) : src(std::move(s)), dest(std::move(d)), params(dest.template init(src)) { call_stream_post_init(dest, make_ref_tuple(params)); } /* pipe(const pipe &) = delete; pipe &operator=(const pipe &) = delete; pipe(pipe &&) = default; pipe &operator=(pipe &&) = default; */ constexpr auto next() { return call_stream_op_run(dest, src, make_ref_tuple(params)); } Src src; Dest dest; Params params; using iterator = detail::iterator<pipe>; using value_opt_type = decltype(std::declval<pipe>().next()); using value_type = typename value_opt_type::value_type; constexpr iterator begin() { return iterator(this); } constexpr iterator end() { return iterator(); } }; template<typename Func, typename InitFunc, typename PostInitFunc> class stream_gen_base { public: constexpr stream_gen_base(Func &&f) : func(std::move(f)) {} constexpr stream_gen_base(Func &&f, InitFunc &&i) : func(std::move(f)), init_func(std::move(i)) {} constexpr stream_gen_base(Func &&f, InitFunc &&i, PostInitFunc &&p) : func(std::move(f)), init_func(std::move(i)), post_init_func(std::move(p)) {} template<typename... Args> constexpr auto run(Args&... args) const { return func(args...); } constexpr auto init() const { return init_func(); } template<typename... Args> constexpr void post_init(Args&... args) const { post_init_func(args...); } template<typename... Args> constexpr auto run(Args&... args) { return func(args...); } constexpr auto init() { return init_func(); } template<typename... Args> constexpr void post_init(Args&... args) { post_init_func(args...); } protected: Func func; InitFunc init_func; PostInitFunc post_init_func; }; template<typename Gen, typename InitFunc, typename Func, typename = std::void_t<>> struct iterator_type { using type = struct error_stream_gen_missing_parameters; }; template<typename Gen, typename InitFunc, typename Func> struct iterator_type<Gen, InitFunc, Func, std::enable_if_t<can_apply_tuple<Func, decltype(std::declval<InitFunc>()())>>> { using type = iterator<gen<Gen>, gen<Gen>>; }; struct default_init { template<typename... Args> constexpr auto operator()(Args&&... args) const { return std::make_tuple(std::forward<Args>(args)...); } }; struct default_op_init { template<typename Src, typename... Args> constexpr auto operator()(Src&, Args&&... args) const { return std::make_tuple(std::forward<Args>(args)...); } }; struct default_post_init { template<typename... Args> constexpr void operator()(Args&&...) const {} }; } // namespace detail template<typename Func, typename InitFunc = detail::default_init, typename PostInitFunc = detail::default_post_init> class stream_gen : public detail::stream_gen_base<Func, InitFunc, PostInitFunc> { public: constexpr stream_gen(Func f) : detail::stream_gen_base<Func, InitFunc, PostInitFunc>(std::move(f)) {} constexpr stream_gen(Func f, InitFunc i) : detail::stream_gen_base<Func, InitFunc, PostInitFunc>(std::move(f), std::move(i)) {} constexpr stream_gen(Func f, InitFunc i, PostInitFunc p) : detail::stream_gen_base<Func, InitFunc, PostInitFunc>(std::move(f), std::move(i), std::move(p)) {} constexpr const stream_gen &operator()() const { return *this; } template<typename... Args> constexpr auto operator()(Args&&... args) const { auto init = [i = this->init_func, a = std::tuple<Args...>(std::forward<Args>(args)...)](auto&&... more_args) { return detail::apply_first(std::move(i), std::move(a), std::forward<decltype(more_args)>(more_args)...); }; return stream_gen<Func, decltype(init), PostInitFunc>(this->func, std::move(init), this->post_init_func); } using iterator = typename detail::iterator_type< detail::stream_gen_base<Func, InitFunc, PostInitFunc>, InitFunc, Func >::type; constexpr auto begin() const { return iterator(detail::gen<detail::stream_gen_base<Func, InitFunc, PostInitFunc>>(*this)); } constexpr auto end() const { return iterator(); } constexpr stream_gen &operator()() { return *this; } template<typename... Args> constexpr auto operator()(Args&&... args) { auto init = [i = this->init_func, a = std::tuple<Args...>(std::forward<Args>(args)...)](auto&&... more_args) { return detail::apply_first(std::move(i), std::move(a), std::forward<decltype(more_args)>(more_args)...); }; return stream_gen<Func, decltype(init), PostInitFunc>(this->func, std::move(init), this->post_init_func); } constexpr auto begin() { return iterator(detail::gen<detail::stream_gen_base<Func, InitFunc, PostInitFunc>>(*this)); } constexpr auto end() { return iterator(); } }; template<typename Func, typename InitFunc = detail::default_op_init, typename PostInitFunc = detail::default_post_init> class stream_op { public: constexpr stream_op(Func f) : func(std::move(f)) {} constexpr stream_op(Func f, InitFunc i) : func(std::move(f)), init_func(std::move(i)) {} constexpr stream_op(Func f, InitFunc i, PostInitFunc p) : func(std::move(f)), init_func(std::move(i)), post_init_func(std::move(p)) {} constexpr const stream_op &operator()() const { return *this; } template<typename... Args> constexpr auto operator()(Args&&... args) const { auto init = [i = init_func, a = std::tuple<Args...>(std::forward<Args>(args)...)](auto &prev_op, auto&&... more_args) { return apply_first(std::move(i), std::tuple_cat(std::tuple<decltype(prev_op)&>(prev_op), std::move(a)), std::forward<decltype(more_args)>(more_args)...); }; return stream_op<Func, decltype(init), PostInitFunc>(func, std::move(init), post_init_func); } template<typename... Args> constexpr auto run(Args&... args) const { return func(args...); } template<typename Src> constexpr auto init(Src &src) const { return init_func(src); } template<typename... Args> constexpr void post_init(Args&... args) const { post_init_func(args...); } constexpr stream_op &operator()() { return *this; } template<typename... Args> constexpr auto operator()(Args&&... args) { auto init = [i = init_func, a = std::tuple<Args...>(std::forward<Args>(args)...)](auto &prev_op, auto&&... more_args) { return apply_first(std::move(i), std::tuple_cat(std::tuple<decltype(prev_op)&>(prev_op), std::move(a)), std::forward<decltype(more_args)>(more_args)...); }; return stream_op<Func, decltype(init), PostInitFunc>(func, std::move(init), post_init_func); } template<typename... Args> constexpr auto run(Args&... args) { return func(args...); } template<typename Src> constexpr auto init(Src &src) { return init_func(src); } template<typename... Args> constexpr void post_init(Args&... args) { post_init_func(args...); } private: Func func; InitFunc init_func; PostInitFunc post_init_func; }; template<typename Func, typename InitFunc = detail::default_op_init, typename PostInitFunc = detail::default_post_init> class stream_term : public stream_op<Func, InitFunc, PostInitFunc> { public: constexpr stream_term(Func f) : stream_op<Func, InitFunc, PostInitFunc>(std::move(f)) {} constexpr stream_term(Func f, InitFunc i) : stream_op<Func, InitFunc, PostInitFunc>(std::move(f), std::move(i)) {} constexpr stream_term(Func f, InitFunc i, PostInitFunc p) : stream_op<Func, InitFunc, PostInitFunc>(std::move(f), std::move(i), std::move(p)) {} }; template<typename... Args> constexpr auto smart_make_tuple(Args&&... args) { return std::tuple<Args...>(std::forward<Args>(args)...); } namespace detail { struct container_gen { template<typename Container, typename It> constexpr auto operator()(Container &cont, std::optional<It> &current) const { if(*current == std::end(cont)) return std::optional<std::decay_t<decltype(**current)>>(); else return std::optional(*(*current)++); } template<typename T> constexpr std::optional<T> operator()(std::optional<T> &opt) const { auto ret = opt; opt.reset(); return ret; } }; struct container_init { template<typename Container> constexpr auto operator()(Container &&cont) const { return smart_make_tuple( std::forward<Container>(cont), std::optional<decltype(std::begin(std::forward<Container>(cont)))>()); } template<typename T> constexpr std::tuple<> operator()(std::optional<T>) const { return {}; } }; struct container_post_init { template<typename Container, typename It> constexpr auto operator()(Container &cont, std::optional<It> &current) const { current = std::begin(cont); } }; } // namespace detail constexpr inline stream_gen container{detail::container_gen{}, detail::container_init{}, detail::container_post_init{}}; template<typename Container, typename... Args> constexpr auto operator|(Container &&c, stream_op<Args...> op) { return detail::pipe(detail::gen(container(std::forward<Container>(c))), std::move(op)); } template<typename Func, typename InitFunc, typename PostInitFunc, typename Func2, typename InitFunc2, typename PostInitFunc2> constexpr auto operator|(stream_gen<Func, InitFunc, PostInitFunc> g, stream_op<Func2, InitFunc2, PostInitFunc2> op) { return detail::pipe(detail::gen(std::move(g)), std::move(op)); } template<typename Src, typename Dest, typename Params, typename... Args> constexpr auto operator|(detail::pipe<Src, Dest, Params> p, stream_op<Args...> op) { return detail::pipe(std::move(p), std::move(op)); } template<typename Container, typename... Args> constexpr auto operator|(Container &&c, stream_term<Args...> op) { return detail::pipe(detail::gen(container(std::forward<Container>(c))), std::move(op)).next(); } template<typename Func, typename InitFunc, typename PostInitFunc, typename Func2, typename InitFunc2, typename PostInitFunc2> constexpr auto operator|(stream_gen<Func, InitFunc, PostInitFunc> g, stream_term<Func2, InitFunc2, PostInitFunc2> op) { return detail::pipe(detail::gen(std::move(g)), std::move(op)).next(); } template<typename Src, typename Dest, typename Params, typename... Args> constexpr auto operator|(detail::pipe<Src, Dest, Params> p, stream_term<Args...> op) { return detail::pipe(std::move(p), std::move(op)).next(); } } // namespace stream namespace std { template<typename Pipe, typename Gen, typename ValueType> struct iterator_traits<stream::detail::iterator<Pipe, Gen, ValueType>> { using difference_type = std::size_t; using value_type = typename ValueType::value_type; using reference = value_type&; using pointer = value_type*; using iterator_category = input_iterator_tag; }; } #endif
35.653422
165
0.667018
alipha
9516beedad8ae9daf9b1fa96b97b46ecb5df3bf9
786
cpp
C++
Drivers/CardsDriver.cpp
mdsharif-me/warzone-reloaded
660194d08422c3d5ffd8c23d00ceb8064b6153ad
[ "MIT" ]
1
2022-02-08T19:08:39.000Z
2022-02-08T19:08:39.000Z
Drivers/CardsDriver.cpp
mdsharif-me/warzone-reloaded
660194d08422c3d5ffd8c23d00ceb8064b6153ad
[ "MIT" ]
null
null
null
Drivers/CardsDriver.cpp
mdsharif-me/warzone-reloaded
660194d08422c3d5ffd8c23d00ceb8064b6153ad
[ "MIT" ]
null
null
null
// // Created by tigerrrr on 2/13/2022. // #include <iostream> #include "../Headers/Cards.h" using namespace std; int main() { Card* card1 = new Card("Bomb"); Card* card2 = new Card("Airlift"); const char * CardTypes[5] = { "Blockade", "Bomb", "Reinforcement", "Diplomacy", "airlift"}; Deck* deck = new Deck(); deck->addToDeck(card1); deck->addToDeck(card2); deck->print(); //Adding 50 cards to complete the deck for (int i = 0; i < 50; i++) { int r = rand() % 5; Card *card = new Card(CardTypes[r]); deck->addToDeck(card); } //Hand* hand = new Hand(); string name = "Deep"; Player* player = new Player(name); deck->draw(player); deck->draw(player); deck->print(); //hand->print(); }
20.153846
97
0.561069
mdsharif-me
9516e154551241d8f72c1d23c5abb7cf3134b3f6
858
cpp
C++
tests/expected/rect.cpp
div72/py2many
60277bc13597bd32d078b88a7390715568115fc6
[ "MIT" ]
345
2021-01-28T17:33:08.000Z
2022-03-25T16:07:56.000Z
tests/expected/rect.cpp
mkos11/py2many
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
[ "MIT" ]
291
2021-01-31T13:15:06.000Z
2022-03-23T21:28:49.000Z
tests/expected/rect.cpp
mkos11/py2many
be6cfaad5af32c43eb24f182cb20ad63b979d4ef
[ "MIT" ]
23
2021-02-09T17:15:03.000Z
2022-02-03T05:57:44.000Z
#include <cassert> // NOLINT(build/include_order) #include <iostream> // NOLINT(build/include_order) #include "pycpp/runtime/builtins.h" // NOLINT(build/include_order) #include "pycpp/runtime/sys.h" // NOLINT(build/include_order) /* This file implements a rectangle class */ class Rectangle { public: int height; int length; Rectangle(int height, int length) { this->height = height; this->length = length; } inline bool is_square() { return this->height == this->length; } }; inline void show() { Rectangle r = Rectangle(1, 1); assert(r.is_square()); r = Rectangle(1, 2); assert(!(r.is_square())); std::cout << r.height; std::cout << std::endl; std::cout << r.length; std::cout << std::endl; } int main(int argc, char** argv) { pycpp::sys::argv = std::vector<std::string>(argv, argv + argc); show(); }
24.514286
67
0.645688
div72
95191f47b17aaae95099d0f6b262c22f923d8bbf
1,025
cpp
C++
test/src/Game_Tests.cpp
gravity981/settlers
0e2684f2358dbab8fdc70de4a9c94133a324a2b7
[ "Unlicense" ]
null
null
null
test/src/Game_Tests.cpp
gravity981/settlers
0e2684f2358dbab8fdc70de4a9c94133a324a2b7
[ "Unlicense" ]
null
null
null
test/src/Game_Tests.cpp
gravity981/settlers
0e2684f2358dbab8fdc70de4a9c94133a324a2b7
[ "Unlicense" ]
null
null
null
#include <gtest/gtest.h> #include <spdlog/spdlog.h> #include "mock/MockGameObserver.h" #include "mock/MockWorld.h" #include "settlers/Game.h" TEST(DISABLED_GameTests, startGameShouldChangeState) { MockWorld world; EXPECT_CALL(world, generateFromFile).Times(1); MockGameObserver observer; EXPECT_CALL(observer, gameStateChanged).Times(1); Game game{ world }; EXPECT_EQ(game.getGameState(), Game::GAMESTATE_IDLE); game.registerGameObserver(&observer); std::vector<Game::SPlayer> players = { { 1, Player::PLAYERCOLOR_RED }, { 2, Player::PLAYERCOLOR_BLUE }, { 3, Player::PLAYERCOLOR_ORANGE } }; ASSERT_TRUE(game.start(players, "some/path", "some/path", "some/path" , 0, 0)); } int main(int argc, char **argv) { spdlog::set_level(spdlog::level::debug); // Set global log level to debug spdlog::set_pattern("[%H:%M:%S.%e %z][%l][%s][%!()][line %#] %v"); ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.344828
81
0.647805
gravity981
951a51bad8332cd5857563ca3efe7a0c76bed8ad
389
cpp
C++
searching/linear.cpp
tusharad/Data-structures-and-algorithms
fde2dffb0ff19c7f88d01ac0ecb926c67348ad21
[ "MIT" ]
null
null
null
searching/linear.cpp
tusharad/Data-structures-and-algorithms
fde2dffb0ff19c7f88d01ac0ecb926c67348ad21
[ "MIT" ]
null
null
null
searching/linear.cpp
tusharad/Data-structures-and-algorithms
fde2dffb0ff19c7f88d01ac0ecb926c67348ad21
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int val,flag = 0; int arr[10] = {23,45,1,56,77,4}; int n = 6; cout<<"Enter element to find"<<endl; cin>>val; for(int i = 0;i < n;i++){ if(arr[i] == val){ cout<<val<<" found at index "<<i+1<<endl; flag = 1; } } if(flag == 0) cout<<"Nothing found!"<<endl; }
20.473684
53
0.467866
tusharad
951c798b5eb4a51a53857ca6b839e586966a78a8
2,336
cpp
C++
code/modules/application/src/application/application.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/modules/application/src/application/application.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
code/modules/application/src/application/application.cpp
BrightComposite/RaptureStateToolkit
6eb3c831540ba6a9d29e903dd3c537aac2e7f91f
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- #include <application/application.h> #include <iostream> #if defined(_MSC_VER) && (defined(_DEBUG) || defined(DEBUG)) //#include <vld.h> #endif //--------------------------------------------------------------------------- namespace asd { wstring get_dir(const wstring & path); #ifdef WIN32 int application::main(int argc, wchar_t * argv[]) { auto & inst = instance(); if (inst.hInstance != nullptr) { throw std::runtime_error("Application has been already loaded!"); } inst.hInstance = (HINSTANCE)GetModuleHandle(nullptr); for (int i = 0; i < argc; ++i) inst.args.push_back(argv[i]); STARTUPINFOW info; GetStartupInfoW(&info); inst._show_command = check_flag(STARTF_USESHOWWINDOW, info.dwFlags) ? info.wShowWindow : SW_NORMAL; inst._root_path = get_dir(get_dir(application::getExecutionPath(inst.hInstance))); return load(); } HINSTANCE application::windows_instance() { auto & inst = instance(); return inst.hInstance; } #else int application::main(int argc, wchar_t ** argv) { auto & inst = instance(); for (int i = 0; i < argc; ++i) inst.args.push_back(wstring(argv[i])); inst._root_path = get_dir(get_dir(argv[0])); return load(); } #endif const wstring & application::root_path() { auto & inst = instance(); return inst._root_path; } const array_list<wstring> & application::arguments() { auto & inst = instance(); return inst.args; } int application::show_command() { auto & inst = instance(); return inst._show_command; } int application::load() { return instance().entrance(); } #ifdef WIN32 wstring application::getExecutionPath(HINSTANCE hInstance) { wchar_t buffer[MAX_PATH]; GetModuleFileNameW(hInstance, buffer, MAX_PATH); return{ buffer, wcslen(buffer) }; } #endif void application::pause() { std::cout << std::endl; std::cout << "Press Enter to exit..."; getchar(); } wstring get_dir(const wstring & path) { return path.substr(0, path.find_last_of(L"/\\")); } }
25.67033
107
0.556507
BrightComposite
951ddc5c5610781a10b5889ec222a12158def757
3,929
cpp
C++
src/apps/processcontroller/KernelMemoryBarMenuItem.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/processcontroller/KernelMemoryBarMenuItem.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/processcontroller/KernelMemoryBarMenuItem.cpp
Yn0ga/haiku
74e271b2a286c239e60f0ec261f4f197f4727eee
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2000, Georges-Edouard Berenger. All rights reserved. * Distributed under the terms of the MIT License. */ #include "KernelMemoryBarMenuItem.h" #include "Colors.h" #include "MemoryBarMenu.h" #include "ProcessController.h" #include <stdio.h> #include <Catalog.h> #include <StringForSize.h> #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ProcessController" KernelMemoryBarMenuItem::KernelMemoryBarMenuItem(system_info& systemInfo) : BMenuItem(B_TRANSLATE("System resources & caches" B_UTF8_ELLIPSIS), NULL) { fLastSum = -1; fGrenze1 = -1; fGrenze2 = -1; fPhysicalMemory = (int64)systemInfo.max_pages * B_PAGE_SIZE / 1024LL; fCommittedMemory = (int64)systemInfo.used_pages * B_PAGE_SIZE / 1024LL; fCachedMemory = (int64)systemInfo.cached_pages * B_PAGE_SIZE / 1024LL; } void KernelMemoryBarMenuItem::DrawContent() { DrawBar(true); Menu()->MovePenTo(ContentLocation()); BMenuItem::DrawContent(); } void KernelMemoryBarMenuItem::UpdateSituation(int64 committedMemory, int64 cachedMemory) { fCommittedMemory = committedMemory; fCachedMemory = cachedMemory; DrawBar(false); } void KernelMemoryBarMenuItem::DrawBar(bool force) { bool selected = IsSelected(); BRect frame = Frame(); BMenu* menu = Menu(); rgb_color highColor = menu->HighColor(); BFont font; menu->GetFont(&font); BRect cadre = bar_rect(frame, &font); // draw the bar itself if (fLastSum < 0) force = true; if (force) { if (selected) menu->SetHighColor(gFrameColorSelected); else menu->SetHighColor(gFrameColor); menu->StrokeRect (cadre); } cadre.InsetBy(1, 1); BRect r = cadre; double grenze1 = cadre.left + (cadre.right - cadre.left) * fCachedMemory / fPhysicalMemory; double grenze2 = cadre.left + (cadre.right - cadre.left) * fCommittedMemory / fPhysicalMemory; if (grenze1 > cadre.right) grenze1 = cadre.right; if (grenze2 > cadre.right) grenze2 = cadre.right; r.right = grenze1; if (!force) r.left = fGrenze1; if (r.left < r.right) { if (selected) menu->SetHighColor(gKernelColorSelected); else menu->SetHighColor(gKernelColor); menu->FillRect (r); } r.left = grenze1; r.right = grenze2; if (!force) { if (fGrenze2 > r.left && r.left >= fGrenze1) r.left = fGrenze2; if (fGrenze1 < r.right && r.right <= fGrenze2) r.right = fGrenze1; } if (r.left < r.right) { if (selected) menu->SetHighColor(tint_color (kLavender, B_HIGHLIGHT_BACKGROUND_TINT)); else menu->SetHighColor(kLavender); menu->FillRect (r); } r.left = grenze2; r.right = cadre.right; if (!force) r.right = fGrenze2; if (r.left < r.right) { if (selected) menu->SetHighColor(gWhiteSelected); else menu->SetHighColor(kWhite); menu->FillRect(r); } menu->SetHighColor(highColor); fGrenze1 = grenze1; fGrenze2 = grenze2; // draw the value double sum = fCachedMemory * FLT_MAX + fCommittedMemory; if (force || sum != fLastSum) { if (selected) { menu->SetLowColor(gMenuBackColorSelected); menu->SetHighColor(gMenuBackColorSelected); } else { menu->SetLowColor(gMenuBackColor); menu->SetHighColor(gMenuBackColor); } BRect trect(cadre.left - kMargin - gMemoryTextWidth, frame.top, cadre.left - kMargin, frame.bottom); menu->FillRect(trect); menu->SetHighColor(highColor); char infos[128]; string_for_size(fCachedMemory * 1024.0, infos, sizeof(infos)); BPoint loc(cadre.left, cadre.bottom + 1); loc.x -= kMargin + gMemoryTextWidth / 2 + menu->StringWidth(infos); menu->DrawString(infos, loc); string_for_size(fCommittedMemory * 1024.0, infos, sizeof(infos)); loc.x = cadre.left - kMargin - menu->StringWidth(infos); menu->DrawString(infos, loc); fLastSum = sum; } } void KernelMemoryBarMenuItem::GetContentSize(float* _width, float* _height) { BMenuItem::GetContentSize(_width, _height); if (*_height < 16) *_height = 16; *_width += 20 + kBarWidth + kMargin + gMemoryTextWidth; }
23.957317
76
0.709086
Yn0ga
95209cb0069d4e1c594836da7a2a341c45809709
4,853
cc
C++
netlibcc/net/EPoller.cc
kohakus/tiny-netlib
da9998ee06f4e2eb5ebcaf0e383196269dea1f33
[ "MIT" ]
1
2021-03-05T10:14:27.000Z
2021-03-05T10:14:27.000Z
netlibcc/net/EPoller.cc
kohakus/tiny-netlib
da9998ee06f4e2eb5ebcaf0e383196269dea1f33
[ "MIT" ]
null
null
null
netlibcc/net/EPoller.cc
kohakus/tiny-netlib
da9998ee06f4e2eb5ebcaf0e383196269dea1f33
[ "MIT" ]
null
null
null
#include "netlibcc/net/EPoller.h" #include <poll.h> #include <errno.h> #include <sys/epoll.h> #include <unistd.h> #include <cassert> #include "netlibcc/net/Channel.h" #include "netlibcc/core/Logger.h" // utilize POLL flags in epoll functions for compatibility static_assert(EPOLLIN == POLLIN, "epoll event flags are implemented identical to poll events"); static_assert(EPOLLERR == POLLERR, "epoll event flags are implemented identical to poll events"); static_assert(EPOLLHUP == POLLHUP, "epoll event flags are implemented identical to poll events"); static_assert(EPOLLPRI == POLLPRI, "epoll event flags are implemented identical to poll events"); static_assert(EPOLLOUT == POLLOUT, "epoll event flags are implemented identical to poll events"); static_assert(EPOLLRDHUP == POLLRDHUP, "epoll event flags are implemented identical to poll events"); namespace netlibcc { namespace net { EPoller::EPoller(EventLoop* loop) : owner_loop_(loop), epollfd_(::epoll_create1(EPOLL_CLOEXEC)), num_fd_(0), event_list_(kInitEventListSize) { if (epollfd_ < 0) { // if epoll_create return -1, the errno is set to indicate the error LOG_SYSFATAL << "EPoller::EPoller, error occur"; } } EPoller::~EPoller() { // for RAII ::close(epollfd_); } void EPoller::poll(ChannelList* active_channels, int timeout) { LOG_TRACE << "fd count: " << num_fd_; int num_event = ::epoll_wait(epollfd_, &*event_list_.begin(), static_cast<int>(event_list_.size()), timeout); // the return value of epoll_wait can be >0, 0, -1 // if return -1, the errno can be EBADF, EFAULT, EINTR or EINVAL int curr_errno = errno; if (num_event < 0) { // ignore signal interrupt if (curr_errno != EINTR) { errno = curr_errno; LOG_SYSERR << "EPoller::poll()"; } } else if (num_event == 0) { LOG_TRACE << "timeout and no file descriptor became ready"; } else { LOG_TRACE << num_event << " events happened"; fillActiveChannels(num_event, active_channels); if (event_list_.size() == static_cast<size_t>(num_event)) { event_list_.resize(event_list_.size() * 2); } } } void EPoller::fillActiveChannels(int num_event, ChannelList* active_channels) const { for (int i = 0; i < num_event; i++) { //* set the corresponding channel obj Channel* channel = static_cast<Channel*>(event_list_[i].data.ptr); channel->set_revents(event_list_[i].events); active_channels->push_back(channel); } } void EPoller::update(int operation, Channel* channel) { //* create and construct epoll_event for registering struct epoll_event channel_event; memset(&channel_event, 0, sizeof channel_event); // set interested events channel_event.events = channel->events(); // set user data channel_event.data.ptr = channel; int fd = channel->fd(); LOG_TRACE << "epoll_ctl op = " << opStr(operation) << " fd = " << fd; if (::epoll_ctl(epollfd_, operation, fd, &channel_event) < 0) { (operation == EPOLL_CTL_DEL ? (LOG_SYSERR) : (LOG_SYSFATAL)) << "epoll_ctl op = " << opStr(operation) << " fd = " << fd; } } void EPoller::updateChannel(Channel* channel) { // check if this is called in the corresponding IO thread owner_loop_->assertInLoopThread(); LOG_TRACE << "fd = " << channel->fd() << (channel->inPollar() ? " in EPollar" : " not in EPollar"); if(!channel->inPollar()) { ++num_fd_; channel->setInPollarState(true); update(EPOLL_CTL_ADD, channel); } else { if (channel->isNoneEvent()) { update(EPOLL_CTL_DEL, channel); channel->setInPollarState(false); --num_fd_; } else { update(EPOLL_CTL_MOD, channel); } } } void EPoller::removeChannel(Channel* channel) { owner_loop_->assertInLoopThread(); LOG_TRACE << "fd = " << channel->fd(); assert(channel->isNoneEvent()); if (channel->inPollar()) { update(EPOLL_CTL_DEL, channel); channel->setInPollarState(false); --num_fd_; } } const char* EPoller::opStr(int op) { switch (op) { case EPOLL_CTL_ADD: return "ADD"; case EPOLL_CTL_DEL: return "DEL"; case EPOLL_CTL_MOD: return "MOD"; default: // must be wrong when op is unrecognizable assert(false && "ERROR EPoll OP"); return "Unknown Operation"; } } } // namespace net } // namespace netlibcc
34.176056
102
0.602102
kohakus
9521d512682ebffd8467f2ed3f6f906106bb5103
1,031
cpp
C++
cs6366-computer-graphics/semester_project/cel_shader/cel_shader/ShaderProgram.cpp
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
3
2017-03-17T15:15:11.000Z
2020-10-01T16:05:17.000Z
cs6366-computer-graphics/semester_project/cel_shader/cel_shader/ShaderProgram.cpp
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
null
null
null
cs6366-computer-graphics/semester_project/cel_shader/cel_shader/ShaderProgram.cpp
gsteelman/utd
65bf3b81b7a089612f6c7546aa0bbdfbdcdb334e
[ "Apache-2.0" ]
7
2016-02-07T22:56:26.000Z
2021-02-26T02:50:28.000Z
#include "ShaderProgram.h" ShaderProgram::ShaderProgram() : m_ID(-1) {} ShaderProgram::~ShaderProgram() {} ShaderProgram::ShaderProgram( const string& vert, const string& frag ) { read( vert, frag ); compile(); } GLvoid ShaderProgram::read( const string& vert, const string& frag ) { m_vert.m_type = GL_VERTEX_SHADER; m_vert.read( vert ); m_frag.m_type = GL_FRAGMENT_SHADER; m_frag.read( frag ); } GLboolean ShaderProgram::compile() { m_vert.compile(); m_frag.compile(); m_ID = glCreateProgram(); glAttachShader( m_ID, m_vert.m_ID ); glAttachShader( m_ID, m_frag.m_ID ); glLinkProgram( m_ID ); glUseProgram( m_ID ); return true; } GLvoid ShaderProgram::printLog() { GLint infoLogLength = 0; GLint count = 0; char* infoLog; glGetProgramiv( m_ID, GL_INFO_LOG_LENGTH, &infoLogLength ); if ( infoLogLength > 0 ) { infoLog = (GLchar*)malloc(infoLogLength); glGetProgramInfoLog( m_ID, infoLogLength, &count, infoLog ); printf( "%s\n", infoLog ); free( infoLog ); } }
21.040816
72
0.682832
gsteelman
95282ab90877db8fc56209b874837ed43ce97156
6,458
cpp
C++
util/summation_test.cpp
RedBeard0531/mongo_utils
402c2023df7d67609ce9da8e405bf13cdd270e20
[ "Apache-2.0" ]
1
2018-03-14T21:48:43.000Z
2018-03-14T21:48:43.000Z
util/summation_test.cpp
RedBeard0531/mongo_utils
402c2023df7d67609ce9da8e405bf13cdd270e20
[ "Apache-2.0" ]
null
null
null
util/summation_test.cpp
RedBeard0531/mongo_utils
402c2023df7d67609ce9da8e405bf13cdd270e20
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2016 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "mongo/platform/basic.h" #include <cmath> #include <limits> #include <vector> #include "mongo/unittest/unittest.h" #include "mongo/util/summation.h" namespace mongo { namespace { using limits = std::numeric_limits<long long>; std::vector<long long> longValues = { limits::min(), limits::min() + 1, limits::min() / 2, -(1LL << 53), -(1LL << 52), -(1LL << 32), -0x100, -0xff, -0xaa, -0x55, -1, 0, 1, 2, 0x55, 0x80, 0xaa, 0x100, 512, 1024, 2048, 1LL << 31, 1LL << 32, 1LL << 52, 1LL << 53, limits::max() / 2, #pragma warning(push) // C4308: negative integral constant converted to unsigned type #pragma warning(disable : 4308) static_cast<long long>(1ULL << 63) - (1ULL << (63 - 53 - 1)), // Halfway between two doubles #pragma warning(pop) limits::max() - 1, limits::max()}; std::vector<double> doubleValues = { 1.4831356930199802e-05, -3.121724665346865, 3041897608700.073, 1001318343149.7166, -1714.6229586696593, 1731390114894580.8, 6.256645803154374e-08, -107144114533844.25, -0.08839485091750919, -265119153.02185738, -0.02450615965231944, 0.0002684331017079073, 32079040427.68358, -0.04733295911845742, 0.061381859083076085, -25329.59126796951, -0.0009567520620034965, -1553879364344.9932, -2.1101077525869814e-08, -298421079729.5547, 0.03182394834273594, 22.201944843278916, -33.35667991109125, 11496013.960449915, -40652595.33210472, 3.8496066090328163, 2.5074042398147304e-08, -0.02208724071782122, -134211.37290639878, 0.17640433666616578, 4.463787499171126, 9.959669945399718, 129265976.35224283, 1.5865526187526546e-07, -4746011.710555799, -712048598925.0789, 582214206210.4034, 0.025236204812875362, 530078170.91147506, -14.865307666195053, 1.6727994895185032e-05, -113386276.03121366, -6.135827207137054, 10644945799901.145, -100848907797.1582, 2.2404406961625282e-08, 1.315662618424494e-09, -0.832190208349044, -9.779323414999364, -546522170658.2997}; const double doubleValuesSum = 1636336982012512.5; // simple summation will yield wrong result std::vector<double> specialValues = {-std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity(), std::numeric_limits<double>::quiet_NaN()}; } // namespace TEST(Summation, AddLongs) { int iter = 0; for (auto x : longValues) { for (auto y : longValues) { for (auto z : longValues) { iter++; DoubleDoubleSummation sum; // This checks for correct results mod 2**64, which helps with checking correctness // around the 2**53 transition between both doubles of the DoubleDouble result in // int64 additions, as well off-by-one errors. uint64_t checkUint64 = static_cast<uint64_t>(x) + static_cast<uint64_t>(y) + static_cast<uint64_t>(z); sum.addLong(x); sum.addLong(y); sum.addLong(z); ASSERT(sum.isInteger()); if (!sum.fitsLong()) { ASSERT(std::abs(sum.getDouble()) >= limits::max()); // Reduce sum to fit in a 64-bit integer. while (!sum.fitsLong()) { sum.addDouble(sum.getDouble() < 0 ? std::ldexp(1, 64) : -std::ldexp(1, 64)); } } ASSERT_EQUALS(static_cast<uint64_t>(sum.getLong()), checkUint64); } } } } TEST(Summation, AddSpecial) { for (auto x : specialValues) { DoubleDoubleSummation sum; // Check that a special number will result in that special number. sum.addLong(-42); sum.addLong(100); sum.addDouble(x); ASSERT(!sum.fitsLong()); ASSERT(!sum.isInteger()); if (std::isnan(x)) { ASSERT(std::isnan(sum.getDouble())); } else { ASSERT_EQUALS(sum.getDouble(), x); } // Check that adding more numbers doesn't reset the special value. sum.addDouble(-1E22); sum.addLong(limits::min()); ASSERT(!sum.fitsLong()); if (std::isnan(x)) { ASSERT(std::isnan(sum.getDouble())); } else { ASSERT_EQUALS(sum.getDouble(), x); } } } TEST(Summation, AddInvalid) { DoubleDoubleSummation sum; sum.addDouble(std::numeric_limits<double>::infinity()); sum.addDouble(-std::numeric_limits<double>::infinity()); ASSERT(std::isnan(sum.getDouble())); ASSERT(!sum.fitsLong()); ASSERT(!sum.isInteger()); } TEST(Summation, LongOverflow) { DoubleDoubleSummation positive; // Overflow should result in number no longer fitting in a long. positive.addLong(limits::max()); positive.addLong(limits::max()); ASSERT(!positive.fitsLong()); // However, actual stored overflow should not overflow or lose precision. positive.addLong(-limits::max()); ASSERT_EQUALS(positive.getLong(), limits::max()); DoubleDoubleSummation negative; // Similarly for negative numbers. negative.addLong(limits::min()); negative.addLong(-1); ASSERT(!negative.fitsLong()); negative.addDouble(-1.0 * limits::min()); ASSERT_EQUALS(negative.getLong(), -1); } TEST(Summation, AddDoubles) { DoubleDoubleSummation sum; double straightSum = 0.0; for (auto x : doubleValues) { sum.addDouble(x); straightSum += x; } ASSERT_EQUALS(sum.getDouble(), doubleValuesSum); ASSERT(straightSum != sum.getDouble()); } } // namespace mongo
33.117949
100
0.611025
RedBeard0531
95288be34441d5030148a28f98df66bf9d4652bd
913
cc
C++
FWCore/MessageService/test/UnitTestClient_O.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
FWCore/MessageService/test/UnitTestClient_O.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
FWCore/MessageService/test/UnitTestClient_O.cc
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/global/EDAnalyzer.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/Utilities/interface/StreamID.h" namespace edmtest { class UnitTestClient_O : public edm::global::EDAnalyzer<> { public: explicit UnitTestClient_O(edm::ParameterSet const&) {} void analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const override; }; void UnitTestClient_O::analyze(edm::StreamID, edm::Event const&, edm::EventSetup const&) const { edm::LogInfo("importantInfo") << "This LogInfo message should appear in both destinations"; edm::LogInfo("routineInfo") << "This LogInfo message should appear in the info destination"; } } // namespace edmtest using edmtest::UnitTestClient_O; DEFINE_FWK_MODULE(UnitTestClient_O);
36.52
98
0.761227
Purva-Chaudhari
9528a92fec5fbccd7dd5027b2c2771880c85cfef
37,860
cpp
C++
Plugins/MadaraLibrary/Source/ThirdParty/madara/transport/Transport.cpp
jredmondson/GamsPlugins
d133f86c263997a55f11b3b3d3344faeee60d726
[ "BSD-2-Clause" ]
3
2020-03-25T01:59:20.000Z
2020-06-02T17:58:05.000Z
Plugins/MadaraLibrary/Source/ThirdParty/madara/transport/Transport.cpp
jredmondson/GamsPlugins
d133f86c263997a55f11b3b3d3344faeee60d726
[ "BSD-2-Clause" ]
null
null
null
Plugins/MadaraLibrary/Source/ThirdParty/madara/transport/Transport.cpp
jredmondson/GamsPlugins
d133f86c263997a55f11b3b3d3344faeee60d726
[ "BSD-2-Clause" ]
1
2020-11-05T23:04:05.000Z
2020-11-05T23:04:05.000Z
#include "Transport.h" #include "madara/utility/Utility.h" #include "madara/expression/Interpreter.h" #include "madara/knowledge/ContextGuard.h" #include <algorithm> namespace madara { namespace transport { Base::Base(const std::string& id, TransportSettings& new_settings, knowledge::ThreadSafeContext& context) : is_valid_(false), shutting_down_(false), id_(id), settings_(new_settings), context_(context) #ifndef _MADARA_NO_KARL_ , on_data_received_(context.get_logger()) #endif // _MADARA_NO_KARL_ { settings_.attach(&context_); packet_scheduler_.attach(&settings_); } Base::~Base() {} int Base::setup(void) { // check for an on_data_received ruleset if(settings_.on_data_received_logic.length() != 0) { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "transport::Base::setup" " setting rules to %s\n", settings_.on_data_received_logic.c_str()); #ifndef _MADARA_NO_KARL_ expression::Interpreter interpreter; on_data_received_ = interpreter.interpret(context_, settings_.on_data_received_logic); #endif // _MADARA_NO_KARL_ } else { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "transport::Base::setup" " no permanent rules were set\n"); } // setup the send buffer if(settings_.queue_length > 0) buffer_ = new char[settings_.queue_length]; // if read domains has not been set, then set to write domain if(settings_.num_read_domains() == 0) { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "transport::Base::setup" " no read domains set. Adding write domain (%s)\n", settings_.write_domain.c_str()); settings_.add_read_domain(settings_.write_domain); } else { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "transport::Base::setup" " settings configured with %d read domains\n", settings_.num_read_domains()); } if(settings_.num_read_domains() > 0 && context_.get_logger().get_level() >= logger::LOG_MAJOR) { std::vector<std::string> domains; settings_.get_read_domains(domains); std::stringstream buffer; for(unsigned int i = 0; i < domains.size(); ++i) { buffer << domains[i]; if(i != domains.size() - 1) { buffer << ", "; } } madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "transport::Base::setup" " Write domain: %s. Read domains: %s\n", settings_.write_domain.c_str(), buffer.str().c_str()); } return validate_transport(); } void Base::close(void) { invalidate_transport(); } int process_received_update(const char* buffer, uint32_t bytes_read, const std::string& id, knowledge::ThreadSafeContext& context, const QoSTransportSettings& settings, BandwidthMonitor& send_monitor, BandwidthMonitor& receive_monitor, knowledge::KnowledgeMap& rebroadcast_records, #ifndef _MADARA_NO_KARL_ knowledge::CompiledExpression& on_data_received, #endif // _MADARA_NO_KARL_ const char* print_prefix, const char* remote_host, MessageHeader*& header) { // reset header to 0, so it is safe to delete header = 0; int max_buffer_size = (int)bytes_read; // tell the receive bandwidth monitor about the transaction receive_monitor.add(bytes_read); madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Receive bandwidth = %" PRIu64 " B/s\n", print_prefix, receive_monitor.get_bytes_per_second()); bool is_reduced = false; bool is_fragment = false; madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " calling decode filters on %" PRIu32 " bytes\n", print_prefix, bytes_read); // call decodes, if applicable bytes_read = (uint32_t)settings.filter_decode( (char*)buffer, max_buffer_size, max_buffer_size); madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Decoding resulted in %" PRIu32 " final bytes\n", print_prefix, bytes_read); // setup buffer remaining, used by the knowledge record read method int64_t buffer_remaining = (int64_t)bytes_read; // clear the rebroadcast records rebroadcast_records.clear(); // receive records will be what we pass to the aggregate filter knowledge::KnowledgeMap updates; // if a key appears multiple times, keep to add to buffer history std::map<std::string, std::vector<knowledge::KnowledgeRecord>> past_updates; // check the buffer for a reduced message header if(bytes_read >= ReducedMessageHeader::static_encoded_size() && ReducedMessageHeader::reduced_message_header_test(buffer)) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " processing reduced KaRL message from %s\n", print_prefix, remote_host); header = new ReducedMessageHeader(); is_reduced = true; } else if(bytes_read >= MessageHeader::static_encoded_size() && MessageHeader::message_header_test(buffer)) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " processing KaRL message from %s\n", print_prefix, remote_host); header = new MessageHeader(); } else if(bytes_read >= FragmentMessageHeader::static_encoded_size() && FragmentMessageHeader::fragment_message_header_test(buffer)) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " processing KaRL fragment message from %s\n", print_prefix, remote_host); header = new FragmentMessageHeader(); is_fragment = true; } else if(bytes_read >= 8 + MADARA_IDENTIFIER_LENGTH) { // get the text that appears as identifier. char identifier[MADARA_IDENTIFIER_LENGTH]; strncpy(identifier, buffer + 8, MADARA_IDENTIFIER_LENGTH); identifier[7] = 0; madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " dropping non-KaRL message with id %s from %s\n", print_prefix, identifier, remote_host); return -1; } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " dropping too short message from %s (length %i)\n", print_prefix, remote_host, bytes_read); return -1; } const char* update = header->read(buffer, buffer_remaining); madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " header info: %s\n", print_prefix, header->to_string().c_str()); if(header->size < bytes_read) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Message header.size (%" PRIu64 " bytes) is less than actual" " bytes read (%" PRIu32 " bytes). Dropping message.\n", print_prefix, header->size, bytes_read); return -1; } if(is_fragment && exists(header->originator, header->clock, ((FragmentMessageHeader*)header)->update_number, settings.fragment_map)) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Fragment already exists in fragment map. Dropping.\n", print_prefix); return -1; } if(!is_reduced) { // reject the message if it is us as the originator (no update necessary) if(id == header->originator) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " dropping message from ourself\n", print_prefix); return -2; } else { madara_logger_log(context.get_logger(), logger::LOG_DETAILED, "%s:" " remote id (%s) is not our own\n", print_prefix, remote_host); } if(settings.is_trusted(remote_host)) { madara_logger_log(context.get_logger(), logger::LOG_DETAILED, "%s: remote id (%s) is trusted\n", print_prefix, remote_host); } else { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " dropping message from untrusted peer (%s\n", print_prefix, remote_host); // delete the header and continue to the svc loop return -3; } std::string originator(header->originator); if(settings.is_trusted(originator)) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " originator (%s) is trusted\n", print_prefix, originator.c_str()); } else { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " dropping message from untrusted originator (%s)\n", print_prefix, originator.c_str()); return -4; } // reject the message if it is from a different domain if(!settings.is_reading_domain(header->domain)) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " remote id (%s) has an untrusted domain (%s). Dropping message.\n", print_prefix, remote_host, header->domain); // delete the header and continue to the svc loop return -5; } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " remote id (%s) message is in our domain\n", print_prefix, remote_host); } } // fragments are special cases if(is_fragment) { // grab the fragment header FragmentMessageHeader* frag_header = dynamic_cast<FragmentMessageHeader*>(header); // total size of the fragmented packet uint64_t total_size = 0; madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Processing fragment %" PRIu32 " of %s:%" PRIu64 ".\n", print_prefix, frag_header->update_number, frag_header->originator, frag_header->clock); // add the fragment and attempt to defrag the message char* message = transport::add_fragment(frag_header->originator, frag_header->clock, frag_header->update_number, buffer, settings.fragment_queue_length, settings.fragment_map, total_size, true); // if we have no return message, we may have previously defragged it if(!message || total_size == 0) { return 0; } // copy the intermediate buffer to the user-allocated buffer char* buffer_override = (char*)buffer; memcpy(buffer_override, message, total_size); // cleanup the old buffer. We should really have a zero-copy delete[] message; int decode_result = (uint32_t)settings.filter_decode( (char*)buffer, total_size, settings.queue_length); if (decode_result <= 0) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " ERROR: Unable to decode fragments. Likely incorrect filters.\n", print_prefix); return 0; } else { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Message has been pieced together from fragments. Processing...\n", print_prefix); /** * if we defragged the message, then we need to process the message. * In order to do that, we need to overwrite buffer with message * so it can be processed normally. **/ buffer_remaining = (int64_t)decode_result; if(buffer_remaining <= settings.queue_length && buffer_remaining > (int64_t)MessageHeader::static_encoded_size ()) { delete header; // check the buffer for a reduced message header if(ReducedMessageHeader::reduced_message_header_test(buffer)) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " processing reduced KaRL message from %s\n", print_prefix, remote_host); header = new ReducedMessageHeader(); is_reduced = true; update = header->read(buffer, buffer_remaining); } else if(MessageHeader::message_header_test(buffer)) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " processing KaRL message from %s\n", print_prefix, remote_host); header = new MessageHeader(); update = header->read(buffer, buffer_remaining); } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " ERROR: defrag resulted in unknown message header.\n", print_prefix); return 0; } madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " past fragment header create.\n", print_prefix); } // end if buffer remaining } // end if decode didn't break } // end if is fragment int actual_updates = 0; uint64_t current_time = utility::get_time(); double deadline = settings.get_deadline(); madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " create transport_context with: " "originator(%s), domain(%s), remote(%s), time(%" PRIu64 ").\n", print_prefix, header->originator, header->domain, remote_host, header->timestamp); TransportContext transport_context(TransportContext::RECEIVING_OPERATION, receive_monitor.get_bytes_per_second(), send_monitor.get_bytes_per_second(), header->timestamp, current_time, header->domain, header->originator, remote_host); madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " past transport_context create.\n", print_prefix); uint64_t latency(0); if(deadline >= 1.0) { if(header->timestamp < current_time) { latency = current_time - header->timestamp; if(latency > deadline) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " deadline violation (latency is %" PRIu64 ", deadline is %f).\n", print_prefix, latency, deadline); return -6; } } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Cannot compute message latency." " Message header timestamp is in the future." " message.timestamp = %" PRIu64 ", cur_timestamp = %" PRIu64 ".\n", print_prefix, header->timestamp, current_time); } } madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " iterating over the %" PRIu32 " updates\n", print_prefix, header->updates); // temporary record for reading from the updates buffer knowledge::KnowledgeRecord record; record.quality = header->quality; record.clock = header->clock; std::string key; bool dropped = false; if(send_monitor.is_bandwidth_violated(settings.get_send_bandwidth_limit())) { dropped = true; madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Send monitor has detected violation of bandwidth limit." " Dropping packet from rebroadcast list\n", print_prefix); } else if(receive_monitor.is_bandwidth_violated( settings.get_total_bandwidth_limit())) { dropped = true; madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Receive monitor has detected violation of bandwidth limit." " Dropping packet from rebroadcast list...\n", print_prefix); } else if(settings.get_participant_ttl() < header->ttl) { dropped = true; madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Transport participant TTL is lower than header ttl." " Dropping packet from rebroadcast list...\n", print_prefix); } madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Applying %" PRIu32 " updates\n", print_prefix, header->updates); const auto add_record = [&](const std::string& key, knowledge::KnowledgeRecord rec) { auto& entry = updates[key]; if(entry.exists()) { using std::swap; swap(rec, entry); past_updates[key].emplace_back(std::move(rec)); } else { entry = std::move(rec); } }; // iterate over the updates for(uint32_t i = 0; i < header->updates; ++i) { // read converts everything into host format from the update stream update = record.read(update, key, buffer_remaining); if(buffer_remaining < 0) { madara_logger_log(context.get_logger(), logger::LOG_EMERGENCY, "%s:" " unable to process message. Buffer remaining is negative." " Server is likely being targeted by custom KaRL tools.\n", print_prefix); // we do not delete the header as this will be cleaned up later break; } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Applying receive filter to %s (clk %i, qual %i) = %s\n", print_prefix, key.c_str(), record.clock, record.quality, record.to_string().c_str()); record = settings.filter_receive(record, key, transport_context); if(record.exists()) { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Filter results for %s were %s\n", print_prefix, key.c_str(), record.to_string().c_str()); add_record(key, record); } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Filter resulted in dropping %s\n", print_prefix, key.c_str()); } } } const knowledge::KnowledgeMap& additionals = transport_context.get_records(); if(additionals.size() > 0) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " %lld additional records being handled after receive.\n", print_prefix, (long long)additionals.size()); for(knowledge::KnowledgeMap::const_iterator i = additionals.begin(); i != additionals.end(); ++i) { add_record(i->first, i->second); } transport_context.clear_records(); if(header->ttl < 2) header->ttl = 2; // modify originator to indicate we are the originator of modifications strncpy(header->originator, id.c_str(), sizeof(header->originator) - 1); } // apply aggregate receive filters if(settings.get_number_of_receive_aggregate_filters() > 0 && (updates.size() > 0 || header->type == transport::REGISTER)) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Applying aggregate receive filters.\n", print_prefix); settings.filter_receive(updates, transport_context); } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " No aggregate receive filters were applied...\n", print_prefix); } madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Locking the context to apply updates.\n", print_prefix); { knowledge::ContextGuard guard(context); madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Applying updates to context.\n", print_prefix); uint64_t now = utility::get_time(); // apply updates from the update list for(knowledge::KnowledgeMap::iterator i = updates.begin(); i != updates.end(); ++i) { const auto apply = [&](knowledge::KnowledgeRecord& record) { int result = 0; record.set_toi(now); result = record.apply( context, i->first, header->quality, header->clock, false); ++actual_updates; if(result != 1) { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " update %s=%s was rejected\n", print_prefix, key.c_str(), record.to_string().c_str()); } else { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " update %s=%s was accepted\n", print_prefix, key.c_str(), record.to_string().c_str()); } }; auto iter = past_updates.find(i->first); if(iter != past_updates.end()) { for(auto& cur : iter->second) { if(cur.exists()) { apply(cur); } } } apply(i->second); } } context.set_changed(); if(!dropped) { transport_context.set_operation(TransportContext::REBROADCASTING_OPERATION); madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Applying rebroadcast filters to receive results.\n", print_prefix); // create a list of rebroadcast records from the updates for(knowledge::KnowledgeMap::iterator i = updates.begin(); i != updates.end(); ++i) { i->second = settings.filter_rebroadcast(i->second, i->first, transport_context); if(i->second.exists()) { if(i->second.to_string() != "") { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Filter results for key %s were %s\n", print_prefix, i->first.c_str(), i->second.to_string().c_str()); } rebroadcast_records[i->first] = i->second; } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Filter resulted in dropping %s\n", print_prefix, i->first.c_str()); } } const knowledge::KnowledgeMap& additionals = transport_context.get_records(); for(knowledge::KnowledgeMap::const_iterator i = additionals.begin(); i != additionals.end(); ++i) { rebroadcast_records[i->first] = i->second; } madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Applying aggregate rebroadcast filters to %d records.\n", print_prefix, rebroadcast_records.size()); // apply aggregate filters to the rebroadcast records if(settings.get_number_of_rebroadcast_aggregate_filters() > 0 && rebroadcast_records.size() > 0) { settings.filter_rebroadcast(rebroadcast_records, transport_context); } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " No aggregate rebroadcast filters were applied...\n", print_prefix); } madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Returning to caller with %d rebroadcast records.\n", print_prefix, rebroadcast_records.size()); } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " Rebroadcast packet was dropped...\n", print_prefix); } // before we send to others, we first execute rules if(settings.on_data_received_logic.length() != 0) { #ifndef _MADARA_NO_KARL_ madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " evaluating rules in %s\n", print_prefix, settings.on_data_received_logic.c_str()); context.evaluate(on_data_received); #endif // _MADARA_NO_KARL_ } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " no permanent rules were set\n", print_prefix); } return actual_updates; } int prep_rebroadcast(knowledge::ThreadSafeContext& context, char* buffer, int64_t& buffer_remaining, const QoSTransportSettings& settings, const char* print_prefix, MessageHeader* header, const knowledge::KnowledgeMap& records, PacketScheduler& packet_scheduler) { int result = 0; if(header->ttl > 0 && records.size() > 0 && packet_scheduler.add()) { // keep track of the message_size portion of buffer uint64_t* message_size = (uint64_t*)buffer; int max_buffer_size = (int)buffer_remaining; // the number of updates will be the size of the records map header->updates = uint32_t(records.size()); // set the update to the end of the header char* update = header->write(buffer, buffer_remaining); for(knowledge::KnowledgeMap::const_iterator i = records.begin(); i != records.end(); ++i) { update = i->second.write(update, i->first, buffer_remaining); } if(buffer_remaining > 0) { int size = (int)(settings.queue_length - buffer_remaining); *message_size = utility::endian_swap((uint64_t)size); madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " %" PRIu64 " bytes prepped for rebroadcast packet\n", print_prefix, size); result = size; madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " calling encode filters\n", print_prefix); settings.filter_encode(buffer, result, max_buffer_size); } else { madara_logger_log(context.get_logger(), logger::LOG_MAJOR, "%s:" " Not enough buffer for rebroadcasting packet\n", print_prefix); result = -2; } } else { madara_logger_log(context.get_logger(), logger::LOG_MINOR, "%s:" " No rebroadcast necessary.\n", print_prefix); result = -1; } packet_scheduler.print_status(logger::LOG_DETAILED, print_prefix); return result; } long Base::prep_send(const knowledge::KnowledgeMap& orig_updates, const char* print_prefix) { // check to see if we are shutting down long ret = this->check_transport(); if(-1 == ret) { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s: transport has been told to shutdown", print_prefix); return ret; } else if(-2 == ret) { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s: transport is not valid", print_prefix); return ret; } // get the maximum quality from the updates uint32_t quality = knowledge::max_quality(orig_updates); uint64_t latest_toi = 0; bool reduced = false; knowledge::KnowledgeMap filtered_updates; madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Applying filters to %zu updates before sending...\n", print_prefix, orig_updates.size()); TransportContext transport_context(TransportContext::SENDING_OPERATION, receive_monitor_.get_bytes_per_second(), send_monitor_.get_bytes_per_second(), (uint64_t)utility::get_time(), (uint64_t)utility::get_time(), settings_.write_domain, id_); bool dropped = false; if(send_monitor_.is_bandwidth_violated(settings_.get_send_bandwidth_limit())) { dropped = true; madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Send monitor has detected violation of bandwidth limit." " Dropping packet...\n", print_prefix); } else if(receive_monitor_.is_bandwidth_violated( settings_.get_total_bandwidth_limit())) { dropped = true; madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Receive monitor has detected violation of bandwidth limit." " Dropping packet...\n", print_prefix); } if(!dropped && packet_scheduler_.add()) { if(settings_.get_number_of_send_filtered_types() > 0) { /** * filter the updates according to the filters specified by * the user in QoSTransportSettings (if applicable) **/ for(auto e : orig_updates) { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Calling filter chain of %s.\n", print_prefix, e.first.c_str()); const auto record = e.second; if(record.toi() > latest_toi) { latest_toi = record.toi(); } // filter the record according to the send filter chain knowledge::KnowledgeRecord result = settings_.filter_send(record, e.first, transport_context); madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Filter returned for %s.\n", print_prefix, e.first.c_str()); // allow updates of 0. Exists probably isn't right here. if(result.exists() || !record.exists()) { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Adding record to update list.\n", print_prefix); filtered_updates.emplace(std::make_pair(e.first, result)); } else { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Filter removed record from update list.\n", print_prefix); } } madara_logger_log(context_.get_logger(), logger::LOG_DETAILED, "%s:" " Through individual record filters. Proceeding to add update " "list.\n", print_prefix); const knowledge::KnowledgeMap& additionals = transport_context.get_records(); for(knowledge::KnowledgeMap::const_iterator i = additionals.begin(); i != additionals.end(); ++i) { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Filter added a record %s to the update list.\n", print_prefix, i->first.c_str()); filtered_updates.emplace(std::make_pair(i->first, i->second)); } } else { for(auto e : orig_updates) { const auto record = e.second; if(record.toi() > latest_toi) { latest_toi = record.toi(); } madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Adding record %s to update list.\n", print_prefix, e.first.c_str()); filtered_updates.emplace(std::make_pair(e.first, record)); // Youtube tutorial is currently throwing this. Need to check GAMS // else // { // std::stringstream message; // message << print_prefix; // message << ": record " << e.first << " produced a null record "; // message << "from get_record_unsafe ()\n"; // madara_logger_log( // context_.get_logger(), logger::LOG_ERROR, message.str().c_str()); // throw exceptions::MemoryException(message.str()); // } } } } else { madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " Packet scheduler has dropped packet...\n", print_prefix); return 0; } madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Applying %d aggregate update send filters to %d updates...\n", print_prefix, (int)settings_.get_number_of_send_aggregate_filters(), (int)filtered_updates.size()); // apply the aggregate filters if(settings_.get_number_of_send_aggregate_filters() > 0 && filtered_updates.size() > 0) { settings_.filter_send(filtered_updates, transport_context); } else { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " No aggregate send filters were applied...\n", print_prefix); } packet_scheduler_.print_status(logger::LOG_DETAILED, print_prefix); madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Finished applying filters before sending...\n", print_prefix); if(filtered_updates.size() == 0) { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Filters removed all data. Nothing to send.\n", print_prefix); return 0; } // allocate a buffer to send char* buffer = buffer_.get_ptr(); int64_t buffer_remaining = settings_.queue_length; if(buffer == 0) { madara_logger_log(context_.get_logger(), logger::LOG_EMERGENCY, "%s:" " Unable to allocate buffer of size %" PRIu32 ". Exiting thread.\n", print_prefix, settings_.queue_length); return -3; } // set the header to the beginning of the buffer MessageHeader* header = 0; if(settings_.send_reduced_message_header) { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Preparing message with reduced message header.\n", print_prefix); header = new ReducedMessageHeader(); reduced = true; } else { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " Preparing message with normal message header.\n", print_prefix); header = new MessageHeader(); } // get the clock header->clock = context_.get_clock(); if(!reduced) { // copy the domain from settings strncpy(header->domain, this->settings_.write_domain.c_str(), sizeof(header->domain) - 1); // get the quality of the key header->quality = quality; // copy the message originator (our id) strncpy(header->originator, id_.c_str(), sizeof(header->originator) - 1); // send data is generally an assign type. However, MessageHeader is // flexible enough to support both, and this will simply our read thread // handling header->type = MULTIASSIGN; } // set the time-to-live header->ttl = settings_.get_rebroadcast_ttl(); header->updates = uint32_t(filtered_updates.size()); // compute size of this header header->size = header->encoded_size(); // keep track of the maximum buffer size for encoding int max_buffer_size = (int)buffer_remaining; // set the update to the end of the header char* update = header->write(buffer, buffer_remaining); uint64_t* message_size = (uint64_t*)buffer; uint32_t* message_updates = (uint32_t*)(buffer + 116); // Message header format // [size|id|domain|originator|type|updates|quality|clock|list of updates] /** * size = buffer[0] (unsigned 64 bit) * transport id = buffer[8] (8 byte) * domain = buffer[16] (32 byte domain name) * originator = buffer[48] (64 byte originator host:port) * type = buffer[112] (unsigned 32 bit type of message--usually MULTIASSIGN) * updates = buffer[116] (unsigned 32 bit number of updates) * quality = buffer[120] (unsigned 32 bit quality of message) * clock = buffer[124] (unsigned 64 bit clock for this message) * ttl = buffer[132] (the new knowledge starts here) * knowledge = buffer[133] (the new knowledge starts here) **/ // zero out the memory // memset(buffer, 0, MAX_PACKET_SIZE); // Message update format // [key|value] int j = 0; uint32_t actual_updates = 0; for(knowledge::KnowledgeMap::const_iterator i = filtered_updates.begin(); i != filtered_updates.end(); ++i) { const auto& key = i->first; const auto& rec = i->second; const auto do_write = [&](const knowledge::KnowledgeRecord& rec) { if(!rec.exists()) { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " update[%d] => value is empty\n", print_prefix, j, key.c_str()); return; } update = rec.write(update, key, buffer_remaining); if(buffer_remaining > 0) { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " update[%d] => encoding %s of type %" PRId32 " and size %" PRIu32 " @%" PRIu64 "\n", print_prefix, j, key.c_str(), rec.type(), rec.size(), rec.toi()); ++actual_updates; ++j; } else { madara_logger_log(context_.get_logger(), logger::LOG_EMERGENCY, "%s:" " unable to encode update[%d] => %s of type %" PRId32 " and size %" PRIu32 "\n", print_prefix, j, key.c_str(), rec.type(), rec.size()); } }; if(!settings_.send_history || !rec.has_history()) { do_write(rec); } else { auto buf = rec.share_circular_buffer(); auto end = buf->end(); auto cur = buf->begin(); if(last_toi_sent_ > 0) { cur = std::upper_bound(cur, end, last_toi_sent_, [](uint64_t lhs, const knowledge::KnowledgeRecord& rhs) { return lhs < rhs.toi(); }); } for(; cur != end; ++cur) { do_write(*cur); } } } long size(0); if(buffer_remaining > 0) { size = (long)(settings_.queue_length - buffer_remaining); header->size = size; *message_size = utility::endian_swap((uint64_t)size); header->updates = actual_updates; *message_updates = utility::endian_swap(actual_updates); // before we send to others, we first execute rules if(settings_.on_data_received_logic.length() != 0) { #ifndef _MADARA_NO_KARL_ madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " evaluating rules in %s\n", print_prefix, settings_.on_data_received_logic.c_str()); on_data_received_.evaluate(); madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " rules have been successfully evaluated\n", print_prefix); #endif // _MADARA_NO_KARL_ } else { madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " no permanent rules were set\n", print_prefix); } } madara_logger_log(context_.get_logger(), logger::LOG_MAJOR, "%s:" " calling encode filters\n", print_prefix); // buffer is ready encoding size = (long)settings_.filter_encode( buffer_.get_ptr(), (int)size, max_buffer_size); madara_logger_log(context_.get_logger(), logger::LOG_MINOR, "%s:" " header info before encode: %s\n", print_prefix, header->to_string().c_str()); delete header; last_toi_sent_ = latest_toi; return size; } } }
29.371606
82
0.624459
jredmondson
952dc2242669efa197fd26b56f945f40a3137c0d
2,850
hpp
C++
include/LIEF/ART/enums.hpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
include/LIEF/ART/enums.hpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
include/LIEF/ART/enums.hpp
ahawad/LIEF
88931ea405d9824faa5749731427533e0c27173e
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017 - 2022 R. Thomas * Copyright 2017 - 2022 Quarkslab * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LIEF_ART_ENUMS_H_ #define LIEF_ART_ENUMS_H_ namespace LIEF { namespace ART { enum STORAGE_MODES { STORAGE_UNCOMPRESSED = 0, STORAGE_LZ4 = 1, STORAGE_LZ4HC = 2, }; namespace ART_17 { enum IMAGE_METHODS { RESOLUTION_METHOD = 0, IMT_CONFLICT_METHOD = 1, IMT_UNIMPLEMENTED_METHOD = 2, CALLEE_SAVE_METHOD = 3, REFS_ONLY_SAVE_METHOD = 4, REFS_AND_ARGS_SAVE_METHOD = 5, }; enum IMAGE_SECTIONS { SECTION_OBJECTS = 0, SECTION_ART_FIELDS = 1, SECTION_ART_METHODS = 2, SECTION_INTERNED_STRINGS = 3, SECTION_IMAGE_BITMAP = 4, }; enum IMAGE_ROOTS { DEX_CACHES = 0, CLASS_ROOTS = 1, }; } // Namespace ART_17 namespace ART_29 { using ART_17::IMAGE_METHODS; using ART_17::IMAGE_ROOTS; enum IMAGE_SECTIONS { SECTION_OBJECTS = 0, SECTION_ART_FIELDS = 1, SECTION_ART_METHODS = 2, SECTION_RUNTIME_METHODS = 3, // New in ART 29 SECTION_IMT_CONFLICT_TABLES = 4, // New in ART 29 SECTION_DEX_CACHE_ARRAYS = 5, // New in ART 29 SECTION_INTERNED_STRINGS = 6, SECTION_CLASS_TABLE = 7, // New in ART 29 SECTION_IMAGE_BITMAP = 8, }; } // Namespace ART_29 namespace ART_30 { using ART_29::IMAGE_METHODS; using ART_29::IMAGE_ROOTS; enum IMAGE_SECTIONS { SECTION_OBJECTS = 0, SECTION_ART_FIELDS = 1, SECTION_ART_METHODS = 2, SECTION_RUNTIME_METHODS = 3, SECTION_IM_TABLES = 4, // New in ART 30 SECTION_IMT_CONFLICT_TABLES = 5, SECTION_DEX_CACHE_ARRAYS = 6, SECTION_INTERNED_STRINGS = 7, SECTION_CLASS_TABLE = 8, SECTION_IMAGE_BITMAP = 9, }; } // Namespace ART_30 namespace ART_44 { using ART_30::IMAGE_SECTIONS; enum IMAGE_METHODS { RESOLUTION_METHOD = 0, IMT_CONFLICT_METHOD = 1, IMT_UNIMPLEMENTED_METHOD = 2, SAVE_ALL_CALLEE_SAVES_METHOD = 3, // New in ART 44 SAVE_REFS_ONLY_METHOD = 4, // New in ART 44 SAVE_REFS_AND_ARGS_METHOD = 5, // New in ART 44 SAVE_EVERYTHING_METHOD = 6, // New in ART 44 }; enum IMAGE_ROOTS { DEX_CACHES = 0, CLASS_ROOTS = 1, CLASS_LOADER = 2, // New in ART 44 }; } // Namespace ART_44 namespace ART_46 { using ART_30::IMAGE_METHODS; using ART_30::IMAGE_ROOTS; using ART_30::IMAGE_SECTIONS; } // Namespace ART_46 } // namespace ART } // namespace LIEF #endif
22.619048
75
0.720702
ahawad
9530cad32c3d43378b6b6ea63c9c34fa820f333e
4,087
cpp
C++
Algorithms/Data Structure/Segment Tree/Segment Tree (all-in-one version).cpp
purhan/mindsport
d14fe8917c64b475589f494d98b74e99c9e064e5
[ "MIT" ]
null
null
null
Algorithms/Data Structure/Segment Tree/Segment Tree (all-in-one version).cpp
purhan/mindsport
d14fe8917c64b475589f494d98b74e99c9e064e5
[ "MIT" ]
null
null
null
Algorithms/Data Structure/Segment Tree/Segment Tree (all-in-one version).cpp
purhan/mindsport
d14fe8917c64b475589f494d98b74e99c9e064e5
[ "MIT" ]
1
2021-07-19T08:39:38.000Z
2021-07-19T08:39:38.000Z
// Segment Tree (all-in-one version) // It supports range update, range adjust, range min query, range max query, range sum query with lazy propagation // Reference: https://noiref.codecla.ws/ds/ #include <bits/stdc++.h> using namespace std; const int INF = 1 << 30; const int MAX_N = 100000 + 5; const int MAX_L = 20; // ~ Log N const long long MOD = 1e9 + 7; typedef long long ll; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector<ii> vii; typedef vector<vi> vvi; #define LSOne(S) (S & (-S)) #define isBitSet(S, i) ((S >> i) & 1) int N, Q, arr[MAX_N]; struct node { int s, e; ll mn, mx, sum; // min, max, sum bool lset; ll add_val, set_val; node *l, *r; node (int _s, int _e, int A[] = NULL): s(_s), e(_e), mn(0), mx(0), sum(0), lset(0), add_val(0), set_val(0), l(NULL), r(NULL) { if (A == NULL) return; if (s == e) mn = mx = sum = A[s]; else { l = new node(s, (s+e)>>1, A), r = new node((s+e+2)>>1, e, A); combine(); } } void create_children() { if (s == e) return; if (l != NULL) return; int m = (s+e)>>1; l = new node(s, m); r = new node(m+1, e); } void self_set(ll v) { lset = 1; mn = mx = set_val = v; sum = v * (e-s+1); add_val = 0; } void self_add(ll v) { if (lset) { self_set(v + set_val); return; } mn += v, mx += v, add_val += v; sum += v*(e-s+1); } void lazy_propagate() { if (s == e) return; if (lset) { l->self_set(set_val), r->self_set(set_val); lset = set_val = 0; } if (add_val != 0) { l->self_add(add_val), r->self_add(add_val); add_val = 0; } } void combine() { if (l == NULL) return; sum = l->sum + r->sum; mn = min(l->mn, r->mn); mx = max(l->mx, r->mx); } void add(int x, int y, ll v) { if (s == x && e == y) { self_add(v); return; } int m = (s+e)>>1; create_children(); lazy_propagate(); if (x <= m) l->add(x, min(y, m), v); if (y > m) r->add(max(x, m+1), y, v); combine(); } void set(int x, int y, ll v) { if (s == x && e == y) { self_set(v); return; } int m = (s+e)>>1; create_children(); lazy_propagate(); if (x <= m) l->set(x, min(y, m), v); if (y > m) r->set(max(x, m+1), y, v); combine(); } ll range_sum(int x, int y) { if (s == x && e == y) return sum; if (l == NULL || lset) return (sum / (e-s+1)) * (y-x+1); int m = (s+e)>>1; lazy_propagate(); if (y <= m) return l->range_sum(x, y); if (x > m) return r->range_sum(x, y); return l->range_sum(x, m) + r->range_sum(m+1, y); } ll range_min(int x, int y) { if (s == x && e == y) return mn; if (l == NULL || lset) return mn; int m = (s+e)>>1; lazy_propagate(); if (y <= m) return l->range_min(x, y); if (x > m) return r->range_min(x, y); return min(l->range_min(x, m), r->range_min(m+1, y)); } ll range_max(int x, int y) { if (s == x && e == y) return mx; if (l == NULL || lset) return mx; int m = (s+e)>>1; lazy_propagate(); if (y <= m) return l->range_max(x, y); if (x > m) return r->range_max(x, y); return max(l->range_max(x, m), r->range_max(m+1, y)); } ~node() { if (l != NULL) delete l; if (r != NULL) delete r; } } *root; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); cin >> N >> Q; for(int i = 0; i < N; i++) cin >> arr[i]; root = new node(0, N - 1, arr); /* root->add(0, 5000, 3); root->add(3000, 9000, -2); root->set(7000, 10000, 5); root->range_max(0, 10000); root->range_min(0, 10000); root->range_sum(0, 10000); */ }
28.78169
130
0.465867
purhan
953140c982d145318fcd52bb87a782273f158fcf
4,569
cpp
C++
X-Engine/src/Platforms/OperatingSystems/Windows10/Win10Window.cpp
JohnMichaelProductions/X-Engine
218ffcf64bfe5d5aed51b483c6f6986831ceeec4
[ "Apache-2.0" ]
4
2020-02-17T07:08:26.000Z
2020-08-07T21:35:12.000Z
X-Engine/src/Platforms/OperatingSystems/Windows10/Win10Window.cpp
JohnMichaelProductions/X-Engine
218ffcf64bfe5d5aed51b483c6f6986831ceeec4
[ "Apache-2.0" ]
25
2020-03-08T05:35:25.000Z
2020-07-08T01:59:52.000Z
X-Engine/src/Platforms/OperatingSystems/Windows10/Win10Window.cpp
JohnMichaelProductions/X-Engine
218ffcf64bfe5d5aed51b483c6f6986831ceeec4
[ "Apache-2.0" ]
1
2020-10-15T12:39:29.000Z
2020-10-15T12:39:29.000Z
// Source file for Win10Window class functions, configured for Windows 10, also derived from window class #include "Xpch.h" #include <wtypes.h> #include "XEngine/Core/Input.h" #include "XEngine/EventSystem/KeyEvent.h" #include "XEngine/EventSystem/MouseEvent.h" #include "XEngine/EventSystem/ApplicationEvent.h" #include "XEngine/Renderer/RendererAPI/Renderer.h" #include "Platforms/RenderingAPIs/OpenGL/OpenGlContext.h" #include "Platforms/OperatingSystems/Windows10/Win10Window.h" namespace XEngine { static uint8_t GLFWWindowCount = 0; static void GLFWErrorCallback(int error, const char* description) { XCORE_ERROR("GLFW Error ({0}): {1}", error, description); }; Win10Window::Win10Window(const WindowProps& props) { XPROFILE_FUNCTION(); XCORE_INFO("Using Windows 10 Window Class"); Init(props); } Win10Window::~Win10Window() { XPROFILE_FUNCTION(); Shutdown(); } void Win10Window::Init(const WindowProps& props) { XPROFILE_FUNCTION(); SetConsoleTitle(TEXT("X-Engine Console")); m_WindowData.Title = props.Title; m_WindowData.Width = props.Width; m_WindowData.Height = props.Height; if (GLFWWindowCount == 0) { int success = glfwInit(); XCORE_ASSERT(success, "Could not initialize GLFW"); glfwSetErrorCallback(GLFWErrorCallback); XCORE_INFO("GLFW intialized"); } { XPROFILE_SCOPE("glfwCreateWindow"); #if defined(XDEBUG) if (Renderer::GetAPI() == RendererAPI::API::OpenGL) glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); #endif m_Window = glfwCreateWindow((int)props.Width, (int)props.Height, m_WindowData.Title.c_str(), nullptr, nullptr); ++GLFWWindowCount; } m_WindowContext = GraphicsContext::Create(m_Window); m_WindowContext->Init(); glfwSetWindowUserPointer(m_Window, &m_WindowData); SetVSync(false); glfwSetWindowSizeCallback(m_Window, [](GLFWwindow* window, int width, int height) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); data.Width = width; data.Height = height; WindowResizeEvent event(width, height); data.EventCallback(event); }); glfwSetWindowCloseCallback(m_Window, [](GLFWwindow* window) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); WindowCloseEvent event; data.EventCallback(event); }); glfwSetKeyCallback(m_Window, [](GLFWwindow* window, int key, int scancode, int action, int mods) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); switch (action) { case GLFW_PRESS: { KeyPressedEvent event(key, 0); data.EventCallback(event); break; } case GLFW_RELEASE: { KeyReleasedEvent event(key); data.EventCallback(event); break; } case GLFW_REPEAT: { KeyPressedEvent event(key, 1); data.EventCallback(event); break; } } }); glfwSetCharCallback(m_Window, [](GLFWwindow* window, uint32_t keycode) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); KeyTypedEvent event(keycode); data.EventCallback(event); }); glfwSetMouseButtonCallback(m_Window, [](GLFWwindow* window, int button, int action, int mods) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); switch (action) { case GLFW_PRESS: { MouseButtonPressedEvent event(button); data.EventCallback(event); break; } case GLFW_RELEASE: { MouseButtonReleasedEvent event(button); data.EventCallback(event); break; } } }); glfwSetScrollCallback(m_Window, [](GLFWwindow* window, double xOffset, double yOffset) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); MouseScrolledEvent event((float)xOffset, (float)yOffset); data.EventCallback(event); }); glfwSetCursorPosCallback(m_Window, [](GLFWwindow* window, double xPos, double yPos) { WindowData& data = *(WindowData*)glfwGetWindowUserPointer(window); MouseMovedEvent event((float)xPos, (float)yPos); data.EventCallback(event); }); } void Win10Window::Shutdown() { XPROFILE_FUNCTION(); glfwDestroyWindow(m_Window); --GLFWWindowCount; if (GLFWWindowCount == 0) { XCORE_INFO("Terminating GLFW"); glfwTerminate(); } } void Win10Window::OnUpdate() { XPROFILE_FUNCTION(); glfwPollEvents(); m_WindowContext->SwapBuffers(); } void Win10Window::SetVSync(bool enabled) { XPROFILE_FUNCTION(); if (enabled) glfwSwapInterval(1); else glfwSwapInterval(0); m_WindowData.VSync = enabled; } bool Win10Window::IsVSync() const { return m_WindowData.VSync; } }
28.735849
115
0.712629
JohnMichaelProductions