hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ee825be7ed59f4d159cab9152ee4e6c01e053b1c
| 1,899
|
cpp
|
C++
|
simulatorCore/src/glBlock.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 4
|
2016-08-18T03:19:49.000Z
|
2020-09-20T03:29:26.000Z
|
simulatorCore/src/glBlock.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 2
|
2016-08-18T03:25:07.000Z
|
2016-08-29T17:51:50.000Z
|
simulatorCore/src/glBlock.cpp
|
claytronics/visiblesim
|
2762a88a23e50516d0f166dd9629f1ac7290fded
|
[
"Apache-2.0"
] | 3
|
2015-05-14T07:29:55.000Z
|
2021-07-18T23:45:36.000Z
|
#include "glBlock.h"
#include <sstream>
#include "objLoader.h"
GlBlock::GlBlock(bID id):blockId(id) {
position[0] = 0.0;
position[1] = 0.0;
position[2] = 0.0;
color[0] = 0.5;
color[1] = 0.5;
color[2] = 0.5;
color[3] = 1.0;
isHighlighted = false;
}
GlBlock::GlBlock(bID id,const Vector3D &pos, const Vector3D &col) : blockId(id) {
position[0] = pos[0];
position[1] = pos[1];
position[2] = pos[2];
color[0] = col[0];
color[1] = col[1];
color[2] = col[2];
color[3] = 1.0;
isHighlighted = false;
}
GlBlock::~GlBlock() {
}
void GlBlock::setPosition(const Vector3D &pos) {
position[0] = GLfloat(pos[0]);
position[1] = GLfloat(pos[1]);
position[2] = GLfloat(pos[2]);
}
void GlBlock::setColor(const Vector3D &col) {
color[0] = GLfloat(col[0]);
color[1] = GLfloat(col[1]);
color[2] = GLfloat(col[2]);
color[3] = 1.0;
}
void GlBlock::setColor(const Color &col) {
color[0] = col[0];
color[1] = col[1];
color[2] = col[2];
color[3] = 1.0;
}
void GlBlock::setVisible(bool visible) {
color[3] = visible;
}
void GlBlock::toggleHighlight() {
isHighlighted=!isHighlighted;
}
string GlBlock::getInfo() {
ostringstream out;
out << blockId << "\n";
out << fixed;
out.precision(1);
out << "Pos=(" << position[0] << "," << position[1] << "," << position[2] << ") ";
out << "Col=(" << (int)(color[0] * 255) << "," << (int)(color[1] * 255) << "," << (int)(color[2] * 255) << ")";
return out.str();
}
string GlBlock::getPopupInfo() {
ostringstream out;
out << blockId << "\n";
return out.str();
}
void GlBlock::glDrawId(ObjLoader::ObjLoader *ptrObj,int &n) {
glPushMatrix();
glTranslatef(position[0],position[1],position[2]);
ptrObj->glDrawId(n);
glPopMatrix();
}
void GlBlock::glDrawIdByMaterial(ObjLoader::ObjLoader *ptrObj,int &n) {
glPushMatrix();
glTranslatef(position[0],position[1],position[2]);
ptrObj->glDrawIdByMaterial(n);
glPopMatrix();
}
| 20.419355
| 112
| 0.617167
|
claytronics
|
ee88d8839f6bf5d8ce143fdc88e75a258efb6a74
| 2,648
|
cpp
|
C++
|
CubeEngine/EngineSrc/Texture/TextureMgr.cpp
|
tangziwen/Cube-Engine
|
c79b878dcc7e2e382f4463ca63519627d6220afd
|
[
"MIT"
] | 360
|
2015-01-26T08:15:01.000Z
|
2021-07-11T16:30:58.000Z
|
CubeEngine/EngineSrc/Texture/TextureMgr.cpp
|
multithread3/Cube-Engine
|
aa76db88fdace41b09cbfc51e5959a9686cca3f3
|
[
"MIT"
] | 6
|
2015-03-09T09:15:07.000Z
|
2020-07-06T01:34:00.000Z
|
CubeEngine/EngineSrc/Texture/TextureMgr.cpp
|
multithread3/Cube-Engine
|
aa76db88fdace41b09cbfc51e5959a9686cca3f3
|
[
"MIT"
] | 41
|
2015-03-10T03:17:46.000Z
|
2021-07-13T06:26:26.000Z
|
#include "TextureMgr.h"
#include <utility>
#include "Utility/log/Log.h"
namespace tzw {
Texture *TextureMgr::getByPath(std::string filePath, bool isNeedMipMap)
{
if (filePath.empty()) return nullptr;
auto result = m_texturePool.find(filePath);
if(result!=m_texturePool.end())
{
return result->second;
}else
{
Texture * tex = new Texture(filePath);
if(isNeedMipMap)
{
tex->genMipMap();
}
m_texturePool.insert(std::make_pair(filePath,tex));
return tex;
}
}
Texture* TextureMgr::getByPathSimple(std::string filePath)
{
return getByPath(filePath, false);
}
Texture* TextureMgr::getByPathAsync(std::string filePath, std::function<void (Texture *)> finishedCallBack, bool isNeedMiMap)
{
if (filePath.empty())
{
if(finishedCallBack)
{
finishedCallBack(nullptr);
}
return nullptr;
}
auto result = m_texturePool.find(filePath);
if(result!=m_texturePool.end())
{
if(finishedCallBack)
{
finishedCallBack(result->second);
}
return result->second;
}else
{
return loadAsync(filePath, finishedCallBack, isNeedMiMap);
}
}
Texture* TextureMgr::loadAsync(std::string filePath, std::function<void(Texture*)> finishedCallBack, bool isNeedMiMap)
{
Texture * tex = new Texture();
auto onFinished = [this, tex, isNeedMiMap, filePath, finishedCallBack](Texture *)
{
if(isNeedMiMap)
{
tex->genMipMap();
}
if(finishedCallBack)
{
finishedCallBack(tex);
}
};
m_texturePool.insert(std::make_pair(filePath,tex));
tex->loadAsync(filePath, onFinished);
return tex;
}
Texture *TextureMgr::getByPath(std::string PosX, std::string NegX, std::string PosY,
std::string NegY, std::string PosZ, std::string NegZ)
{
auto result = m_texturePool.find(PosX);
if(result!=m_texturePool.end())
{
return result->second;
}else
{
Texture * tex = new Texture(PosX,NegX,PosY,NegY,PosZ,NegZ);
m_texturePool.insert(std::make_pair(PosX,tex));
return tex;
}
}
Texture* TextureMgr::loadSingleCubeMap(std::string filePath)
{
auto result = m_texturePool.find(filePath);
if(result!=m_texturePool.end())
{
return result->second;
}else
{
//there is a bug, should be EWUDNS
Texture * tex = new Texture(filePath, "EWDUNS");
m_texturePool.insert(std::make_pair(filePath,tex));
return tex;
}
}
TextureMgr::TextureMgr()
{
}
TextureMgr::~TextureMgr()
{
tlog("somebody kill me");
}
} // namespace tzw
| 22.632479
| 125
| 0.629909
|
tangziwen
|
ee8bdbd14703200c0abba03f35df7f3c29f0c2b1
| 5,980
|
cc
|
C++
|
get-energy.cc
|
mhirki/rapl-tools
|
bf27fe416e7c93ea7f54904b47646a3471e8b910
|
[
"MIT"
] | 8
|
2019-01-17T12:48:34.000Z
|
2022-02-04T11:40:58.000Z
|
get-energy.cc
|
mhirki/rapl-tools
|
bf27fe416e7c93ea7f54904b47646a3471e8b910
|
[
"MIT"
] | null | null | null |
get-energy.cc
|
mhirki/rapl-tools
|
bf27fe416e7c93ea7f54904b47646a3471e8b910
|
[
"MIT"
] | 2
|
2019-12-01T02:23:07.000Z
|
2019-12-09T02:56:44.000Z
|
/*
* Measure the energy of executing another program.
* Code based on IgProf energy profiling module by Filip Nybäck.
*
* TODO:
* Use waitpid() instead of wait().
* Account for RAPL overflows.
*
* Author: Mikael Hirki <mikael.hirki@aalto.fi>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <signal.h>
#include <vector>
#include <papi.h>
#define READ_ENERGY(a) PAPI_read(s_event_set, a)
static int s_event_set = 0;
static int s_num_events = 0;
static long long *s_begin_values = NULL;
static long long *s_end_values = NULL;
static int idx_pkg_energy = -1;
static int idx_pp0_energy = -1;
static int idx_pp1_energy = -1;
static int idx_dram_energy = -1;
// Set the scale factor for the RAPL energy readings:
// one integer step is 15.3 microjoules, scale everything to joules.
static const double scaleFactor = 1e-9;
static pid_t child_pid = -1;
static double gettimeofday_double() {
struct timeval now;
gettimeofday(&now, NULL);
return now.tv_sec + now.tv_usec * 1e-6;
}
static void sighandler(int signum) {
printf("Received signal %d\n", signum);
if (child_pid > 0) {
kill(child_pid, signum);
} else {
exit(-1);
}
}
static void do_signals() {
signal(SIGQUIT, sighandler);
signal(SIGTERM, sighandler);
signal(SIGINT, sighandler);
}
static bool init_rapl() {
if (PAPI_library_init(PAPI_VER_CURRENT) != PAPI_VER_CURRENT) {
fprintf(stderr, "PAPI library initialisation failed.\n");
return false;
}
// Find the RAPL component of PAPI.
int num_components = PAPI_num_components();
int component_id;
const PAPI_component_info_t *component_info = 0;
for (component_id = 0; component_id < num_components; ++component_id)
{
component_info = PAPI_get_component_info(component_id);
if (component_info && strstr(component_info->name, "rapl")) {
break;
}
}
if (component_id == num_components) {
fprintf(stderr, "No RAPL component found in PAPI library.\n");
return false;
}
if (component_info->disabled) {
fprintf(stderr, "RAPL component of PAPI disabled: %s.\n",
component_info->disabled_reason);
return false;
}
// Create an event set.
s_event_set = PAPI_NULL;
if (PAPI_create_eventset(&s_event_set) != PAPI_OK) {
fprintf(stderr, "Could not create PAPI event set.\n");
return false;
}
int code = PAPI_NATIVE_MASK;
for (int retval = PAPI_enum_cmp_event(&code, PAPI_ENUM_FIRST, component_id); retval == PAPI_OK; retval = PAPI_enum_cmp_event(&code, PAPI_ENUM_EVENTS, component_id)) {
char event_name[PAPI_MAX_STR_LEN];
if (PAPI_event_code_to_name(code, event_name) != PAPI_OK) {
fprintf(stderr, "Could not get PAPI event name.\n");
return false;
}
PAPI_event_info_t event_info;
if (PAPI_get_event_info(code, &event_info) != PAPI_OK) {
fprintf(stderr, "Could not get PAPI event info.\n");
return false;
}
if (event_info.data_type != PAPI_DATATYPE_UINT64) {
continue;
}
if (strstr(event_name, "PACKAGE_ENERGY:")) {
idx_pkg_energy = s_num_events;
} else if (strstr(event_name, "PP0_ENERGY:")) {
idx_pp0_energy = s_num_events;
} else if (strstr(event_name, "PP1_ENERGY:")) {
idx_pp1_energy = s_num_events;
} else if (strstr(event_name, "DRAM_ENERGY:")) {
idx_dram_energy = s_num_events;
} else {
continue; // Skip other counters
}
//printf("Adding %s to event set.\n", event_name);
if (PAPI_add_event(s_event_set, code) != PAPI_OK)
break;
++s_num_events;
}
if (s_num_events == 0) {
fprintf(stderr, "Could not find any RAPL events.\n");
return false;
}
// Allocate memory for reading the counters
s_begin_values = (long long *)calloc(s_num_events, sizeof(long long));
s_end_values = (long long *)calloc(s_num_events, sizeof(long long));
// Activate the event set.
if (PAPI_start(s_event_set) != PAPI_OK) {
fprintf(stderr, "Could not activate the event set.\n");
return false;
}
return true;
}
static void do_fork_and_exec(int argc, char **argv) {
if (argc > 1) {
child_pid = fork();
if (child_pid == 0) {
execvp(argv[1], &argv[1]);
perror("execlp");
exit(-1);
} else if (child_pid < 0) {
perror("fork");
} else {
int status;
while (true) {
int rval = wait(&status);
if (rval < 0) {
if (errno == EINTR) continue;
else break;
}
if (WIFEXITED(status) || WIFSIGNALED(status)) {
child_pid = -1;
break;
}
}
}
} else {
printf("Usage: %s <program> [parameters]\n", argv[0]);
}
}
int main(int argc, char **argv) {
do_signals();
if (init_rapl()) {
double begin_time = gettimeofday_double();
READ_ENERGY(s_begin_values);
do_fork_and_exec(argc, argv);
READ_ENERGY(s_end_values);
double end_time = gettimeofday_double();
double time_elapsed = end_time - begin_time;
printf("Real time elapsed: %f seconds\n", time_elapsed);
if (idx_pkg_energy != -1) {
double pkg_energy = scaleFactor * (s_end_values[idx_pkg_energy] - s_begin_values[idx_pkg_energy]);
printf("Package energy consumed: %f J\n", pkg_energy);
printf("Package average power: %f W\n", pkg_energy / time_elapsed);
}
if (idx_pp0_energy != -1) {
double pp0_energy = scaleFactor * (s_end_values[idx_pp0_energy] - s_begin_values[idx_pp0_energy]);
printf("PP0 energy consumed: %f J\n", pp0_energy);
printf("PP0 average power: %f W\n", pp0_energy / time_elapsed);
}
if (idx_pp1_energy != -1) {
double pp1_energy = scaleFactor * (s_end_values[idx_pp1_energy] - s_begin_values[idx_pp1_energy]);
printf("PP1 energy consumed: %f J\n", pp1_energy);
printf("PP1 average power: %f W\n", pp1_energy / time_elapsed);
}
if (idx_dram_energy != -1) {
double dram_energy = scaleFactor * (s_end_values[idx_dram_energy] - s_begin_values[idx_dram_energy]);
printf("DRAM energy consumed: %f J\n", dram_energy);
printf("DRAM average power: %f W\n", dram_energy / time_elapsed);
}
}
return 0;
}
| 27.813953
| 167
| 0.691304
|
mhirki
|
ee8d2481fa3ec70137fdeb4b8fcc3b83a23d4188
| 2,624
|
cpp
|
C++
|
src/main.cpp
|
IllidanS4/samp-compat
|
91a7762f32d89fa3cab0d174546a6529e46dff27
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
IllidanS4/samp-compat
|
91a7762f32d89fa3cab0d174546a6529e46dff27
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
IllidanS4/samp-compat
|
91a7762f32d89fa3cab0d174546a6529e46dff27
|
[
"MIT"
] | null | null | null |
/*
# main.cpp
The "main" source file with most of the boilerplate code. Includes the
`NativesMain` header for initialising plugin-natives.
- `Supports` declares to the SA:MP server which features this plugin uses.
- `Load` is called when the plugin loads and sets up the `logprintf` function.
*/
#include <amx/amx.h>
#include <plugincommon.h>
#include <string.h>
#include "common.hpp"
#include "natives.hpp"
#include "addresses.hpp"
#include "impl.hpp"
logprintf_t logprintf;
void** ppPluginData = NULL;
void* pRakServer = NULL;
bool Initialized = false;
bool PostInitialized = false;
int iNetVersion;
int iCompatVersion;
int iCompatVersion2;
char szVersion[64] = "Unknown";
unsigned char PlayerCompat[MAX_PLAYERS] = { 0 };
int currentVersion = SAMPVersion::VERSION_UNKNOWN;
extern "C"
{
AMX_NATIVE_INFO nativeList[] = {
{ "IsPlayerCompat", Natives::IsPlayerCompat},
{ 0, 0 }
};
}
void Initialize()
{
switch (currentVersion)
{
case SAMPVersion::VERSION_037_R2:
{
iNetVersion = 4057;
iCompatVersion = 4062;
iCompatVersion2 = 32769;
strcpy(szVersion, "0.3.7-R2");
break;
}
case SAMPVersion::VERSION_03DL_R1:
{
iNetVersion = 4062;
iCompatVersion = 4057;
iCompatVersion2 = 4057;
strcpy(szVersion, "0.3.DL-R1");
break;
}
}
Addresses::Initialize();
Impl::InstallPreHooks();
logprintf(" -- samp-compat for %s initialized", szVersion);
Initialized = true;
}
PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}
PLUGIN_EXPORT bool PLUGIN_CALL Load(void** ppData)
{
ppPluginData = ppData;
pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];
DWORD addr = reinterpret_cast<DWORD>(logprintf);
if (addr == Addresses::FUNC_Logprintf_037_R2)
{
currentVersion = SAMPVersion::VERSION_037_R2;
Initialize();
}
else if (addr == Addresses::FUNC_Logprintf_03DL_R1)
{
currentVersion = SAMPVersion::VERSION_03DL_R1;
Initialize();
}
else
{
logprintf(" -- samp-compat: Unsupported version", szVersion);
return false;
}
return true;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxLoad(AMX* amx)
{
if (!PostInitialized)
{
// Get pRakServer
int(*pfn_GetRakServer)(void) = (int(*)(void))ppPluginData[PLUGIN_DATA_RAKSERVER];
pRakServer = (void*)pfn_GetRakServer();
Impl::InstallPostHooks();
PostInitialized = true;
}
return amx_Register(amx, nativeList, -1);
}
PLUGIN_EXPORT int PLUGIN_CALL Unload()
{
if (Initialized)
{
Impl::UninstallHooks();
}
return 1;
}
PLUGIN_EXPORT int PLUGIN_CALL AmxUnload(AMX* amx)
{
return 1;
}
| 19.58209
| 83
| 0.716082
|
IllidanS4
|
ee8e079de7f4afbd0ca4779cb9be34e2761d2f32
| 137
|
cpp
|
C++
|
docs/assets/playground/char_class_union.cpp
|
gkgoat1/lexy
|
9c600fa906e81efbb3e34b8951ebc56809f2a0df
|
[
"BSL-1.0"
] | null | null | null |
docs/assets/playground/char_class_union.cpp
|
gkgoat1/lexy
|
9c600fa906e81efbb3e34b8951ebc56809f2a0df
|
[
"BSL-1.0"
] | null | null | null |
docs/assets/playground/char_class_union.cpp
|
gkgoat1/lexy
|
9c600fa906e81efbb3e34b8951ebc56809f2a0df
|
[
"BSL-1.0"
] | null | null | null |
// INPUT:H123
struct production
{
static constexpr auto rule //
= dsl::identifier(dsl::ascii::upper / dsl::ascii::digit);
};
| 19.571429
| 65
| 0.635036
|
gkgoat1
|
ee9425fc42b56f5644c040b5b052deb2d31bc2ad
| 1,096
|
hpp
|
C++
|
include/GlobalNamespace/SR.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/SR.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/SR.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Completed includes
// Type namespace:
namespace GlobalNamespace {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: SR
class SR : public ::Il2CppObject {
public:
// Creating value type constructor for type: SR
SR() noexcept {}
// static System.String Format(System.String resourceFormat, System.Object p1)
// Offset: 0x1A648DC
static ::Il2CppString* Format(::Il2CppString* resourceFormat, ::Il2CppObject* p1);
// static System.String Format(System.String resourceFormat, System.Object p1, System.Object p2)
// Offset: 0x1A6495C
static ::Il2CppString* Format(::Il2CppString* resourceFormat, ::Il2CppObject* p1, ::Il2CppObject* p2);
}; // SR
#pragma pack(pop)
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::SR*, "", "SR");
| 39.142857
| 107
| 0.652372
|
darknight1050
|
ee96685d4b1d0cea12e5ed0ad31f5b2b98dd200c
| 4,718
|
cpp
|
C++
|
vm/drivers/cli.cpp
|
samleb/rubinius
|
38eec1983b9b6739d7a552081e208aa433b99483
|
[
"BSD-3-Clause"
] | 1
|
2016-05-09T10:45:38.000Z
|
2016-05-09T10:45:38.000Z
|
vm/drivers/cli.cpp
|
samleb/rubinius
|
38eec1983b9b6739d7a552081e208aa433b99483
|
[
"BSD-3-Clause"
] | null | null | null |
vm/drivers/cli.cpp
|
samleb/rubinius
|
38eec1983b9b6739d7a552081e208aa433b99483
|
[
"BSD-3-Clause"
] | null | null | null |
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include "vm/environment.hpp"
#include "vm/oop.hpp"
#include "vm/type_info.hpp"
#include "vm/exception.hpp"
using namespace std;
using namespace rubinius;
/* Loads the runtime kernel files. They're stored in /kernel.
* These files consist of classes needed to bootstrap the kernel
* and just get things started in general.
*
* @param root [String] The file root for /kernel. This expects to find
* alpha.rbc (will compile if not there).
* @param env [Environment&] The environment for Rubinius. It is the uber
* manager for multiple VMs and process-Ruby interaction.
*/
static void load_runtime_kernel(Environment& env, std::string root) {
std::string dirs = root + "/index";
std::ifstream stream(dirs.c_str());
if(!stream) {
std::cout << "It appears that " << root << "/index is missing.\n";
exit(1);
}
// Load the ruby file to prepare for bootstrapping Ruby!
// The bootstrapping for the VM is already done by the time we're here.
env.run_file(root + "/alpha.rbc");
while(!stream.eof()) {
std::string line;
stream >> line;
stream.get(); // eat newline
// skip empty lines
if(line.size() == 0) continue;
env.load_directory(root + "/" + line);
}
}
/* The main function here handles the CL arguments passed to it.
* It then boots the VM, runs the appropriate file (`loader`),
* and returns 0. If there is an Assertion raised or an Exception,
* it prints the backtrace supplied. This function is the wrapper for
* the entire VM, as it deals with anything that could possibly happen
* to the VM. It's like the person playing whack-a-mole, in that if
* something tries to come out of the VM that's evil (such as a failed
* assertion or exception), it catches it and skins it and shows it to
* the user.
*
* Note: Although Rubinius is gathering support for multiple VMs, this
* function does not deal with that subject.
*/
int main(int argc, char** argv) {
Environment env(argc, argv);
env.state->init_stack_size();
env.state->set_stack_start(&env);
try {
const char* runtime = getenv("RBX_RUNTIME");
if(!runtime) {
struct stat st;
runtime = RBA_PATH;
if(stat(runtime, &st) == -1 || !S_ISDIR(st.st_mode)) {
// Use throw rather than ::raise here because we're outside
// the VM really.
throw new Assertion("set RBX_RUNTIME to runtime (or equiv)");
}
}
std::string root = std::string(runtime);
env.load_platform_conf(root);
env.boot_vm();
env.load_argv(argc, argv);
load_runtime_kernel(env, std::string(root));
std::string loader = root + "/loader.rbc";
env.enable_preemption();
env.start_signal_thread();
env.run_file(loader);
return env.exit_code();
} catch(Assertion *e) {
std::cout << "VM Assertion:" << std::endl;
std::cout << " " << e->reason << std::endl << std::endl;
e->print_backtrace();
std::cout << std::endl << "Ruby backtrace:" << std::endl;
env.state->print_backtrace();
delete e;
} catch(RubyException &e) {
std::cout << "Ruby Exception hit toplevel:\n";
// Prints Ruby backtrace, and VM backtrace if captured
e.show(env.state);
} catch(TypeError &e) {
/* TypeError's here are dealt with specially so that they can deliver
* more information, such as _why_ there was a type error issue.
*
* This has the same name as the RubyException TypeError (run `5 + "string"`
* as an example), but these are NOT the same - this exception is raised
* internally when Qnil gets passed to an array method, for instance, when
* an array was expected.
*/
std::cout << "Type Error detected:" << std::endl;
TypeInfo* wanted = env.state->find_type(e.type);
if(!e.object->reference_p()) {
std::cout << " Tried to use non-reference value " << e.object;
} else {
TypeInfo* was = env.state->find_type(e.object->type_id());
std::cout << " Tried to use object of type " <<
was->type_name << " (" << was->type << ")";
}
std::cout << " as type " << wanted->type_name << " (" <<
wanted->type << ")" << std::endl;
e.print_backtrace();
std::cout << "Ruby backtrace:" << std::endl;
env.state->print_backtrace();
} catch(std::runtime_error& e) {
std::cout << "Runtime exception: " << e.what() << std::endl;
} catch(VMException &e) {
std::cout << "Unknown VM exception detected." << std::endl;
e.print_backtrace();
} catch(std::string e) {
std::cout << e << std::endl;
} catch(...) {
std::cout << "Unknown exception detected." << std::endl;
}
}
| 32.095238
| 80
| 0.633319
|
samleb
|
ee97070dd1aa511ba5b3855ccb16fd8b5e3351d6
| 3,336
|
hpp
|
C++
|
bmc_state_manager.hpp
|
msbarth/ibm-phosphor-state-manager
|
bce16c8e6d653f43a9dca5b05d9741ccdbb3ab5d
|
[
"Apache-2.0"
] | null | null | null |
bmc_state_manager.hpp
|
msbarth/ibm-phosphor-state-manager
|
bce16c8e6d653f43a9dca5b05d9741ccdbb3ab5d
|
[
"Apache-2.0"
] | null | null | null |
bmc_state_manager.hpp
|
msbarth/ibm-phosphor-state-manager
|
bce16c8e6d653f43a9dca5b05d9741ccdbb3ab5d
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "xyz/openbmc_project/State/BMC/server.hpp"
#include <linux/watchdog.h>
#include <sdbusplus/bus.hpp>
#include <functional>
namespace phosphor
{
namespace state
{
namespace manager
{
using BMCInherit = sdbusplus::server::object::object<
sdbusplus::xyz::openbmc_project::State::server::BMC>;
namespace sdbusRule = sdbusplus::bus::match::rules;
/** @class BMC
* @brief OpenBMC BMC state management implementation.
* @details A concrete implementation for xyz.openbmc_project.State.BMC
* DBus API.
*/
class BMC : public BMCInherit
{
public:
/** @brief Constructs BMC State Manager
*
* @param[in] bus - The Dbus bus object
* @param[in] busName - The Dbus name to own
* @param[in] objPath - The Dbus object path
*/
BMC(sdbusplus::bus::bus& bus, const char* objPath) :
BMCInherit(bus, objPath, true), bus(bus),
stateSignal(std::make_unique<decltype(stateSignal)::element_type>(
bus,
sdbusRule::type::signal() + sdbusRule::member("JobRemoved") +
sdbusRule::path("/org/freedesktop/systemd1") +
sdbusRule::interface("org.freedesktop.systemd1.Manager"),
std::bind(std::mem_fn(&BMC::bmcStateChange), this,
std::placeholders::_1)))
{
subscribeToSystemdSignals();
discoverInitialState();
discoverLastRebootCause();
this->emit_object_added();
};
/** @brief Set value of BMCTransition **/
Transition requestedBMCTransition(Transition value) override;
/** @brief Set value of CurrentBMCState **/
BMCState currentBMCState(BMCState value) override;
/** @brief Returns the last time the BMC was rebooted
*
* @details Uses uptime information to determine when
* the BMC was last rebooted.
*
* @return uint64_t - Epoch time, in milliseconds, of the
* last reboot.
*/
uint64_t lastRebootTime() const override;
/** @brief Set value of LastRebootCause **/
RebootCause lastRebootCause(RebootCause value) override;
private:
/**
* @brief Retrieve input systemd unit state
**/
std::string getUnitState(const std::string& unitToCheck);
/**
* @brief discover the state of the bmc
**/
void discoverInitialState();
/**
* @brief subscribe to the systemd signals
**/
void subscribeToSystemdSignals();
/** @brief Execute the transition request
*
* @param[in] tranReq - Transition requested
*/
void executeTransition(Transition tranReq);
/** @brief Callback function on bmc state change
*
* Check if the state is relevant to the BMC and if so, update
* corresponding BMC object's state
*
* @param[in] msg - Data associated with subscribed signal
*
*/
int bmcStateChange(sdbusplus::message::message& msg);
/** @brief Persistent sdbusplus DBus bus connection. **/
sdbusplus::bus::bus& bus;
/** @brief Used to subscribe to dbus system state changes **/
std::unique_ptr<sdbusplus::bus::match_t> stateSignal;
/**
* @brief discover the last reboot cause of the bmc
**/
void discoverLastRebootCause();
};
} // namespace manager
} // namespace state
} // namespace phosphor
| 28.512821
| 74
| 0.639089
|
msbarth
|
ee9883d50c029ffa8aec2c438de71d0e1409e4ec
| 130
|
hxx
|
C++
|
src/Providers/UNIXProviders/QueryCapabilities/UNIX_QueryCapabilities_LINUX.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | 1
|
2020-10-12T09:00:09.000Z
|
2020-10-12T09:00:09.000Z
|
src/Providers/UNIXProviders/QueryCapabilities/UNIX_QueryCapabilities_LINUX.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
src/Providers/UNIXProviders/QueryCapabilities/UNIX_QueryCapabilities_LINUX.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
#ifdef PEGASUS_OS_LINUX
#ifndef __UNIX_QUERYCAPABILITIES_PRIVATE_H
#define __UNIX_QUERYCAPABILITIES_PRIVATE_H
#endif
#endif
| 10.833333
| 42
| 0.853846
|
brunolauze
|
ee9ad06223a193620c30a7c0344ac7a114660687
| 1,120
|
cpp
|
C++
|
dataset/test/1624B/8.cpp
|
Karina5005/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | 3
|
2022-02-15T00:29:39.000Z
|
2022-03-15T08:36:44.000Z
|
dataset/test/1624B/8.cpp
|
Kira5005-code/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | null | null | null |
dataset/test/1624B/8.cpp
|
Kira5005-code/Plagiarism
|
ce11f72ba21a754ca84a27e5f26a31a19d6cb6fb
|
[
"MIT"
] | null | null | null |
#include <complex>
#include <queue>
#include <set>
#include <unordered_set>
#include <list>
#include <chrono>
#include <random>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <stack>
#include <array>
#include <iomanip>
using namespace std;
typedef long long int ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef vector<ll> vl;
typedef vector<int> vi;
#define fo(i, a, n) for(int i = a; i < n; i++)
#define fi(i, n, a) for(int i = n; i >= a; i--)
#define mp make_pair
#define pb push_back
#define INF 2e18
#define all(x) (x).begin(), (x).end()
#define sz(x) ((ll)(x).size())
void solve() {
ll A, B, C; cin >> A >> B >> C;
ll G1 = 2*B-C;
ll G2 = 2*B-A;
ll G3 = A+C;
cout << ((G1%A==0&&G1>0)||(G2%C==0&&G2>0)||(G3%2==0&&(G3/2)%B==0&&G3>0)?"YES":"NO") << "\n";
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
int T = 1;
cin >> T;
while(T--) {
solve();
}
return 0;
}
| 20.740741
| 97
| 0.55625
|
Karina5005
|
eea25dcdca81b713365256e88123e13734c81441
| 399
|
cpp
|
C++
|
Nebula-Storm/src/App.cpp
|
GalacticKittenSS/Nebula
|
1620a1dab815d6721b1ae1e3e390ae16313309da
|
[
"Apache-2.0"
] | 3
|
2021-11-21T21:05:44.000Z
|
2021-12-27T20:44:08.000Z
|
Nebula-Storm/src/App.cpp
|
GalacticKittenSS/Nebula
|
1620a1dab815d6721b1ae1e3e390ae16313309da
|
[
"Apache-2.0"
] | null | null | null |
Nebula-Storm/src/App.cpp
|
GalacticKittenSS/Nebula
|
1620a1dab815d6721b1ae1e3e390ae16313309da
|
[
"Apache-2.0"
] | null | null | null |
#include <Nebula.h>
#include <Nebula_EntryPoint.h>
#include "EditorLayer.h"
namespace Nebula {
class NebulaStorm : public Application {
public:
NebulaStorm(ApplicationCommandLineArgs args): Application("Nebula Storm", args) {
PushLayer(new EditorLayer());
}
~NebulaStorm() { }
};
Application* CreateApplication(ApplicationCommandLineArgs args) {
return new NebulaStorm(args);
}
}
| 21
| 83
| 0.739348
|
GalacticKittenSS
|
eea5d071de1039c97fa41edb0cfaf94d2dc5f739
| 1,337
|
cpp
|
C++
|
effective-modern-cpp/item39_multi.cpp
|
miaogen123/daily-coding
|
5d7f463ad1fee5e512aeb36206526b53b9a781f6
|
[
"MIT"
] | 19
|
2018-07-06T06:53:56.000Z
|
2022-01-01T16:36:26.000Z
|
effective-modern-cpp/item39_multi.cpp
|
miaogen123/daily-coding
|
5d7f463ad1fee5e512aeb36206526b53b9a781f6
|
[
"MIT"
] | null | null | null |
effective-modern-cpp/item39_multi.cpp
|
miaogen123/daily-coding
|
5d7f463ad1fee5e512aeb36206526b53b9a781f6
|
[
"MIT"
] | 17
|
2019-03-27T23:18:43.000Z
|
2021-01-18T11:17:57.000Z
|
#include<iostream>
#include<vector>
#include<windows.h>
#include<atomic>
#include<thread>
#include<chrono>
#include<future>
using namespace std;
using namespace std::literals;
//
//以及多个线程之间使用shared_future
std::promise<void> commu_channel;
std::atomic<bool> poll_flag(false);
std::condition_variable cv;
void f()
{
std::this_thread::sleep_for(1s);
}
//FIXME:: 下面的 这个模板 有问题
template <typename T, typename... param>
inline std::future<typename std::result_of<T(param...)>::type>
ReallyAsync(T&& f, param&&... params){
return async(std::launch::async,
std::forward<T>(f),
std::forward<param>(params)...);
}
void react()
{
std::cout<<"hello i'm in the react"<<endl;
}
void detect()
{
cout<<"inside the detect!!!"<<endl;
auto sf=commu_channel.get_future().share();
std::vector<std::thread> vt;
for(auto i=0;i<5;i++){
vt.emplace_back([sf]{sf.wait();react();});
vt.back().detach();
}
//thread to_react([](){commu_channel.get_future().wait();react();});
//to_react.detach();
while(!poll_flag)
Sleep(1);
commu_channel.set_value();
}
int main(void)
{
cout<<"ready to work!!!"<<endl;
//ReallyAsync(detect);
auto detect_async=std::async(std::launch::async,detect);
cout<<"to work!!!"<<endl;
poll_flag=true;
auto futu=std::async(f);
while(futu.wait_for(100ms)!=std::future_status::ready){}
return 0;
}
| 19.1
| 69
| 0.673897
|
miaogen123
|
eea86c32bd28db9d839add2d0cfb13ef7a607c1b
| 928
|
cpp
|
C++
|
arduino/hellospiffs/src/main.cpp
|
ricklon/kombuchamanager
|
5ab11322637294e49a4f85c8cc65bdd780af806c
|
[
"Apache-2.0"
] | null | null | null |
arduino/hellospiffs/src/main.cpp
|
ricklon/kombuchamanager
|
5ab11322637294e49a4f85c8cc65bdd780af806c
|
[
"Apache-2.0"
] | null | null | null |
arduino/hellospiffs/src/main.cpp
|
ricklon/kombuchamanager
|
5ab11322637294e49a4f85c8cc65bdd780af806c
|
[
"Apache-2.0"
] | null | null | null |
/*
Hello World SPIFFS
based of DFRObot Tutorial
https://www.dfrobot.com/blog-1111.html
*/
#include <Arduino.h>
#include "SPIFFS.h"
void setup() {
Serial.begin(115200);
if(!SPIFFS.begin(true)){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
File file = SPIFFS.open("/test.txt", FILE_WRITE);
if(!file){
Serial.println("There was an error opening the file for writing");
return;
}
if(file.print("TEST")){
Serial.println("File was written");;
} else {
Serial.println("File write failed");
}
file.close();
File file2 = SPIFFS.open("/test.txt");
if(!file2){
Serial.println("Failed to open file for reading");
return;
}
Serial.println("File Content:");
while(file2.available()){
Serial.write(file2.read());
}
file2.close();
}
void loop() {}
| 17.509434
| 74
| 0.578664
|
ricklon
|
eeab701031cf569d33514c1ac4220f3a1ac2d52b
| 3,118
|
cpp
|
C++
|
src/main.cpp
|
pawREP/Glacier-Prim-IO
|
5c6a512656e526b5c5d859623c3670eaa802d88f
|
[
"MIT"
] | 12
|
2020-04-03T00:00:16.000Z
|
2022-03-09T11:40:48.000Z
|
src/main.cpp
|
pawREP/Glacier-Prim-IO
|
5c6a512656e526b5c5d859623c3670eaa802d88f
|
[
"MIT"
] | 2
|
2020-04-12T03:10:09.000Z
|
2020-05-10T22:24:45.000Z
|
src/main.cpp
|
pawREP/Glacier-Prim-IO
|
5c6a512656e526b5c5d859623c3670eaa802d88f
|
[
"MIT"
] | 4
|
2020-04-10T03:06:05.000Z
|
2021-09-30T06:03:30.000Z
|
#include "mainwindow.h"
#include "GlacierFormats.h"
#include <iostream>
#include <QApplication>
#include <QtConcurrent/qtconcurrentrun.h>
void initAppStyle() {
qApp->setStyle(QStyleFactory::create("Fusion"));
QPalette darkPalette;
darkPalette.setColor(QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::HighlightedText, Qt::black);
darkPalette.setColor(QPalette::Disabled, QPalette::Window, QColor(53, 53, 53));
darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, Qt::gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Base, QColor(25, 25, 25));
darkPalette.setColor(QPalette::Disabled, QPalette::AlternateBase, QColor(53, 53, 53));
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipBase, Qt::gray);
darkPalette.setColor(QPalette::Disabled, QPalette::ToolTipText, Qt::gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, Qt::gray);
darkPalette.setColor(QPalette::Disabled, QPalette::Button, QColor(53, 53, 53));
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, Qt::gray);
darkPalette.setColor(QPalette::Disabled, QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Disabled, QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, Qt::black);
qApp->setPalette(darkPalette);
qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }");
}
void initGlacierFormats() {
QProgressDialog progressDialog;
progressDialog.setWindowTitle("Loading...");
progressDialog.setRange(0, 0);
progressDialog.setLabel(new QLabel("Initilizing GlacierFormats, this might take a few seconds...", &progressDialog));
progressDialog.show();
auto future = QtConcurrent::run(&GlacierFormats::GlacierInit);
while (!future.isFinished()) {
qApp->processEvents();
Sleep(33);
}
if (progressDialog.wasCanceled())
exit(0);
progressDialog.close();
}
int main(int argc, char *argv[]) {
#ifndef _DEBUG
ShowWindow(GetConsoleWindow(), SW_HIDE);
#endif
QApplication app(argc, argv);
initAppStyle();
initGlacierFormats();
MainWindow window;
QSize windowSize(1200, 800);
window.resize(windowSize);
window.show();
return app.exec();
}
| 39.468354
| 121
| 0.716806
|
pawREP
|
eead54f4bba87a27acef158e255573de02dfcf37
| 2,068
|
cpp
|
C++
|
QSettingsDialog/core/qsettingsentry.cpp
|
cybik/QSettingsDialog
|
106ab053f042d57a89acec49ddb348aaf2aec14d
|
[
"BSD-3-Clause"
] | 9
|
2017-04-18T06:10:49.000Z
|
2022-03-28T14:35:07.000Z
|
QSettingsDialog/core/qsettingsentry.cpp
|
cybik/QSettingsDialog
|
106ab053f042d57a89acec49ddb348aaf2aec14d
|
[
"BSD-3-Clause"
] | null | null | null |
QSettingsDialog/core/qsettingsentry.cpp
|
cybik/QSettingsDialog
|
106ab053f042d57a89acec49ddb348aaf2aec14d
|
[
"BSD-3-Clause"
] | 8
|
2016-12-23T08:24:23.000Z
|
2022-02-18T01:54:15.000Z
|
#include "qsettingsentry.h"
#include "qsettingsentry_p.h"
#include <QThread>
#define d this->d_ptr
QSettingsEntry::QSettingsEntry(int displaytype, QSettingsLoader *loader) :
d_ptr(new QSettingsEntryPrivate(displaytype, loader))
{}
QSettingsEntry::QSettingsEntry(int displaytype, QSettingsLoader *loader, const QString &name, bool optional, const QString &tooltip, const UiPropertyMap &properties) :
d_ptr(new QSettingsEntryPrivate(displaytype, loader))
{
d->name = name;
d->optional = optional;
d->tooltip = tooltip;
d->properties = properties;
}
QSettingsEntry::~QSettingsEntry()
{
#ifndef QT_NO_DEBUG
Q_ASSERT_X(d->refCounter == 0, Q_FUNC_INFO, "settings entry destroyed with active loaders!");
#endif
}
QString QSettingsEntry::entryName() const
{
return d->name;
}
void QSettingsEntry::setEntryName(const QString &name)
{
d->name = name;
}
bool QSettingsEntry::isOptional() const
{
return d->optional;
}
void QSettingsEntry::setOptional(bool optional)
{
d->optional = optional;
}
QString QSettingsEntry::tooltip() const
{
return d->tooltip;
}
void QSettingsEntry::setTooltip(const QString &tooltip)
{
d->tooltip = tooltip;
}
UiPropertyMap QSettingsEntry::uiProperties() const
{
return d->properties;
}
void QSettingsEntry::setUiProperties(const UiPropertyMap &properties)
{
d->properties = properties;
}
void QSettingsEntry::setUiProperty(const QString &name, const QVariant &value)
{
d->properties.insert(name, value);
}
int QSettingsEntry::displaytype()
{
return d->displaytype;
}
QSettingsLoader *QSettingsEntry::getLoader()
{
#ifndef QT_NO_DEBUG
d->refCounter++;
#endif
return d->loader.data();
}
void QSettingsEntry::freeLoader(QSettingsLoader *)
{
#ifndef QT_NO_DEBUG
d->refCounter--;
#endif
}
void QSettingsEntryPrivate::LoaderDeleter::cleanup(QSettingsLoader *loader)
{
if(loader && loader->isAsync()) {
auto async = loader->async();
if(async->thread() == QThread::currentThread())
async->deleteLater();
else
QMetaObject::invokeMethod(async, "deleteLater", Qt::QueuedConnection);
} else
delete loader;
}
| 20.07767
| 167
| 0.747582
|
cybik
|
eead7264b40b36f4dc87ea386eedb960a958322b
| 1,700
|
cpp
|
C++
|
Practice/2018/2018.12.16/SP-DIVCNTK.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | 4
|
2017-10-31T14:25:18.000Z
|
2018-06-10T16:10:17.000Z
|
Practice/2018/2018.12.16/SP-DIVCNTK.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
Practice/2018/2018.12.16/SP-DIVCNTK.cpp
|
SYCstudio/OI
|
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define ull unsigned long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
#define RG register
#define IL inline
const int maxN=101000;
const int inf=2147483647;
ull n,K,srt;
bool notprime[maxN];
int pcnt,P[maxN];
ull num,Num[maxN+maxN],Id[maxN+maxN],G[maxN+maxN],H[maxN+maxN],Sum[maxN+maxN];
IL void Init();
IL int GetId(RG ull x);
ull Calc(RG ull m,RG ull k);
ull S(RG ull x,RG int p);
int main(){
Init();RG int TTT;RG ull nn,k;
scanf("%d",&TTT);
while (TTT--){
scanf("%llu%llu",&nn,&k);
printf("%llu\n",Calc(nn,k));
}
return 0;
}
IL void Init(){
notprime[1]=1;
for (RG int i=2;i<maxN;++i){
if (notprime[i]==0) P[++pcnt]=i,Sum[pcnt]=Sum[pcnt-1]+i;
for (RG int j=1;(j<=pcnt)&&(1ll*i*P[j]<maxN);++j){
notprime[i*P[j]]=1;if (i%P[j]==0) break;
}
}
return;
}
IL int GetId(RG ull x){
if (x<=srt) return Id[x];
else return Id[n/x+maxN];
}
IL ull Calc(RG ull m,RG ull k){
num=0;n=m;srt=sqrt(m);K=k;
for (RG ull i=1,j;i<=n;i=j+1){
j=n/i;Num[++num]=j;//G[num]=j*(j+1)/2-1;
H[num]=j-1;
if (j<=srt) Id[j]=num;
else Id[i+maxN]=num;j=n/j;
}
//for (int i=1;i<=100;i++) cout<<P[i]<<" ";cout<<endl;
for (RG int j=1;j<=pcnt;++j)
for (RG int i=1;(i<=num)&&(1ll*P[j]*P[j]<=Num[i]);++i)
H[i]=H[i]-H[GetId(Num[i]/P[j])]+j-1;
return S(m,1)+1;
}
ull S(RG ull x,RG int p){
if ((x<=1)||(P[p]>x)) return 0;
RG int id=GetId(x);RG ull ret=(H[id]-(p-1))*(K+1);
for (RG int i=p;(i<=pcnt)&&(1ll*P[i]*P[i]<=x);++i){
RG ull mul=P[i];
for (RG int j=1;mul*P[i]<=x;j++,mul*=P[i])
ret=ret+S(x/mul,i+1)*(K*j+1)+(ull)K*(j+1)+1;
}
return ret;
}
| 21.794872
| 78
| 0.58
|
SYCstudio
|
eeae7fd238aeeb0ea28c1039413c0ecc1f76b3d7
| 507
|
hpp
|
C++
|
lib/wedges/wedge.hpp
|
llpm/llpm
|
47000202b2bb5f09cf739b9094f948744f6d72d2
|
[
"Apache-2.0"
] | 1
|
2021-11-28T14:56:21.000Z
|
2021-11-28T14:56:21.000Z
|
lib/wedges/wedge.hpp
|
llpm/llpm
|
47000202b2bb5f09cf739b9094f948744f6d72d2
|
[
"Apache-2.0"
] | null | null | null |
lib/wedges/wedge.hpp
|
llpm/llpm
|
47000202b2bb5f09cf739b9094f948744f6d72d2
|
[
"Apache-2.0"
] | null | null | null |
#ifndef __LLPM_WEDGES_WEDGE_HPP__
#define __LLPM_WEDGES_WEDGE_HPP__
#include <util/files.hpp>
namespace llpm {
// Fwd defs
class Module;
class Wedge {
public:
virtual ~Wedge() { }
virtual void writeModule(FileSet& fileset, Module* mod) = 0;
};
/**
* Specifies a class which wraps a module in another, usually to
* provide translation. Good accessory for a wedge.
*/
class Wrapper {
public:
virtual Module* wrapModule(Module* mod) = 0;
};
} // llpm
#endif // __LLPM_WEDGES_WEDGE_HPP__
| 16.9
| 64
| 0.712032
|
llpm
|
eeb0a2314fe1a6c64d24e5dee64c0a0f92499f25
| 17,794
|
cpp
|
C++
|
source/Lib/CommonLib/ContextModelling.cpp
|
theambient/hhi_next_software
|
a99e39bad84ccde327c81e62dc2aa83fa73a295a
|
[
"BSD-3-Clause"
] | null | null | null |
source/Lib/CommonLib/ContextModelling.cpp
|
theambient/hhi_next_software
|
a99e39bad84ccde327c81e62dc2aa83fa73a295a
|
[
"BSD-3-Clause"
] | null | null | null |
source/Lib/CommonLib/ContextModelling.cpp
|
theambient/hhi_next_software
|
a99e39bad84ccde327c81e62dc2aa83fa73a295a
|
[
"BSD-3-Clause"
] | null | null | null |
/* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2017, ITU/ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
/** \file ContextModelling.cpp
\brief Classes providing probability descriptions and contexts
*/
#include "ContextModelling.h"
#include "UnitTools.h"
#include "CodingStructure.h"
#include "Picture.h"
CoeffCodingContext::CoeffCodingContext(const TransformUnit& tu, ComponentID component, bool signHide)
: m_compID (component)
, m_chType (toChannelType(m_compID))
, m_width (tu.block(m_compID).width)
, m_height (tu.block(m_compID).height)
, m_log2CGWidth ((m_width & 3) || (m_height & 3) ? 1 : 2)
, m_log2CGHeight ((m_width & 3) || (m_height & 3) ? 1 : 2)
, m_log2CGSize (m_log2CGWidth + m_log2CGHeight)
, m_widthInGroups (m_width >> m_log2CGWidth)
, m_heightInGroups (m_height >> m_log2CGHeight)
, m_log2BlockWidth (g_aucLog2[m_width])
, m_log2BlockHeight (g_aucLog2[m_height])
, m_log2WidthInGroups (g_aucLog2[m_widthInGroups])
, m_log2HeightInGroups (g_aucLog2[m_heightInGroups])
, m_log2BlockSize ((m_log2BlockWidth + m_log2BlockHeight)>>1)
, m_maxNumCoeff (m_width * m_height)
, m_AlignFlag (tu.cs->sps->getSpsRangeExtension().getCabacBypassAlignmentEnabledFlag())
, m_signHiding (signHide)
, m_useGoRiceParAdapt (tu.cs->sps->getSpsRangeExtension().getPersistentRiceAdaptationEnabledFlag())
, m_extendedPrecision (tu.cs->sps->getSpsRangeExtension().getExtendedPrecisionProcessingFlag())
, m_maxLog2TrDynamicRange (tu.cs->sps->getMaxLog2TrDynamicRange(m_chType))
, m_scanType (CoeffScanType(TU::getCoefScanIdx( tu, m_compID)))
, m_scan (g_scanOrder [SCAN_GROUPED_4x4][m_scanType][gp_sizeIdxInfo->idxFrom(m_width )][gp_sizeIdxInfo->idxFrom(m_height )])
, m_scanPosX (g_scanOrderPosXY[SCAN_GROUPED_4x4][m_scanType][gp_sizeIdxInfo->idxFrom(m_width )][gp_sizeIdxInfo->idxFrom(m_height )][0])
, m_scanPosY (g_scanOrderPosXY[SCAN_GROUPED_4x4][m_scanType][gp_sizeIdxInfo->idxFrom(m_width )][gp_sizeIdxInfo->idxFrom(m_height )][1])
, m_scanCG (g_scanOrder[SCAN_UNGROUPED ][m_scanType][gp_sizeIdxInfo->idxFrom(m_widthInGroups)][gp_sizeIdxInfo->idxFrom(m_heightInGroups)])
, m_CtxSetLastX (Ctx::LastX[m_chType])
, m_CtxSetLastY (Ctx::LastY[m_chType])
, m_maxLastPosX (g_uiGroupIdx[m_width - 1])
, m_maxLastPosY (g_uiGroupIdx[m_height - 1])
, m_lastOffsetX (0)
, m_lastOffsetY (0)
, m_lastShiftX (0)
, m_lastShiftY (0)
, m_TrafoBypass (tu.cs->sps->getSpsRangeExtension().getTransformSkipContextEnabledFlag() && (tu.cu->transQuantBypass || tu.transformSkip[m_compID]))
, m_SigBlockType (m_TrafoBypass ? 0 : m_width == 4 && m_height == 4 ? 1 : m_width == 8 && m_height == 8 ? 2 : m_log2CGSize==2 ? 4 : 3 )
, m_sigCtxSet (Ctx::SigFlag[m_chType])
, m_scanPosLast (-1)
, m_subSetId (-1)
, m_subSetPos (-1)
, m_minSubPos (-1)
, m_maxSubPos (-1)
, m_sigGroupCtxId (-1)
, m_gt1FlagCtxSet (0, 0)
, m_gt2FlagCtxId (-1)
, m_currentGolombRiceStatistic(-1)
, m_prevGt2 (false)
, m_sigCoeffGroupFlag ()
, m_altResiCompId ( tu.cs->sps->getSpsNext().getAltResiCompId() )
, m_emtNumSigCoeff (0)
{
// LOGTODO
unsigned log2sizeX = m_log2BlockWidth;
unsigned log2sizeY = m_log2BlockHeight;
if (m_scanType == SCAN_VER)
{
std::swap(log2sizeX, log2sizeY);
std::swap(const_cast<unsigned&>(m_maxLastPosX), const_cast<unsigned&>(m_maxLastPosY));
}
if (m_chType == CHANNEL_TYPE_CHROMA)
{
if( tu.cs->pcv->rectCUs )
{
const_cast<int&>(m_lastShiftX) = Clip3( 0, 2, int( ( m_scanType == SCAN_VER ? m_height : m_width ) >> 3) );
const_cast<int&>(m_lastShiftY) = Clip3( 0, 2, int( ( m_scanType == SCAN_VER ? m_width : m_height ) >> 3) );
}
else
{
const_cast<int&>(m_lastShiftX) = log2sizeX - 2;
const_cast<int&>(m_lastShiftY) = log2sizeY - 2;
}
}
else
{
if( tu.cs->pcv->rectCUs )
{
static const int prefix_ctx[8] = { 0, 0, 0, 3, 6, 10, 15, 21 };
const_cast<int&>(m_lastOffsetX) = prefix_ctx[ log2sizeX ];
const_cast<int&>(m_lastOffsetY) = prefix_ctx[ log2sizeY ];;
}
else
{
const_cast<int&>(m_lastOffsetX) = 3 * (log2sizeX - 2) + ((log2sizeX - 1) >> 2);
const_cast<int&>(m_lastOffsetY) = 3 * (log2sizeY - 2) + ((log2sizeY - 1) >> 2);
}
const_cast<int&>(m_lastShiftX) = (log2sizeX + 1) >> 2;
const_cast<int&>(m_lastShiftY) = (log2sizeY + 1) >> 2;
}
if( m_altResiCompId == 1 )
{
if( m_scanType && m_log2BlockWidth == 3 && m_log2BlockHeight == 3 )
{
m_scan = g_scanOrder [ SCAN_UNGROUPED ][ m_scanType ][ gp_sizeIdxInfo->idxFrom( m_width ) ][ gp_sizeIdxInfo->idxFrom( m_height ) ];
m_scanPosX = g_scanOrderPosXY[ SCAN_UNGROUPED ][ m_scanType ][ gp_sizeIdxInfo->idxFrom( m_width ) ][ gp_sizeIdxInfo->idxFrom( m_height ) ][0];
m_scanPosY = g_scanOrderPosXY[ SCAN_UNGROUPED ][ m_scanType ][ gp_sizeIdxInfo->idxFrom( m_width ) ][ gp_sizeIdxInfo->idxFrom( m_height ) ][1];
}
if( m_scanType == SCAN_VER && m_log2WidthInGroups == 1 && m_log2HeightInGroups == 1 )
{
m_scanCG = g_scanOrder[ SCAN_UNGROUPED ][ m_scanType - 1 ][ gp_sizeIdxInfo->idxFrom( m_widthInGroups ) ][ gp_sizeIdxInfo->idxFrom( m_heightInGroups ) ];
}
}
}
void CoeffCodingContext::initSubblock( int SubsetId, bool sigGroupFlag )
{
m_subSetId = SubsetId;
m_subSetPos = m_scanCG[ m_subSetId ];
m_minSubPos = m_subSetId << m_log2CGSize;
m_maxSubPos = m_minSubPos + ( 1 << m_log2CGSize ) - 1;
if( sigGroupFlag )
{
m_sigCoeffGroupFlag.set ( m_subSetPos );
}
unsigned CGPosY = 0;
unsigned CGPosX = 0;
unsigned sigRight = 0;
unsigned sigLower = 0;
if( m_altResiCompId == 1 )
{
unsigned widthInGroups = m_widthInGroups;
unsigned heightInGroups = m_heightInGroups;
if( m_widthInGroups == 2 && m_heightInGroups )
{
if( m_scanType == SCAN_HOR )
{
widthInGroups = 1;
heightInGroups = 4;
}
else if( m_scanType == SCAN_VER )
{
widthInGroups = 4;
heightInGroups = 1;
}
}
CGPosY = m_subSetPos >> m_log2WidthInGroups;
CGPosX = m_subSetPos - ( CGPosY << m_log2WidthInGroups );
bool hor8x8 = m_width == 8 && m_height == 8 && m_scanType == SCAN_HOR;
bool ver8x8 = m_width == 8 && m_height == 8 && m_scanType == SCAN_VER;
bool bonDiag8x8 = hor8x8 || ver8x8;
if( bonDiag8x8 )
{
CGPosY = ( bonDiag8x8 ? m_subSetPos : 0 );
CGPosX = ( bonDiag8x8 ? m_subSetPos : 0 );
}
sigRight = unsigned( ( CGPosX + 1 ) < widthInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + 1 ] : false );
sigLower = unsigned( ( CGPosY + 1 ) < heightInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + widthInGroups ] : false );
}
else
{
CGPosY = m_subSetPos >> m_log2WidthInGroups;
CGPosX = m_subSetPos - ( CGPosY << m_log2WidthInGroups );
sigRight = unsigned( ( CGPosX + 1 ) < m_widthInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + 1 ] : false );
sigLower = unsigned( ( CGPosY + 1 ) < m_heightInGroups ? m_sigCoeffGroupFlag[ m_subSetPos + m_widthInGroups ] : false );
}
const unsigned ctxSet = m_prevGt2 + ( m_chType == CHANNEL_TYPE_LUMA ? ( m_subSetId > 0 ? 2 : 0 ) : 4 );
m_sigGroupCtxId = Ctx::SigCoeffGroup[m_chType]( sigRight | sigLower );
m_gt1FlagCtxSet = Ctx::GreaterOneFlag[ ctxSet ];
m_gt2FlagCtxId = Ctx::GreaterTwoFlag( ctxSet );
m_sigCGPattern = sigRight + ( sigLower << 1 );
if( m_altResiCompId > 0 )
{
m_sigCtxSet = Ctx::SigFlag [ m_chType + 2 ];
m_gt1FlagCtxSet = Ctx::GreaterOneFlag[ m_chType + 6 ];
m_sigGroupCtxId = Ctx::SigCoeffGroup [ m_chType + 2 ]( sigRight | sigLower );
}
}
unsigned CoeffCodingContext::sigCtxId( int scanPos ) const
{
int offset = 0; // DC
if( m_SigBlockType == 0 ) // bypass
{
offset = ( m_chType == CHANNEL_TYPE_LUMA ? 27 : 15 );
}
else if( scanPos )
{
const unsigned posY = m_scanPosY[ scanPos ];
const unsigned posX = m_scanPosX[ scanPos ];
if( m_SigBlockType == 1 ) // 4x4
{
// const unsigned ctxIndMap4x4[16] = { 0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8 };
offset = ctxIndMap4x4[ ( posY << 2 ) + posX ];
}
else
{
int cnt = 0;
switch( m_sigCGPattern )
{
case 0:
{
unsigned posIS = ( posX & 3 ) + ( posY & 3 );
cnt = ( posIS >= 3 ? 0 : posIS >= 1 ? 1 : 2 );
}
break;
case 1:
{
unsigned posIS = ( posY & 3 );
cnt = ( posIS >= 2 ? 0 : posIS >= 1 ? 1 : 2 );
}
break;
case 2:
{
unsigned posIS = ( posX & 3 );
cnt = ( posIS >= 2 ? 0 : posIS >= 1 ? 1 : 2 );
}
break;
case 3:
{
cnt = 2;
}
break;
default:
THROW( "sig pattern must be in range [0;3]" );
}
offset = ( m_chType == CHANNEL_TYPE_LUMA && ( posX > 3 || posY > 3 ) ? 3 : 0 ) + cnt;
if( m_SigBlockType == 2 ) // 8x8
{
offset += ( m_scanType != SCAN_DIAG && m_chType == CHANNEL_TYPE_LUMA ? 15 : 9 );
}
else // NxN
{
offset += ( m_chType == CHANNEL_TYPE_LUMA ? 21 : 12 );
}
}
}
return m_sigCtxSet( offset );
}
unsigned DeriveCtx::CtxCUsplit( const CodingStructure& cs, Partitioner& partitioner )
{
auto adPartitioner = dynamic_cast<AdaptiveDepthPartitioner*>( &partitioner );
if( !adPartitioner )
{
return 0;
}
const Position pos = partitioner.currArea().blocks[cs.chType];
const unsigned curSliceIdx = cs.slice->getIndependentSliceIdx();
const unsigned curTileIdx = cs.picture->tileMap->getTileIdxMap( partitioner.currArea().lumaPos() );
unsigned ctxId = 0;
// get left depth
const CodingUnit* cuLeft = cs.getCURestricted( pos.offset( -1, 0 ), curSliceIdx, curTileIdx, cs.chType );
ctxId = ( cuLeft && cuLeft->qtDepth > partitioner.currQtDepth ) ? 1 : 0;
// get above depth
const CodingUnit* cuAbove = cs.getCURestricted( pos.offset( 0, -1 ), curSliceIdx, curTileIdx, cs.chType );
ctxId += ( cuAbove && cuAbove->qtDepth > partitioner.currQtDepth ) ? 1 : 0;
if( cs.sps->getSpsNext().getUseLargeCTU() )
{
unsigned minDepth = 0;
unsigned maxDepth = 0;
adPartitioner->setMaxMinDepth( minDepth, maxDepth, cs );
if( partitioner.currDepth < minDepth )
{
ctxId = 3;
}
else if( partitioner.currDepth >= maxDepth + 1 )
{
ctxId = 4;
}
}
return ctxId;
}
unsigned DeriveCtx::CtxQtCbf( const ComponentID compID, const unsigned trDepth )
{
if( isChroma( compID ) )
{
return trDepth;
}
else
{
return ( trDepth == 0 ? 1 : 0 );
}
}
unsigned DeriveCtx::CtxInterDir( const PredictionUnit& pu )
{
if( pu.cs->sps->getSpsNext().getUseLargeCTU() )
{
if( pu.cs->pcv->rectCUs )
{
return Clip3( 0, 3, 7 - ( ( g_aucLog2[pu.lumaSize().width] + g_aucLog2[pu.lumaSize().height] + 1 ) >> 1 ) ); // VG-ASYMM DONE
}
return Clip3( 0, 3, 6 - g_aucLog2[pu.cu->lumaSize().width] );
}
return pu.cu->qtDepth;
}
unsigned DeriveCtx::CtxAffineFlag( const CodingUnit& cu )
{
const CodingStructure *cs = cu.cs;
unsigned ctxId = 0;
const CodingUnit *cuLeft = cs->getCURestricted(cu.lumaPos().offset(-1, 0), cu);
ctxId = (cuLeft && cuLeft->affine) ? 1 : 0;
const CodingUnit *cuAbove= cs->getCURestricted(cu.lumaPos().offset(0, -1), cu);
ctxId += (cuAbove && cuAbove->affine) ? 1 : 0;
return ctxId;
}
unsigned DeriveCtx::CtxSkipFlag( const CodingUnit& cu )
{
const CodingStructure *cs = cu.cs;
unsigned ctxId = 0;
// Get BCBP of left PU
const CodingUnit *cuLeft = cs->getCURestricted(cu.lumaPos().offset(-1, 0), cu);
ctxId = (cuLeft && cuLeft->skip) ? 1 : 0;
// Get BCBP of above PU
const CodingUnit *cuAbove= cs->getCURestricted(cu.lumaPos().offset(0, -1), cu);
ctxId += (cuAbove && cuAbove->skip) ? 1 : 0;
return ctxId;
}
unsigned DeriveCtx::CtxIMVFlag( const CodingUnit& cu )
{
const CodingStructure *cs = cu.cs;
unsigned ctxId = 0;
// Get BCBP of left PU
const CodingUnit *cuLeft = cs->getCURestricted(cu.lumaPos().offset(-1, 0), cu);
ctxId = ( cuLeft && cuLeft->imv ) ? 1 : 0;
// Get BCBP of above PU
const CodingUnit *cuAbove = cs->getCURestricted(cu.lumaPos().offset(0, -1), cu);
ctxId += ( cuAbove && cuAbove->imv ) ? 1 : 0;
return ctxId;
}
unsigned DeriveCtx::CtxBTsplit(const CodingStructure& cs, Partitioner& partitioner)
{
const Position pos = partitioner.currArea().blocks[cs.chType];
const unsigned curSliceIdx = cs.slice->getIndependentSliceIdx();
const unsigned curTileIdx = cs.picture->tileMap->getTileIdxMap( pos );
unsigned ctx = 0;
const CodingUnit *cuLeft = cs.getCURestricted( pos.offset( -1, 0 ), curSliceIdx, curTileIdx, cs.chType );
const CodingUnit *cuAbove = cs.getCURestricted( pos.offset( 0, -1 ), curSliceIdx, curTileIdx, cs.chType );
{
const unsigned currDepth = partitioner.currQtDepth * 2 + partitioner.currBtDepth;
if( cuLeft ) ctx += ( ( 2 * cuLeft->qtDepth + cuLeft->btDepth ) > currDepth ? 1 : 0 );
if( cuAbove ) ctx += ( ( 2 * cuAbove->qtDepth + cuAbove->btDepth ) > currDepth ? 1 : 0 );
}
return ctx;
}
unsigned DeriveCtx::CtxFrucFlag( const PredictionUnit& pu )
{
unsigned ctxId = 0;
const CodingStructure &cs = *pu.cs;
const Position pos = pu.lumaPos();
const PredictionUnit *puLeft = cs.getPURestricted( pos.offset( -1, 0 ), pu );
ctxId = ( puLeft ) ? puLeft->frucMrgMode > 0 : 0;
const PredictionUnit *puAbove = cs.getPURestricted( pos.offset( 0, -1 ), pu );
ctxId += ( puAbove ) ? puAbove->frucMrgMode > 0 : 0;
return ctxId;
}
unsigned DeriveCtx::CtxFrucMode( const PredictionUnit& pu )
{
unsigned ctxId = 0;
const CodingStructure &cs = *pu.cs;
const Position pos = pu.lumaPos();
const PredictionUnit *puLeft = cs.getPURestricted( pos.offset( -1, 0 ), pu );
ctxId = ( puLeft ) ? puLeft->frucMrgMode == FRUC_MERGE_BILATERALMV : 0;
const PredictionUnit *puAbove = cs.getPURestricted( pos.offset( 0, -1 ), pu );
ctxId += ( puAbove ) ? puAbove->frucMrgMode == FRUC_MERGE_BILATERALMV : 0;
return ctxId;
}
Void MergeCtx::setMergeInfo( PredictionUnit& pu, int candIdx )
{
CHECK( candIdx >= numValidMergeCand, "Merge candidate does not exist" );
pu.mergeFlag = true;
pu.interDir = interDirNeighbours[candIdx];
pu.mergeIdx = candIdx;
pu.mergeType = mrgTypeNeighnours[candIdx];
pu.mv [REF_PIC_LIST_0] = mvFieldNeighbours[(candIdx << 1) + 0].mv;
pu.mv [REF_PIC_LIST_1] = mvFieldNeighbours[(candIdx << 1) + 1].mv;
pu.mvd [REF_PIC_LIST_0] = Mv();
pu.mvd [REF_PIC_LIST_1] = Mv();
pu.refIdx [REF_PIC_LIST_0] = mvFieldNeighbours[( candIdx << 1 ) + 0].refIdx;
pu.refIdx [REF_PIC_LIST_1] = mvFieldNeighbours[( candIdx << 1 ) + 1].refIdx;
pu.mvpIdx [REF_PIC_LIST_0] = NOT_VALID;
pu.mvpIdx [REF_PIC_LIST_1] = NOT_VALID;
pu.mvpNum [REF_PIC_LIST_0] = NOT_VALID;
pu.mvpNum [REF_PIC_LIST_1] = NOT_VALID;
if( pu.lumaSize() == pu.cu->lumaSize() )
{
pu.cu->LICFlag = ( pu.cs->slice->getUseLIC() ? LICFlags[candIdx] : false );
}
}
| 37.940299
| 168
| 0.621052
|
theambient
|
eeb16b553883c3e711070e8293e2d53f7dae71d6
| 288
|
hpp
|
C++
|
src/PointwiseFunctions/AnalyticSolutions/NewtonianEuler/Solutions.hpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | 117
|
2017-04-08T22:52:48.000Z
|
2022-03-25T07:23:36.000Z
|
src/PointwiseFunctions/AnalyticSolutions/NewtonianEuler/Solutions.hpp
|
GitHimanshuc/spectre
|
4de4033ba36547113293fe4dbdd77591485a4aee
|
[
"MIT"
] | 3,177
|
2017-04-07T21:10:18.000Z
|
2022-03-31T23:55:59.000Z
|
src/PointwiseFunctions/AnalyticSolutions/NewtonianEuler/Solutions.hpp
|
geoffrey4444/spectre
|
9350d61830b360e2d5b273fdd176dcc841dbefb0
|
[
"MIT"
] | 85
|
2017-04-07T19:36:13.000Z
|
2022-03-01T10:21:00.000Z
|
// Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
namespace NewtonianEuler {
/*!
* \ingroup AnalyticSolutionsGroup
* \brief Holds classes implementing a solution to the Newtonian Euler system.
*/
namespace Solutions {}
} // namespace NewtonianEuler
| 22.153846
| 78
| 0.756944
|
macedo22
|
eeb2595c15e215af9d108f10e63e0a2a7aca8c70
| 8,829
|
cpp
|
C++
|
jerome/npc/factories/WeightingFactory.cpp
|
leuski-ict/jerome
|
6141a21c50903e98a04c79899164e7d0e82fe1c2
|
[
"Apache-2.0"
] | 3
|
2018-06-11T10:48:54.000Z
|
2021-05-30T07:10:15.000Z
|
jerome/npc/factories/WeightingFactory.cpp
|
leuski-ict/jerome
|
6141a21c50903e98a04c79899164e7d0e82fe1c2
|
[
"Apache-2.0"
] | null | null | null |
jerome/npc/factories/WeightingFactory.cpp
|
leuski-ict/jerome
|
6141a21c50903e98a04c79899164e7d0e82fe1c2
|
[
"Apache-2.0"
] | null | null | null |
//
// WeightingFactory.cpp
//
// Created by Anton Leuski on 9/1/15.
// Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved.
//
// This file is part of Jerome.
//
// 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 <jerome/type/Record.hpp>
#include <jerome/ir/rm/weighting.hpp>
#include <jerome/ir/rm/AnyWeighting.hpp>
#include <jerome/ir/rm/weighting/query/jelinek_mercer.hpp>
#include <jerome/ir/rm/weighting/document/cross_entropy_jelinek_mercer.hpp>
#include "WeightingFactory.hpp"
namespace jerome {
namespace npc {
namespace detail {
struct SubWeightingParsingVisitor
: public Record::Visitor
{
String weightingName;
SubWeightingParsingVisitor(const String& inDefaultWeightingName)
: weightingName(inDefaultWeightingName)
{
}
using Record::Visitor::operator ();
void operator () (const String& inKey, const String& inValue)
{
if (inKey == ir::rm::weighting::Weighting::NAME_KEY) {
weightingName = inValue;
}
}
};
struct WeightingParsingVisitor
: public Record::Visitor
{
std::vector<String> fieldName;
String weightingName;
String defaultFieldName;
using Record::Visitor::operator ();
WeightingParsingVisitor(const String& inDefaultWeightingName,
const String& inDefaultFieldName)
: weightingName(inDefaultWeightingName)
, defaultFieldName(inDefaultFieldName)
{
}
void operator () (const String& inKey, const String& inValue)
{
if (inKey == ir::rm::weighting::Weighting::NAME_KEY) {
weightingName = inValue;
}
}
void operator () (const String& inKey, const Record& inValue)
{
if (inKey == ir::rm::weighting::Weighting::SUB_WEIGHTING_KEY) {
SubWeightingParsingVisitor visitor(defaultFieldName);
inValue.visit(visitor);
fieldName.push_back(visitor.weightingName);
}
}
template <typename Object, typename DW, template <typename ...> class W>
inline Result<Object> makeWeighting(const String& inProviderID)
{
switch (fieldName.size()) {
case 1: return Object::template make<W>(inProviderID, weightingName,
DW(fieldName[0]));
case 2: return Object::template make<W>(inProviderID, weightingName,
DW(fieldName[0]), DW(fieldName[1]));
case 3: return Object::template make<W>(inProviderID, weightingName,
DW(fieldName[0]), DW(fieldName[1]), DW(fieldName[2]));
case 4: return Object::template make<W>(inProviderID, weightingName,
DW(fieldName[0]), DW(fieldName[1]), DW(fieldName[2]),
DW(fieldName[3]));
case 5: return Object::template make<W>(inProviderID, weightingName,
DW(fieldName[0]), DW(fieldName[1]), DW(fieldName[2]),
DW(fieldName[3]), DW(fieldName[4]));
default:
return Error("too many fields when creating a weighting: "
+ std::to_string(fieldName.size()));
}
}
template <typename Object, typename DW, template <typename ...> class W>
inline Result<Object> parseRecord(const String& inProviderID)
{
if (fieldName.size() == 0) {
fieldName.push_back("unigram");
}
return makeWeighting<Object, DW, W>(inProviderID);
}
};
struct DefaultDocumentWeightingProvider
: public AnswerWeightingFactory::provider_type
{
static constexpr const char* IDENTIFIER =
"jerome.weighting.document.addCrossEntropyJelinekMercer";
Result<AnswerWeightingFactory::object_type> provide(
const Record& inRecord) override
{
WeightingParsingVisitor visitor("answer", "unigram");
inRecord.visit(visitor);
return visitor.parseRecord<AnswerWeightingFactory::object_type,
ir::rm::weighting::document::CrossEntropyJelinekMercer,
ir::rm::weighting::document::AddDocumentProbabilities>(IDENTIFIER);
}
};
struct DefaultQueryWeightingProvider
: public QuestionWeightingFactory::provider_type
{
static constexpr const char* IDENTIFIER =
"jerome.weighting.query.multiplyJelinekMercer";
Result<QuestionWeightingFactory::object_type> provide(
const Record& inRecord) override
{
WeightingParsingVisitor visitor("question", "unigram");
inRecord.visit(visitor);
return visitor.parseRecord<QuestionWeightingFactory::object_type,
jerome::ir::rm::weighting::query::JelinekMercer,
ir::rm::weighting::query::MultiplyQueryProbabilities>(IDENTIFIER);
}
};
}
AnswerWeightingFactory::AnswerWeightingFactory()
{
registerProviderClass<detail::DefaultDocumentWeightingProvider>();
using namespace jerome::ir::rm::weighting;
// text unigram
registerModel("unigram", {
AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultDocumentWeightingProvider::IDENTIFIER
, Weighting::IDENTIFIER_KEY, document::AddDocumentProbabilitiesConst::IDENTIFIER
, Weighting::NAME_KEY, "answer"
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "unigram"
}
});
registerModel("bigram", {
AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultDocumentWeightingProvider::IDENTIFIER
, Weighting::IDENTIFIER_KEY, document::AddDocumentProbabilitiesConst::IDENTIFIER
, Weighting::NAME_KEY, "answer"
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "unigram"
}
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "bigram"
}
});
registerModel("unigram+id", {
AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultDocumentWeightingProvider::IDENTIFIER
, Weighting::IDENTIFIER_KEY, document::AddDocumentProbabilitiesConst::IDENTIFIER
, Weighting::NAME_KEY, "answer"
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "unigram"
}
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, document::CrossEntropyJelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "id"
}
});
setDefaultModelKey("unigram");
}
QuestionWeightingFactory::QuestionWeightingFactory()
{
registerProviderClass<detail::DefaultQueryWeightingProvider>();
using namespace jerome::ir::rm::weighting;
// text unigram
registerModel("unigram", {
AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultQueryWeightingProvider::IDENTIFIER
, Weighting::IDENTIFIER_KEY, query::MultiplyQueryProbabilitiesConst::IDENTIFIER
, Weighting::NAME_KEY, "question"
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, query::JelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "unigram"
}
});
// text unigram
registerModel("bigram", {
AnswerWeightingFactory::PROVIDER_KEY, detail::DefaultQueryWeightingProvider::IDENTIFIER
, Weighting::IDENTIFIER_KEY, query::MultiplyQueryProbabilitiesConst::IDENTIFIER
, Weighting::NAME_KEY, "question"
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, query::JelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "unigram"
}
, Weighting::SUB_WEIGHTING_KEY, Record {
Weighting::IDENTIFIER_KEY, query::JelinekMercer::IDENTIFIER
, Weighting::NAME_KEY, "bigram"
}
});
setDefaultModelKey("unigram");
}
}
}
| 35.175299
| 98
| 0.643901
|
leuski-ict
|
eeb657c35074beacab88d2f7c50b17d4655916c3
| 179
|
c++
|
C++
|
extra/xftp/xftp-client/supercontrol_exit.c++
|
maciek-27/Rgp
|
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
|
[
"MIT"
] | null | null | null |
extra/xftp/xftp-client/supercontrol_exit.c++
|
maciek-27/Rgp
|
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
|
[
"MIT"
] | null | null | null |
extra/xftp/xftp-client/supercontrol_exit.c++
|
maciek-27/Rgp
|
d28b5522e640e4c7b951f6861d97cbe52b0a35c9
|
[
"MIT"
] | null | null | null |
#include "supercontrol.h++"
#include <cstdlib>
#include "client.h++"
#include "superduperclient.h++"
void xftpclient::SuperControl::Exit (Tokenizer & optns)
{
app.Exit();
}
| 14.916667
| 57
| 0.687151
|
maciek-27
|
eeb7d5bb63d4585f6319ba12baf25c3fbaf09b13
| 1,945
|
cpp
|
C++
|
aws-cpp-sdk-appflow/source/model/UpsolverS3OutputFormatConfig.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2021-12-06T20:36:35.000Z
|
2021-12-06T20:36:35.000Z
|
aws-cpp-sdk-appflow/source/model/UpsolverS3OutputFormatConfig.cpp
|
perfectrecall/aws-sdk-cpp
|
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
|
[
"Apache-2.0"
] | 1
|
2022-01-03T23:59:37.000Z
|
2022-01-03T23:59:37.000Z
|
aws-cpp-sdk-appflow/source/model/UpsolverS3OutputFormatConfig.cpp
|
ravindra-wagh/aws-sdk-cpp
|
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
|
[
"Apache-2.0"
] | 1
|
2021-12-30T04:25:33.000Z
|
2021-12-30T04:25:33.000Z
|
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/appflow/model/UpsolverS3OutputFormatConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Appflow
{
namespace Model
{
UpsolverS3OutputFormatConfig::UpsolverS3OutputFormatConfig() :
m_fileType(FileType::NOT_SET),
m_fileTypeHasBeenSet(false),
m_prefixConfigHasBeenSet(false),
m_aggregationConfigHasBeenSet(false)
{
}
UpsolverS3OutputFormatConfig::UpsolverS3OutputFormatConfig(JsonView jsonValue) :
m_fileType(FileType::NOT_SET),
m_fileTypeHasBeenSet(false),
m_prefixConfigHasBeenSet(false),
m_aggregationConfigHasBeenSet(false)
{
*this = jsonValue;
}
UpsolverS3OutputFormatConfig& UpsolverS3OutputFormatConfig::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("fileType"))
{
m_fileType = FileTypeMapper::GetFileTypeForName(jsonValue.GetString("fileType"));
m_fileTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("prefixConfig"))
{
m_prefixConfig = jsonValue.GetObject("prefixConfig");
m_prefixConfigHasBeenSet = true;
}
if(jsonValue.ValueExists("aggregationConfig"))
{
m_aggregationConfig = jsonValue.GetObject("aggregationConfig");
m_aggregationConfigHasBeenSet = true;
}
return *this;
}
JsonValue UpsolverS3OutputFormatConfig::Jsonize() const
{
JsonValue payload;
if(m_fileTypeHasBeenSet)
{
payload.WithString("fileType", FileTypeMapper::GetNameForFileType(m_fileType));
}
if(m_prefixConfigHasBeenSet)
{
payload.WithObject("prefixConfig", m_prefixConfig.Jsonize());
}
if(m_aggregationConfigHasBeenSet)
{
payload.WithObject("aggregationConfig", m_aggregationConfig.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace Appflow
} // namespace Aws
| 21.373626
| 90
| 0.752699
|
perfectrecall
|
eeb8c16b1ee43e8392f2e79fdc2253b928372354
| 8,661
|
cc
|
C++
|
src/DAF/AE/AESender.cc
|
Miguel-A/RinaSim
|
70ff28dc05e8250ca28c438290cf8c08f8a94a23
|
[
"MIT"
] | 1
|
2016-02-24T19:31:04.000Z
|
2016-02-24T19:31:04.000Z
|
src/DAF/AE/AESender.cc
|
Miguel-A/RinaSim
|
70ff28dc05e8250ca28c438290cf8c08f8a94a23
|
[
"MIT"
] | null | null | null |
src/DAF/AE/AESender.cc
|
Miguel-A/RinaSim
|
70ff28dc05e8250ca28c438290cf8c08f8a94a23
|
[
"MIT"
] | null | null | null |
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Brno University of Technology, PRISTINE project
//
// 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 "AESender.h"
Define_Module(AESender);
PingMsg::PingMsg(){
pingAt = simTime();
}
PongMsg::PongMsg(simtime_t _pingAt){
pingAt = _pingAt;
pongAt = simTime();
}
AESender::AESender() : AE() {
S_TIM_START = "StartCommunication";
S_TIM_COM = "MakeCommunication";
S_TIM_STOP = "StopCommunication";
S_PAR_START = "startAt";
S_PAR_STOP = "stopAt";
S_PAR_SEND = "sendAfter";
S_PAR_DSTAPNAME = "dstApName";
S_PAR_DSTAPINSTANCE = "dstApInstance";
S_PAR_DSTAENAME = "dstAeName";
S_PAR_DSTAEINSTANCE = "dstAeInstance";
S_PAR_RATE = "rate";
S_PAR_RATE_VAR = "ratevar";
S_PAR_SIZE = "size";
S_PAR_SIZE_VAR = "sizevar";
S_MSG_PING = "PING-";
S_PAR_PING = "pingAt";
S_VAL_MODULEPATH = "getFullPath()";
}
AESender::~AESender() {
connectionState = NIL;
FlowObject = NULL;
Irm = NULL;
Cdap = NULL;
}
void AESender::prepareAllocateRequest() {
//Schedule AllocateRequest
cMessage* m1 = new cMessage(S_TIM_START);
scheduleAt(startAt, m1);
}
void AESender::prepareDeallocateRequest() {
//Schedule DeallocateRequest
cMessage* m3 = new cMessage(S_TIM_STOP);
scheduleAt(stopAt, m3);
}
void AESender::initialize()
{
//Init pointers
initPointers();
//Source info
initNamingInfo();
//Setup signals
initSignalsAndListeners();
//Init QoSRequirements
initQoSRequiremets();
//Timers
startAt = simTime() + par(S_PAR_START);
stopAt = simTime() + par(S_PAR_STOP);
sendAfter = par(S_PAR_SEND);
if(sendAfter<1){
sendAfter = 1;
}
//Time between PDUS (s)
rate = par(S_PAR_RATE).doubleValue();
ratevar = par(S_PAR_RATE_VAR).doubleValue();
//SIZE of PDU
size = par(S_PAR_SIZE);
sizevar = par(S_PAR_SIZE_VAR);
//Destination for flow
dstApName = this->par(S_PAR_DSTAPNAME).stringValue();
dstApInstance = this->par(S_PAR_DSTAPINSTANCE).stringValue();
dstAeName = this->par(S_PAR_DSTAENAME).stringValue();
dstAeInstance = this->par(S_PAR_DSTAEINSTANCE).stringValue();
//Schedule AllocateRequest
if (startAt > 0)
prepareAllocateRequest();
//Schedule DeallocateRequest
/*
if (stopAt > 0)
prepareDeallocateRequest();
*/
myPath = this->getFullPath();
send = 0;
received = 0;
pingreceived = 0;
sendSize = 0;
receivedSize = 0;
pingreceivedSize = 0;
minDelay = 999;
maxDelay = -1;
firstR = -1;
lastR = 0;
recTimes = par("recTimes").boolValue();
pduburst = par("pduburst").longValue();
if(pduburst<1) { pduburst = 1; }
//Watchers
WATCH(FlowObject);
WATCH(send);
WATCH(received);
WATCH(pingreceived);
WATCH(sendSize);
WATCH(receivedSize);
WATCH(pingreceivedSize);
WATCH(minDelay);
WATCH(maxDelay);
}
void AESender::finish()
{
if(par("printAtEnd").boolValue()){
EV << "At "<<this->getApni()<<endl;
if(FlowObject != NULL) {
EV << "With QoS " << FlowObject->getConId().getQoSId() <<endl;
}
EV << "send " << send << " ("<<sendSize << ")"<<endl;
// EV << "pingsRcv " << pingreceived << " ("<<pingreceivedSize << ")"<<endl;
EV << "pongsRcv " << received << " ("<<receivedSize << ")"<<endl;
EV << "delay " << minDelay << " / "<<maxDelay<<endl;
EV << "timestamps " << firstR << " -> "<<lastR<<endl;
if(recTimes){
EV << "-----------------"<<endl;
for(std::map<double, int>::iterator it = times.begin(); it!=times.end(); it++) {
EV << " " << it->first << " " << it->second <<endl;
}
EV << "-----------------"<<endl;
}
EV << "-----------------"<<endl;
}
}
void AESender::handleSelfMessage(cMessage *msg) {
//EV << flows.back().info() << endl;
if ( !strcmp(msg->getName(), S_TIM_START) ) {
//FIXME: Vesely - last flow in a list?!
//Flow
APNamingInfo src = this->getApni();
APNamingInfo dst = APNamingInfo( APN(this->dstApName), this->dstApInstance,
this->dstAeName, this->dstAeInstance);
FlowObject = new Flow(src, dst);
FlowObject->setQosRequirements(this->getQoSRequirements());
//Insert it to the Flows ADT
insertFlow();
sendAllocationRequest(FlowObject);
//Schedule ComRequest
cMessage* m = new cMessage(S_TIM_COM);
scheduleAt(simTime()+sendAfter+uniform(0,rate), m);
}
else if ( !strcmp(msg->getName(), S_TIM_STOP) ) {
sendDeallocationRequest(FlowObject);
}
else if ( !strcmp(msg->getName(), S_TIM_COM) ) {
if(stopAt > simTime()){
int tburst = intuniform(1,pduburst);
double msgWait = tburst*rate;
for(int i = 0; i < tburst; i++){
int msgSize = size + intuniform(-sizevar,sizevar);
msgWait += uniform(-ratevar,ratevar);
//Create PING messsage
CDAP_M_Read* ping = new PingMsg();
ping->setByteLength(msgSize);
//Send message
sendData(FlowObject, ping);
send++;
sendSize += msgSize;
}
//Schedule ComRequest
cMessage* m = new cMessage(S_TIM_COM);
scheduleAt(simTime()+msgWait, m);
}
}
else
EV << this->getFullPath() << " received unknown self-message " << msg->getName();
delete(msg);
}
void AESender::handleMessage(cMessage *msg)
{
if ( msg->isSelfMessage() )
this->handleSelfMessage(msg);
}
void AESender::processMRead(CDAPMessage* msg) {
PingMsg* ping = check_and_cast<PingMsg*>(msg);
if(ping){
PongMsg* pong = new PongMsg(ping->pingAt);
pong->setByteLength(msg->getByteLength());
sendData(FlowObject, pong);
/*
pingreceived++;
pingreceivedSize += msg->getByteLength();
simtime_t delay = simTime() - ping->pingAt;
if(minDelay>delay){
minDelay = delay;
}
if(maxDelay<delay){
maxDelay = delay;
}
if(firstR<0) {
firstR = simTime();
}
lastR = simTime();
*/
}
}
void AESender::processMReadR(CDAPMessage* msg) {
PongMsg* pong = check_and_cast<PongMsg*>(msg);
if(pong){
received++;
receivedSize += msg->getByteLength();
simtime_t delay = simTime() - pong->pingAt;
if(minDelay>delay){
minDelay = delay;
}
if(maxDelay<delay){
maxDelay = delay;
}
if(firstR<0) {
firstR = simTime();
}
lastR = simTime();
if(recTimes){
double dl = dround(delay.dbl(), 3);
times[dl]++;
}
}
}
double AESender::dround(double a, int ndigits) {
int exp_base10 = round(log10(a));
double man_base10 = a*pow(10.0,-exp_base10);
double factor = pow(10.0,-ndigits+1);
double truncated_man_base10 = man_base10 - fmod(man_base10,factor);
double rounded_remainder = fmod(man_base10,factor)/factor;
rounded_remainder = rounded_remainder > 0.5 ? 1.0*factor : 0.0;
return (truncated_man_base10 + rounded_remainder)*pow(10.0,exp_base10) ;
}
| 29.161616
| 92
| 0.583882
|
Miguel-A
|
eeb910648792ca5927ca049160a7f2e931de0bfc
| 3,374
|
cpp
|
C++
|
src/analyze/anaylzeMZ.cpp
|
Alex4386/pe-parser
|
45cf63e923adc66e914f913c0094ad3615e126c5
|
[
"MIT-0"
] | 5
|
2019-08-20T14:04:32.000Z
|
2020-10-06T10:32:52.000Z
|
src/analyze/anaylzeMZ.cpp
|
Alex4386/pe-parser
|
45cf63e923adc66e914f913c0094ad3615e126c5
|
[
"MIT-0"
] | 1
|
2019-06-11T03:35:13.000Z
|
2019-06-11T06:31:13.000Z
|
src/analyze/anaylzeMZ.cpp
|
Alex4386/pe-parser
|
45cf63e923adc66e914f913c0094ad3615e126c5
|
[
"MIT-0"
] | 1
|
2019-05-27T21:21:32.000Z
|
2019-05-27T21:21:32.000Z
|
#include "../common/common.hpp"
#include "../parser/parser.hpp"
#include "../common/options.hpp"
#include "analyze.hpp"
int analyzeMZ(MZParser mzParser, CommandLineOptions options) {
MZHeader parsedHeader = mzParser.mzHeader;
if (!options.outputAsJson) {
analyzeMZTerminal(parsedHeader);
} else {
analyzeMZJson(parsedHeader);
}
return 0;
}
int analyzeMZTerminal(MZHeader parsedHeader) {
std::cout << "MZ Header:" << std::endl;
std::cout << " Page Count: " << parsedHeader.howManyPages << std::endl;
std::cout << " Last Page Size: " << decimalWithHex(parsedHeader.lastPageBytes, "bytes") << std::endl;
std::cout << " Relocations: " << parsedHeader.relocations << std::endl;
std::cout << " Header Size: " << decimalWithHex(parsedHeader.headerSize, "bytes") << std::endl;
std::cout << " Minimum Memory: " << decimalWithHex(parsedHeader.minMemory, "bytes") << std::endl;
std::cout << " Maximum Memory: " << decimalWithHex(parsedHeader.maxMemory, "bytes") << std::endl;
std::cout << " Init StackSegment: " << decimalWithHex(parsedHeader.initStackSegment) << std::endl;
std::cout << " Init StackPointer: " << decimalWithHex(parsedHeader.initStackPointer) << std::endl;
std::cout << " Checksum: " << decimalWithHex(parsedHeader.checksum) << std::endl;
std::cout << " Init IP: " << outputHex(parsedHeader.initInstructionPointer) << std::endl;
std::cout << " Init CS: " << outputHex(parsedHeader.initCodeSegment) << std::endl;
std::cout << " Reloc. Table Addr: " << outputHex(parsedHeader.relocationTableAddress) << std::endl;
std::cout << " Overlay counts: " << outputHex(parsedHeader.howManyOverlays) << std::endl;
std::cout << " Oem ID: " << outputHex(parsedHeader.howManyOverlays) << std::endl;
std::cout << " Oem Info: " << outputHex(parsedHeader.howManyOverlays) << std::endl;
std::cout << " PE Header Address: " << outputHex(parsedHeader.peHeaderPointer) << std::endl;
std::cout << "" << std::endl;
std::cout << "MZ Header Extra:" << std::endl;
std::cout << " Entrypoint: " << outputHex(parsedHeader.headerSize * 0x10) << std::endl;
return 0;
}
int analyzeMZJson(MZHeader parsedHeader) {
std::cout << "\"mzHeader\": {";
std::cout << "\"pageCount\": " << parsedHeader.howManyPages << ", ";
std::cout << "\"lastPageSize\": " << parsedHeader.lastPageBytes << ", ";
std::cout << "\"relocationCount\": " << parsedHeader.relocations << ", ";
std::cout << "\"headerSize\": " << parsedHeader.headerSize << ", ";
std::cout << "\"minMemory\": " << parsedHeader.minMemory << ", ";
std::cout << "\"maxMemory\": " << parsedHeader.maxMemory << ", ";
std::cout << "\"initSS\": " << parsedHeader.initStackSegment << ", ";
std::cout << "\"initSP\": " << parsedHeader.initStackPointer << ", ";
std::cout << "\"checksum\": " << parsedHeader.checksum << ", ";
std::cout << "\"initIP\": " << parsedHeader.initInstructionPointer << ", ";
std::cout << "\"initCS\": " << parsedHeader.initCodeSegment << ", ";
std::cout << "\"relocationTableAddress\": " << parsedHeader.relocationTableAddress << ", ";
std::cout << "\"overlayCount\": " << parsedHeader.howManyOverlays << ", ";
std::cout << "\"oemId\": " << parsedHeader.oemId << ", ";
std::cout << "\"oemInfo\": " << parsedHeader.oemInfo << ", ";
std::cout << "\"peHeaderPointer\": " << parsedHeader.oemInfo << "} ";
return 0;
}
| 52.71875
| 104
| 0.633669
|
Alex4386
|
eebd14c6097aa7f5e7970c3f16d4346041f9694d
| 5,459
|
cpp
|
C++
|
src_lib/csutil.cpp
|
serjinio/thesis_ana
|
633a61dee56cf2cf4dcb67997ac87338537fb578
|
[
"MIT"
] | null | null | null |
src_lib/csutil.cpp
|
serjinio/thesis_ana
|
633a61dee56cf2cf4dcb67997ac87338537fb578
|
[
"MIT"
] | null | null | null |
src_lib/csutil.cpp
|
serjinio/thesis_ana
|
633a61dee56cf2cf4dcb67997ac87338537fb578
|
[
"MIT"
] | null | null | null |
#include <csutil.hpp>
double
s13::ana::lab2cm_solid_angle_factor(double proton_cm_theta_rad,
DatasetType ds_type) {
const double p_he4_gamma_cm = 1.12654467394258;
const double p_he6_gamma_cm = 1.14966481938141;
double gamma = p_he4_gamma_cm;
if (ds_type == DatasetType::he6 || ds_type == DatasetType::carbon) {
gamma = p_he6_gamma_cm;
} else if (ds_type == DatasetType::he4) {
gamma = p_he4_gamma_cm;
} else {
throw std::invalid_argument("Invalid dataset type!");
}
double theta = proton_cm_theta_rad;
double num = gamma * std::abs(std::cos(theta) - 1);
double denom = std::pow(std::sin(theta), 2) +
std::pow(gamma, 2) * std::pow(1 - std::cos(theta), 2);
denom = std::pow(denom, 3./2);
return num / denom;
}
s13::ana::ScatteringYield
s13::ana::lab_yield_to_cm(const s13::ana::ScatteringYield& lab_yield,
DatasetType ds_type) {
misc::MessageLogger log_("lab_yield_to_cm()");
TInterpPtr angle_interp = make_lab2cm_angle_interp(ds_type);
const double lab_theta_min =
(lab_yield.GetBinArg(0) - lab_yield.GetBinWidth() / 2);
const double lab_theta_max =
(lab_yield.GetBinArg(lab_yield.GetBinsNumber() - 1)
+ lab_yield.GetBinWidth() / 2);
// const double cm_theta_max = lab_theta_angle_to_cm(lab_theta_min);
// const double cm_theta_min = lab_theta_angle_to_cm(lab_theta_max);
const double cm_theta_max = angle_interp->Eval(lab_theta_min);
const double cm_theta_min = angle_interp->Eval(lab_theta_max);
log_.debug("CM angular range: [%.1f; %.1f]", cm_theta_min, cm_theta_max);
ScatteringYield cm_yield(lab_yield.GetBinsNumber(), cm_theta_min, cm_theta_max);
log_.debug("Converting yield...");
for (int i = cm_yield.GetBinsNumber() - 1; i >= 0; --i) {
// Double_t cm_angle = lab_theta_angle_to_cm(lab_yield.GetBinArg(i));
Double_t cm_angle = angle_interp->Eval(lab_yield.GetBinArg(i));
cm_yield.SetBinValue(cm_angle, lab_yield.GetBinValue(i));
cm_yield.SetBinError(cm_angle, lab_yield.GetBinError(i));
}
return cm_yield;
}
s13::ana::TInterpPtr
s13::ana::make_lab2cm_angle_interp(DatasetType ds_type) {
std::string fname = ds_type == DatasetType::he4
? "data/p_he4_recoil_A_lab_A_cm.csv" : "data/p_he6_recoil_A_lab_A_cm.csv";
auto csv_data = io::load_csv(fname, 2, 2);
assert (csv_data.size() == 2 && "Invalid number of columns in input file.");
std::vector<double> a_cm, a_lab;
for (size_t i = 0; i < csv_data[0].size(); i++) {
a_lab.push_back(csv_data[0][i]);
a_cm.push_back(csv_data[1][i]);
}
TInterp* interp = new TInterp{static_cast<unsigned int>(a_lab.size()),
ROOT::Math::Interpolation::kLINEAR};
interp->SetData(a_lab, a_cm);
return TInterpPtr{interp};
}
/*
Converts CS from lab to center of mass frame.
*/
s13::ana::ScatteringYield
s13::ana::lab_cs_to_cm(const s13::ana::ScatteringYield& lab_cs,
DatasetType ds_type) {
misc::MessageLogger log_("lab_cs_to_cm()");
TInterpPtr angle_interp = make_lab2cm_angle_interp(ds_type);
const double lab_theta_min =
(lab_cs.GetBinArg(0) - lab_cs.GetBinWidth() / 2);
const double lab_theta_max =
(lab_cs.GetBinArg(lab_cs.GetBinsNumber() - 1)
+ lab_cs.GetBinWidth() / 2);
// const double cm_theta_max = lab_theta_angle_to_cm(lab_theta_min);
// const double cm_theta_min = lab_theta_angle_to_cm(lab_theta_max);
const double cm_theta_max = angle_interp->Eval(lab_theta_min);
const double cm_theta_min = angle_interp->Eval(lab_theta_max);
log_.debug("CM angular range: [%.1f; %.1f]", cm_theta_min, cm_theta_max);
ScatteringYield cm_cs(lab_cs.GetBinsNumber(), cm_theta_min, cm_theta_max);
log_.debug("Converting cross-section...");
for (int i = cm_cs.GetBinsNumber() - 1; i >= 0; --i) {
int cm_cs_idx = cm_cs.GetBinsNumber() - 1 - i;
// Double_t cm_angle = lab_theta_angle_to_cm(lab_cs.GetBinArg(i));
Double_t cm_angle = angle_interp->Eval(lab_cs.GetBinArg(i));
log_.debug("\t Computing CM MS for angle: %.3f; angle in scattering "
"yield object: %.3f", cm_angle, cm_cs.GetBinArg(cm_cs_idx));
Double_t solid_angle_factor_nonrel = 1 /
(4 * TMath::Sin((cm_angle * gk_d2r) / 2));
Double_t solid_angle_factor =
lab2cm_solid_angle_factor(cm_angle * s13::gk_d2r, ds_type);
log_.debug("SA factors (rel; non-rel): %.4f, %.4f",
solid_angle_factor, solid_angle_factor_nonrel);
Double_t cm_cs_value = lab_cs.GetBinValue(i) * solid_angle_factor;
log_.debug("\t CS value in lab frame: %.3f; in CM frame: %.3f",
lab_cs.GetBinValue(i), cm_cs_value);
cm_cs.SetBinValue(cm_angle, cm_cs_value);
cm_cs.SetBinError(cm_angle, lab_cs.GetBinError(i) * solid_angle_factor);
}
return cm_cs;
}
s13::ana::ScatteringYield
s13::ana::cs_from_yields(s13::ana::ScatteringYield& yields,
s13::ana::SolidAngle& solid_angle,
double num_beam_incident,
double tgt_areal_density) {
ScatteringYield cs = yields;
for (int i = 0; i < yields.GetBinsNumber(); i++) {
double theta = yields.GetBinArg(i);
double sa = solid_angle.at(theta);
Double_t norm_factor =
1 / (num_beam_incident * tgt_areal_density * sa);
// from cm2 to barns
norm_factor *= 1e24;
// now into millibarns
norm_factor *= 1e3;
cs.ScaleBin(i, norm_factor);
}
return cs;
}
| 38.174825
| 82
| 0.680528
|
serjinio
|
eebe79c6c6f524e7f66284e31053c5b8659a7fe1
| 8,998
|
cpp
|
C++
|
SJone/firmware/lib/L0_LowLevel/source/lpc_sys.cpp
|
jpan127/RJD-MP3
|
8659a12e46021882cce6202befa59d88afe4d7c2
|
[
"MIT"
] | null | null | null |
SJone/firmware/lib/L0_LowLevel/source/lpc_sys.cpp
|
jpan127/RJD-MP3
|
8659a12e46021882cce6202befa59d88afe4d7c2
|
[
"MIT"
] | null | null | null |
SJone/firmware/lib/L0_LowLevel/source/lpc_sys.cpp
|
jpan127/RJD-MP3
|
8659a12e46021882cce6202befa59d88afe4d7c2
|
[
"MIT"
] | null | null | null |
/*
* SocialLedge.com - Copyright (C) 2013
*
* This file is part of free software framework for embedded processors.
* You can use it and/or distribute it as long as this copyright header
* remains unmodified. The code is free for personal use and requires
* permission to use in a commercial product.
*
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
* You can reach the author of this software at :
* p r e e t . w i k i @ g m a i l . c o m
*/
#include <stdio.h>
#include "lpc_sys.h"
#include "wireless.h"
#include "lpc_timers.h"
#include "io.hpp"
#include "FreeRTOS.h"
#include "task.h"
/// These bitmasks should match up with the timer MCR register to trigger interrupt upon match
enum {
mr0_mcr_for_overflow = (UINT32_C(1) << 0),
mr1_mcr_for_mesh_bckgnd_task = (UINT32_C(1) << 3),
mr2_mcr_for_ir_sensor_timeout = (UINT32_C(1) << 6),
mr3_mcr_for_watchdog_reset = (UINT32_C(1) << 9),
};
/// Periodic interrupt for mesh networking. This timer match interrupt is disabled if FreeRTOS starts to run.
#define LPC_SYS_TIME_FOR_BCKGND_TASK_US (1 * 1000)
/// Time in microseconds that will feed the watchdog, which should be roughly half of the actual watchdog reset
#define LPC_SYS_WATCHDOG_RESET_TIME_US ((SYS_CFG_WATCHDOG_TIMEOUT_MS / 2) * 1000)
/// Timer overflow interrupt will increment this upon the last UINT32 value, 16-bit is enough for many years!
static volatile uint16_t g_timer_rollover_count = 0;
/// Pointer to the timer struct based on SYS_CFG_SYS_TIMER
LPC_TIM_TypeDef *gp_timer_ptr = NULL;
extern "C" void lpc_sys_setup_system_timer(void)
{
// Note: Timer1 is required for IR sensor's decoding logic since its pin is tied to Timer1 Capture Pin
const lpc_timer_t sys_timer_source = (lpc_timer_t) SYS_CFG_SYS_TIMER;
// Get the IRQ number of the timer to enable the interrupt
const IRQn_Type timer_irq = lpc_timer_get_irq_num(sys_timer_source);
// Initialize the timer structure pointer
gp_timer_ptr = lpc_timer_get_struct(sys_timer_source);
// Setup the timer to tick with a fine-grain resolution
const uint32_t one_micro_second = 1;
lpc_timer_enable(sys_timer_source, one_micro_second);
/**
* MR0: Setup the match register to take care of the overflow.
* Upon the roll-over, we increment the roll-over count and the timer restarts from zero.
*/
gp_timer_ptr->MR0 = UINT32_MAX;
// MR1: Setup the periodic interrupt to do background processing
gp_timer_ptr->MR1 = LPC_SYS_TIME_FOR_BCKGND_TASK_US;
#if (1 == SYS_CFG_SYS_TIMER)
// MR2: IR code timeout when timer1 is used since IR receiver is tied to timer1 capture pin
gp_timer_ptr->MR2 = 0;
#else
#warning "IR receiver will not work unless SYS_CFG_SYS_TIMER uses TIMER1, so set it to 1 if possible"
#endif
/* Setup the first match interrupt to reset the watchdog */
gp_timer_ptr->MR3 = LPC_SYS_WATCHDOG_RESET_TIME_US;
// Enable the timer match interrupts
gp_timer_ptr->MCR = (mr0_mcr_for_overflow | mr1_mcr_for_mesh_bckgnd_task | mr3_mcr_for_watchdog_reset);
// Only if we have got TIMER1, we can use IR sensor timeout match interrupt
#if (1 == SYS_CFG_SYS_TIMER)
gp_timer_ptr->MCR |= (mr2_mcr_for_ir_sensor_timeout);
#endif
/* Enable the interrupt and use higher priority than other peripherals because we want
* to drive the periodic ISR above other interrupts since we reset the watchdog timer.
*/
NVIC_SetPriority(timer_irq, IP_high);
vTraceSetISRProperties(timer_irq, "AUX Timer", IP_high);
NVIC_EnableIRQ(timer_irq);
}
extern "C" uint64_t sys_get_uptime_us(void)
{
uint32_t before = 0;
uint32_t after = 0;
uint32_t rollovers = 0;
/**
* Loop until we can safely read both the rollover value and the timer value.
* When the timer rolls over, the TC value will start from zero, and the "after"
* value will be less than the before value in which case, we will loop again
* and pick up the new rollover count. This avoid critical section and simplifies
* the logic of reading higher 16-bit (roll-over) and lower 32-bit (timer value).
*/
do
{
before = gp_timer_ptr->TC;
rollovers = g_timer_rollover_count;
after = gp_timer_ptr->TC;
} while (after < before);
// each rollover is 2^32 or UINT32_MAX
return (((uint64_t)rollovers << 32) | after);
}
/**
* Actual ISR function (@see startup.cpp)
*/
#if (0 == SYS_CFG_SYS_TIMER)
extern "C" void TIMER0_IRQHandler()
#elif (1 == SYS_CFG_SYS_TIMER)
extern "C" void TIMER1_IRQHandler()
#elif (2 == SYS_CFG_SYS_TIMER)
extern "C" void TIMER2_IRQHandler()
#elif (3 == SYS_CFG_SYS_TIMER)
extern "C" void TIMER3_IRQHandler()
#else
#error "SYS_CFG_SYS_TIMER must be between 0-3 inclusively"
void TIMERX_BAD_IRQHandler()
#endif
{
enum {
timer_mr0_intr_timer_rollover = (1 << 0),
timer_mr1_intr_mesh_servicing = (1 << 1),
timer_mr2_intr_ir_sensor_timeout = (1 << 2),
timer_mr3_intr_for_watchdog_rst = (1 << 3),
timer_capt0_intr_ir_sensor_edge_time_captured = (1 << 4),
timer_capt1_intr = (1 << 5),
};
const uint32_t intr_reason = gp_timer_ptr->IR;
#if (1 == SYS_CFG_SYS_TIMER)
/* ISR for captured time of the capture input pin */
if (intr_reason & timer_capt0_intr_ir_sensor_edge_time_captured)
{
gp_timer_ptr->IR = timer_capt0_intr_ir_sensor_edge_time_captured;
// Store the IR capture time and setup timeout of the IR signal (unless we reset it again)
IS.storeIrCode(gp_timer_ptr->CR0);
gp_timer_ptr->MR2 = 10000 + gp_timer_ptr->TC;
}
/* MR2: End of IR capture (no IR capture after initial IR signal) */
else if (intr_reason & timer_mr2_intr_ir_sensor_timeout)
{
gp_timer_ptr->IR = timer_mr2_intr_ir_sensor_timeout;
IS.decodeIrCode();
}
/* MR0 is used for the timer rollover count */
else
#endif
if(intr_reason & timer_mr0_intr_timer_rollover)
{
gp_timer_ptr->IR = timer_mr0_intr_timer_rollover;
++g_timer_rollover_count;
}
else if(intr_reason & timer_mr1_intr_mesh_servicing)
{
gp_timer_ptr->IR = timer_mr1_intr_mesh_servicing;
/* FreeRTOS task is used to service the wireless_service() function, otherwise if FreeRTOS
* is not running, timer ISR will call this function to carry out mesh networking logic.
*/
if (taskSCHEDULER_RUNNING != xTaskGetSchedulerState()) {
wireless_service();
}
else {
/* Disable this timer interrupt if FreeRTOS starts to run */
gp_timer_ptr->MCR &= ~(mr1_mcr_for_mesh_bckgnd_task);
}
/* Setup the next periodic interrupt */
gp_timer_ptr->MR1 += gp_timer_ptr->TC + LPC_SYS_TIME_FOR_BCKGND_TASK_US;
}
else if (intr_reason & timer_mr3_intr_for_watchdog_rst) {
gp_timer_ptr->IR = timer_mr3_intr_for_watchdog_rst;
/* If no one feeds the watchdog, we will watchdog reset. We are using a periodic ISR
* to feed watchdog because if a critical exception hits, it will enter while(1) loop inside
* the interrupt, and since watchdog won't reset, it will trigger system reset.
*/
sys_watchdog_feed();
/* Setup the next watchdog reset timer */
gp_timer_ptr->MR3 = gp_timer_ptr->TC + LPC_SYS_WATCHDOG_RESET_TIME_US;
}
else
{
// Unexpected interrupt, so stay here to trigger watchdog interrupt
puts("Unexpected ISR call at lpc_sys.c");
while (1) {
;
}
}
}
extern "C" void sys_get_mem_info_str(char buffer[280])
{
sys_mem_t info = sys_get_mem_info();
sprintf(buffer,
"Memory Information:\n"
"Global Used : %5d\n"
"malloc Used : %5d\n"
"malloc Avail. : %5d\n"
"System Avail. : %5d\n"
"Next Heap ptr : 0x%08X\n"
"Last sbrk() ptr : 0x%08X\n"
"Last sbrk() size : %u\n"
"Num sbrk() calls: %u\n",
(int)info.used_global, (int)info.used_heap, (int)info.avail_heap, (int)info.avail_sys,
(unsigned int)info.next_malloc_ptr,
(unsigned int)info.last_sbrk_ptr,
(unsigned int)info.last_sbrk_size,
(unsigned int)info.num_sbrk_calls);
}
| 37.491667
| 112
| 0.660369
|
jpan127
|
eec0066e8515af438eb866eed0d8668214158c7c
| 4,428
|
cpp
|
C++
|
sp/src/game/server/ai_condition.cpp
|
joshmartel/source-sdk-2013
|
524e87f708d6c30360613b1f65ee174deafa20f4
|
[
"Unlicense"
] | 2,268
|
2015-01-01T19:31:56.000Z
|
2022-03-31T20:15:31.000Z
|
sp/src/game/server/ai_condition.cpp
|
joshmartel/source-sdk-2013
|
524e87f708d6c30360613b1f65ee174deafa20f4
|
[
"Unlicense"
] | 241
|
2015-01-01T15:26:14.000Z
|
2022-03-31T22:09:59.000Z
|
sp/src/game/server/ai_condition.cpp
|
joshmartel/source-sdk-2013
|
524e87f708d6c30360613b1f65ee174deafa20f4
|
[
"Unlicense"
] | 2,174
|
2015-01-01T08:18:05.000Z
|
2022-03-31T10:43:59.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#include "cbase.h"
#include "stringregistry.h"
#include "ai_basenpc.h"
#include "ai_condition.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//-----------------------------------------------------------------------------
// Purpose: Given and condition name, return the condition ID
//-----------------------------------------------------------------------------
int CAI_BaseNPC::GetConditionID(const char* condName)
{
return GetSchedulingSymbols()->ConditionSymbolToId(condName);
}
//-----------------------------------------------------------------------------
// Purpose: Register the default conditions
// Input :
// Output :
//-----------------------------------------------------------------------------
#define ADD_CONDITION_TO_SR( _n ) idSpace.AddCondition( #_n, _n, "CAI_BaseNPC" )
void CAI_BaseNPC::InitDefaultConditionSR(void)
{
CAI_ClassScheduleIdSpace &idSpace = CAI_BaseNPC::AccessClassScheduleIdSpaceDirect();
ADD_CONDITION_TO_SR( COND_NONE );
ADD_CONDITION_TO_SR( COND_IN_PVS );
ADD_CONDITION_TO_SR( COND_IDLE_INTERRUPT );
ADD_CONDITION_TO_SR( COND_LOW_PRIMARY_AMMO );
ADD_CONDITION_TO_SR( COND_NO_PRIMARY_AMMO );
ADD_CONDITION_TO_SR( COND_NO_SECONDARY_AMMO );
ADD_CONDITION_TO_SR( COND_NO_WEAPON );
ADD_CONDITION_TO_SR( COND_SEE_HATE );
ADD_CONDITION_TO_SR( COND_SEE_FEAR );
ADD_CONDITION_TO_SR( COND_SEE_DISLIKE );
ADD_CONDITION_TO_SR( COND_SEE_ENEMY );
ADD_CONDITION_TO_SR( COND_LOST_ENEMY );
ADD_CONDITION_TO_SR( COND_ENEMY_WENT_NULL );
ADD_CONDITION_TO_SR( COND_HAVE_ENEMY_LOS );
ADD_CONDITION_TO_SR( COND_HAVE_TARGET_LOS );
ADD_CONDITION_TO_SR( COND_ENEMY_OCCLUDED );
ADD_CONDITION_TO_SR( COND_TARGET_OCCLUDED );
ADD_CONDITION_TO_SR( COND_ENEMY_TOO_FAR );
ADD_CONDITION_TO_SR( COND_LIGHT_DAMAGE );
ADD_CONDITION_TO_SR( COND_HEAVY_DAMAGE );
ADD_CONDITION_TO_SR( COND_PHYSICS_DAMAGE );
ADD_CONDITION_TO_SR( COND_REPEATED_DAMAGE );
ADD_CONDITION_TO_SR( COND_CAN_RANGE_ATTACK1 );
ADD_CONDITION_TO_SR( COND_CAN_RANGE_ATTACK2 );
ADD_CONDITION_TO_SR( COND_CAN_MELEE_ATTACK1 );
ADD_CONDITION_TO_SR( COND_CAN_MELEE_ATTACK2 );
ADD_CONDITION_TO_SR( COND_PROVOKED );
ADD_CONDITION_TO_SR( COND_NEW_ENEMY );
ADD_CONDITION_TO_SR( COND_ENEMY_FACING_ME );
ADD_CONDITION_TO_SR( COND_BEHIND_ENEMY );
ADD_CONDITION_TO_SR( COND_ENEMY_DEAD );
ADD_CONDITION_TO_SR( COND_ENEMY_UNREACHABLE );
ADD_CONDITION_TO_SR( COND_SEE_PLAYER );
ADD_CONDITION_TO_SR( COND_LOST_PLAYER );
ADD_CONDITION_TO_SR( COND_SEE_NEMESIS );
ADD_CONDITION_TO_SR( COND_TASK_FAILED );
ADD_CONDITION_TO_SR( COND_SCHEDULE_DONE );
ADD_CONDITION_TO_SR( COND_SMELL );
ADD_CONDITION_TO_SR( COND_TOO_CLOSE_TO_ATTACK );
ADD_CONDITION_TO_SR( COND_TOO_FAR_TO_ATTACK );
ADD_CONDITION_TO_SR( COND_NOT_FACING_ATTACK );
ADD_CONDITION_TO_SR( COND_WEAPON_HAS_LOS );
ADD_CONDITION_TO_SR( COND_WEAPON_BLOCKED_BY_FRIEND ); // Friend between gun and target
ADD_CONDITION_TO_SR( COND_WEAPON_PLAYER_IN_SPREAD ); // Player in shooting direction
ADD_CONDITION_TO_SR( COND_WEAPON_PLAYER_NEAR_TARGET ); // Player near shooting position
ADD_CONDITION_TO_SR( COND_WEAPON_SIGHT_OCCLUDED );
ADD_CONDITION_TO_SR( COND_BETTER_WEAPON_AVAILABLE );
ADD_CONDITION_TO_SR( COND_HEALTH_ITEM_AVAILABLE );
ADD_CONDITION_TO_SR( COND_FLOATING_OFF_GROUND );
ADD_CONDITION_TO_SR( COND_MOBBED_BY_ENEMIES );
ADD_CONDITION_TO_SR( COND_GIVE_WAY );
ADD_CONDITION_TO_SR( COND_WAY_CLEAR );
ADD_CONDITION_TO_SR( COND_HEAR_DANGER );
ADD_CONDITION_TO_SR( COND_HEAR_THUMPER );
ADD_CONDITION_TO_SR( COND_HEAR_COMBAT );
ADD_CONDITION_TO_SR( COND_HEAR_WORLD );
ADD_CONDITION_TO_SR( COND_HEAR_PLAYER );
ADD_CONDITION_TO_SR( COND_HEAR_BULLET_IMPACT );
ADD_CONDITION_TO_SR( COND_HEAR_BUGBAIT );
ADD_CONDITION_TO_SR( COND_HEAR_PHYSICS_DANGER );
ADD_CONDITION_TO_SR( COND_HEAR_MOVE_AWAY );
ADD_CONDITION_TO_SR( COND_NO_HEAR_DANGER );
ADD_CONDITION_TO_SR( COND_PLAYER_PUSHING );
ADD_CONDITION_TO_SR( COND_RECEIVED_ORDERS );
ADD_CONDITION_TO_SR( COND_PLAYER_ADDED_TO_SQUAD );
ADD_CONDITION_TO_SR( COND_PLAYER_REMOVED_FROM_SQUAD );
ADD_CONDITION_TO_SR( COND_NPC_FREEZE );
ADD_CONDITION_TO_SR( COND_NPC_UNFREEZE );
ADD_CONDITION_TO_SR( COND_TALKER_RESPOND_TO_QUESTION );
ADD_CONDITION_TO_SR( COND_NO_CUSTOM_INTERRUPTS );
}
| 41.773585
| 89
| 0.746838
|
joshmartel
|
eec0dbdd299e7bcb80be5939c1bfe15d0e5b89db
| 323
|
cpp
|
C++
|
examples/example_bindings.cpp
|
avilchess/carma
|
32857b2ab70a0338d15c81fdaf30945ba238a32e
|
[
"Apache-2.0"
] | null | null | null |
examples/example_bindings.cpp
|
avilchess/carma
|
32857b2ab70a0338d15c81fdaf30945ba238a32e
|
[
"Apache-2.0"
] | null | null | null |
examples/example_bindings.cpp
|
avilchess/carma
|
32857b2ab70a0338d15c81fdaf30945ba238a32e
|
[
"Apache-2.0"
] | null | null | null |
#include <pybind11/pybind11.h>
// include numpy header for usage of array_t
#include <pybind11/numpy.h>
namespace py = pybind11;
#include "manual_conversion.h"
#include "automatic_conversion.h"
PYBIND11_MODULE(carma_examples, m) {
bind_manual_example(m);
bind_update_example(m);
bind_automatic_example(m);
}
| 21.533333
| 44
| 0.758514
|
avilchess
|
eec2798f36b1875b318b67e27356e2438fc7d94c
| 2,317
|
cpp
|
C++
|
src/game_components/Input.cpp
|
sgol13/boulder-dash
|
140b7eac3c9f820e84abda07164d057c22540db9
|
[
"MIT"
] | 5
|
2021-11-28T10:13:12.000Z
|
2021-12-12T14:51:36.000Z
|
src/game_components/Input.cpp
|
sgol13/boulder-dash
|
140b7eac3c9f820e84abda07164d057c22540db9
|
[
"MIT"
] | null | null | null |
src/game_components/Input.cpp
|
sgol13/boulder-dash
|
140b7eac3c9f820e84abda07164d057c22540db9
|
[
"MIT"
] | null | null | null |
// Szymon Golebiowski
// Boulder Dash
#include "boulder-dash/game_components/Input.hpp"
bd::Input::Input(sf::RenderWindow &_window) : Engine(_window) {}
void bd::Input::processInputOperations() {
handleEvents();
if (!pause_game_) {
handleControl();
}
}
void bd::Input::handleEvents() {
sf::Event event;
while (window_.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed: // exit the game
end_game_ = true;
window_.close();
break;
case sf::Event::KeyPressed:
if (window_.hasFocus()) {
handleKeyPressed(event.key);
}
break;
default:
break;
}
}
}
void bd::Input::handleKeyPressed(const sf::Event::KeyEvent &key) {
switch (key.code) {
case sf::Keyboard::C: // exit the game using C
exit_game_ = true;
window_.close();
break;
case sf::Keyboard::Return: // exit the game - enter
exit_game_ = true;
break;
case sf::Keyboard::Space: // pause the game - space
if (!end_game_) {
pause_game_ = !pause_game_;
}
break;
default:
break;
}
}
void bd::Input::handleControl() {
MapCoordinates arrow_keys = {0, 0};
// read the current states of the arrow keys
if (window_.hasFocus() && !end_game_) {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
arrow_keys += DIR_UP;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
arrow_keys += DIR_RIGHT;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
arrow_keys += DIR_DOWN;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
arrow_keys += DIR_LEFT;
}
}
// set the player's planned move on the basis of the arrow keys' states
if (abs(arrow_keys.r) + abs(arrow_keys.c) <= 1) {
player_->setPlannedMove(arrow_keys);
}
if (player_->getMovePhase() == Moveable::MovePhase::MOVING) {
if ((arrow_keys.r != 0 && player_->getCurrentMove().r == -arrow_keys.r) ||
(arrow_keys.c != 0 && player_->getCurrentMove().c == -arrow_keys.c)) {
player_->reverseMove();
}
}
}
| 22.495146
| 82
| 0.547259
|
sgol13
|
eec54846508065fb7c8e441810362307fc52fdb9
| 60
|
hpp
|
C++
|
src/boost_geometry_multi_algorithms_intersection.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_geometry_multi_algorithms_intersection.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_geometry_multi_algorithms_intersection.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/geometry/multi/algorithms/intersection.hpp>
| 30
| 59
| 0.833333
|
miathedev
|
eec6c98ef1163653d659d69f1693ed732156245e
| 1,307
|
cpp
|
C++
|
platform/eSDK_LogAPI_V2.1.10/log4cpp/StringQueueAppender.cpp
|
chewaiwai/huaweicloud-sdk-c-obs
|
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
|
[
"Apache-2.0"
] | 22
|
2019-06-13T01:16:44.000Z
|
2022-03-29T02:42:39.000Z
|
platform/eSDK_LogAPI_V2.1.10/log4cpp/StringQueueAppender.cpp
|
chewaiwai/huaweicloud-sdk-c-obs
|
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
|
[
"Apache-2.0"
] | 26
|
2019-09-20T06:46:05.000Z
|
2022-03-11T08:07:14.000Z
|
platform/eSDK_LogAPI_V2.1.10/log4cpp/StringQueueAppender.cpp
|
chewaiwai/huaweicloud-sdk-c-obs
|
fbcd3dadd910c22af3a91aeb73ca0fee94d759fb
|
[
"Apache-2.0"
] | 14
|
2019-07-15T06:42:39.000Z
|
2022-02-15T10:32:28.000Z
|
/*
* StringQueueAppender.cpp
*
* Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.
* Copyright 2000, Bastiaan Bakker. All rights reserved.
*
* See the COPYING file for the terms of usage and distribution.
*/
#include "PortabilityImpl.hh"
#include "log4cpp/StringQueueAppender.hh"
namespace log4cpp {
StringQueueAppender::StringQueueAppender(const std::string& name) :
LayoutAppender(name) {
}
StringQueueAppender::~StringQueueAppender() {
close();
}
void StringQueueAppender::close() {
// empty
}
void StringQueueAppender::_append(const LoggingEvent& event) {
_queue.push(_getLayout().format(event));
}
bool StringQueueAppender::reopen() {
return true;
}
std::queue<std::string>& StringQueueAppender::getQueue() {
return _queue;
}
const std::queue<std::string>& StringQueueAppender::getQueue() const {
return _queue;
}
size_t StringQueueAppender::queueSize() const {
return getQueue().size();
}
std::string StringQueueAppender::popMessage() {
std::string message;
if (!_queue.empty()) {
message = _queue.front();
_queue.pop();
}
return message;
}
}
| 22.534483
| 79
| 0.61974
|
chewaiwai
|
eecb0ad8d95d2e9dc558a674b6ca49095dba1708
| 3,522
|
cpp
|
C++
|
codeforces/B - Cubes/Wrong answer on test 5 (2).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/B - Cubes/Wrong answer on test 5 (2).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/B - Cubes/Wrong answer on test 5 (2).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Oct/03/2020 22:17
* solution_verdict: Wrong answer on test 5 language: GNU C++14
* run_time: 30 ms memory_used: 11900 KB
* problem: https://codeforces.com/contest/521/problem/B
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#include<queue>
#include<sstream>
#include<unordered_map>
#include<unordered_set>
#include<chrono>
#include<stack>
#include<deque>
#include<random>
#define long long long
using namespace std;
const int N=1e6;
int a[N+2],b[N+2];
set<pair<int,int> >st;set<int>fr;
map<pair<int,int>,int>mp;
int up(int x,int y)
{
int cnt=0;
cnt+=(st.find({x-1,y+1})!=st.end());
cnt+=(st.find({x,y+1})!=st.end());
cnt+=(st.find({x+1,y+1})!=st.end());
return cnt;
}
int dw(int x,int y)
{
int cnt=0;
cnt+=(st.find({x-1,y-1})!=st.end());
cnt+=(st.find({x,y-1})!=st.end());
cnt+=(st.find({x+1,y-1})!=st.end());
return cnt;
}
void ck(int x,int y)
{
if(st.find({x,y})==st.end())return ;
int id=mp[{x,y}];
if(up(x,y)==0)
{
fr.insert(id);//cout<<id<<endl;
}
}
int tk[N+2];
const int mod=1e9+9;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;
for(int i=0;i<n;i++)
{
int x,y;cin>>x>>y;a[i]=x,b[i]=y;
mp[{x,y}]=i;st.insert({x,y});
}
for(int i=0;i<n;i++)
{
if(up(a[i],b[i])==0)fr.insert(i);
}
int lo=0,hi=n-1,tr=1;vector<int>ans;
for(int i=1;i<=n;i++)
{
if(tr)
{
int dl=-1;
while(true)
{
if(hi<lo)break;
if(tk[hi]){hi--;continue;}
if(*fr.rbegin()>=hi){dl=*fr.rbegin();break;}
int c1=2,c2=2,c3=2;
if(st.find({a[hi]-1,b[hi]+1})!=st.end())c1=dw(a[hi]-1,b[hi]+1);
if(st.find({a[hi],b[hi]+1})!=st.end())c2=dw(a[hi],b[hi]+1);
if(st.find({a[hi]+1,b[hi]+1})!=st.end())c3=dw(a[hi]+1,b[hi]+1);
if(c1>=2&&c2>=2&&c3>=2){dl=hi;break;}
else hi--;
}
//cout<<"*"<<fr.size()<<endl;
if(dl==-1)dl=*fr.rbegin();
//cout<<"*"<<dl<<endl;
ans.push_back(dl);st.erase({a[dl],b[dl]});
tk[dl]=1;if(fr.find(dl)!=fr.end())fr.erase(dl);
ck(a[dl]-1,b[dl]-1);ck(a[dl],b[dl]-1);ck(a[dl]+1,b[dl]-1);
}
else
{
int dl=-1;
while(true)
{
if(hi<lo)break;
if(tk[lo]){lo++;continue;}
if(*fr.begin()<=lo){dl=*fr.begin();break;}
int c1=2,c2=2,c3=2;
if(st.find({a[lo]-1,b[lo]+1})!=st.end())c1=dw(a[lo]-1,b[lo]+1);
if(st.find({a[lo],b[lo]+1})!=st.end())c2=dw(a[lo],b[lo]+1);
if(st.find({a[lo]+1,b[lo]+1})!=st.end())c3=dw(a[lo]+1,b[lo]+1);
if(c1>=2&&c2>=2&&c3>=2){dl=lo;break;}
else lo++;
}
if(dl==-1)dl=*fr.begin();
//cout<<"*"<<fr.size()<<endl;
//cout<<"*"<<dl<<endl;
ans.push_back(dl);st.erase({a[dl],b[dl]});
tk[dl]=1;if(fr.find(dl)!=fr.end())fr.erase(dl);
ck(a[dl]-1,b[dl]-1);ck(a[dl],b[dl]-1);ck(a[dl]+1,b[dl]-1);
}
tr^=1;
}
int ad=0,p=1;
for(int i=n-1;i>=0;i--)
{
ad=(ad+1LL*ans[i]*p)%mod;
p=(1LL*p*n)%mod;
}
cout<<ad<<endl;
return 0;
}
| 27.515625
| 111
| 0.463941
|
kzvd4729
|
eed5a0939b1523d408d7065ff83dc28ac8038ea4
| 1,132
|
hpp
|
C++
|
Source/Gui/MainWindow.hpp
|
alvinahmadov/Dixter
|
6f98f1e84192e1e43eee409bdee6b3dac75d6443
|
[
"MIT"
] | 4
|
2018-12-06T01:20:50.000Z
|
2019-08-04T10:19:23.000Z
|
Source/Gui/MainWindow.hpp
|
alvinahmadov/Dixter
|
6f98f1e84192e1e43eee409bdee6b3dac75d6443
|
[
"MIT"
] | null | null | null |
Source/Gui/MainWindow.hpp
|
alvinahmadov/Dixter
|
6f98f1e84192e1e43eee409bdee6b3dac75d6443
|
[
"MIT"
] | null | null | null |
/**
* Copyright (C) 2015-2019
* Author Alvin Ahmadov <alvin.dev.ahmadov@gmail.com>
*
* This file is part of Dixter Project
* License-Identifier: MIT License
* See README.md for more information.
*/
#pragma once
#include "WindowBase.hpp"
namespace Dixter
{
namespace Gui
{
class Panel;
class TranslatorPanel;
class DictionaryPanel;
class SettingsDialog;
/**
* Main window
* */
class DixterWindow : public WindowBase
{
Q_OBJECT
public:
explicit DixterWindow(const QString& title, int width = -1, int height = -1, bool visible = true);
virtual ~DixterWindow() dxDECL_NOEXCEPT dxDECL_OVERRIDE;
void showAll(bool visible = true, bool showChildren = true);
DictionaryPanel* getDictionary();
TranslatorPanel* getTranslator();
protected:
void init() dxDECL_OVERRIDE;
void connectEvents() dxDECL_OVERRIDE;
void initDictionary();
void initTranslator();
private:
Group <QWidget, WidgetID>* m_widgets;
DictionaryPanel* m_dictionaryPanel = nullptr;
TranslatorPanel* m_translatorPanel = nullptr;
};
}
}
| 18.557377
| 101
| 0.674028
|
alvinahmadov
|
eed6f642bef3262feb6223e8b7a37f06093b6549
| 6,612
|
cpp
|
C++
|
tests/BufferPipeTest.cpp
|
Manuvr/ManuvrOS
|
e3a812c9b609ad69670ff2f8050a07bd423ebc78
|
[
"Apache-2.0"
] | 5
|
2015-03-26T22:58:58.000Z
|
2021-06-15T05:36:57.000Z
|
tests/BufferPipeTest.cpp
|
Manuvr/ManuvrOS
|
e3a812c9b609ad69670ff2f8050a07bd423ebc78
|
[
"Apache-2.0"
] | 2
|
2016-09-26T09:25:58.000Z
|
2017-08-03T05:27:24.000Z
|
tests/BufferPipeTest.cpp
|
Manuvr/ManuvrOS
|
e3a812c9b609ad69670ff2f8050a07bd423ebc78
|
[
"Apache-2.0"
] | 2
|
2016-04-29T07:43:32.000Z
|
2020-02-07T06:43:01.000Z
|
#include <cstdio>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <fstream>
#include <iostream>
#include <Platform/Platform.h>
#include "DataStructures/BufferPipe.h"
#include "Transports/BufferPipes/XportBridge/XportBridge.h"
class DummyTransport : public BufferPipe {
public:
DummyTransport(const char*);
DummyTransport(const char*, BufferPipe*);
/* Override from BufferPipe. */
virtual int8_t toCounterparty(uint8_t* buf, unsigned int len, int8_t mm);
virtual int8_t fromCounterparty(uint8_t* buf, unsigned int len, int8_t mm);
void printDebug(StringBuilder*);
void runTest(StringBuilder*);
private:
const char* _name;
StringBuilder _accumulator;
};
DummyTransport::DummyTransport(const char* nom) : BufferPipe() {
_name = nom;
}
/**
* Constructor. We are passed one BufferPipe. Presumably the instance that gave
* rise to us.
* Without both sides of the bridge, all transfers in either direction will
* fail with MEM_MGMT_RESPONSIBLE_CALLER.
*/
DummyTransport::DummyTransport(const char* nom, BufferPipe* x) : BufferPipe() {
_name = nom;
setNear(x);
}
/*******************************************************************************
* Functions specific to this class *
*******************************************************************************/
/*
* This should just accumulate.
*/
int8_t DummyTransport::toCounterparty(uint8_t* buf, unsigned int len, int8_t mm) {
switch (mm) {
case MEM_MGMT_RESPONSIBLE_CALLER:
// NOTE: No break. This might be construed as a way of saying CREATOR.
case MEM_MGMT_RESPONSIBLE_CREATOR:
_accumulator.concat(buf, len);
return MEM_MGMT_RESPONSIBLE_CREATOR; // Reject the buffer.
case MEM_MGMT_RESPONSIBLE_BEARER:
_accumulator.concat(buf, len);
free(buf);
return MEM_MGMT_RESPONSIBLE_BEARER; // Reject the buffer.
default:
/* This is more ambiguity than we are willing to bear... */
return MEM_MGMT_RESPONSIBLE_ERROR;
}
}
/*
* The other side of the bridge.
*/
int8_t DummyTransport::fromCounterparty(uint8_t* buf, unsigned int len, int8_t mm) {
switch (mm) {
case MEM_MGMT_RESPONSIBLE_CALLER:
// NOTE: No break. This might be construed as a way of saying CREATOR.
case MEM_MGMT_RESPONSIBLE_CREATOR:
/* The system that allocated this buffer either...
a) Did so with the intention that it never be free'd, or...
b) Has a means of discovering when it is safe to free. */
if (haveFar()) {
/* We are not the transport driver, and we do no transformation. */
return far()->fromCounterparty(buf, len, mm);
}
return MEM_MGMT_RESPONSIBLE_CALLER; // Reject the buffer.
case MEM_MGMT_RESPONSIBLE_BEARER:
/* We are now the bearer. That means that by returning non-failure, the
caller will expect _us_ to manage this memory. */
if (haveFar()) {
/* We are not the transport driver, and we do no transformation. */
return far()->fromCounterparty(buf, len, mm);
}
return MEM_MGMT_RESPONSIBLE_CALLER; // Reject the buffer.
default:
/* This is more ambiguity than we are willing to bear... */
return MEM_MGMT_RESPONSIBLE_ERROR;
}
}
void DummyTransport::printDebug(StringBuilder* output) {
output->concatf("\t-- %s ----------------------------------\n", _name);
if (haveNear()) {
output->concatf("\t _near \t[%p]\n", (unsigned long)near());
}
if (haveFar()) {
output->concatf("\t _far \t[%p]\n", (unsigned long)far());
}
if (_accumulator.length() > 0) {
output->concatf("\t _accumulator (%d bytes): ", _accumulator.length());
_accumulator.printDebug(output);
}
}
void DummyTransport::runTest(StringBuilder* output) {
printf("runTest() ---> fromCounterparty() ---> %s\n",
BufferPipe::memMgmtString(
this->toCounterparty(output->string(), output->length(), MEM_MGMT_RESPONSIBLE_CREATOR)
)
);
}
/*
* Allocates two dummy objects and tries to move data between them.
*/
int test_BufferPipe_0(void) {
printf("Beginning test_BufferPipe_0()....\n");
StringBuilder log;
StringBuilder* tmp_str = new StringBuilder("data to move...\n");
DummyTransport _xport0("Xport0");
DummyTransport _xport1("Xport1", &_xport0);
// NOTE: This will make the pair circular, and thus make the test crash from
// a stack overflow.
//_xport0.setNear(&_xport1);
_xport1.runTest(tmp_str);
log.concat("\n_xport0\n");
_xport0.printDebug(&log);
log.concat("\n_xport1\n");
_xport1.printDebug(&log);
log.concat("\n");
_xport0.runTest(tmp_str);
log.concat("\n_xport0\n");
_xport0.printDebug(&log);
log.concat("\n_xport1\n");
_xport1.printDebug(&log);
printf("%s\n", log.string());
return 0;
}
/*
* Allocates two dummy objects and tries to move data between them via an XportBridge.
*/
int test_BufferPipe_1(void) {
printf("Beginning test_BufferPipe_1()....\n");
StringBuilder log;
StringBuilder* tmp_str = new StringBuilder("data to move...\n");
DummyTransport _xport2("Xport2");
DummyTransport _xport3("Xport3");
XportBridge _bridge(&_xport2, &_xport3);
log.concatf("_xport2->toCounterparty() ---> %s\n",
BufferPipe::memMgmtString(
_xport2.toCounterparty(tmp_str->string(), tmp_str->length(), MEM_MGMT_RESPONSIBLE_CREATOR)
)
);
_xport2.printDebug(&log);
_xport3.printDebug(&log);
log.concat("\n");
tmp_str->clear();
tmp_str->concat("This is a differnt bits.\n");
log.concatf("_xport3->toCounterparty() ---> %s\n",
BufferPipe::memMgmtString(
_xport3.toCounterparty(tmp_str->string(), tmp_str->length(), MEM_MGMT_RESPONSIBLE_CREATOR)
)
);
_xport2.printDebug(&log);
_xport3.printDebug(&log);
printf("%s\n", log.string());
return 0;
}
/****************************************************************************************************
* The main function. *
****************************************************************************************************/
int main(int argc, char *argv[]) {
platform.platformPreInit(); // Our test fixture needs random numbers.
platform.bootstrap();
// TODO: This is presently needed to prevent the program from hanging. WHY??
StringBuilder out;
platform.kernel()->printScheduler(&out);
printf("\n");
test_BufferPipe_0();
printf("\n\n");
//test_BufferPipe_1();
printf("\n\n");
exit(0);
}
| 29
| 101
| 0.624773
|
Manuvr
|
eed94336a762afe8f1e2cf259bceaf86d58c5ecf
| 4,667
|
hpp
|
C++
|
libs/fnd/serialization/include/bksge/fnd/serialization/detail/load_dispatch.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 4
|
2018-06-10T13:35:32.000Z
|
2021-06-03T14:27:41.000Z
|
libs/fnd/serialization/include/bksge/fnd/serialization/detail/load_dispatch.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 566
|
2017-01-31T05:36:09.000Z
|
2022-02-09T05:04:37.000Z
|
libs/fnd/serialization/include/bksge/fnd/serialization/detail/load_dispatch.hpp
|
myoukaku/bksge
|
0f8b60e475a3f1709723906e4796b5e60decf06e
|
[
"MIT"
] | 1
|
2018-07-05T04:40:53.000Z
|
2018-07-05T04:40:53.000Z
|
/**
* @file load_dispatch.hpp
*
* @brief load_dispatch の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_SERIALIZATION_DETAIL_LOAD_DISPATCH_HPP
#define BKSGE_FND_SERIALIZATION_DETAIL_LOAD_DISPATCH_HPP
#include <bksge/fnd/serialization/detail/serialize_dispatch.hpp>
#include <bksge/fnd/serialization/version.hpp>
#include <bksge/fnd/serialization/nvp.hpp>
#include <bksge/fnd/type_traits/bool_constant.hpp>
#include <bksge/fnd/type_traits/is_null_pointer.hpp>
#include <bksge/fnd/type_traits/is_array.hpp>
#include <bksge/fnd/type_traits/is_arithmetic.hpp>
#include <bksge/fnd/type_traits/is_enum.hpp>
#include <bksge/fnd/type_traits/is_pointer.hpp>
#include <bksge/fnd/type_traits/remove_const.hpp>
#include <bksge/fnd/type_traits/conditional.hpp>
#include <utility>
namespace bksge
{
namespace serialization
{
namespace detail
{
class load_dispatch
{
private:
template <typename Archive, typename T>
struct is_load_version_free_invocable
{
private:
template <typename A2, typename T2>
static auto test(int) -> decltype(
load(std::declval<A2&>(), std::declval<T2&>(), std::declval<bksge::serialization::version_t>()),
bksge::true_type());
template <typename A2, typename T2>
static auto test(...)->bksge::false_type;
using type = decltype(test<Archive, T>(0));
public:
static const bool value = type::value;
};
template <typename Archive, typename T>
struct is_load_free_invocable
{
private:
template <typename A2, typename T2>
static auto test(int) -> decltype(
load(std::declval<A2&>(), std::declval<T2&>()),
bksge::true_type());
template <typename A2, typename T2>
static auto test(...)->bksge::false_type;
using type = decltype(test<Archive, T>(0));
public:
static const bool value = type::value;
};
struct load_array
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
ar.load_array(t);
}
};
struct load_arithmetic
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
ar.load_arithmetic(t);
}
};
struct load_enum
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
ar.load_enum(t);
}
};
struct load_pointer
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
ar.load_pointer(t);
}
};
struct load_null_pointer
{
template <typename Archive, typename T>
static void invoke(Archive&, T& t)
{
t = nullptr;
}
};
struct load_nvp
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
ar.load_nvp(const_cast<bksge::remove_const_t<T>&>(t));
}
};
struct load_version_free
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t, bksge::serialization::version_t version)
{
load(ar, t, version);
}
};
struct load_free
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t, bksge::serialization::version_t)
{
load(ar, t);
}
};
struct load_object
{
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
using type =
bksge::conditional_t<
access::is_load_version_memfun_invocable<Archive, T>::value,
access::load_version_memfun,
bksge::conditional_t<
access::is_load_memfun_invocable<Archive, T>::value,
access::load_memfun,
bksge::conditional_t<
is_load_version_free_invocable<Archive, T>::value,
load_version_free,
bksge::conditional_t<
is_load_free_invocable<Archive, T>::value,
load_free,
serialize_dispatch
>>>>;
bksge::serialization::version_t version;
ar.load(version);
type::invoke(ar, t, version);
}
};
public:
template <typename Archive, typename T>
static void invoke(Archive& ar, T& t)
{
using type =
bksge::conditional_t<
bksge::is_array<T>::value,
load_array,
bksge::conditional_t<
bksge::is_arithmetic<T>::value,
load_arithmetic,
bksge::conditional_t<
bksge::is_enum<T>::value,
load_enum,
bksge::conditional_t<
bksge::is_pointer<T>::value,
load_pointer,
bksge::conditional_t<
bksge::is_null_pointer<T>::value,
load_null_pointer,
bksge::conditional_t<
is_nvp<T>::value,
load_nvp,
load_object
>>>>>>;
type::invoke(ar, t);
}
};
} // namespace detail
} // namespace serialization
} // namespace bksge
#endif // BKSGE_FND_SERIALIZATION_DETAIL_LOAD_DISPATCH_HPP
| 21.310502
| 100
| 0.664453
|
myoukaku
|
eed989a805c02eed03d7c14c8306bf81ff2b10c3
| 9,433
|
hh
|
C++
|
src/USRP.hh
|
drexelwireless/dragonradio
|
885abd68d56af709e7a53737352641908005c45b
|
[
"MIT"
] | 8
|
2020-12-05T20:30:54.000Z
|
2022-01-22T13:32:14.000Z
|
src/USRP.hh
|
drexelwireless/dragonradio
|
885abd68d56af709e7a53737352641908005c45b
|
[
"MIT"
] | 3
|
2020-10-28T22:15:27.000Z
|
2021-01-27T14:43:41.000Z
|
src/USRP.hh
|
drexelwireless/dragonradio
|
885abd68d56af709e7a53737352641908005c45b
|
[
"MIT"
] | null | null | null |
// Copyright 2018-2020 Drexel University
// Author: Geoffrey Mainland <mainland@drexel.edu>
#ifndef USRP_H_
#define USRP_H_
#include <atomic>
#include <deque>
#include <string>
#include <thread>
#include <uhd/usrp/multi_usrp.hpp>
#include "logging.hh"
#include "Clock.hh"
#include "IQBuffer.hh"
/** @brief A USRP. */
class USRP
{
public:
enum DeviceType {
kUSRPN210,
kUSRPX310,
kUSRPUnknown
};
USRP(const std::string& addr,
const std::optional<std::string>& tx_subdev,
const std::optional<std::string>& rx_subdev,
double freq,
const std::string& tx_ant,
const std::string& rx_ant,
float tx_gain,
float rx_gain);
~USRP();
USRP() = delete;
USRP(const USRP&) = delete;
USRP(USRP&&) = delete;
USRP& operator=(const USRP&) = delete;
USRP& operator=(USRP&&) = delete;
/** @brief Get type of this device. */
DeviceType getDeviceType(void)
{
return device_type_;
}
/** @brief Get clock sources. */
std::vector<std::string> getClockSources(const size_t mboard = 0)
{
return usrp_->get_clock_sources(mboard);
}
/** @brief Get clock source. */
std::string getClockSource(const size_t mboard = 0)
{
return usrp_->get_clock_source(mboard);
}
/** @brief Set clock source. */
void setClockSource(const std::string clock_source,
const size_t mboard = uhd::usrp::multi_usrp::ALL_MBOARDS)
{
return usrp_->set_clock_source(clock_source, mboard);
}
/** @brief Get time sources. */
std::vector<std::string> getTimeSources(const size_t mboard = 0)
{
return usrp_->get_time_sources(mboard);
}
/** @brief Get time source. */
std::string getTimeSource(const size_t mboard = 0)
{
return usrp_->get_time_source(mboard);
}
/** @brief Set time source. */
void setTimeSource(const std::string &time_source,
const size_t mboard = uhd::usrp::multi_usrp::ALL_MBOARDS)
{
return usrp_->set_time_source(time_source, mboard);
}
/** @brief Get master clock rate. */
double getMasterClockRate(void)
{
return usrp_->get_master_clock_rate(0);
}
/** @brief Get TX frequency. */
double getTXFrequency(void)
{
return usrp_->get_tx_freq();
}
/** @brief Set TX frequency.
* @param freq The center frequency
*/
void setTXFrequency(double freq);
/** @brief Get RX frequency. */
double getRXFrequency(void)
{
return usrp_->get_rx_freq();
}
/** @brief Set RX frequency.
* @param freq The center frequency
*/
void setRXFrequency(double freq);
/** @brief Get TX rate. */
double getTXRate(void)
{
return usrp_->get_tx_rate();
}
/** @brief Set TX rate. */
void setTXRate(double rate)
{
usrp_->set_tx_rate(rate);
logUSRP(LOGDEBUG, "TX rate set to %f", rate);
tx_rate_ = usrp_->get_tx_rate();
}
/** @brief Get RX rate. */
double getRXRate(void)
{
return usrp_->get_rx_rate();
}
/** @brief Set RX rate. */
void setRXRate(double rate)
{
usrp_->set_rx_rate(rate);
logUSRP(LOGDEBUG, "RX rate set to %f", rate);
rx_rate_ = usrp_->get_rx_rate();
}
/** @brief Get TX gain (dB). */
double getTXGain(void)
{
return usrp_->get_tx_gain();
}
/** @brief Set TX gain (dB). */
void setTXGain(float db)
{
return usrp_->set_tx_gain(db);
}
/** @brief Get RX gain (dB). */
double getRXGain(void)
{
return usrp_->get_rx_gain();
}
/** @brief Set RX gain (dB). */
void setRXGain(float db)
{
return usrp_->set_rx_gain(db);
}
/** @brief Get automatic DC offset correction. */
bool getAutoDCOffset(bool enable)
{
return auto_dc_offset_;
}
/** @brief Get time at which next transmission will occur */
std::optional<MonoClock::time_point> getNextTXTime()
{
return t_next_tx_;
}
/** @brief Set automatic DC offset correction. */
void setAutoDCOffset(bool enable)
{
auto_dc_offset_ = enable;
usrp_->set_rx_dc_offset(auto_dc_offset_);
usrp_->set_tx_dc_offset(auto_dc_offset_);
}
/** @brief Transmit a burst of IQ buffers at the given time.
* @param when Time at which to start the burst.
* @param start_of_burst Is this the start of a burst?
* @param end_of_burst Is this the end of a burst?
* @param bufs A list of IQBuf%s to transmit.
*/
void burstTX(std::optional<MonoClock::time_point> when,
bool start_of_burst,
bool end_of_burst,
std::list<std::shared_ptr<IQBuf>>& bufs);
/** @brief Stop TX burst */
void stopTXBurst(void);
/** @brief Start streaming read */
void startRXStream(MonoClock::time_point when);
/** @brief Stop streaming read */
void stopRXStream(void);
/** @brief Receive specified number of samples at the given time
* @param when The time at which to start receiving.
* @param nsamps The number of samples to receive.
* @param buf The IQBuf to hold received IQ samples. The buffer should be at
* least getRecommendedBurstRXSize(nsamps) bytes.
* @returns Returns true if the burst was successfully received, false
* otherwise.
*/
bool burstRX(MonoClock::time_point when, size_t nsamps, IQBuf& buf);
/** @brief Return the maximum number of samples we will read at a time
* during burstRX.
*/
size_t getMaxRXSamps(void)
{
return rx_max_samps_;
}
/** @brief Set the maximum number of samples we will read at a time
* during burstRX.
*/
void setMaxRXSamps(size_t count)
{
rx_max_samps_ = count;
logUSRP(LOGDEBUG, "rx_max_samps_=%lu", rx_max_samps_);
}
/** @brief Set the multiplier for the maximum number of samples we will read
* at a time during burstRX.
*/
void setMaxRXSampsFactor(unsigned n)
{
setMaxRXSamps(n*rx_stream_->get_max_num_samps());
}
/** @brief Return the maximum number of samples we will write at a time
* during burstTX.
*/
size_t getMaxTXSamps(void)
{
return tx_max_samps_;
}
/** @brief Set the maximum number of samples we will write at a time
* during burstTX.
*/
void setMaxTXSamps(size_t count)
{
tx_max_samps_ = count;
logUSRP(LOGDEBUG, "tx_max_samps_=%lu", tx_max_samps_);
}
/** @brief Set the multiplier for the maximum number of samples we will read
* at a time during burstTX.
*/
void setMaxTXSampsFactor(unsigned n)
{
setMaxTXSamps(n*tx_stream_->get_max_num_samps());
}
/** @brief Return the recommended buffer size during burstRX.
* @param nsamps Number of samples to read during burst
* @return Recommended buffer size
*/
size_t getRecommendedBurstRXSize(size_t nsamps)
{
return nsamps + 8*rx_max_samps_;
}
/** @brief Get the TX underflow count.
* @return The number of TX underflow errors
*/
/** Return the number of TX underflow errors and reset the counter */
uint64_t getTXUnderflowCount(void)
{
return tx_underflow_count_.exchange(0, std::memory_order_relaxed);
}
/** @brief Get the TX late count.
* @return The number of late TX packet errors
*/
/** Return the number of TX late packet errors and reset the counter */
uint64_t getTXLateCount(void)
{
return tx_late_count_.exchange(0, std::memory_order_relaxed);
}
/** @brief Stop processing data. */
void stop(void);
private:
/** @brief Our associated UHD USRP. */
uhd::usrp::multi_usrp::sptr usrp_;
/** @brief The DeviceType of the main device */
DeviceType device_type_;
/** @brief Current TX rate */
double tx_rate_;
/** @brief Current RX rate */
double rx_rate_;
/** @brief Current TX frequency */
double tx_freq_;
/** @brief Current RX frequency */
double rx_freq_;
/** @brief The UHD TX stream for this USRP. */
uhd::tx_streamer::sptr tx_stream_;
/** @brief The UHD RX stream for this USRP. */
uhd::rx_streamer::sptr rx_stream_;
/** @brief Maximum number of samples we will send at a time during burstTX.
*/
size_t tx_max_samps_;
/** @brief Maximum number of samples we will read at a time during burstRX.
*/
size_t rx_max_samps_;
/** @brief Time at which next transmission will occur */
std::optional<MonoClock::time_point> t_next_tx_;
/** @brief Flag indicating whether or not to enable automatic DC offset
* correction.
*/
bool auto_dc_offset_;
/** @brief Flag indicating the we should stop processing data. */
bool done_;
/** @brief TX underflow count. */
std::atomic<uint64_t> tx_underflow_count_;
/** @brief TX late count. */
std::atomic<uint64_t> tx_late_count_;
/** @brief Thread that receives TX errors. */
std::thread tx_error_thread_;
/** @brief Determine the type of the main device. */
void determineDeviceType(void);
/** @brief Worker that receives TX errors. */
void txErrorWorker(void);
};
#endif /* USRP_H_ */
| 26.202778
| 81
| 0.618573
|
drexelwireless
|
eedc7e0b05041c3e743fb143b219f6aaa77bc50c
| 9,215
|
cpp
|
C++
|
DLL/RenderingHUD/rendering-hud.cpp
|
ClementDreptin/ModdingResources
|
e5e52285493bd138daf5db373753aaffccf1227a
|
[
"MIT"
] | null | null | null |
DLL/RenderingHUD/rendering-hud.cpp
|
ClementDreptin/ModdingResources
|
e5e52285493bd138daf5db373753aaffccf1227a
|
[
"MIT"
] | null | null | null |
DLL/RenderingHUD/rendering-hud.cpp
|
ClementDreptin/ModdingResources
|
e5e52285493bd138daf5db373753aaffccf1227a
|
[
"MIT"
] | null | null | null |
#include "pch.h"
#include "..\Utils\Utils.h"
// HUD API structs and enums
enum he_type_t : int
{
HE_TYPE_FREE,
HE_TYPE_TEXT,
HE_TYPE_VALUE,
HE_TYPE_PLAYERNAME,
HE_TYPE_MATERIAL,
HE_TYPE_MAPNAME,
HE_TYPE_GAMETYPE,
HE_TYPE_TIMER_DOWN,
HE_TYPE_TIMER_UP,
HE_TYPE_TIMER_STATIC,
HE_TYPE_TENTHS_TIMER_DOWN,
HE_TYPE_TENTHS_TIMER_UP,
HE_TYPE_CLOCK_DOWN,
HE_TYPE_CLOCK_UP,
HE_TYPE_WAYPOINT,
HE_TYPE_COUNT,
};
typedef enum align_t : int
{
ALIGN_TOP_LEFT = 0,
ALIGN_MIDDLE_LEFT = 1,
ALIGN_BOTTOM_LEFT = 2,
ALIGN_TOP_MIDDLE = 4,
ALIGN_MIDDLE_MIDDLE = 5,
ALIGN_BOTTOM_MIDDLE = 6,
ALIGN_TOP_RIGHT = 8,
ALIGN_MIDDLE_RIGHT = 9,
ALIGN_BOTTOM_RIGHT = 10
};
struct hudelem_color_t
{
uint8_t r;
uint8_t g;
uint8_t b;
uint8_t a;
};
struct hudelem_s
{
he_type_t type;
float y;
float x;
float z;
int targetEntNum;
float fontScale;
float fromFontScale;
int fontScaleStartTime;
int fontScaleTime;
int label;
int font;
align_t alignOrg;
align_t alignScreen;
hudelem_color_t color;
hudelem_color_t fromColor;
int fadeStartTime;
int fadeTime;
int height;
int width;
int materialIndex;
int fromHeight;
int fromWidth;
int scaleStartTime;
int scaleTime;
float fromY;
float fromX;
int fromAlignOrg;
int fromAlignScreen;
int moveStartTime;
int moveTime;
float value;
int time;
int duration;
int text;
float sort;
hudelem_color_t glowColor;
int fxBirthTime;
int fxLetterTime;
int fxDecayStartTime;
int fxDecayDuration;
int soundID;
int flags;
};
struct game_hudelem_s
{
hudelem_s elem;
int clientNum;
int teamNum;
int archived;
};
// HUD API functions
game_hudelem_s *(*HudElem_Alloc)(int clientNum, int teamNum) = reinterpret_cast<game_hudelem_s *(*)(int, int)>(0x821DF928);
int (*G_MaterialIndex)(const char *name) = reinterpret_cast<int(*)(const char *)>(0x8220C960);
int (*G_LocalizedStringIndex)(const char *string) = reinterpret_cast<int(*)(const char *)>(0x8220C7A0);
// Rendering API structs
struct Color
{
float r;
float g;
float b;
float a;
};
struct Font_s
{
int fontName;
int pixelHeight;
int glyphCount;
int material;
int glowMaterial;
int glyphs;
};
// Rendering API functions
void (*R_AddCmdDrawStretchPic)(float x, float y, float w, float h, float s0, float t0, float s1, float t1, const float *color, HANDLE material) =
reinterpret_cast<void(*)(float, float, float, float, float, float, float, float, const float *, HANDLE)>(0x8234F9B8);
void (*R_AddCmdDrawText)(const char *text, int maxChars, Font_s *font, float x, float y, float xScale, float yScale, float rotation, const float *color, int style) =
reinterpret_cast<void(*)(const char *, int, Font_s *, float, float, float, float, float, const float *, int)>(0x82350278);
Font_s *(*R_RegisterFont)(const char *font, int imageTrack) = reinterpret_cast<Font_s *(*)(const char *, int)>(0x8234DCB0);
HANDLE (*Material_RegisterHandle)(const char *name, int imageTrack) = reinterpret_cast<HANDLE(*)(const char *, int)>(0x8234E510);
// Used to change some dvars
void (*SV_GameSendServerCommand)(int clientNum, int type, const char *text) = reinterpret_cast<void(*)(int, int, const char *)>(0x822548D8);
void __declspec(naked) SCR_DrawScreenFieldStub(const int localClientNum, int refreshedUI)
{
// The stub needs to, at least, contain 7 instructions
__asm
{
nop
nop
nop
nop
nop
nop
nop
}
}
HANDLE hMaterial = nullptr;
Font_s *normalFont = nullptr;
Color black = { 0.0f, 0.0f, 0.0f, 0.0f };
Color white = { 1.0f, 1.0f, 1.0f, 0.0f };
void SCR_DrawScreenFieldHook(const int localClientNum, int refreshedUI)
{
// Calling the original SCR_DrawScreenField function
SCR_DrawScreenFieldStub(localClientNum, refreshedUI);
// Register the white material the first time we draw
if (!hMaterial)
hMaterial = Material_RegisterHandle("white", 0);
// Register the normal font the first time we draw
if (!pFont)
pFont = R_RegisterFont("fonts/normalFont", 0);
// Rendering the rectangle only if the alpha channel is positive
if (black.a > 0.0f)
R_AddCmdDrawStretchPic(5.0f, 5.0f, 400.0f, 710.0f, 0.0f, 0.0f, 1.0f, 1.0f, reinterpret_cast<float *>(&black), hMaterial);
// Rendering the text only if the alpha channel is positive
if (white.a > 0.0f)
{
const char *text = "Rendering API Text";
R_AddCmdDrawText(text, strlen(text), normalFont, 90.0f, 375.0f, 1.0f, 1.0f, 0.0f, reinterpret_cast<float *>(&white), 0);
}
}
void __declspec(naked) SV_ExecuteClientCommandStub(int client, const char *s, int clientOK, int fromOldServer)
{
// The stub needs to, at least, contain 7 instructions
__asm
{
nop
nop
nop
nop
nop
nop
li r3, 1
}
}
game_hudelem_s *rectangleElem = nullptr;
game_hudelem_s *textElem = nullptr;
void SV_ExecuteClientCommandHook(int client, const char *s, int clientOK, int fromOldServer)
{
// Calling the original SV_ExecuteClientCommand function
SV_ExecuteClientCommandStub(client, s, clientOK, fromOldServer);
// Checking if dpad left is pressed
if (!strcmp(s, "n 19"))
{
// Creating the rectangle and removing localization warnings only the first time we press the button
if (!pRectangleElem)
{
// Removing UNLOCALIZED() around texts
SV_GameSendServerCommand(0, 0, "s loc_warnings \"0\"");
SV_GameSendServerCommand(0, 0, "s loc_warningsUI \"0\"");
pRectangleElem = HudElem_Alloc(0, 0);
pRectangleElem->elem.x = 441.0f;
pRectangleElem->elem.y = 5.0f;
pRectangleElem->elem.width = 300;
pRectangleElem->elem.height = 470;
pRectangleElem->elem.color.r = 0;
pRectangleElem->elem.color.g = 0;
pRectangleElem->elem.color.b = 0;
pRectangleElem->elem.color.a = 0;
pRectangleElem->elem.type = HE_TYPE_MATERIAL;
pRectangleElem->elem.alignOrg = ALIGN_TOP_LEFT;
pRectangleElem->elem.alignScreen = ALIGN_TOP_LEFT;
pRectangleElem->elem.sort = 0.0f;
pRectangleElem->elem.materialIndex = G_MaterialIndex("white");
}
// Creating the text only the first time we press the button
if (!pTextElem)
{
pTextElem = HudElem_Alloc(0, 0);
pTextElem->elem.x = 441.0f + (300.0f / 2.0f) + (5.0f / 2.0f);
pTextElem->elem.y = 5.0f + (470.0f / 2.0f);
pTextElem->elem.color.r = 255;
pTextElem->elem.color.g = 255;
pTextElem->elem.color.b = 255;
pTextElem->elem.color.a = 0;
pTextElem->elem.type = HE_TYPE_TEXT;
pTextElem->elem.alignOrg = ALIGN_MIDDLE_MIDDLE;
pTextElem->elem.alignScreen = ALIGN_TOP_LEFT;
pTextElem->elem.font = 4;
pTextElem->elem.sort = 1.0f;
pTextElem->elem.fontScale = 2.0f;
pTextElem->elem.text = G_LocalizedStringIndex("HUD API Text");
}
// Toggle the visibility of the rectangle and the text from the HUD API
if (!pRectangleElem->elem.color.a)
{
pRectangleElem->elem.color.a = 255;
pTextElem->elem.color.a = 255;
}
else
{
pRectangleElem->elem.color.a = 0;
pTextElem->elem.color.a = 0;
}
// Toggle the visibility of the rectangle and the text from the rendering API
if (!black.a)
{
black.a = 1.0f;
white.a = 1.0f;
}
else
{
black.a = 0.0f;
white.a = 0.0f;
}
}
}
// Sets up the hook
void InitMW2()
{
XNotifyQueueUI(0, 0, XNOTIFY_SYSTEM, L"MW2", nullptr);
// Waiting a little bit for the game to be fully loaded in memory
Sleep(200);
const DWORD SV_ExecuteClientCommandAddr = 0x82253140;
const DWORD SCR_DrawScreenFieldAddr = 0x8214BEB8;
// Hooking SV_ExecuteClientCommand
HookFunctionStart(reinterpret_cast<DWORD *>(SV_ExecuteClientCommandAddr), reinterpret_cast<DWORD *>(SV_ExecuteClientCommandStub), reinterpret_cast<DWORD>(SV_ExecuteClientCommandHook));
HookFunctionStart(reinterpret_cast<DWORD *>(SCR_DrawScreenFieldAddr), reinterpret_cast<DWORD *>(SCR_DrawScreenFieldStub), reinterpret_cast<DWORD>(SCR_DrawScreenFieldHook));
}
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, void *pReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// Runs MonitorTitleId in separate thread
ExCreateThread(nullptr, 0, nullptr, nullptr, reinterpret_cast<PTHREAD_START_ROUTINE>(MonitorTitleId), nullptr, 2);
break;
case DLL_PROCESS_DETACH:
g_bRunning = FALSE;
// We give the system some time to clean up the thread before exiting
Sleep(250);
break;
}
return TRUE;
}
| 29.347134
| 188
| 0.644276
|
ClementDreptin
|
4ac02aae273428114c62b071a2417e29c378c34b
| 991
|
hpp
|
C++
|
src/mlpack/core/math/log_add.hpp
|
tomjpsun/mlpack
|
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1
|
2019-11-07T14:34:37.000Z
|
2019-11-07T14:34:37.000Z
|
src/mlpack/core/math/log_add.hpp
|
tomjpsun/mlpack
|
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2
|
2020-04-10T17:39:50.000Z
|
2020-04-11T14:56:25.000Z
|
src/mlpack/core/math/log_add.hpp
|
tomjpsun/mlpack
|
39b9a852c58b648ddb9b87a3d87aa3db2bacbf0a
|
[
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null |
/**
* @file log_add.hpp
* @author Arash Abghari
*
* Functions for logarithmic addition.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_MATH_LOG_ADD_HPP
#define MLPACK_CORE_MATH_LOG_ADD_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace math {
/**
* Internal log-addition.
*
* @param x log value
* @param y log value
* @return log(e^x + e^y)
*/
template<typename T>
T LogAdd(T x, T y);
/**
* Sum a vector of log values. (T should be an Armadillo type.)
*
* @param x vector of log values
* @return log(e^x0 + e^x1 + ...)
*/
template<typename T>
typename T::elem_type AccuLog(const T& x);
} // namespace math
} // namespace mlpack
// Include implementation.
#include "log_add_impl.hpp"
#endif
| 21.543478
| 78
| 0.699294
|
tomjpsun
|
4ac445f3891caf4866ab3d9f4575bd66e461d1c1
| 17,738
|
cpp
|
C++
|
sample/src/VK/Sources/SssrSample.cpp
|
TheozZhh79/FidelityFX-SSSR
|
d9bfe98d43782c758e3c28b90754be209471dd96
|
[
"MIT"
] | 126
|
2020-05-11T16:57:41.000Z
|
2022-03-29T11:43:53.000Z
|
sample/src/VK/Sources/SssrSample.cpp
|
TheozZhh79/FidelityFX-SSSR
|
d9bfe98d43782c758e3c28b90754be209471dd96
|
[
"MIT"
] | 1
|
2022-01-28T09:38:08.000Z
|
2022-01-29T02:27:58.000Z
|
sample/src/VK/Sources/SssrSample.cpp
|
TheozZhh79/FidelityFX-SSSR
|
d9bfe98d43782c758e3c28b90754be209471dd96
|
[
"MIT"
] | 14
|
2020-05-20T06:15:12.000Z
|
2022-02-25T21:17:49.000Z
|
/**********************************************************************
Copyright (c) 2020 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
********************************************************************/
#include "stdafx.h"
#include "SssrSample.h"
#include "base/ShaderCompilerCache.h"
#include "base/Instance.h"
namespace SSSR_SAMPLE_VK
{
SssrSample::SssrSample(LPCSTR name) : FrameworkWindows(name)
{
m_DeltaTime = 0;
m_Distance = 0;
m_Pitch = 0;
m_Yaw = 0;
m_selectedScene = 0;
m_LastFrameTime = MillisecondsNow();
m_Time = 0;
m_bPlay = true;
m_bShowUI = true;
m_CameraControlSelected = 0; // select WASD on start up
m_pGltfLoader = NULL;
}
//--------------------------------------------------------------------------------------
//
// OnCreate
//
//--------------------------------------------------------------------------------------
void SssrSample::OnCreate(HWND hWnd)
{
// get the list of scenes
for (const auto& scene : m_JsonConfigFile["scenes"])
m_SceneNames.push_back(scene["name"]);
DWORD dwAttrib = GetFileAttributes("..\\media\\");
if ((dwAttrib == INVALID_FILE_ATTRIBUTES) || ((dwAttrib & FILE_ATTRIBUTE_DIRECTORY)) == 0)
{
MessageBox(NULL, "Media files not found!\n\nPlease check the readme on how to get the media files.", "Cauldron Panic!", MB_ICONERROR);
exit(0);
}
// Create Device
//
#ifdef _DEBUG
bool cpuValidationLayerEnabled = true;
bool gpuValidationLayerEnabled = false;
#else
bool cpuValidationLayerEnabled = false;
bool gpuValidationLayerEnabled = false;
#endif
// Create the device
InstanceProperties ip;
ip.Init();
m_Device.SetEssentialInstanceExtensions(cpuValidationLayerEnabled, gpuValidationLayerEnabled, &ip);
// Create instance
VkInstance vulkanInstance;
VkPhysicalDevice physicalDevice;
CreateInstance("SssrSample", "Cauldron", &vulkanInstance, &physicalDevice, &ip);
DeviceProperties dp;
dp.Init(physicalDevice);
m_Device.SetEssentialDeviceExtensions(&dp);
dp.AddDeviceExtensionName(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME);
bool addedSubgroupSizeControl = dp.AddDeviceExtensionName(VK_EXT_SUBGROUP_SIZE_CONTROL_EXTENSION_NAME);
VkPhysicalDeviceSubgroupSizeControlFeaturesEXT subgroupSizeControlFeatures = {};
subgroupSizeControlFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SUBGROUP_SIZE_CONTROL_FEATURES_EXT;
subgroupSizeControlFeatures.pNext = nullptr;
subgroupSizeControlFeatures.subgroupSizeControl = true;
subgroupSizeControlFeatures.computeFullSubgroups = false;
if (addedSubgroupSizeControl)
{
dp.SetNewNext(&subgroupSizeControlFeatures);
}
// Create device
m_Device.OnCreateEx(vulkanInstance, physicalDevice, hWnd, &dp);
m_Device.CreatePipelineCache();
// Init the shader compiler
InitDirectXCompiler();
CreateShaderCache();
// Create Swapchain
//
uint32_t dwNumberOfBackBuffers = 2;
m_SwapChain.OnCreate(&m_Device, dwNumberOfBackBuffers, hWnd);
// Create a instance of the renderer and initialize it, we need to do that for each GPU
//
m_Node = new SampleRenderer();
m_Node->OnCreate(&m_Device, &m_SwapChain);
// init GUI (non gfx stuff)
//
ImGUI_Init((void*)hWnd);
// Init Camera, looking at the origin
//
m_Yaw = 0.0f;
m_Pitch = 0.0f;
m_Distance = 3.5f;
// init GUI state
m_State.toneMapper = 2;
m_State.skyDomeType = 1;
m_State.exposure = 1.0f;
m_State.emmisiveFactor = 1.0f;
m_State.iblFactor = 1.0f;
m_State.bDrawBoundingBoxes = false;
m_State.bDrawLightFrustum = false;
m_State.bDrawBloom = false;
m_State.camera.LookAt(m_Yaw, m_Pitch, m_Distance, XMVectorSet(0, 0, 0, 0));
m_State.lightIntensity = 10.f;
m_State.lightCamera.SetFov(XM_PI / 6.0f, 1024, 1024, 0.1f, 20.0f);
m_State.lightCamera.LookAt(XM_PI / 2.0f, 0.58f, 3.5f, XMVectorSet(0, 0, 0, 0));
m_State.lightColor = XMFLOAT3(1, 1, 1);
m_State.targetFrametime = 0;
m_State.temporalStability = 0.99f;
m_State.temporalVarianceThreshold = 0.002f;
m_State.maxTraversalIterations = 128;
m_State.mostDetailedDepthHierarchyMipLevel = 1;
m_State.depthBufferThickness = 0.015f;
m_State.minTraversalOccupancy = 4;
m_State.samplesPerQuad = 1;
m_State.bEnableVarianceGuidedTracing = true;
m_State.bShowIntersectionResults = false;
m_State.roughnessThreshold = 0.2f;
m_State.showReflectionTarget = false;
m_State.bDrawScreenSpaceReflections = true;
LoadScene(m_selectedScene);
}
//--------------------------------------------------------------------------------------
//
// OnDestroy
//
//--------------------------------------------------------------------------------------
void SssrSample::OnDestroy()
{
ImGUI_Shutdown();
m_Device.GPUFlush();
// Fullscreen state should always be false before exiting the app.
m_SwapChain.SetFullScreen(false);
m_Node->UnloadScene();
m_Node->OnDestroyWindowSizeDependentResources();
m_Node->OnDestroy();
delete m_Node;
m_SwapChain.OnDestroyWindowSizeDependentResources();
m_SwapChain.OnDestroy();
//shut down the shader compiler
DestroyShaderCache(&m_Device);
m_Device.DestroyPipelineCache();
if (m_pGltfLoader)
{
delete m_pGltfLoader;
m_pGltfLoader = NULL;
}
m_Device.OnDestroy();
}
//--------------------------------------------------------------------------------------
//
// OnEvent, forward Win32 events to ImGUI
//
//--------------------------------------------------------------------------------------
bool SssrSample::OnEvent(MSG msg)
{
if (ImGUI_WndProcHandler(msg.hwnd, msg.message, msg.wParam, msg.lParam))
return true;
return true;
}
//--------------------------------------------------------------------------------------
//
// SetFullScreen
//
//--------------------------------------------------------------------------------------
void SssrSample::SetFullScreen(bool fullscreen)
{
m_Device.GPUFlush();
m_SwapChain.SetFullScreen(fullscreen);
}
void SssrSample::OnParseCommandLine(LPSTR lpCmdLine, uint32_t* pWidth, uint32_t* pHeight, bool* pbFullScreen)
{
// First load configuration
std::ifstream f("config.json");
if (!f)
{
MessageBox(NULL, "Config file not found!\n", "Cauldron Panic!", MB_ICONERROR);
exit(-1);
}
f >> m_JsonConfigFile;
// Parse command line and override the config file
try
{
if (strlen(lpCmdLine) > 0)
{
auto j3 = json::parse(lpCmdLine);
m_JsonConfigFile.merge_patch(j3);
}
}
catch (json::parse_error)
{
Trace("Error parsing commandline\n");
exit(0);
}
// Set values
*pWidth = m_JsonConfigFile.value("width", 1920);
*pHeight = m_JsonConfigFile.value("height", 1080);
*pbFullScreen = m_JsonConfigFile.value("fullScreen", false);
m_State.isBenchmarking = m_JsonConfigFile.value("benchmark", false);
}
void SssrSample::BuildUI()
{
ImGuiStyle& style = ImGui::GetStyle();
style.FrameBorderSize = 1.0f;
bool opened = true;
ImGui::Begin("FidelityFX SSSR", &opened);
if (ImGui::CollapsingHeader("Info", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Text("Resolution : %ix%i", m_Width, m_Height);
}
if (ImGui::CollapsingHeader("Controls", ImGuiTreeNodeFlags_DefaultOpen))
{
char* cameraControl[] = { "WASD", "Orbit", "cam #0", "cam #1", "cam #2", "cam #3" , "cam #4", "cam #5" };
if (m_CameraControlSelected >= m_pGltfLoader->m_cameras.size() + 2)
m_CameraControlSelected = 0;
ImGui::Combo("Camera", &m_CameraControlSelected, cameraControl, (int)(m_pGltfLoader->m_cameras.size() + 2));
}
if (ImGui::CollapsingHeader("Reflections", ImGuiTreeNodeFlags_DefaultOpen))
{
ImGui::Checkbox("Draw Screen Space Reflections", &m_State.bDrawScreenSpaceReflections);
ImGui::Checkbox("Show Reflection Target", &m_State.showReflectionTarget);
ImGui::Checkbox("Show Intersection Results", &m_State.bShowIntersectionResults);
ImGui::SliderFloat("Target Frametime in ms", &m_State.targetFrametime, 0.0f, 50.0f);
ImGui::SliderInt("Max Traversal Iterations", &m_State.maxTraversalIterations, 0, 256);
ImGui::SliderInt("Min Traversal Occupancy", &m_State.minTraversalOccupancy, 0, 32);
ImGui::SliderInt("Most Detailed Level", &m_State.mostDetailedDepthHierarchyMipLevel, 0, 5);
ImGui::SliderFloat("Depth Buffer Thickness", &m_State.depthBufferThickness, 0.0f, 0.03f);
ImGui::SliderFloat("Roughness Threshold", &m_State.roughnessThreshold, 0.0f, 1.f);
ImGui::SliderFloat("Temporal Stability", &m_State.temporalStability, 0.0f, 1.0f);
ImGui::SliderFloat("Temporal Variance Threshold", &m_State.temporalVarianceThreshold, 0.0f, 0.01f);
ImGui::Checkbox("Enable Variance Guided Tracing", &m_State.bEnableVarianceGuidedTracing);
ImGui::Text("Samples Per Quad"); ImGui::SameLine();
ImGui::RadioButton("1", &m_State.samplesPerQuad, 1); ImGui::SameLine();
ImGui::RadioButton("2", &m_State.samplesPerQuad, 2); ImGui::SameLine();
ImGui::RadioButton("4", &m_State.samplesPerQuad, 4);
ImGui::Value("Tile Classification Elapsed Time", 1000 * m_State.tileClassificationTime, "%.1f us");
ImGui::Value("Intersection Elapsed Time", 1000 * m_State.intersectionTime, "%.1f us");
ImGui::Value("Denoising Elapsed Time", 1000 * m_State.denoisingTime, "%.1f us");
}
if (ImGui::CollapsingHeader("Profiler"))
{
const std::vector<TimeStamp>& timeStamps = m_Node->GetTimingValues();
if (timeStamps.size() > 0)
{
for (uint32_t i = 0; i < timeStamps.size(); i++)
{
ImGui::Text("%-22s: %7.1f", timeStamps[i].m_label.c_str(), timeStamps[i].m_microseconds);
}
//scrolling data and average computing
static float values[128];
values[127] = timeStamps.back().m_microseconds;
for (uint32_t i = 0; i < 128 - 1; i++) { values[i] = values[i + 1]; }
ImGui::PlotLines("", values, 128, 0, "GPU frame time (us)", 0.0f, 30000.0f, ImVec2(0, 80));
}
}
ImGui::Text("'X' to show/hide GUI");
ImGui::End();
}
void SssrSample::HandleInput()
{
// If the mouse was not used by the GUI then it's for the camera
//
ImGuiIO& io = ImGui::GetIO();
static std::chrono::system_clock::time_point last = std::chrono::system_clock::now();
std::chrono::system_clock::time_point now = std::chrono::system_clock::now();
std::chrono::duration<double> diff = now - last;
last = now;
io.DeltaTime = static_cast<float>(diff.count());
if (ImGui::IsKeyPressed('X'))
{
m_bShowUI = !m_bShowUI;
ShowCursor(m_bShowUI);
}
if (io.WantCaptureMouse == false || !m_bShowUI)
{
if ((io.KeyCtrl == false) && (io.MouseDown[0] == true))
{
m_Yaw -= io.MouseDelta.x / 100.f;
m_Pitch += io.MouseDelta.y / 100.f;
}
// Choose camera movement depending on setting
//
if (m_CameraControlSelected == 0)
{
// WASD
//
m_State.camera.UpdateCameraWASD(m_Yaw, m_Pitch, io.KeysDown, io.DeltaTime);
}
else if (m_CameraControlSelected == 1)
{
// Orbiting
//
m_Distance -= (float)io.MouseWheel / 3.0f;
m_Distance = std::max<float>(m_Distance, 0.1f);
bool panning = (io.KeyCtrl == true) && (io.MouseDown[0] == true);
m_State.camera.UpdateCameraPolar(m_Yaw, m_Pitch, panning ? -io.MouseDelta.x / 100.0f : 0.0f, panning ? io.MouseDelta.y / 100.0f : 0.0f, m_Distance);
}
else
{
// Use a camera from the GLTF
//
m_pGltfLoader->GetCamera(m_CameraControlSelected - 2, &m_State.camera);
m_Yaw = m_State.camera.GetYaw();
m_Pitch = m_State.camera.GetPitch();
}
}
}
void SssrSample::LoadScene(int sceneIndex)
{
json scene = m_JsonConfigFile["scenes"][sceneIndex];
if (m_pGltfLoader != NULL)
{
//free resources, unload the current scene, and load new scene...
m_Device.GPUFlush();
m_Node->UnloadScene();
m_Node->OnDestroyWindowSizeDependentResources();
m_Node->OnDestroy();
m_pGltfLoader->Unload();
m_Node->OnCreate(&m_Device, &m_SwapChain);
m_Node->OnCreateWindowSizeDependentResources(&m_SwapChain, m_Width, m_Height);
}
delete(m_pGltfLoader);
m_pGltfLoader = new GLTFCommon();
if (m_pGltfLoader->Load(scene["directory"], scene["filename"]) == false)
{
MessageBox(NULL, "The selected model couldn't be found, please check the documentation", "Cauldron Panic!", MB_ICONERROR);
exit(0);
}
// Load the UI settings, and also some defaults cameras and lights, in case the GLTF has none
{
#define LOAD(j, key, val) val = j.value(key, val)
// global settings
LOAD(scene, "toneMapper", m_State.toneMapper);
LOAD(scene, "skyDomeType", m_State.skyDomeType);
LOAD(scene, "exposure", m_State.exposure);
LOAD(scene, "iblFactor", m_State.iblFactor);
LOAD(scene, "emmisiveFactor", m_State.emmisiveFactor);
LOAD(scene, "skyDomeType", m_State.skyDomeType);
// default light
m_State.lightIntensity = scene.value("intensity", 1.0f);
// default camera (in case the gltf has none)
json camera = scene["camera"];
LOAD(camera, "yaw", m_Yaw);
LOAD(camera, "pitch", m_Pitch);
LOAD(camera, "distance", m_Distance);
XMVECTOR lookAt = GetVector(GetElementJsonArray(camera, "lookAt", { 0.0, 0.0, 0.0 }));
m_State.camera.LookAt(m_Yaw, m_Pitch, m_Distance, lookAt);
// set benchmarking state if enabled
if (m_State.isBenchmarking)
{
BenchmarkConfig(scene["BenchmarkSettings"], -1, m_pGltfLoader);
}
// indicate the mainloop we started loading a GLTF and it needs to load the rest (textures and geometry)
m_bLoadingScene = true;
}
}
//--------------------------------------------------------------------------------------
//
// OnResize
//
//--------------------------------------------------------------------------------------
void SssrSample::OnResize(uint32_t width, uint32_t height)
{
if (m_Width != width || m_Height != height)
{
// Flush GPU
//
m_Device.GPUFlush();
// If resizing but no minimizing
//
if (m_Width > 0 && m_Height > 0)
{
if (m_Node != NULL)
{
m_Node->OnDestroyWindowSizeDependentResources();
}
m_SwapChain.OnDestroyWindowSizeDependentResources();
}
m_Width = width;
m_Height = height;
// if resizing but not minimizing the recreate it with the new size
//
if (m_Width > 0 && m_Height > 0)
{
m_SwapChain.OnCreateWindowSizeDependentResources(m_Width, m_Height, false, DISPLAYMODE_SDR);
if (m_Node != NULL)
{
m_Node->OnCreateWindowSizeDependentResources(&m_SwapChain, m_Width, m_Height);
}
}
}
m_State.camera.SetFov(XM_PI / 4, m_Width, m_Height, 0.1f, 1000.0f);
}
//--------------------------------------------------------------------------------------
//
// OnRender, updates the state from the UI, animates, transforms and renders the scene
//
//--------------------------------------------------------------------------------------
void SssrSample::OnRender()
{
// Get timings
//
double timeNow = MillisecondsNow();
m_DeltaTime = timeNow - m_LastFrameTime;
m_LastFrameTime = timeNow;
// Build UI and set the scene state. Note that the rendering of the UI happens later.
//
ImGUI_UpdateIO();
ImGui::NewFrame();
if (m_bLoadingScene)
{
static int loadingStage = 0;
// LoadScene needs to be called a number of times, the scene is not fully loaded until it returns 0
// This is done so we can display a progress bar when the scene is loading
loadingStage = m_Node->LoadScene(m_pGltfLoader, loadingStage);
if (loadingStage == 0)
{
m_Time = 0;
m_bLoadingScene = false;
}
}
else if (m_pGltfLoader && m_State.isBenchmarking)
{
const std::vector<TimeStamp>& timeStamps = m_Node->GetTimingValues();
const std::string* screenshotName;
m_Time = BenchmarkLoop(timeStamps, &m_State.camera, &screenshotName);
}
else
{
if (m_bShowUI)
{
BuildUI();
}
if (!m_bLoadingScene)
{
HandleInput();
}
}
// Set animation time
//
if (m_bPlay)
{
m_Time += (float)m_DeltaTime / 1000.0f;
}
// Animate and transform the scene
//
if (m_pGltfLoader)
{
m_pGltfLoader->SetAnimationTime(0, m_Time);
m_pGltfLoader->TransformScene(0, XMMatrixIdentity());
}
m_State.time = m_Time;
// Do Render frame using AFR
//
m_Node->OnRender(&m_State, &m_SwapChain);
m_SwapChain.Present();
}
}
//--------------------------------------------------------------------------------------
//
// WinMain
//
//--------------------------------------------------------------------------------------
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
LPCSTR Name = "FidelityFX Stochastic Screen Space Reflection Sample VK v1.2";
// create new sample
return RunFramework(hInstance, lpCmdLine, nCmdShow, new SSSR_SAMPLE_VK::SssrSample(Name));
}
| 31.064799
| 152
| 0.648664
|
TheozZhh79
|
4ac7c3c55c26329ff2bdc88a48551c5760a2c3c6
| 54
|
cpp
|
C++
|
templates/src/bar.cpp
|
mcqueen256/mql4dllft
|
2b918da25efa8056eca967e4d40d07487f030ee8
|
[
"MIT"
] | null | null | null |
templates/src/bar.cpp
|
mcqueen256/mql4dllft
|
2b918da25efa8056eca967e4d40d07487f030ee8
|
[
"MIT"
] | 11
|
2017-07-11T22:26:44.000Z
|
2017-07-20T04:14:54.000Z
|
templates/src/bar.cpp
|
mcqueen256/mql4dllft
|
2b918da25efa8056eca967e4d40d07487f030ee8
|
[
"MIT"
] | null | null | null |
#include "Bar.hpp"
Bar::Bar() {
}
Bar::~Bar() {
}
| 6
| 18
| 0.462963
|
mcqueen256
|
4acab282d778b0dc51a38c4f29fc67826ab297e7
| 739
|
cpp
|
C++
|
Semester 2-2/CSE 2202 Numerical Method Lab/Lab 01/BisectionMethod.cpp
|
AKC23/AUST
|
102fb96d79b45c826fb4eb467ba6a7798e1ab4f4
|
[
"MIT"
] | null | null | null |
Semester 2-2/CSE 2202 Numerical Method Lab/Lab 01/BisectionMethod.cpp
|
AKC23/AUST
|
102fb96d79b45c826fb4eb467ba6a7798e1ab4f4
|
[
"MIT"
] | null | null | null |
Semester 2-2/CSE 2202 Numerical Method Lab/Lab 01/BisectionMethod.cpp
|
AKC23/AUST
|
102fb96d79b45c826fb4eb467ba6a7798e1ab4f4
|
[
"MIT"
] | null | null | null |
#include <stdio.h>
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
double f(float x)
{
// return (x*x*x - x -1);
return (tan(x)+x);
}
int main()
{
float a = 2, b = 2.1;
float root;
float f0, f1, f2;
if (f(a) * f(b) > 0)
{
printf("wrong guess");
}
do
{
f1 = f(a);
f2 = f(b);
root = (a + b) / 2;
f0 = f(root);
if (f1 * f0 < 0)
{
b = root;
// f2 = f0;
}
else
{
a = root;
// f1 = f0;
}
printf("\nRoot = %f", root);
} while (fabs(f(root)) >= 0.01);
printf("\nRoot = %f", root);
}
| 16.065217
| 37
| 0.345061
|
AKC23
|
4acae05e90a409aabe41ac3c578007667de6f69d
| 1,030
|
cc
|
C++
|
labs/evthrift/thrift_server.cc
|
sandeepsgangwar/evpp
|
38f0e3e775072a268060a36b6c871a8475ed90bc
|
[
"BSD-3-Clause"
] | null | null | null |
labs/evthrift/thrift_server.cc
|
sandeepsgangwar/evpp
|
38f0e3e775072a268060a36b6c871a8475ed90bc
|
[
"BSD-3-Clause"
] | null | null | null |
labs/evthrift/thrift_server.cc
|
sandeepsgangwar/evpp
|
38f0e3e775072a268060a36b6c871a8475ed90bc
|
[
"BSD-3-Clause"
] | 3
|
2019-04-24T08:51:27.000Z
|
2019-09-04T06:40:00.000Z
|
#include "thrift_server.h"
namespace evthrift {
ThriftServer::~ThriftServer() {}
void ThriftServer::serve() {
server_.SetMessageCallback(std::bind(&ThriftServer::OnMessage,
this, std::placeholders::_1,
std::placeholders::_2));
server_.Init();
server_.Start();
}
void ThriftServer::stop() {
server_.Stop();
}
void ThriftServer::OnConnection(const evpp::TCPConnPtr& conn) {
if (conn->IsConnected()) {
ThriftConnectionPtr ptr(new ThriftConn(this, conn));
conn->set_context(evpp::Any(ptr));
} else {
conn->set_context(evpp::Any());
}
}
void ThriftServer::OnMessage(const evpp::TCPConnPtr& conn, evpp::Buffer* buffer) {
const evpp::Any& a = conn->context();
if (a.IsEmpty()) {
EVPP_LOG_ERROR << "The evpp::TCPConn is not assoiated with a Thrift Connection";
return;
}
ThriftConnectionPtr ptr = a.Get<ThriftConnectionPtr>();
ptr->OnMessage(conn, buffer);
}
}
| 26.410256
| 88
| 0.605825
|
sandeepsgangwar
|
4acde5994af6af142394ab93acf9d67b6c2e8c3f
| 1,986
|
cc
|
C++
|
cartographer/common/rate_timer_test.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | 36
|
2017-01-17T10:19:30.000Z
|
2022-02-13T09:11:51.000Z
|
cartographer/common/rate_timer_test.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | 2
|
2019-06-26T06:01:49.000Z
|
2019-08-02T04:27:27.000Z
|
cartographer/common/rate_timer_test.cc
|
linghusmile/Cartographer_-
|
28be85c1af353efae802cebb299b8d2486fbd800
|
[
"Apache-2.0"
] | 37
|
2016-10-09T01:52:45.000Z
|
2022-01-22T10:51:54.000Z
|
/*
* Copyright 2016 The Cartographer Authors
*
* 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 "cartographer/common/rate_timer.h"
#include "gtest/gtest.h"
namespace cartographer {
namespace common {
namespace {
TEST(RateTimerTest, ComputeRate) {
RateTimer<> rate_timer(common::FromSeconds(1.));
common::Time time = common::FromUniversal(42);
for (int i = 0; i < 100; ++i) {
rate_timer.Pulse(time);
time += common::FromSeconds(0.1);
}
EXPECT_NEAR(10., rate_timer.ComputeRate(), 1e-3);
}
struct SimulatedClock {
using rep = std::chrono::steady_clock::rep;
using period = std::chrono::steady_clock::period;
using duration = std::chrono::steady_clock::duration;
using time_point = std::chrono::steady_clock::time_point;
static constexpr bool is_steady = true;
static time_point time;
static time_point now() noexcept { return time; }
};
SimulatedClock::time_point SimulatedClock::time;
TEST(RateTimerTest, ComputeWallTimeRateRatio) {
common::Time time = common::FromUniversal(42);
RateTimer<SimulatedClock> rate_timer(common::FromSeconds(1.));
for (int i = 0; i < 100; ++i) {
rate_timer.Pulse(time);
time += common::FromSeconds(0.1);
SimulatedClock::time +=
std::chrono::duration_cast<SimulatedClock::duration>(
std::chrono::duration<double>(0.05));
}
EXPECT_NEAR(2., rate_timer.ComputeWallTimeRateRatio(), 1e-3);
}
} // namespace
} // namespace common
} // namespace cartographer
| 31.03125
| 75
| 0.712487
|
linghusmile
|
4acde62f9f0434f5e9bc4a846c5e84444d5e3efb
| 1,210
|
cpp
|
C++
|
Difficulty 900/Mocha_and_Red_and_Blue.cpp
|
desmondweh29/A-Problem-A-Day
|
135b21d21d74e6c716c9f7e36e8fa3a216f02727
|
[
"MIT"
] | null | null | null |
Difficulty 900/Mocha_and_Red_and_Blue.cpp
|
desmondweh29/A-Problem-A-Day
|
135b21d21d74e6c716c9f7e36e8fa3a216f02727
|
[
"MIT"
] | null | null | null |
Difficulty 900/Mocha_and_Red_and_Blue.cpp
|
desmondweh29/A-Problem-A-Day
|
135b21d21d74e6c716c9f7e36e8fa3a216f02727
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
// Question: https://codeforces.com/problemset/problem/1559/B
void solve()
{
int n;
cin >> n;
string a;
cin >> a;
string s1 = a;
string s2 = a;
if (a[0] == '?')
{
s1[0] = 'B';
s2[0] = 'R';
}
for (int i = 1; i < n; i++)
{
if (a[i] == '?')
{
if (s1[i-1] == 'R')
{
s1[i] = 'B';
}
else
{
s1[i] = 'R';
}
}
if (a[i] == '?')
{
if (s2[i-1] == 'R')
{
s2[i] = 'B';
}
else
{
s2[i] = 'R';
}
}
}
int c1 = 0;
int c2 = 0;
for (int i = 1; i < n; i++)
{
if (s1[i-1] == s1[i])
{
c1++;
}
if (s2[i-1] == s2[i])
{
c2++;
}
}
if (c1 < c2)
{
cout << s1 << "\n";
}
else
{
cout << s2 << "\n";
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
int t;
cin >> t;
while(t--)
{
solve();
}
}
| 14.069767
| 61
| 0.261983
|
desmondweh29
|
4ad042b3c25eed4bf4366b794766f3757459652d
| 23,384
|
hpp
|
C++
|
include/GlobalNamespace/MainSettingsModelSO.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/MainSettingsModelSO.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/GlobalNamespace/MainSettingsModelSO.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: PersistentScriptableObject
#include "GlobalNamespace/PersistentScriptableObject.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: FloatSO
class FloatSO;
// Forward declaring type: BoolSO
class BoolSO;
// Forward declaring type: Vector2IntSO
class Vector2IntSO;
// Forward declaring type: IntSO
class IntSO;
// Forward declaring type: Vector3SO
class Vector3SO;
// Forward declaring type: LanguageSO
class LanguageSO;
// Forward declaring type: StringSO
class StringSO;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: String
class String;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Size: 0x154
#pragma pack(push, 1)
// Autogenerated type: MainSettingsModelSO
class MainSettingsModelSO : public GlobalNamespace::PersistentScriptableObject {
public:
// Nested type: GlobalNamespace::MainSettingsModelSO::WindowMode
struct WindowMode;
// Nested type: GlobalNamespace::MainSettingsModelSO::Config
class Config;
// [SOVariableAttribute] Offset: 0xE172D4
// public FloatSO vrResolutionScale
// Size: 0x8
// Offset: 0x18
GlobalNamespace::FloatSO* vrResolutionScale;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE172E4
// public FloatSO menuVRResolutionScaleMultiplier
// Size: 0x8
// Offset: 0x20
GlobalNamespace::FloatSO* menuVRResolutionScaleMultiplier;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE172F4
// public BoolSO useFixedFoveatedRenderingDuringGameplay
// Size: 0x8
// Offset: 0x28
GlobalNamespace::BoolSO* useFixedFoveatedRenderingDuringGameplay;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17304
// public Vector2IntSO windowResolution
// Size: 0x8
// Offset: 0x30
GlobalNamespace::Vector2IntSO* windowResolution;
// Field size check
static_assert(sizeof(GlobalNamespace::Vector2IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17314
// public BoolSO fullscreen
// Size: 0x8
// Offset: 0x38
GlobalNamespace::BoolSO* fullscreen;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17324
// public IntSO antiAliasingLevel
// Size: 0x8
// Offset: 0x40
GlobalNamespace::IntSO* antiAliasingLevel;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17334
// public FloatSO volume
// Size: 0x8
// Offset: 0x48
GlobalNamespace::FloatSO* volume;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17344
// public FloatSO ambientVolumeScale
// Size: 0x8
// Offset: 0x50
GlobalNamespace::FloatSO* ambientVolumeScale;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17354
// public BoolSO controllersRumbleEnabled
// Size: 0x8
// Offset: 0x58
GlobalNamespace::BoolSO* controllersRumbleEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17364
// public Vector3SO roomCenter
// Size: 0x8
// Offset: 0x60
GlobalNamespace::Vector3SO* roomCenter;
// Field size check
static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17374
// public FloatSO roomRotation
// Size: 0x8
// Offset: 0x68
GlobalNamespace::FloatSO* roomRotation;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17384
// public Vector3SO controllerPosition
// Size: 0x8
// Offset: 0x70
GlobalNamespace::Vector3SO* controllerPosition;
// Field size check
static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17394
// public Vector3SO controllerRotation
// Size: 0x8
// Offset: 0x78
GlobalNamespace::Vector3SO* controllerRotation;
// Field size check
static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE173A4
// public IntSO mirrorGraphicsSettings
// Size: 0x8
// Offset: 0x80
GlobalNamespace::IntSO* mirrorGraphicsSettings;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE173B4
// public IntSO mainEffectGraphicsSettings
// Size: 0x8
// Offset: 0x88
GlobalNamespace::IntSO* mainEffectGraphicsSettings;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE173C4
// public IntSO bloomPrePassGraphicsSettings
// Size: 0x8
// Offset: 0x90
GlobalNamespace::IntSO* bloomPrePassGraphicsSettings;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE173D4
// public BoolSO smokeGraphicsSettings
// Size: 0x8
// Offset: 0x98
GlobalNamespace::BoolSO* smokeGraphicsSettings;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE173E4
// public BoolSO enableAlphaFeatures
// Size: 0x8
// Offset: 0xA0
GlobalNamespace::BoolSO* enableAlphaFeatures;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE173F4
// public IntSO pauseButtonPressDurationLevel
// Size: 0x8
// Offset: 0xA8
GlobalNamespace::IntSO* pauseButtonPressDurationLevel;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17404
// public BoolSO burnMarkTrailsEnabled
// Size: 0x8
// Offset: 0xB0
GlobalNamespace::BoolSO* burnMarkTrailsEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17414
// public BoolSO screenDisplacementEffectsEnabled
// Size: 0x8
// Offset: 0xB8
GlobalNamespace::BoolSO* screenDisplacementEffectsEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17424
// public BoolSO smoothCameraEnabled
// Size: 0x8
// Offset: 0xC0
GlobalNamespace::BoolSO* smoothCameraEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17434
// public FloatSO smoothCameraFieldOfView
// Size: 0x8
// Offset: 0xC8
GlobalNamespace::FloatSO* smoothCameraFieldOfView;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17444
// public Vector3SO smoothCameraThirdPersonPosition
// Size: 0x8
// Offset: 0xD0
GlobalNamespace::Vector3SO* smoothCameraThirdPersonPosition;
// Field size check
static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17454
// public Vector3SO smoothCameraThirdPersonEulerAngles
// Size: 0x8
// Offset: 0xD8
GlobalNamespace::Vector3SO* smoothCameraThirdPersonEulerAngles;
// Field size check
static_assert(sizeof(GlobalNamespace::Vector3SO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17464
// public BoolSO smoothCameraThirdPersonEnabled
// Size: 0x8
// Offset: 0xE0
GlobalNamespace::BoolSO* smoothCameraThirdPersonEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17474
// public FloatSO smoothCameraRotationSmooth
// Size: 0x8
// Offset: 0xE8
GlobalNamespace::FloatSO* smoothCameraRotationSmooth;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17484
// public FloatSO smoothCameraPositionSmooth
// Size: 0x8
// Offset: 0xF0
GlobalNamespace::FloatSO* smoothCameraPositionSmooth;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17494
// public BoolSO overrideAudioLatency
// Size: 0x8
// Offset: 0xF8
GlobalNamespace::BoolSO* overrideAudioLatency;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE174A4
// public FloatSO audioLatency
// Size: 0x8
// Offset: 0x100
GlobalNamespace::FloatSO* audioLatency;
// Field size check
static_assert(sizeof(GlobalNamespace::FloatSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE174B4
// public IntSO maxShockwaveParticles
// Size: 0x8
// Offset: 0x108
GlobalNamespace::IntSO* maxShockwaveParticles;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE174C4
// public IntSO maxNumberOfCutSoundEffects
// Size: 0x8
// Offset: 0x110
GlobalNamespace::IntSO* maxNumberOfCutSoundEffects;
// Field size check
static_assert(sizeof(GlobalNamespace::IntSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE174D4
// public BoolSO onlineServicesEnabled
// Size: 0x8
// Offset: 0x118
GlobalNamespace::BoolSO* onlineServicesEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE174E4
// public BoolSO oculusMRCEnabled
// Size: 0x8
// Offset: 0x120
GlobalNamespace::BoolSO* oculusMRCEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE174F4
// public BoolSO openVrThreadedHaptics
// Size: 0x8
// Offset: 0x128
GlobalNamespace::BoolSO* openVrThreadedHaptics;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17504
// public LanguageSO language
// Size: 0x8
// Offset: 0x130
GlobalNamespace::LanguageSO* language;
// Field size check
static_assert(sizeof(GlobalNamespace::LanguageSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17514
// public BoolSO useCustomServerEnvironment
// Size: 0x8
// Offset: 0x138
GlobalNamespace::BoolSO* useCustomServerEnvironment;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17524
// public StringSO customServerHostName
// Size: 0x8
// Offset: 0x140
GlobalNamespace::StringSO* customServerHostName;
// Field size check
static_assert(sizeof(GlobalNamespace::StringSO*) == 0x8);
// [SOVariableAttribute] Offset: 0xE17534
// public BoolSO depthTextureEnabled
// Size: 0x8
// Offset: 0x148
GlobalNamespace::BoolSO* depthTextureEnabled;
// Field size check
static_assert(sizeof(GlobalNamespace::BoolSO*) == 0x8);
// [CompilerGeneratedAttribute] Offset: 0xE17544
// private System.Boolean <createScreenshotDuringTheGame>k__BackingField
// Size: 0x1
// Offset: 0x150
bool createScreenshotDuringTheGame;
// Field size check
static_assert(sizeof(bool) == 0x1);
// [CompilerGeneratedAttribute] Offset: 0xE17554
// private System.Boolean <playingForTheFirstTime>k__BackingField
// Size: 0x1
// Offset: 0x151
bool playingForTheFirstTime;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _playingForTheFirstTimeChecked
// Size: 0x1
// Offset: 0x152
bool playingForTheFirstTimeChecked;
// Field size check
static_assert(sizeof(bool) == 0x1);
// private System.Boolean _isLoaded
// Size: 0x1
// Offset: 0x153
bool isLoaded;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: MainSettingsModelSO
MainSettingsModelSO(GlobalNamespace::FloatSO* vrResolutionScale_ = {}, GlobalNamespace::FloatSO* menuVRResolutionScaleMultiplier_ = {}, GlobalNamespace::BoolSO* useFixedFoveatedRenderingDuringGameplay_ = {}, GlobalNamespace::Vector2IntSO* windowResolution_ = {}, GlobalNamespace::BoolSO* fullscreen_ = {}, GlobalNamespace::IntSO* antiAliasingLevel_ = {}, GlobalNamespace::FloatSO* volume_ = {}, GlobalNamespace::FloatSO* ambientVolumeScale_ = {}, GlobalNamespace::BoolSO* controllersRumbleEnabled_ = {}, GlobalNamespace::Vector3SO* roomCenter_ = {}, GlobalNamespace::FloatSO* roomRotation_ = {}, GlobalNamespace::Vector3SO* controllerPosition_ = {}, GlobalNamespace::Vector3SO* controllerRotation_ = {}, GlobalNamespace::IntSO* mirrorGraphicsSettings_ = {}, GlobalNamespace::IntSO* mainEffectGraphicsSettings_ = {}, GlobalNamespace::IntSO* bloomPrePassGraphicsSettings_ = {}, GlobalNamespace::BoolSO* smokeGraphicsSettings_ = {}, GlobalNamespace::BoolSO* enableAlphaFeatures_ = {}, GlobalNamespace::IntSO* pauseButtonPressDurationLevel_ = {}, GlobalNamespace::BoolSO* burnMarkTrailsEnabled_ = {}, GlobalNamespace::BoolSO* screenDisplacementEffectsEnabled_ = {}, GlobalNamespace::BoolSO* smoothCameraEnabled_ = {}, GlobalNamespace::FloatSO* smoothCameraFieldOfView_ = {}, GlobalNamespace::Vector3SO* smoothCameraThirdPersonPosition_ = {}, GlobalNamespace::Vector3SO* smoothCameraThirdPersonEulerAngles_ = {}, GlobalNamespace::BoolSO* smoothCameraThirdPersonEnabled_ = {}, GlobalNamespace::FloatSO* smoothCameraRotationSmooth_ = {}, GlobalNamespace::FloatSO* smoothCameraPositionSmooth_ = {}, GlobalNamespace::BoolSO* overrideAudioLatency_ = {}, GlobalNamespace::FloatSO* audioLatency_ = {}, GlobalNamespace::IntSO* maxShockwaveParticles_ = {}, GlobalNamespace::IntSO* maxNumberOfCutSoundEffects_ = {}, GlobalNamespace::BoolSO* onlineServicesEnabled_ = {}, GlobalNamespace::BoolSO* oculusMRCEnabled_ = {}, GlobalNamespace::BoolSO* openVrThreadedHaptics_ = {}, GlobalNamespace::LanguageSO* language_ = {}, GlobalNamespace::BoolSO* useCustomServerEnvironment_ = {}, GlobalNamespace::StringSO* customServerHostName_ = {}, GlobalNamespace::BoolSO* depthTextureEnabled_ = {}, bool createScreenshotDuringTheGame_ = {}, bool playingForTheFirstTime_ = {}, bool playingForTheFirstTimeChecked_ = {}, bool isLoaded_ = {}) noexcept : vrResolutionScale{vrResolutionScale_}, menuVRResolutionScaleMultiplier{menuVRResolutionScaleMultiplier_}, useFixedFoveatedRenderingDuringGameplay{useFixedFoveatedRenderingDuringGameplay_}, windowResolution{windowResolution_}, fullscreen{fullscreen_}, antiAliasingLevel{antiAliasingLevel_}, volume{volume_}, ambientVolumeScale{ambientVolumeScale_}, controllersRumbleEnabled{controllersRumbleEnabled_}, roomCenter{roomCenter_}, roomRotation{roomRotation_}, controllerPosition{controllerPosition_}, controllerRotation{controllerRotation_}, mirrorGraphicsSettings{mirrorGraphicsSettings_}, mainEffectGraphicsSettings{mainEffectGraphicsSettings_}, bloomPrePassGraphicsSettings{bloomPrePassGraphicsSettings_}, smokeGraphicsSettings{smokeGraphicsSettings_}, enableAlphaFeatures{enableAlphaFeatures_}, pauseButtonPressDurationLevel{pauseButtonPressDurationLevel_}, burnMarkTrailsEnabled{burnMarkTrailsEnabled_}, screenDisplacementEffectsEnabled{screenDisplacementEffectsEnabled_}, smoothCameraEnabled{smoothCameraEnabled_}, smoothCameraFieldOfView{smoothCameraFieldOfView_}, smoothCameraThirdPersonPosition{smoothCameraThirdPersonPosition_}, smoothCameraThirdPersonEulerAngles{smoothCameraThirdPersonEulerAngles_}, smoothCameraThirdPersonEnabled{smoothCameraThirdPersonEnabled_}, smoothCameraRotationSmooth{smoothCameraRotationSmooth_}, smoothCameraPositionSmooth{smoothCameraPositionSmooth_}, overrideAudioLatency{overrideAudioLatency_}, audioLatency{audioLatency_}, maxShockwaveParticles{maxShockwaveParticles_}, maxNumberOfCutSoundEffects{maxNumberOfCutSoundEffects_}, onlineServicesEnabled{onlineServicesEnabled_}, oculusMRCEnabled{oculusMRCEnabled_}, openVrThreadedHaptics{openVrThreadedHaptics_}, language{language_}, useCustomServerEnvironment{useCustomServerEnvironment_}, customServerHostName{customServerHostName_}, depthTextureEnabled{depthTextureEnabled_}, createScreenshotDuringTheGame{createScreenshotDuringTheGame_}, playingForTheFirstTime{playingForTheFirstTime_}, playingForTheFirstTimeChecked{playingForTheFirstTimeChecked_}, isLoaded{isLoaded_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// static field const value: static public System.Single kDefaultPlayerHeight
static constexpr const float kDefaultPlayerHeight = 1.8;
// Get static field: static public System.Single kDefaultPlayerHeight
static float _get_kDefaultPlayerHeight();
// Set static field: static public System.Single kDefaultPlayerHeight
static void _set_kDefaultPlayerHeight(float value);
// static field const value: static public System.Single kHeadPosToPlayerHeightOffset
static constexpr const float kHeadPosToPlayerHeightOffset = 0.1;
// Get static field: static public System.Single kHeadPosToPlayerHeightOffset
static float _get_kHeadPosToPlayerHeightOffset();
// Set static field: static public System.Single kHeadPosToPlayerHeightOffset
static void _set_kHeadPosToPlayerHeightOffset(float value);
// static field const value: static private System.String kFileName
static constexpr const char* kFileName = "settings.cfg";
// Get static field: static private System.String kFileName
static ::Il2CppString* _get_kFileName();
// Set static field: static private System.String kFileName
static void _set_kFileName(::Il2CppString* value);
// static field const value: static private System.String kTempFileName
static constexpr const char* kTempFileName = "settings.cfg.tmp";
// Get static field: static private System.String kTempFileName
static ::Il2CppString* _get_kTempFileName();
// Set static field: static private System.String kTempFileName
static void _set_kTempFileName(::Il2CppString* value);
// static field const value: static private System.String kBackupFileName
static constexpr const char* kBackupFileName = "settings.cfg.bak";
// Get static field: static private System.String kBackupFileName
static ::Il2CppString* _get_kBackupFileName();
// Set static field: static private System.String kBackupFileName
static void _set_kBackupFileName(::Il2CppString* value);
// static field const value: static private System.String kCurrentVersion
static constexpr const char* kCurrentVersion = "1.7.0";
// Get static field: static private System.String kCurrentVersion
static ::Il2CppString* _get_kCurrentVersion();
// Set static field: static private System.String kCurrentVersion
static void _set_kCurrentVersion(::Il2CppString* value);
// static field const value: static public System.Single kControllersPositionOffsetLimit
static constexpr const float kControllersPositionOffsetLimit = 0.1;
// Get static field: static public System.Single kControllersPositionOffsetLimit
static float _get_kControllersPositionOffsetLimit();
// Set static field: static public System.Single kControllersPositionOffsetLimit
static void _set_kControllersPositionOffsetLimit(float value);
// static field const value: static public System.Single kControllersRotationOffsetLimit
static constexpr const float kControllersRotationOffsetLimit = 180;
// Get static field: static public System.Single kControllersRotationOffsetLimit
static float _get_kControllersRotationOffsetLimit();
// Set static field: static public System.Single kControllersRotationOffsetLimit
static void _set_kControllersRotationOffsetLimit(float value);
// public System.Boolean get_createScreenshotDuringTheGame()
// Offset: 0x10D8D80
bool get_createScreenshotDuringTheGame();
// private System.Void set_createScreenshotDuringTheGame(System.Boolean value)
// Offset: 0x10D8D88
void set_createScreenshotDuringTheGame(bool value);
// public System.Boolean get_playingForTheFirstTime()
// Offset: 0x10D8D94
bool get_playingForTheFirstTime();
// private System.Void set_playingForTheFirstTime(System.Boolean value)
// Offset: 0x10D8D9C
void set_playingForTheFirstTime(bool value);
// public System.Void Save()
// Offset: 0x10D8DA8
void Save();
// public System.Void Load(System.Boolean forced)
// Offset: 0x10D92F0
void Load(bool forced);
// public System.Void __DeleteSettingsFiles()
// Offset: 0x10D99AC
void __DeleteSettingsFiles();
// protected System.Void OnDisable()
// Offset: 0x10D9B78
void OnDisable();
// protected override System.Void OnEnable()
// Offset: 0x10D9AE4
// Implemented from: PersistentScriptableObject
// Base method: System.Void PersistentScriptableObject::OnEnable()
void OnEnable();
// public System.Void .ctor()
// Offset: 0x10D9B88
// Implemented from: PersistentScriptableObject
// Base method: System.Void PersistentScriptableObject::.ctor()
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static MainSettingsModelSO* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("GlobalNamespace::MainSettingsModelSO::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<MainSettingsModelSO*, creationType>()));
}
}; // MainSettingsModelSO
#pragma pack(pop)
static check_size<sizeof(MainSettingsModelSO), 339 + sizeof(bool)> __GlobalNamespace_MainSettingsModelSOSizeCheck;
static_assert(sizeof(MainSettingsModelSO) == 0x154);
}
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::MainSettingsModelSO*, "", "MainSettingsModelSO");
| 52.313199
| 4,383
| 0.731996
|
darknight1050
|
4ad308989037d81fec68b1f177b02b8c699e7396
| 2,907
|
cpp
|
C++
|
Source/AstralShipwright/Nova.cpp
|
arbonagw/AstralShipwright
|
8a41015f23fa810ab79d72460f9ada2dd7e37852
|
[
"BSD-3-Clause"
] | 59
|
2021-11-29T22:20:03.000Z
|
2022-03-17T00:07:48.000Z
|
Source/AstralShipwright/Nova.cpp
|
arbonagw/AstralShipwright
|
8a41015f23fa810ab79d72460f9ada2dd7e37852
|
[
"BSD-3-Clause"
] | null | null | null |
Source/AstralShipwright/Nova.cpp
|
arbonagw/AstralShipwright
|
8a41015f23fa810ab79d72460f9ada2dd7e37852
|
[
"BSD-3-Clause"
] | 4
|
2022-01-05T09:44:12.000Z
|
2022-02-21T02:02:32.000Z
|
// Astral Shipwright - Gwennaël Arbona
#include "Nova.h"
#include "Game/NovaGameTypes.h"
#include "Engine.h"
IMPLEMENT_PRIMARY_GAME_MODULE(FNovaModule, AstralShipwright, "AstralShipwright");
#define LOCTEXT_NAMESPACE "AstralShipwright"
/*----------------------------------------------------
Debugging tools
----------------------------------------------------*/
FText GetDateText(struct FNovaTime Time)
{
FDateTime DateTime = FDateTime(ENovaConstants::ZeroTime) + FDateTime(Time.AsMinutes() * ETimespan::TicksPerMinute);
return FText::AsDateTime(DateTime);
}
FText GetDurationText(FNovaTime Time, int32 MaxComponents)
{
FString Result;
double SourceMinutes = Time.AsMinutes();
if (SourceMinutes > 365 * 24 * 60)
{
return LOCTEXT("VeryLongTime", "A very long time");
}
// Break up the time
int32 Days = FMath::Floor(SourceMinutes / (24 * 60));
SourceMinutes -= Days * 24 * 60;
int32 Hours = FMath::Floor(SourceMinutes / 60);
SourceMinutes -= Hours * 60;
int32 Minutes = FMath::Floor(SourceMinutes);
SourceMinutes -= Minutes;
int32 Seconds = FMath::Floor(SourceMinutes * 60.0f);
// Format the time
int32 ComponentCount = 0;
if (Days)
{
if (ComponentCount == MaxComponents - 1)
{
Days++;
}
Result += FText::FormatNamed(LOCTEXT("DaysFormat", "{days} {days}|plural(one=day,other=days)"), TEXT("days"), FText::AsNumber(Days))
.ToString();
ComponentCount++;
}
if (Hours && ComponentCount < MaxComponents)
{
if (ComponentCount > 0)
{
Result += TEXT(", ");
}
if (ComponentCount == MaxComponents - 1)
{
Hours++;
}
Result += FText::FormatNamed(
LOCTEXT("HoursFormat", "{hours} {hours}|plural(one=hour,other=hours)"), TEXT("hours"), FText::AsNumber(Hours))
.ToString();
ComponentCount++;
}
if (Minutes && ComponentCount < MaxComponents)
{
if (ComponentCount > 0)
{
Result += TEXT(", ");
}
if (ComponentCount == MaxComponents - 1)
{
Minutes++;
}
Result += FText::FormatNamed(
LOCTEXT("MinutesFormat", "{minutes} {minutes}|plural(one=minute,other=minutes)"), TEXT("minutes"), FText::AsNumber(Minutes))
.ToString();
ComponentCount++;
}
if ((Seconds && ComponentCount < MaxComponents) || ComponentCount == 0)
{
if (ComponentCount > 0)
{
Result += TEXT(", ");
}
if (ComponentCount == MaxComponents - 1)
{
Seconds++;
}
Result += FText::FormatNamed(
LOCTEXT("SecondsFormat", "{seconds} {seconds}|plural(one=second,other=seconds)"), TEXT("seconds"), FText::AsNumber(Seconds))
.ToString();
ComponentCount++;
}
return FText::FromString(Result);
}
FText GetPriceText(FNovaCredits Credits)
{
FNumberFormattingOptions Options;
Options.MaximumFractionalDigits = 0;
return FText::FromString(FText::AsCurrency(Credits.GetValue(), TEXT("CUR"), &Options).ToString().Replace(TEXT("CUR"), TEXT("Ѥ")));
}
#undef LOCTEXT_NAMESPACE
| 25.060345
| 134
| 0.643619
|
arbonagw
|
4ad9625feae2e3e5c1786b78ceefe6760fb080a7
| 7,248
|
cc
|
C++
|
service/zookeeper_configuration_service.cc
|
sharpyfox/soa
|
193cdae4e1412f09d655d8135c41f82225907099
|
[
"Apache-2.0"
] | 1
|
2018-12-14T17:47:20.000Z
|
2018-12-14T17:47:20.000Z
|
service/zookeeper_configuration_service.cc
|
sharpyfox/soa
|
193cdae4e1412f09d655d8135c41f82225907099
|
[
"Apache-2.0"
] | null | null | null |
service/zookeeper_configuration_service.cc
|
sharpyfox/soa
|
193cdae4e1412f09d655d8135c41f82225907099
|
[
"Apache-2.0"
] | null | null | null |
/** zookeeper_configuration_service.cc
Jeremy Barnes, 26 September 2012
Copyright (c) 2012 Datacratic Inc. All rights reserved.
Configuration service using Zookeeper.
*/
#include "zookeeper_configuration_service.h"
#include "soa/service/zookeeper.h"
#include "jml/utils/exc_assert.h"
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace ML;
namespace Datacratic {
std::string printZookeeperEventType(int type)
{
if (type == ZOO_CREATED_EVENT)
return "CREATED";
if (type == ZOO_DELETED_EVENT)
return "DELETED";
if (type == ZOO_CHANGED_EVENT)
return "CHANGED";
if (type == ZOO_CHILD_EVENT)
return "CHILD";
if (type == ZOO_SESSION_EVENT)
return "SESSION";
if (type == ZOO_NOTWATCHING_EVENT)
return "NOTWATCHING";
return ML::format("UNKNOWN(%d)", type);
}
std::string printZookeeperState(int state)
{
if (state == ZOO_EXPIRED_SESSION_STATE)
return "ZOO_EXPIRED_SESSION_STATE";
if (state == ZOO_AUTH_FAILED_STATE)
return "ZOO_AUTH_FAILED_STATE";
if (state == ZOO_CONNECTING_STATE)
return "ZOO_CONNECTING_STATE";
if (state == ZOO_ASSOCIATING_STATE)
return "ZOO_ASSOCIATING_STATE";
if (state == ZOO_CONNECTED_STATE)
return "ZOO_CONNECTED_STATE";
return ML::format("ZOO_UNKNOWN_STATE(%d)", state);
}
void
watcherFn(int type, std::string const & path, void * watcherCtx)
{
typedef std::shared_ptr<ConfigurationService::Watch::Data> SharedPtr;
std::unique_ptr<SharedPtr> data(reinterpret_cast<SharedPtr *>(watcherCtx));
#if 0
cerr << "type = " << printZookeeperEventType(type)
<< " state = " << printZookeeperState(state)
<< " path = " << path << " context "
<< watcherCtx << " data " << data->get() << endl;
#endif
ConfigurationService::ChangeType change;
if (type == ZOO_CREATED_EVENT)
change = ConfigurationService::CREATED;
if (type == ZOO_DELETED_EVENT)
change = ConfigurationService::DELETED;
if (type == ZOO_CHANGED_EVENT)
change = ConfigurationService::VALUE_CHANGED;
if (type == ZOO_CHILD_EVENT)
change = ConfigurationService::NEW_CHILD;
auto & item = *data;
if (item->watchReferences > 0) {
item->onChange(path, change);
}
}
ZookeeperConnection::Callback::Type
getWatcherFn(const ConfigurationService::Watch & watch)
{
if (!watch)
return nullptr;
return watcherFn;
}
/*****************************************************************************/
/* ZOOKEEPER CONFIGURATION SERVICE */
/*****************************************************************************/
ZookeeperConfigurationService::
ZookeeperConfigurationService()
{
}
ZookeeperConfigurationService::
ZookeeperConfigurationService(const std::string & host,
const std::string & prefix,
int timeout)
{
init(host, prefix, timeout);
}
ZookeeperConfigurationService::
~ZookeeperConfigurationService()
{
}
void
ZookeeperConfigurationService::
init(const std::string & host,
const std::string & prefix,
int timeout)
{
zoo.reset(new ZookeeperConnection());
zoo->connect(host, timeout);
this->prefix = prefix;
if (!this->prefix.empty()
&& this->prefix[this->prefix.size() - 1] != '/')
this->prefix = this->prefix + "/";
if (!this->prefix.empty()
&& this->prefix[0] != '/')
this->prefix = "/" + this->prefix;
zoo->createPath(this->prefix);
#if 0
for (unsigned i = 1; i < prefix.size(); ++i) {
if (prefix[i] == '/') {
zoo->createNode(string(prefix, 0, i),
"",
false,
false,
false /* must succeed */);
}
}
#endif
}
Json::Value
ZookeeperConfigurationService::
getJson(const std::string & key, Watch watch)
{
ExcAssert(zoo);
auto val = zoo->readNode(prefix + key, getWatcherFn(watch),
watch.get());
try {
if (val == "")
return Json::Value();
return Json::parse(val);
} catch (...) {
cerr << "error parsing JSON entry '" << val << "'" << endl;
throw;
}
}
void
ZookeeperConfigurationService::
set(const std::string & key,
const Json::Value & value)
{
//cerr << "setting " << key << " to " << value << endl;
// TODO: race condition
if (!zoo->createNode(prefix + key, boost::trim_copy(value.toString()),
false, false,
false /* must succeed */,
true /* create path */).second)
zoo->writeNode(prefix + key, boost::trim_copy(value.toString()));
ExcAssert(zoo);
}
std::string
ZookeeperConfigurationService::
setUnique(const std::string & key,
const Json::Value & value)
{
//cerr << "setting unique " << key << " to " << value << endl;
ExcAssert(zoo);
return zoo->createNode(prefix + key, boost::trim_copy(value.toString()),
true /* ephemeral */,
false /* sequential */,
true /* mustSucceed */,
true /* create path */)
.first;
}
std::vector<std::string>
ZookeeperConfigurationService::
getChildren(const std::string & key,
Watch watch)
{
//cerr << "getChildren " << key << " watch " << watch << endl;
return zoo->getChildren(prefix + key,
false /* fail if not there */,
getWatcherFn(watch),
watch.get());
}
bool
ZookeeperConfigurationService::
forEachEntry(const OnEntry & onEntry,
const std::string & startPrefix) const
{
//cerr << "forEachEntry: startPrefix = " << startPrefix << endl;
ExcAssert(zoo);
std::function<bool (const std::string &)> doNode
= [&] (const std::string & currentPrefix)
{
//cerr << "doNode " << currentPrefix << endl;
string r = zoo->readNode(prefix + currentPrefix);
//cerr << "r = " << r << endl;
if (r != "") {
if (!onEntry(currentPrefix, Json::parse(r)))
return false;
}
vector<string> children = zoo->getChildren(prefix + currentPrefix,
false);
for (auto child: children) {
//cerr << "child = " << child << endl;
string newPrefix = currentPrefix + "/" + child;
if (currentPrefix.empty())
newPrefix = child;
if (!doNode(newPrefix))
return false;
}
return true;
};
if (!zoo->nodeExists(prefix + startPrefix)) {
return true;
}
return doNode(startPrefix);
}
void
ZookeeperConfigurationService::
removePath(const std::string & path)
{
ExcAssert(zoo);
zoo->removePath(prefix + path);
}
} // namespace Datacratic
| 27.664122
| 79
| 0.545116
|
sharpyfox
|
4ada621e9b0d35e0fc2dc045239521f1cd592c27
| 13,933
|
cc
|
C++
|
src/fluid/fluidmsg/fluid/ofcommon/common.cc
|
lionelgo/openair-mme
|
75bc0993613f61072342f5ae13dca28574253671
|
[
"BSD-3-Clause"
] | 19
|
2020-04-25T15:51:52.000Z
|
2021-11-24T04:51:02.000Z
|
src/fluid/fluidmsg/fluid/ofcommon/common.cc
|
lionelgo/openair-mme
|
75bc0993613f61072342f5ae13dca28574253671
|
[
"BSD-3-Clause"
] | 10
|
2020-09-09T09:54:20.000Z
|
2021-04-27T20:47:52.000Z
|
src/fluid/fluidmsg/fluid/ofcommon/common.cc
|
lionelgo/openair-mme
|
75bc0993613f61072342f5ae13dca28574253671
|
[
"BSD-3-Clause"
] | 24
|
2020-05-31T01:41:12.000Z
|
2022-01-16T17:06:35.000Z
|
#include "common.hh"
namespace fluid_msg {
PortCommon::PortCommon()
: hw_addr_(),
name_(),
config_(0),
state_(0),
curr_(0),
advertised_(0),
supported_(0),
peer_(0) {}
PortCommon::PortCommon(EthAddress hw_addr, std::string name, uint32_t config,
uint32_t state, uint32_t curr, uint32_t advertised,
uint32_t supported, uint32_t peer)
: hw_addr_(hw_addr),
name_(name),
config_(config),
state_(state),
curr_(curr),
advertised_(advertised),
supported_(supported),
peer_(peer) {}
bool PortCommon::operator==(const PortCommon &other) const {
return ((this->hw_addr_ == other.hw_addr_) && (this->name_ == other.name_) &&
(this->config_ == other.config_) && (this->state_ == other.state_) &&
(this->curr_ == other.curr_) &&
(this->advertised_ == other.advertised_) &&
(this->supported_ == other.supported_) &&
(this->peer_ == other.peer_));
}
bool PortCommon::operator!=(const PortCommon &other) const {
return !(*this == other);
}
QueueProperty::QueueProperty() : property_(0), len_(0) {}
QueueProperty::QueueProperty(uint16_t property)
: property_(property), len_(sizeof(struct ofp_queue_prop_header)) {}
bool QueueProperty::equals(const QueueProperty &other) {
return ((*this == other));
}
bool QueueProperty::operator==(const QueueProperty &other) const {
return ((this->property_ == other.property_) && (this->len_ == other.len_));
}
bool QueueProperty::operator!=(const QueueProperty &other) const {
return !(*this == other);
}
size_t QueueProperty::pack(uint8_t *buffer) {
struct ofp_queue_prop_header *qp = (struct ofp_queue_prop_header *)buffer;
qp->property = hton16(this->property_);
qp->len = hton16(this->len_);
return this->len_;
}
of_error QueueProperty::unpack(uint8_t *buffer) {
struct ofp_queue_prop_header *qp = (struct ofp_queue_prop_header *)buffer;
this->property_ = ntoh16(qp->property);
this->len_ = ntoh16(qp->len);
return 0;
}
QueuePropertyList::QueuePropertyList(std::list<QueueProperty *> property_list) {
this->property_list_ = property_list_;
for (std::list<QueueProperty *>::const_iterator it = property_list.begin();
it != property_list.end(); ++it) {
this->length_ += (*it)->len();
}
}
QueuePropertyList::QueuePropertyList(const QueuePropertyList &other) {
this->length_ = other.length_;
for (std::list<QueueProperty *>::const_iterator it =
other.property_list_.begin();
it != other.property_list_.end(); ++it) {
this->property_list_.push_back((*it)->clone());
}
}
QueuePropertyList::~QueuePropertyList() {
this->property_list_.remove_if(QueueProperty::delete_all);
}
bool QueuePropertyList::operator==(const QueuePropertyList &other) const {
std::list<QueueProperty *>::const_iterator ot = other.property_list_.begin();
for (std::list<QueueProperty *>::const_iterator it =
this->property_list_.begin();
it != this->property_list_.end(); ++it, ++ot) {
if (!((*it)->equals(**ot))) {
return false;
}
}
return true;
}
bool QueuePropertyList::operator!=(const QueuePropertyList &other) const {
return !(*this == other);
}
size_t QueuePropertyList::pack(uint8_t *buffer) {
uint8_t *p = buffer;
for (std::list<QueueProperty *>::iterator it = this->property_list_.begin(),
end = this->property_list_.end();
it != end; it++) {
(*it)->pack(p);
p += (*it)->len();
}
return 0;
}
of_error QueuePropertyList::unpack10(uint8_t *buffer) {
uint8_t *p = buffer;
size_t len = this->length_;
QueueProperty *prop;
while (len) {
uint16_t type = ntoh16(*((uint16_t *)p));
prop = QueueProperty::make_queue_of10_property(type);
prop->unpack(p);
this->property_list_.push_back(prop);
len -= prop->len();
p += prop->len();
}
return 0;
}
of_error QueuePropertyList::unpack13(uint8_t *buffer) {
uint8_t *p = buffer;
size_t len = this->length_;
QueueProperty *prop;
while (len) {
uint16_t type = ntoh16(*((uint16_t *)p));
prop = QueueProperty::make_queue_of13_property(type);
prop->unpack(p);
this->property_list_.push_back(prop);
len -= prop->len();
p += prop->len();
}
return 0;
}
QueuePropertyList &QueuePropertyList::operator=(QueuePropertyList other) {
swap(*this, other);
return *this;
}
void swap(QueuePropertyList &first, QueuePropertyList &second) {
std::swap(first.length_, second.length_);
std::swap(first.property_list_, second.property_list_);
}
void QueuePropertyList::add_property(QueueProperty *prop) {
this->property_list_.push_back(prop);
this->length_ += prop->len();
}
QueuePropRate::QueuePropRate() : QueueProperty(), rate_(0) {}
QueuePropRate::QueuePropRate(uint16_t property)
: QueueProperty(property), rate_(0){};
QueuePropRate::QueuePropRate(uint16_t property, uint16_t rate)
: QueueProperty(property), rate_(rate) {}
bool QueuePropRate::equals(const QueueProperty &other) {
if (const QueuePropRate *prop = dynamic_cast<const QueuePropRate *>(&other)) {
return ((QueueProperty::equals(other)) && (this->rate_ == prop->rate_));
} else {
return false;
}
}
PacketQueueCommon::PacketQueueCommon() : len_(0), queue_id_(0), properties_() {}
PacketQueueCommon::PacketQueueCommon(uint32_t queue_id)
: len_(0), queue_id_(queue_id) {}
void PacketQueueCommon::property(QueuePropertyList properties) {
this->properties_ = properties;
this->len_ += properties.length();
}
bool PacketQueueCommon::operator==(const PacketQueueCommon &other) const {
return ((this->properties_ == other.properties_) &&
(this->len_ == other.len_));
}
bool PacketQueueCommon::operator!=(const PacketQueueCommon &other) const {
return !(*this == other);
}
void PacketQueueCommon::add_property(QueueProperty *qp) {
this->properties_.add_property(qp);
this->len_ += qp->len();
}
SwitchDesc::SwitchDesc(std::string mfr_desc, std::string hw_desc,
std::string sw_desc, std::string serial_num,
std::string dp_desc) {
this->mfr_desc_ = mfr_desc;
this->hw_desc_ = hw_desc;
this->sw_desc_ = sw_desc;
this->serial_num_ = serial_num;
this->dp_desc_ = dp_desc;
}
bool SwitchDesc::operator==(const SwitchDesc &other) const {
return ((this->mfr_desc_ == other.mfr_desc_) &&
(this->hw_desc_ == other.hw_desc_) &&
(this->sw_desc_ == other.sw_desc_) &&
(this->serial_num_ == other.serial_num_) &&
(this->dp_desc_ == other.dp_desc_));
}
bool SwitchDesc::operator!=(const SwitchDesc &other) const {
return !(*this == other);
}
size_t SwitchDesc::pack(uint8_t *buffer) {
struct ofp_desc *ds = (struct ofp_desc *)buffer;
memset(ds->mfr_desc, 0x0, DESC_STR_LEN);
memset(ds->hw_desc, 0x0, DESC_STR_LEN);
memset(ds->sw_desc, 0x0, DESC_STR_LEN);
memset(ds->serial_num, 0x0, SERIAL_NUM_LEN);
memset(ds->dp_desc, 0x0, DESC_STR_LEN);
memcpy(ds->mfr_desc, this->mfr_desc_.c_str(),
this->mfr_desc_.size() < DESC_STR_LEN ? this->mfr_desc_.size()
: DESC_STR_LEN);
memcpy(ds->hw_desc, this->hw_desc_.c_str(),
this->hw_desc_.size() < DESC_STR_LEN ? this->hw_desc_.size()
: DESC_STR_LEN);
memcpy(ds->sw_desc, this->sw_desc_.c_str(),
this->sw_desc_.size() < DESC_STR_LEN ? this->sw_desc_.size()
: DESC_STR_LEN);
memcpy(ds->serial_num, this->serial_num_.c_str(),
this->serial_num_.size() < SERIAL_NUM_LEN ? this->serial_num_.size()
: SERIAL_NUM_LEN);
memcpy(ds->dp_desc, this->dp_desc_.c_str(),
this->dp_desc_.size() < DESC_STR_LEN ? this->dp_desc_.size()
: DESC_STR_LEN);
return 0;
}
of_error SwitchDesc::unpack(uint8_t *buffer) {
struct ofp_desc *ds = (struct ofp_desc *)buffer;
this->mfr_desc_ = std::string(ds->mfr_desc);
this->hw_desc_ = std::string(ds->hw_desc);
this->sw_desc_ = std::string(ds->sw_desc);
this->serial_num_ = std::string(ds->serial_num);
this->dp_desc_ = std::string(ds->dp_desc);
return 0;
}
FlowStatsCommon::FlowStatsCommon()
: length_(0),
table_id_(0),
duration_sec_(0),
duration_nsec_(0),
priority_(0),
idle_timeout_(0),
hard_timeout_(0),
cookie_(0),
packet_count_(0),
byte_count_(0) {}
FlowStatsCommon::FlowStatsCommon(uint8_t table_id, uint32_t duration_sec,
uint32_t duration_nsec, uint16_t priority,
uint16_t idle_timeout, uint16_t hard_timeout,
uint64_t cookie, uint64_t packet_count,
uint64_t byte_count)
: length_(0),
table_id_(table_id),
duration_sec_(duration_sec),
duration_nsec_(duration_nsec),
priority_(priority),
idle_timeout_(idle_timeout),
hard_timeout_(hard_timeout),
cookie_(cookie),
packet_count_(packet_count),
byte_count_(byte_count) {}
bool FlowStatsCommon::operator==(const FlowStatsCommon &other) const {
return ((this->table_id_ == other.table_id_) &&
(this->duration_sec_ == other.duration_sec_) &&
(this->duration_nsec_ == other.duration_nsec_) &&
(this->priority_ == other.priority_) &&
(this->idle_timeout_ == other.idle_timeout_) &&
(this->hard_timeout_ == other.hard_timeout_) &&
(this->cookie_ == other.cookie_) &&
(this->packet_count_ == other.packet_count_) &&
(this->byte_count_ == other.byte_count_));
}
bool FlowStatsCommon::operator!=(const FlowStatsCommon &other) const {
return !(*this == other);
}
TableStatsCommon::TableStatsCommon()
: table_id_(0), active_count_(0), lookup_count_(0), matched_count_(0) {}
TableStatsCommon::TableStatsCommon(uint8_t table_id, uint32_t active_count,
uint64_t lookup_count,
uint64_t matched_count)
: table_id_(table_id),
active_count_(active_count),
lookup_count_(lookup_count),
matched_count_(matched_count) {}
bool TableStatsCommon::operator==(const TableStatsCommon &other) const {
return ((this->table_id_ == other.table_id_) &&
(this->active_count_ == other.active_count_) &&
(this->lookup_count_ == other.lookup_count_) &&
(this->matched_count_ == other.matched_count_));
}
bool TableStatsCommon::operator!=(const TableStatsCommon &other) const {
return !(*this == other);
}
PortStatsCommon::PortStatsCommon() : collisions_(0) {}
PortStatsCommon::PortStatsCommon(struct port_rx_tx_stats rx_tx_stats,
struct port_err_stats err_stats,
uint64_t collisions) {
this->rx_tx_stats = rx_tx_stats;
this->err_stats = err_stats;
this->collisions_ = collisions;
}
bool PortStatsCommon::operator==(const PortStatsCommon &other) const {
return ((this->rx_tx_stats == other.rx_tx_stats) &&
(this->err_stats == other.err_stats) &&
(this->collisions_ == other.collisions_));
}
bool PortStatsCommon::operator!=(const PortStatsCommon &other) const {
return !(*this == other);
}
size_t PortStatsCommon::pack(uint8_t *buffer) {
struct port_rx_tx_stats *rt = (struct port_rx_tx_stats *)buffer;
struct port_err_stats *es =
(struct port_err_stats *)(buffer + sizeof(struct port_rx_tx_stats));
rt->rx_packets = hton64(this->rx_tx_stats.rx_packets);
rt->tx_packets = hton64(this->rx_tx_stats.tx_packets);
rt->rx_bytes = hton64(this->rx_tx_stats.rx_bytes);
rt->tx_bytes = hton64(this->rx_tx_stats.tx_bytes);
rt->rx_dropped = hton64(this->rx_tx_stats.rx_dropped);
rt->tx_dropped = hton64(this->rx_tx_stats.tx_dropped);
es->rx_errors = hton64(this->err_stats.rx_errors);
es->tx_errors = hton64(this->err_stats.tx_errors);
es->rx_frame_err = hton64(this->err_stats.rx_frame_err);
es->rx_over_err = hton64(this->err_stats.rx_over_err);
es->rx_crc_err = hton64(this->err_stats.rx_crc_err);
return 0;
}
of_error PortStatsCommon::unpack(uint8_t *buffer) {
struct port_rx_tx_stats *rt = (struct port_rx_tx_stats *)buffer;
struct port_err_stats *es =
(struct port_err_stats *)(buffer + sizeof(struct port_rx_tx_stats));
this->rx_tx_stats.rx_packets = hton64(rt->rx_packets);
this->rx_tx_stats.tx_packets = hton64(rt->tx_packets);
this->rx_tx_stats.rx_bytes = hton64(rt->rx_bytes);
this->rx_tx_stats.tx_bytes = hton64(rt->tx_bytes);
this->rx_tx_stats.rx_dropped = hton64(rt->rx_dropped);
this->rx_tx_stats.tx_dropped = hton64(rt->tx_dropped);
this->err_stats.rx_errors = hton64(es->rx_errors);
this->err_stats.tx_errors = hton64(es->tx_errors);
this->err_stats.rx_frame_err = hton64(es->rx_frame_err);
this->err_stats.rx_over_err = hton64(es->rx_over_err);
this->err_stats.rx_crc_err = hton64(es->rx_crc_err);
return 0;
}
QueueStatsCommon::QueueStatsCommon()
: queue_id_(0), tx_bytes_(0), tx_packets_(0), tx_errors_(0) {}
QueueStatsCommon::QueueStatsCommon(uint32_t queue_id, uint64_t tx_bytes,
uint64_t tx_packets, uint64_t tx_errors)
: queue_id_(queue_id),
tx_bytes_(tx_bytes),
tx_packets_(tx_packets),
tx_errors_(tx_errors) {}
bool QueueStatsCommon::operator==(const QueueStatsCommon &other) const {
return ((this->queue_id_ == other.queue_id_) &&
(this->tx_bytes_ == other.tx_bytes_) &&
(this->tx_packets_ == other.tx_packets_) &&
(this->tx_errors_ == other.tx_errors_));
}
bool QueueStatsCommon::operator!=(const QueueStatsCommon &other) const {
return !(*this == other);
}
} // End of namespace fluid_msg
| 34.317734
| 80
| 0.656355
|
lionelgo
|
4adc33604e648353d6d2e5170a482ca0824e84ed
| 8,353
|
cpp
|
C++
|
XMath/XErrHand/NT4ProcessInfo.cpp
|
koalefant/yasli
|
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
|
[
"MIT"
] | 8
|
2021-07-08T18:06:33.000Z
|
2022-01-17T18:29:57.000Z
|
XMath/XErrHand/NT4ProcessInfo.cpp
|
koalefant/yasli
|
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
|
[
"MIT"
] | null | null | null |
XMath/XErrHand/NT4ProcessInfo.cpp
|
koalefant/yasli
|
2096ed8a59ae9c7da467d8de8f1eb811a989dc39
|
[
"MIT"
] | 1
|
2021-12-31T15:52:56.000Z
|
2021-12-31T15:52:56.000Z
|
/*----------------------------------------------------------------------
John Robbins - Microsoft Systems Journal Bugslayer Column
Windows NT 4.0 access functions for getting to process information.
Windows95 and NT5 can use TOOLHELP32.DLL.
----------------------------------------------------------------------*/
#include "stdafx.h"
#include "PCH.h"
#include "BugslayerUtil.h"
/*//////////////////////////////////////////////////////////////////////
Typedefs
//////////////////////////////////////////////////////////////////////*/
// The typedefs for the PSAPI.DLL functions used by this module.
typedef BOOL (WINAPI *ENUMPROCESSMODULES) ( HANDLE hProcess ,
HMODULE * lphModule ,
DWORD cb ,
LPDWORD lpcbNeeded ) ;
typedef DWORD (WINAPI *GETMODULEBASENAME) ( HANDLE hProcess ,
HMODULE hModule ,
LPTSTR lpBaseName ,
DWORD nSize ) ;
/*//////////////////////////////////////////////////////////////////////
File Static Data
//////////////////////////////////////////////////////////////////////*/
// Has the function stuff here been initialized? This is only to be
// used by the InitPSAPI function and nothing else.
static BOOL g_bInitialized = FALSE ;
// The pointer to EnumProcessModules.
static ENUMPROCESSMODULES g_pEnumProcessModules = NULL ;
// The pointer to GetModuleBaseName.
static GETMODULEBASENAME g_pGetModuleBaseName = NULL ;
/*----------------------------------------------------------------------
FUNCTION : InitPSAPI
DISCUSSION :
Loads PSAPI.DLL and initializes all the pointers needed by this
file. If BugslayerUtil.DLL statically linked to PSAPI.DLL, it would not
work on Windows95.
Note that I conciously chose to allow the resource leak on loading
PSAPI.DLL.
PARAMETERS :
None.
RETURNS :
TRUE - Everything initialized properly.
FALSE - There was a problem.
----------------------------------------------------------------------*/
static BOOL InitPSAPI ( void )
{
if ( TRUE == g_bInitialized )
{
return ( TRUE ) ;
}
// Load up PSAPI.DLL.
HINSTANCE hInst = LoadLibraryA ( "PSAPI.DLL" ) ;
ASSERT ( NULL != hInst ) ;
if ( NULL == hInst )
{
TRACE0 ( "Unable to load PSAPI.DLL!\n" ) ;
return ( FALSE ) ;
}
// Now do the GetProcAddress stuff.
g_pEnumProcessModules =
(ENUMPROCESSMODULES)GetProcAddress ( hInst ,
"EnumProcessModules" ) ;
ASSERT ( NULL != g_pEnumProcessModules ) ;
if ( NULL == g_pEnumProcessModules )
{
TRACE0 ( "GetProcAddress failed on EnumProcessModules!\n" ) ;
return ( FALSE ) ;
}
g_pGetModuleBaseName =
(GETMODULEBASENAME)GetProcAddress ( hInst ,
"GetModuleBaseNameA" ) ;
ASSERT ( NULL != g_pGetModuleBaseName ) ;
if ( NULL == g_pGetModuleBaseName )
{
TRACE0 ( "GetProcAddress failed on GetModuleBaseNameA!\n" ) ;
return ( FALSE ) ;
}
// All OK, Jumpmaster!
g_bInitialized = TRUE ;
return ( TRUE ) ;
}
/*----------------------------------------------------------------------
FUNCTION : NT4GetLoadedModules
DISCUSSION :
The NT4 specific version of GetLoadedModules. This function assumes
that GetLoadedModules does the work to validate the parameters.
PARAMETERS :
dwPID - The process ID to look into.
uiCount - The number of slots in the paModArray buffer. If
this value is 0, then the return value will be TRUE
and puiRealCount will hold the number of items
needed.
paModArray - The array to place the HMODULES into. If this buffer
is too small to hold the result and uiCount is not
zero, then FALSE is returned, but puiRealCount will
be the real number of items needed.
puiRealCount - The count of items needed in paModArray, if uiCount
is zero, or the real number of items in paModArray.
RETURNS :
FALSE - There was a problem, check GetLastError.
TRUE - The function succeeded. See the parameter discussion for
the output parameters.
----------------------------------------------------------------------*/
BOOL NT4GetLoadedModules ( DWORD dwPID ,
UINT uiCount ,
HMODULE * paModArray ,
LPUINT puiRealCount )
{
// Initialize PSAPI.DLL, if needed.
if ( FALSE == InitPSAPI ( ) )
{
ASSERT ( FALSE ) ;
SetLastErrorEx ( ERROR_DLL_INIT_FAILED , SLE_ERROR ) ;
return ( FALSE ) ;
}
// Convert the process ID into a process handle.
HANDLE hProc = OpenProcess ( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ ,
FALSE ,
dwPID ) ;
ASSERT ( NULL != hProc ) ;
if ( NULL == hProc )
{
TRACE1 ( "Unable to OpenProcess on %08X\n" , dwPID ) ;
return ( FALSE ) ;
}
// Now get the modules for the specified process.
ASSERT ( NULL != g_pEnumProcessModules ) ;
// Because of possible DLL unload order differences, make sure that
// PSAPI.DLL is still loaded in case this function is called during
// shutdown.
ASSERT ( FALSE == IsBadCodePtr ( (FARPROC)g_pEnumProcessModules ) );
if ( TRUE == IsBadCodePtr ( (FARPROC)g_pEnumProcessModules ) )
{
TRACE0 ( "PSAPI.DLL has been unloaded on us!\n" ) ;
// Close the process handle used.
VERIFY ( CloseHandle ( hProc ) ) ;
SetLastErrorEx ( ERROR_INVALID_DLL , SLE_ERROR ) ;
return ( FALSE ) ;
}
DWORD dwTotal = 0 ;
BOOL bRet = g_pEnumProcessModules ( hProc ,
paModArray ,
uiCount * sizeof ( HMODULE ) ,
&dwTotal );
// Close the process handle used.
VERIFY ( CloseHandle ( hProc ) ) ;
// Convert the count from bytes to HMODULE values.
*puiRealCount = dwTotal / sizeof ( HMODULE ) ;
// If bRet was FALSE, and the user was not just asking for the
// total, there was a problem.
if ( ( ( FALSE == bRet ) && ( uiCount > 0 ) ) || ( 0 == dwTotal ) )
{
ASSERT ( FALSE ) ;
TRACE0 ( "EnumProcessModules failed!\n" ) ;
return ( FALSE ) ;
}
// If the total returned in puiRealCount is larger than the value in
// uiCount, then return an error. If uiCount is zero, then it is
// not an error.
if ( ( *puiRealCount > uiCount ) && ( uiCount > 0 ) )
{
ASSERT ( FALSE ) ;
TRACE0 ( "Buffer is too small in NT4GetLoadedModules!\n" ) ;
SetLastErrorEx ( ERROR_INSUFFICIENT_BUFFER , SLE_ERROR ) ;
return ( FALSE ) ;
}
// All OK, Jumpmaster!
SetLastError ( ERROR_SUCCESS ) ;
return ( TRUE ) ;
}
DWORD __stdcall NTGetModuleBaseName ( HANDLE hProcess ,
HMODULE hModule ,
LPTSTR lpBaseName ,
DWORD nSize )
{
// Initialize PSAPI.DLL, if needed.
if ( FALSE == InitPSAPI ( ) )
{
ASSERT ( FALSE ) ;
SetLastErrorEx ( ERROR_DLL_INIT_FAILED , SLE_ERROR ) ;
return ( FALSE ) ;
}
return ( g_pGetModuleBaseName ( hProcess ,
hModule ,
lpBaseName ,
nSize ) ) ;
}
| 38.851163
| 73
| 0.477912
|
koalefant
|
4adcff3d14f6a5d04685ea81eee3d833bd4ec8aa
| 599
|
cpp
|
C++
|
1-100/3.longest-substring-without-repeating-characters.cpp
|
chadwick2143/Leetcode-Problems
|
a07ad0165c86305a77acbf480bcba279316256af
|
[
"MIT"
] | null | null | null |
1-100/3.longest-substring-without-repeating-characters.cpp
|
chadwick2143/Leetcode-Problems
|
a07ad0165c86305a77acbf480bcba279316256af
|
[
"MIT"
] | null | null | null |
1-100/3.longest-substring-without-repeating-characters.cpp
|
chadwick2143/Leetcode-Problems
|
a07ad0165c86305a77acbf480bcba279316256af
|
[
"MIT"
] | 1
|
2021-07-27T07:03:05.000Z
|
2021-07-27T07:03:05.000Z
|
class Solution {
public:
int lengthOfLongestSubstring(const string& s) {
unordered_map<char, int> mapChrIdx;
int nMaxLen = 0;
int nChrBeg = -1;
int nChrIdx = 0;
for (const char& c : s)
{
if (mapChrIdx.count(c) == 1 && mapChrIdx[c] > nChrBeg)
{
nChrBeg = mapChrIdx[c];
}
else if (nChrIdx - nChrBeg > nMaxLen)
{
nMaxLen = nChrIdx - nChrBeg;
}
mapChrIdx[c] = nChrIdx;
++nChrIdx;
}
return nMaxLen;
}
};
| 24.958333
| 66
| 0.452421
|
chadwick2143
|
4adecf3561bc0798c3d9fca682a5604b1cc337ce
| 850
|
cpp
|
C++
|
client/UI/angelscript/RegistryUtils.cpp
|
vblanco20-1/NovusCore-Client
|
662596465a1851cb87240290f34544f4edf76aa0
|
[
"MIT"
] | null | null | null |
client/UI/angelscript/RegistryUtils.cpp
|
vblanco20-1/NovusCore-Client
|
662596465a1851cb87240290f34544f4edf76aa0
|
[
"MIT"
] | null | null | null |
client/UI/angelscript/RegistryUtils.cpp
|
vblanco20-1/NovusCore-Client
|
662596465a1851cb87240290f34544f4edf76aa0
|
[
"MIT"
] | null | null | null |
#include "RegistryUtils.h"
#include <entity/registry.hpp>
#include <angelscript.h>
#include "../../Scripting/ScriptEngine.h"
#include "../../Utils/ServiceLocator.h"
#include "../ECS/Components/Singletons/UILockSingleton.h"
namespace UIUtils::Registry
{
void RegisterNamespace()
{
i32 r = ScriptEngine::SetNamespace("UI"); assert(r >= 0);
{
r = ScriptEngine::RegisterScriptFunction("LockToken@ GetLock(uint8 state)", asFUNCTION(GetLock)); assert(r >= 0);
}
r = ScriptEngine::ResetNamespace();
}
UIScripting::LockToken* GetLock(UIScripting::LockState state)
{
entt::registry* registry = ServiceLocator::GetUIRegistry();
auto lockSingleton = ®istry->ctx<UISingleton::UILockSingleton>();
return new UIScripting::LockToken(lockSingleton->mutex, state);
}
}
| 31.481481
| 125
| 0.667059
|
vblanco20-1
|
4ae17bffcf832c2d3d387c99b83e349b73b95b58
| 1,749
|
hpp
|
C++
|
CSGOSimple/features/visuals.hpp
|
dodo343434/aurawareSelfLeak
|
ca05649ce42fb4ceed7dea52e04f73d0627feb65
|
[
"MIT"
] | null | null | null |
CSGOSimple/features/visuals.hpp
|
dodo343434/aurawareSelfLeak
|
ca05649ce42fb4ceed7dea52e04f73d0627feb65
|
[
"MIT"
] | null | null | null |
CSGOSimple/features/visuals.hpp
|
dodo343434/aurawareSelfLeak
|
ca05649ce42fb4ceed7dea52e04f73d0627feb65
|
[
"MIT"
] | null | null | null |
#pragma once
class C_BasePlayer;
class C_BaseEntity;
class C_BaseCombatWeapon;
class C_PlantedC4;
class Color;
class ClientClass;
class CUserCmd;
extern unsigned long esp_font;
extern unsigned long hit_font;
namespace Visuals
{
namespace Player
{
bool Begin(C_BasePlayer* pl);
void RenderBox();
void RenderName();
void RenderHealth();
void RenderArmour();
void RenderWeapon();
void RenderSnapline();
//void BoneESP(C_BasePlayer * entity);
void HeadEsp(C_BasePlayer * entity);
void KevESP(C_BasePlayer * entity);
void EyePos(C_BasePlayer * ent);
}
namespace Misc
{;
void Radar();
void RenderC4Info(C_PlantedC4 * ent);
void Flash(C_BasePlayer * entity);
void GrenESP(C_BaseCombatWeapon * m_nade);
void EyePos(C_BasePlayer * ent);
void Skel(C_BasePlayer * ent);
void SniperX(C_BasePlayer * entity);
void RenderWeapon(C_BaseCombatWeapon* ent)
;
void RenderNet(C_BasePlayer * Player);
void RenderDefuseKit(C_BasePlayer * ent);
//void RenderDefuseKit(C_BaseEntity* ent);
void RenderPlantedC4(C_BaseEntity* ent);
void NightMode();
void KnifeLeft();
void RecoilCrosshair();
void SkyChanger();
void ColorModulateSkybox();
void ThirdPerson();
void Noscope();
void SetLocalPlayerReady();
//void DamageInd;
//void Recoilx(C_BaseEntity * loc, C_BasePlayer * ply);
}
/* if (g_Options.ColorSkybox)
{
Visuals::Misc::ColorModulateSkybox();
}/**/
bool CreateFonts();
void DestroyFonts();
bool IsVisibleScan(C_BasePlayer * player);
void DrawString(unsigned long font, int x, int y, Color color, unsigned long alignment, const char * msg, ...);
void Hitbox(int index);
}
| 16.817308
| 112
| 0.683248
|
dodo343434
|
4ae471ce2322fd2eb3a37e23556ac93916f5ae13
| 1,270
|
hpp
|
C++
|
src/oath/base32.hpp
|
animeslave/bbauth
|
d10861c8a4a72ee8186fb11de739556c03cbfc4d
|
[
"Apache-2.0"
] | 1
|
2021-05-20T03:50:21.000Z
|
2021-05-20T03:50:21.000Z
|
src/oath/base32.hpp
|
animeslave/bbry-gauth
|
d10861c8a4a72ee8186fb11de739556c03cbfc4d
|
[
"Apache-2.0"
] | 3
|
2021-05-20T03:52:23.000Z
|
2021-05-20T16:20:29.000Z
|
src/oath/base32.hpp
|
BerryTrucks/bbry-gauth
|
1d6850a0a7756077f55b8253b18611bc3df5045d
|
[
"Apache-2.0"
] | 1
|
2021-05-20T03:51:14.000Z
|
2021-05-20T03:51:14.000Z
|
//////////////////////////////////////////////////////////////////////
// Base32.h
//////////////////////////////////////////////////////////////////////
#ifndef BASE32_HPP_
#define BASE32_HPP_
#include <stdint.h>
/*
Base32 encoding / decoding.
Encode32 outputs at out bytes with values from 0 to 32 that can be mapped to 32 signs.
Decode32 input is the output of Encode32. The out parameters should be unsigned char[] of
length GetDecode32Length(inLen) and GetEncode32Length(inLen) respectively.
To map the output of Encode32 to an alphabet of 32 characters use Map32.
To unmap back the output of Map32 to an array understood by Decode32 use Unmap32.
Both Map32 and Unmap32 do inplace modification of the inout32 array.
The alpha32 array must be exactly 32 chars long.
*/
struct Base32
{
static bool Decode32(unsigned char* in, int inLen, unsigned char* out);
static bool Encode32(unsigned char* in, int inLen, unsigned char* out);
static int GetDecode32Length(int bytes);
static int GetEncode32Length(int bytes);
static bool Map32(unsigned char* inout32, int inout32Len, unsigned char* alpha32);
static bool Unmap32(unsigned char* inout32, int inout32Len, unsigned char* alpha32);
};
#endif /* BASE32_HPP_ */
| 37.352941
| 91
| 0.662992
|
animeslave
|
4ae7be5391a247fdb49f2c6a31f7ca2d7f6c61e0
| 1,130
|
cpp
|
C++
|
src/ROSUnit_UpdateReference.cpp
|
CaptCrunch333/positioning_system
|
62da7f2773dae9a66f3e89d6134453fba526bb11
|
[
"BSD-3-Clause"
] | null | null | null |
src/ROSUnit_UpdateReference.cpp
|
CaptCrunch333/positioning_system
|
62da7f2773dae9a66f3e89d6134453fba526bb11
|
[
"BSD-3-Clause"
] | null | null | null |
src/ROSUnit_UpdateReference.cpp
|
CaptCrunch333/positioning_system
|
62da7f2773dae9a66f3e89d6134453fba526bb11
|
[
"BSD-3-Clause"
] | null | null | null |
#include "ROSUnit_UpdateReference.hpp"
//TODO rename the topics and class
ROSUnit_UpdateReference* ROSUnit_UpdateReference::_instance_ptr = NULL;
UpdatePoseMessage ROSUnit_UpdateReference::_pose_ref_msg;
ROSUnit_UpdateReference::ROSUnit_UpdateReference(ros::NodeHandle& t_main_handler) : ROSUnit(t_main_handler) {
_srv_setpoint = t_main_handler.advertiseService("update_pose_reference", callbackSetpoint);
_instance_ptr = this;
}
ROSUnit_UpdateReference::~ROSUnit_UpdateReference() {
}
void ROSUnit_UpdateReference::receive_msg_data(DataMessage* t_msg){
}
bool ROSUnit_UpdateReference::callbackSetpoint( positioning_system::Update_Pose_Reference::Request &req,
positioning_system::Update_Pose_Reference::Response &res){
//TODO change to receive only one reference at a time
float x, y, z, yaw;
x = req.setpoint_pose.x;
y = req.setpoint_pose.y;
z = req.setpoint_pose.z;
yaw = req.setpoint_pose.yaw;
_pose_ref_msg.setPoseMessage(x, y, z, yaw);
_instance_ptr->emit_message((DataMessage*) &_pose_ref_msg);
return true;
}
| 30.540541
| 109
| 0.738938
|
CaptCrunch333
|
4ae8970872e04db2464dc837d48998bde06abfbb
| 2,675
|
hpp
|
C++
|
include/board.hpp
|
oschonrock/chess
|
51da68c767879ef44a7fcdba85ae9a212ceb7b8b
|
[
"BSD-3-Clause"
] | null | null | null |
include/board.hpp
|
oschonrock/chess
|
51da68c767879ef44a7fcdba85ae9a212ceb7b8b
|
[
"BSD-3-Clause"
] | null | null | null |
include/board.hpp
|
oschonrock/chess
|
51da68c767879ef44a7fcdba85ae9a212ceb7b8b
|
[
"BSD-3-Clause"
] | null | null | null |
/**
* File: board.h
*
* Content on and manipulation of a chess board implemented as 10x12 squares,
* with default out_of_border values.
*
* "magic" numbers will be used, they aren't magic if you know this structure.
* Source way too messy with a lot of variable names and variable calculations instead of plain
* numbers.
*
* Author: Ken Rouwas
* Date 2017-09-14
*
* Refactored and expanded upon by Oliver Schönrock - 2021
*/
#pragma once
#include <array>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <sys/types.h>
#include <vector>
namespace chess {
constexpr size_t board_size = 10 * 12;
enum class color { white, black, none };
inline color flip_turn(color turn) { return (turn == color::white) ? color::black : color::white; }
enum class piece : int {
king, // a king without castle potential
king_castle, // a king with castle potential
queen,
pawn, // a pawn without en passant potential
pawn_en_passant, // a pawn with en passant potential
rook,
rook_castle,
knight,
bishop,
none,
out_of_board // Illegal position
};
struct square {
square() = default;
square(piece p, color c) : piece_color_(c), piece_(p) {}
color piece_color_ = color::none;
piece piece_ = piece::out_of_board;
};
struct board_change {
board_change() : where_(move_done) {} // default is terminator, at end of move sequence
board_change(ssize_t where, square old_square) : where_(where), old_square_(old_square) {}
[[nodiscard]] bool is_terminator() const { return where_ == move_done; }
size_t where_;
square old_square_;
constexpr static size_t move_done = board_size;
};
class board {
public:
void init();
void set(const size_t where, square s) {
if (where >= board_size) throw std::out_of_range("board::set : out of range error");
squares_[where] = s;
}
[[nodiscard]] square get(const size_t where) const {
if (where >= board_size) throw std::out_of_range("board::get : out of range error");
return squares_[where];
}
void undo_move() {
if (bh_.empty()) return;
if (bh_.back().is_terminator()) bh_.pop_back();
while (!bh_.empty() && !bh_.back().is_terminator()) {
set(bh_.back().where_, bh_.back().old_square_);
bh_.pop_back();
}
}
void do_change(size_t where, square new_square) {
bh_.emplace_back(where, get(where));
set(where, new_square);
}
void terminate_change() {
bh_.emplace_back(); // default constructor gives the terminator
}
private:
std::array<square, board_size> squares_;
std::vector<board_change> bh_;
};
std::string where_to_str(size_t where);
} // namespace chess
| 24.768519
| 99
| 0.680374
|
oschonrock
|
4aece99356a22bba0e4530067873fc7e15b0d15f
| 605
|
hpp
|
C++
|
top-k_OAFP_pos/src/varlist.hpp
|
ShowHey57/top-k_AOFP_pos
|
afbd69ca41a73dc5f0fcd86cad643a01df16e0a9
|
[
"MIT"
] | null | null | null |
top-k_OAFP_pos/src/varlist.hpp
|
ShowHey57/top-k_AOFP_pos
|
afbd69ca41a73dc5f0fcd86cad643a01df16e0a9
|
[
"MIT"
] | null | null | null |
top-k_OAFP_pos/src/varlist.hpp
|
ShowHey57/top-k_AOFP_pos
|
afbd69ca41a73dc5f0fcd86cad643a01df16e0a9
|
[
"MIT"
] | null | null | null |
#ifndef VAR_LIST_HPP_
#define VAR_LIST_HPP_
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <vector>
#include "constant_numbers.hpp"
#include "common_functions.hpp"
#include "vardata.hpp"
class VarList{
private:
std::vector<VarData*> varlist_; //pointer of VarData's vector
public:
VarList(): varlist_(0){};
~VarList(){};
void Init();
void Set(VarData* kVdata);
void Push(VarData* kVdata);
uint64_t Pop();
bool IsEmpty();
void Free();
VarData* VpPop();
uint64_t Size();
uint64_t GetVar();
uint64_t GetFreq();
};
#endif // VAR_LIST_HPP_
| 18.333333
| 63
| 0.67438
|
ShowHey57
|
4aefe700dc764e8752c22c91169835f102615662
| 38,368
|
cpp
|
C++
|
TEST_APPS/device/socket_app/cmd_socket.cpp
|
c1728p9/mbed
|
784fa91294fb4849ab761fe558af7c3cfa2a9174
|
[
"Apache-2.0"
] | null | null | null |
TEST_APPS/device/socket_app/cmd_socket.cpp
|
c1728p9/mbed
|
784fa91294fb4849ab761fe558af7c3cfa2a9174
|
[
"Apache-2.0"
] | 5
|
2018-08-15T12:02:20.000Z
|
2018-09-03T11:28:18.000Z
|
TEST_APPS/device/socket_app/cmd_socket.cpp
|
c1728p9/mbed
|
784fa91294fb4849ab761fe558af7c3cfa2a9174
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2018 ARM Limited. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
* 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 "mbed.h"
#include "NetworkStack.h"
#include "UDPSocket.h"
#include "TCPSocket.h"
#include "TCPServer.h"
#include "NetworkInterface.h"
#include "SocketAddress.h"
#include "Queue.h"
#include <vector>
#include <cctype>
#include <cassert>
#include <cstring>
#ifndef __STDC_FORMAT_MACROS
#define __STDC_FORMAT_MACROS
#endif
#include <inttypes.h>
#include "mbed-client-cli/ns_cmdline.h"
#include "mbed-trace/mbed_trace.h"
#include "strconv.h"
#define TRACE_GROUP "Asck"
#include "cmd_ifconfig.h"
#include "cmd_socket.h"
#define SIGNAL_SIGIO 0x1
#define PACKET_SIZE_ARRAY_LEN 5
#define MAN_SOCKET "\r\nSOCKET API\r\n"\
"\r\n"\
"socket <operation> [options]\r\n\r\n"\
" new <type>\r\n" \
" type: UDPSocket|TCPSocket|TCPServer\r\n"\
" return socket id\r\n"\
" <id> delete\r\n"\
" remote the space allocated for Socket\r\n"\
" <id> open\r\n"\
" <id> close\r\n"\
" <id> bind [port] <port> [addr <addr>]\r\n"\
" <id> set_blocking <bool>\r\n"\
" <id> set_timeout <ms>\r\n"\
" <id> register_sigio_cb\r\n"\
" <id> set_RFC_864_pattern_check <true|false>\r\n"\
"\r\nFor UDPSocket\r\n"\
" <id> sendto <addr> <port> (\"msg\" | --data_len <len>)\r\n"\
" \"msg\" Send packet with defined string content\r\n"\
" --data_len Send packet with random content with size <len>\r\n"\
" <id> recvfrom <len>\r\n"\
" <id> start_udp_receiver_thread --max_data_len <len> [--packets <N>]\r\n"\
" --max_data_len Size of input buffer to fill up\r\n"\
" --packets Receive N number of packets, default 1\r\n"\
"\r\nFor TCPSocket\r\n"\
" <id> connect <host> <port>\r\n"\
" <id> send (\"msg\" | --data_len <len>)\r\n"\
" <id> recv <len>\r\n"\
" <id> start_tcp_receiver_thread --data_len <len> [--max_recv_len <L>] [--repeat <N>]\r\n"\
" --data_len Size of input buffer to fill up\r\n"\
" --max_recv_len Read maximum of L bytes in at a time. Default full buffer <len>\r\n"\
" --repeat Repeat buffer filling N times, default 1\r\n"\
" <id> join_tcp_receiver_thread\r\n"\
" <id> start_bg_traffic_thread\r\n"\
" <id> join_bg_traffic_thread\r\n"\
" <id> setsockopt_keepalive <seconds[0-7200]>\r\n"\
" <id> getsockopt_keepalive\r\n"\
"\r\nFor TCPServer\r\n"\
" <id> listen [backlog]\r\n"\
" <id> accept <new_id>\r\n"\
" accept new connection into <new_id> socket. Requires <new_id> to be pre-allocated.\r\n"\
"\r\nOther options\r\n"\
" print-mode [--string|--hex|--disabled] [--col-width <width>]"
class SInfo;
static Queue<SInfo, 10> event_queue;
static int id_count = 0;
class SInfo {
public:
enum SocketType {
TCP_CLIENT,
TCP_SERVER,
UDP
};
SInfo(TCPSocket *sock):
_id(id_count++),
_sock(sock),
_type(SInfo::TCP_CLIENT),
_blocking(true),
_dataLen(0),
_maxRecvLen(0),
_repeatBufferFill(1),
_receivedTotal(0),
_receiverThread(NULL),
_receiveBuffer(NULL),
_senderThreadId(NULL),
_receiverThreadId(NULL),
_packetSizes(NULL),
_check_pattern(false)
{
assert(sock);
}
SInfo(TCPServer *sock):
_id(id_count++),
_sock(sock),
_type(SInfo::TCP_SERVER),
_blocking(true),
_dataLen(0),
_maxRecvLen(0),
_repeatBufferFill(1),
_receivedTotal(0),
_receiverThread(NULL),
_receiveBuffer(NULL),
_senderThreadId(NULL),
_receiverThreadId(NULL),
_packetSizes(NULL),
_check_pattern(false)
{
assert(sock);
}
SInfo(UDPSocket *sock):
_id(id_count++),
_sock(sock),
_type(SInfo::UDP),
_blocking(true),
_dataLen(0),
_maxRecvLen(0),
_repeatBufferFill(1),
_receivedTotal(0),
_receiverThread(NULL),
_receiveBuffer(NULL),
_senderThreadId(NULL),
_receiverThreadId(NULL),
_packetSizes(NULL),
_check_pattern(false)
{
assert(sock);
}
~SInfo()
{
this->_sock->sigio(Callback<void()>());
if (this->_receiverThread) {
this->_receiverThread->terminate();
delete this->_receiverThread;
}
if (this->_receiveBuffer) {
delete this->_receiveBuffer;
}
delete this->_sock;
}
int id() const
{
return this->_id;
}
Socket &socket()
{
return *(this->_sock);
}
Socket &socket() const
{
return *(this->_sock);
}
TCPSocket *tcp_socket()
{
return this->_type == SInfo::TCP_CLIENT ? static_cast<TCPSocket *>(this->_sock) : NULL;
}
TCPServer *tcp_server()
{
return this->_type == SInfo::TCP_SERVER ? static_cast<TCPServer *>(this->_sock) : NULL;
}
UDPSocket *udp_socket()
{
return this->_type == SInfo::UDP ? static_cast<UDPSocket *>(this->_sock) : NULL;
}
SInfo::SocketType type() const
{
return this->_type;
}
void setDataCount(int dataCount)
{
this->_dataLen = dataCount;
}
int getDataCount()
{
return this->_dataLen;
}
void setReceiverThread(Thread *receiverThread)
{
this->_receiverThread = receiverThread;
}
Thread *getReceiverThread()
{
return this->_receiverThread;
}
void setReceiveBuffer(uint8_t *receiveBuffer)
{
this->_receiveBuffer = receiveBuffer;
}
uint8_t *getReceiveBuffer()
{
return this->_receiveBuffer;
}
void setMaxRecvLen(int recvLen)
{
this->_maxRecvLen = recvLen;
}
int getMaxRecvLen()
{
return this->_maxRecvLen;
}
void setRepeatBufferFill(int n)
{
this->_repeatBufferFill = n;
}
int getRepeatBufferFill()
{
return this->_repeatBufferFill;
}
void setRecvTotal(int n)
{
this->_receivedTotal = n;
}
int getRecvTotal()
{
return this->_receivedTotal;
}
void setSenderThreadId(osThreadId threadID)
{
this->_senderThreadId = threadID;
}
void setReceiverThreadId(osThreadId threadID)
{
this->_receiverThreadId = threadID;
}
osThreadId getSenderThreadId()
{
return this->_senderThreadId;
}
osThreadId getReceiverThreadId()
{
return this->_receiverThreadId;
}
void setPacketSizeArray(int *ptr)
{
this->_packetSizes = ptr;
}
int *getPacketSizeArray()
{
return this->_packetSizes;
}
void setUnavailable()
{
this->_available = false;
}
void setAvailable()
{
this->_available = true;
}
bool available()
{
return this->_available;
}
void set_pattern_check(bool enabled)
{
_check_pattern = enabled;
};
bool check_pattern(void *buffer, size_t len);
const char *type_str() const
{
const char *str;
switch (this->_type) {
case SInfo::TCP_CLIENT:
str = "TCPSocket";
break;
case SInfo::TCP_SERVER:
str = "TCPServer";
break;
case SInfo::UDP:
str = "UDPSocket";
break;
default:
assert(0);
break;
}
return str;
}
bool blocking() const
{
return this->_blocking;
}
void set_blocking(bool blocking)
{
socket().set_blocking(blocking);
this->_blocking = blocking;
}
bool can_connect()
{
return (this->type() == SInfo::TCP_CLIENT);
}
bool can_bind()
{
return (this->type() == SInfo::UDP || this->type() == SInfo::TCP_SERVER);
}
bool can_send()
{
return (this->type() == SInfo::TCP_CLIENT);
}
bool can_recv()
{
return (this->type() == SInfo::TCP_CLIENT);
}
bool can_sendto()
{
return (this->type() == SInfo::UDP);
}
bool can_recvfrom()
{
return (this->type() == SInfo::UDP);
}
bool can_listen()
{
return (this->type() == SInfo::TCP_SERVER);
}
bool can_accept()
{
return (this->type() == SInfo::TCP_SERVER);
}
private:
const int _id;
Socket *_sock;
const SInfo::SocketType _type;
bool _blocking;
int _dataLen;
int _maxRecvLen;
int _repeatBufferFill;
int _receivedTotal;
Thread *_receiverThread;
uint8_t *_receiveBuffer;
osThreadId _senderThreadId;
osThreadId _receiverThreadId;
int *_packetSizes;
bool _available;
bool _check_pattern;
SInfo();
};
static std::vector<SInfo *> m_sockets;
static enum {
PRINT_DISABLED,
PRINT_STRING,
PRINT_HEX
} printing_mode = PRINT_STRING;
static int printing_col_width = 20;
static int cmd_socket(int argc, char *argv[]);
static void print_data(const uint8_t *buf, int len);
static void print_data_as_string(const uint8_t *buf, int len, int col_width);
static void print_data_as_hex(const uint8_t *buf, int len, int col_width);
/** Generate RFC 864 example pattern.
*
* Pattern is 72 chraracter lines of the ASCII printing characters ending with "\r\n".
* There are 95 printing characters in the ASCII character set.
* Example: `nc echo.mbedcloudtesting.com 19 | dd bs=1 count=222`
* !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefg
* !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefgh
* "#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghi
*
* NOTE: Pattern starts with space, not !
*
* \param offset Start pattern from offset
* \param len Length of pattern to generate.
*/
static void generate_RFC_864_pattern(size_t offset, uint8_t *buf, size_t len)
{
while (len--) {
if (offset % 74 == 72) {
*buf++ = '\r';
} else if (offset % 74 == 73) {
*buf++ = '\n';
} else {
*buf++ = ' ' + (offset % 74 + offset / 74) % 95 ;
}
offset++;
}
}
bool SInfo::check_pattern(void *buffer, size_t len)
{
if (!_check_pattern) {
return true;
}
void *buf = malloc(len);
if (!buf) {
return false;
}
size_t offset = _receivedTotal;
generate_RFC_864_pattern(offset, (uint8_t *)buf, len);
bool match = memcmp(buf, buffer, len) == 0;
if (!match) {
cmd_printf("Pattern check failed\r\nWAS:%.*s\r\nREF:%.*s\r\n", len, (char *)buffer, len, (char *)buf);
}
free(buf);
return match;
}
static void sigio_handler(SInfo *info)
{
if (info->getReceiverThreadId()) {
osSignalSet(info->getReceiverThreadId(), SIGNAL_SIGIO);
}
if (info->getSenderThreadId()) {
osSignalSet(info->getSenderThreadId(), SIGNAL_SIGIO);
}
}
void cmd_socket_init(void)
{
cmd_add("socket", cmd_socket, "socket", MAN_SOCKET);
}
int handle_nsapi_error(const char *function, nsapi_error_t ret)
{
if (ret != NSAPI_ERROR_OK) {
cmd_printf("%s returned: %d -> %s\r\n", function, ret, networkstack_error_to_str(ret));
return CMDLINE_RETCODE_FAIL;
}
return CMDLINE_RETCODE_SUCCESS;
}
int handle_nsapi_size_or_error(const char *function, nsapi_size_or_error_t ret)
{
if (ret < 0) {
return handle_nsapi_error(function, ret);
} else {
cmd_printf("%s returned: %d\r\n", function, ret);
}
return CMDLINE_RETCODE_SUCCESS;
}
static SInfo *get_sinfo(int id)
{
for (std::vector<SInfo *>::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) {
if ((*it)->id() == id) {
return *it;
}
}
return NULL;
}
static int del_sinfo(SInfo *info)
{
for (std::vector<SInfo *>::iterator it = m_sockets.begin(); it != m_sockets.end(); it++) {
if ((*it) == info) {
delete info;
m_sockets.erase(it);
return CMDLINE_RETCODE_SUCCESS;
}
}
return CMDLINE_RETCODE_FAIL;
}
static int cmd_socket_new(int argc, char *argv[])
{
const char *s;
SInfo *info;
if (cmd_parameter_last(argc, argv)) {
s = cmd_parameter_last(argc, argv);
if (strcmp(s, "UDPSocket") == 0) {
tr_debug("Creating a new UDPSocket");
info = new SInfo(new UDPSocket);
} else if (strcmp(s, "TCPSocket") == 0) {
tr_debug("Creating a new TCPSocket");
info = new SInfo(new TCPSocket);
} else if (strcmp(s, "TCPServer") == 0) {
tr_debug("Creating a new TCPServer");
info = new SInfo(new TCPServer);
} else {
cmd_printf("unsupported protocol: %s\r\n", s);
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
} else {
cmd_printf("Must specify socket type\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
// Note, this cannot fail. We either succeed or "new" woud call exit(1) in failure.
// We did not ask no_throw version of it.
cmd_printf("new socket. sid: %d\r\n", info->id());
m_sockets.push_back(info);
return CMDLINE_RETCODE_SUCCESS;
}
static void udp_receiver_thread(SInfo *info)
{
SocketAddress addr;
int i = 0, received = 0;
int n = info->getRepeatBufferFill();
int *packetSizes = info->getPacketSizeArray();
nsapi_size_or_error_t ret = 0;
info->setReceiverThreadId(Thread::gettid());
while (i < n) {
ret = static_cast<UDPSocket &>(info->socket()).recvfrom(&addr, info->getReceiveBuffer() + received, info->getDataCount() - received);
if (ret > 0) {
if (!info->check_pattern(info->getReceiveBuffer() + received, ret)) {
return;
}
received += ret;
packetSizes[i % PACKET_SIZE_ARRAY_LEN] = ret;
i++;
info->setRecvTotal(info->getRecvTotal() + ret);
} else if (ret == NSAPI_ERROR_WOULD_BLOCK) {
Thread::signal_wait(SIGNAL_SIGIO);
} else {
handle_nsapi_size_or_error("Thread: UDPSocket::recvfrom()", ret);
return;
}
}
}
static nsapi_size_or_error_t start_udp_receiver_thread(SInfo *info, int argc, char *argv[])
{
int32_t max_size;
int32_t n = 1;
if (!cmd_parameter_int(argc, argv, "--max_data_len", &max_size)) {
cmd_printf("Need data max data size\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
if (cmd_parameter_index(argc, argv, "--packets") > 0) {
if (!cmd_parameter_int(argc, argv, "--packets", &n)) {
cmd_printf("Need number of packets\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
}
uint8_t *dataIn = (uint8_t *)malloc(max_size + 1);
if (!dataIn) {
cmd_printf("malloc() failed\r\n");
return CMDLINE_RETCODE_FAIL;
}
int *packetSizes = new (nothrow) int[PACKET_SIZE_ARRAY_LEN];
if (!packetSizes) {
cmd_printf("Allocation failed\r\n");
return CMDLINE_RETCODE_FAIL;
}
for (int i = 0; i < PACKET_SIZE_ARRAY_LEN; i++) {
packetSizes[i] = 0;
}
memset(dataIn, 0x00, max_size + 1);
info->setReceiveBuffer(dataIn);
info->setDataCount(max_size);
info->setRepeatBufferFill(n);
info->setPacketSizeArray(packetSizes);
info->setReceiverThread(new Thread());
info->getReceiverThread()->start(callback(udp_receiver_thread, info));
return CMDLINE_RETCODE_SUCCESS;
}
static nsapi_size_or_error_t udp_sendto_command_handler(SInfo *info, int argc, char *argv[])
{
char *host;
int32_t port;
if (!cmd_parameter_val(argc, argv, "sendto", &host)) {
cmd_printf("Need host name\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
if (!cmd_parameter_int(argc, argv, host, &port)) {
cmd_printf("Need port number\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
// Replace NULL-strings with NULL
host = strcmp(host, "NULL") ? host : NULL;
int32_t len;
void *data;
if (cmd_parameter_int(argc, argv, "--data_len", &len)) {
data = malloc(len);
if (!data) {
cmd_printf("Failed to allocate memory\r\n");
return CMDLINE_RETCODE_FAIL;
}
} else {
// Replace NULL-strings with NULL
if (strcmp(argv[5], "NULL") == 0) {
data = NULL;
len = 0;
} else {
data = argv[5];
len = strlen(argv[5]);
}
}
nsapi_size_or_error_t ret = static_cast<UDPSocket &>(info->socket()).sendto(host, port, data, len);
if (ret > 0) {
cmd_printf("sent: %d bytes\r\n", ret);
}
if (data != argv[5]) {
free(data);
}
return handle_nsapi_size_or_error("UDPSocket::sendto()", ret);
}
static nsapi_size_or_error_t udp_recvfrom_command_handler(SInfo *info, int argc, char *argv[])
{
SocketAddress addr;
int32_t len;
if (!cmd_parameter_int(argc, argv, "recvfrom", &len)) {
cmd_printf("Need len\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
void *data = malloc(len);
if (!data) {
cmd_printf("malloc() failed\r\n");
return CMDLINE_RETCODE_FAIL;
}
nsapi_size_or_error_t ret = static_cast<UDPSocket &>(info->socket()).recvfrom(&addr, data, len);
if (ret > 0) {
cmd_printf("UDPSocket::recvfrom, addr=%s port=%d\r\n", addr.get_ip_address(), addr.get_port());
cmd_printf("received: %d bytes\r\n", ret);
print_data((const uint8_t *)data, len);
if (!info->check_pattern(data, len)) {
ret = -1;
}
info->setRecvTotal(info->getRecvTotal() + ret);
}
free(data);
return handle_nsapi_size_or_error("UDPSocket::recvfrom()", ret);
}
static void tcp_receiver_thread(SInfo *info)
{
int i, received;
int n = info->getRepeatBufferFill();
int recv_len = info->getMaxRecvLen();
int bufferSize = info->getDataCount();
nsapi_size_or_error_t ret = 0;
info->setReceiverThreadId(Thread::gettid());
for (i = 0; i < n; i++) {
received = 0;
while (received < bufferSize) {
ret = static_cast<TCPSocket &>(info->socket()).recv(info->getReceiveBuffer() + received, recv_len - received);
if (ret > 0) {
if (!info->check_pattern(info->getReceiveBuffer() + received, ret)) {
return;
}
received += ret;
info->setRecvTotal(info->getRecvTotal() + ret);
} else if (ret == NSAPI_ERROR_WOULD_BLOCK) {
Thread::signal_wait(SIGNAL_SIGIO);
} else {
handle_nsapi_size_or_error("Thread: TCPSocket::recv()", ret);
return;
}
}
}
}
static nsapi_size_or_error_t start_tcp_receiver_thread(SInfo *info, int argc, char *argv[])
{
int32_t len;
int32_t recv_len;
int32_t n = 1;
if (!cmd_parameter_int(argc, argv, "--data_len", &len)) {
cmd_printf("Need data len\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
recv_len = len;
if (cmd_parameter_index(argc, argv, "--max_recv_len") > 0) {
if (!cmd_parameter_int(argc, argv, "--max_recv_len", &recv_len)) {
cmd_printf("Need max recv len\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
}
if (cmd_parameter_index(argc, argv, "--repeat") > 0) {
if (!cmd_parameter_int(argc, argv, "--repeat", &n)) {
cmd_printf("Need repeat number\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
}
uint8_t *dataIn = (uint8_t *)malloc(len + 1);
if (!dataIn) {
cmd_printf("malloc() failed\r\n");
return CMDLINE_RETCODE_FAIL;
}
info->setReceiveBuffer(dataIn);
info->setDataCount(len);
info->setMaxRecvLen(recv_len);
info->setRepeatBufferFill(n);
info->setReceiverThread(new Thread());
info->getReceiverThread()->start(callback(tcp_receiver_thread, info));
return CMDLINE_RETCODE_SUCCESS;
}
static nsapi_size_or_error_t tcp_send_command_handler(SInfo *info, int argc, char *argv[])
{
int32_t len;
void *data;
nsapi_size_or_error_t ret = 0;
info->setSenderThreadId(Thread::gettid());
if (cmd_parameter_int(argc, argv, "--data_len", &len)) {
data = malloc(len);
if (!data) {
cmd_printf("Failed to allocate memory\r\n");
return CMDLINE_RETCODE_FAIL;
}
} else {
data = argv[3];
len = strlen(argv[3]);
}
ret = static_cast<TCPSocket &>(info->socket()).send(data, len);
if (ret > 0) {
cmd_printf("sent: %d bytes\r\n", ret);
}
if (data != argv[3]) {
free(data);
}
return handle_nsapi_size_or_error("TCPSocket::send()", ret);
}
static nsapi_size_or_error_t tcp_recv_command_handler(SInfo *info, int argc, char *argv[])
{
int32_t len;
if (!cmd_parameter_int(argc, argv, "recv", &len)) {
cmd_printf("Need length\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
void *data = malloc(len);
if (!data) {
cmd_printf("malloc() failed\r\n");
return CMDLINE_RETCODE_FAIL;
}
nsapi_size_or_error_t ret = static_cast<TCPSocket &>(info->socket()).recv(data, len);
if (ret > 0) {
cmd_printf("received: %d bytes\r\n", ret);
print_data((const uint8_t *)data, ret);
if (!info->check_pattern(data, ret)) {
ret = -1;
}
info->setRecvTotal(info->getRecvTotal() + ret);
}
free(data);
return handle_nsapi_size_or_error("TCPSocket::recv()", ret);
}
static nsapi_size_or_error_t recv_all(char *const rbuffer, const int expt_len, SInfo *const info)
{
int rtotal, rbytes;
char *rhead;
rtotal = 0;
rhead = rbuffer;
while (rtotal < expt_len) {
rbytes = info->tcp_socket()->recv(rhead, expt_len);
if (rbytes <= 0) { // Connection closed abruptly
rbuffer[rtotal] = '\0';
return rbytes;
}
rtotal += rbytes;
rhead = rbuffer + rtotal;
}
rbuffer[rtotal] = '\0';
info->setRecvTotal(info->getRecvTotal() + rtotal);
return rtotal;
}
static void bg_traffic_thread(SInfo *info)
{
static const int data_len = 10;
char sbuffer[data_len + 1] = "dummydata_";
char rbuffer[data_len + 1];
int scount, rtotal = 0;
info->setSenderThreadId(Thread::gettid());
for (;;) {
if (!info->available()) {
(void)handle_nsapi_size_or_error(__func__, rtotal);
break;
}
sbuffer[data_len - 1] = 'A' + (rand() % 26);
scount = info->tcp_socket()->send(sbuffer, data_len);
rtotal = recv_all(rbuffer, data_len, info);
if (scount != rtotal || (strcmp(sbuffer, rbuffer) != 0)) {
info->setUnavailable();
tr_err("Background received data does not match to sent data");
tr_err("Background sent: \"%s\"", sbuffer);
tr_err("Background received: \"%s\"", rbuffer);
}
wait_ms(10);
}
}
static nsapi_size_or_error_t start_bg_traffic_thread(SInfo *info, int argc, char *argv[])
{
info->setReceiverThread(new Thread());
info->setAvailable();
info->getReceiverThread()->start(callback(bg_traffic_thread, info));
return CMDLINE_RETCODE_SUCCESS;
}
static void thread_clean_up(SInfo *info)
{
if (info->getReceiverThread()) {
delete info->getReceiverThread();
info->setReceiverThread(NULL);
}
if (info->getReceiveBuffer()) {
delete info->getReceiveBuffer();
info->setReceiveBuffer(NULL);
}
if (info->getPacketSizeArray()) {
delete[] info->getPacketSizeArray();
info->setPacketSizeArray(NULL);
}
}
static int cmd_socket(int argc, char *argv[])
{
if (cmd_parameter_index(argc, argv, "new") == 1) {
return cmd_socket_new(argc, argv);
} else if (cmd_parameter_index(argc, argv, "print-mode") > 0) {
if (cmd_parameter_index(argc, argv, "--string") > 0) {
printing_mode = PRINT_STRING;
} else if (cmd_parameter_index(argc, argv, "--hex") > 0) {
printing_mode = PRINT_HEX;
} else if (cmd_parameter_index(argc, argv, "--disabled") > 0) {
printing_mode = PRINT_DISABLED;
}
int32_t parsed_col_width = 0;
if (cmd_parameter_int(argc, argv, "--col-width", &parsed_col_width)) {
if (parsed_col_width <= 0) {
cmd_printf("Printing column width must be > 0");
return CMDLINE_RETCODE_FAIL;
}
if (printing_mode == PRINT_HEX && parsed_col_width > 42) {
cmd_printf("Maximum column width for hex data is 42 bytes");
return CMDLINE_RETCODE_FAIL;
}
printing_col_width = (int)parsed_col_width;
}
// Allow print-mode to be used as a parameter to other commands
if (cmd_parameter_index(argc, argv, "print-mode") == 1) {
return CMDLINE_RETCODE_SUCCESS;
}
}
// Rest of the commands require Socket
SInfo *info = get_sinfo(strtol(argv[1], NULL, 10));
if (!info) {
cmd_printf("Invalid socket id %s\r\n", argv[1]);
return CMDLINE_RETCODE_FAIL;
}
bool enable_pattern_check;
if (cmd_parameter_bool(argc, argv, "set_RFC_864_pattern_check", &enable_pattern_check)) {
info->set_pattern_check(enable_pattern_check);
return CMDLINE_RETCODE_SUCCESS;
}
// Helper macro for checking the which command was given
#define COMMAND_IS(cmd) (cmd_parameter_index(argc, argv, cmd) == 2)
/*
* Generic Socket commands:
* delete, open, close, bind, set_blocking, set_timeout
*/
if (COMMAND_IS("delete")) {
return del_sinfo(info);
} else if (COMMAND_IS("open")) {
NetworkInterface *interface;
interface = get_interface(); // get default interface
if (!interface) {
cmd_printf("Invalid interface\r\n");
return CMDLINE_RETCODE_FAIL;
}
switch (info->type()) {
case SInfo::TCP_CLIENT:
return handle_nsapi_error("Socket::open()", info->tcp_socket()->open(interface));
case SInfo::UDP:
return handle_nsapi_error("Socket::open()", info->udp_socket()->open(interface));
case SInfo::TCP_SERVER:
return handle_nsapi_error("Socket::open()", info->tcp_server()->open(interface));
}
} else if (COMMAND_IS("close")) {
return handle_nsapi_error("Socket::close()", info->socket().close());
} else if (COMMAND_IS("bind")) {
int32_t port = 0;
char *addr;
if (!cmd_parameter_int(argc, argv, "port", &port) && !cmd_parameter_int(argc, argv, "bind", &port) && port <= 0 && port > 65535) {
printf("Missing or invalid port number\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
if (cmd_parameter_val(argc, argv, "addr", &addr)) {
// Replace NULL-strings with NULL
addr = strcmp(addr, "NULL") ? addr : NULL;
cmd_printf("Socket::bind(%s, %" PRId32 ")\r\n", addr, port);
SocketAddress tmp(addr, port);
return handle_nsapi_error("Socket::bind(addr, port)", info->socket().bind(tmp));
} else {
cmd_printf("Socket::bind(%" PRId32 ")\r\n", port);
SocketAddress tmp(NULL, port);
return handle_nsapi_error("Socket::bind(port)", info->socket().bind(tmp));
}
} else if (COMMAND_IS("set_blocking")) {
bool val;
if (!cmd_parameter_bool(argc, argv, "set_blocking", &val)) {
cmd_printf("Need boolean value");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
info->set_blocking(val);
return CMDLINE_RETCODE_SUCCESS;
} else if (COMMAND_IS("set_timeout")) {
int32_t ms;
if (!cmd_parameter_int(argc, argv, "set_timeout", &ms)) {
cmd_printf("Need timeout value");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
if (ms == -1) {
info->set_blocking(true);
} else {
info->set_blocking(false);
}
info->socket().set_timeout(ms);
return CMDLINE_RETCODE_SUCCESS;
} else if (COMMAND_IS("register_sigio_cb")) {
info->socket().sigio(callback(sigio_handler, info));
return CMDLINE_RETCODE_SUCCESS;
}
/*
* Commands related to UDPSocket:
* sendto, recvfrom
*/
if ((COMMAND_IS("sendto") || COMMAND_IS("recvfrom") || COMMAND_IS("start_udp_receiver_thread")
|| COMMAND_IS("last_data_received")) && info->type() != SInfo::UDP) {
cmd_printf("Not UDPSocket\r\n");
return CMDLINE_RETCODE_FAIL;
}
if (COMMAND_IS("sendto")) {
return udp_sendto_command_handler(info, argc, argv);
} else if (COMMAND_IS("recvfrom")) {
return udp_recvfrom_command_handler(info, argc, argv);
} else if (COMMAND_IS("start_udp_receiver_thread")) {
return start_udp_receiver_thread(info, argc, argv);
} else if (COMMAND_IS("last_data_received")) {
print_data((const uint8_t *)info->getReceiveBuffer(), info->getDataCount());
if (info->getPacketSizeArray()) {
int *packetSizes = info->getPacketSizeArray();
cmd_printf("packet_sizes: ");
for (int i = 0; i < PACKET_SIZE_ARRAY_LEN; i++) {
cmd_printf("%d ", packetSizes[i]);
}
cmd_printf("\r\n");
}
if (info->getReceiverThread()) {
info->getReceiverThread()->terminate();
}
thread_clean_up(info);
return handle_nsapi_error("UDPSocket::last_data_received()", NSAPI_ERROR_OK);
}
/*
* Commands related to TCPSocket
* connect, send, recv
*/
if ((COMMAND_IS("connect") || COMMAND_IS("recv")
|| COMMAND_IS("start_tcp_receiver_thread") || COMMAND_IS("join_tcp_receiver_thread")
|| COMMAND_IS("start_bg_traffic_thread") || COMMAND_IS("join_bg_traffic_thread")
|| COMMAND_IS("setsockopt_keepalive") || COMMAND_IS("getsockopt_keepalive"))
&& info->type() != SInfo::TCP_CLIENT) {
cmd_printf("Not TCPSocket\r\n");
return CMDLINE_RETCODE_FAIL;
}
if (COMMAND_IS("connect")) {
char *host;
int32_t port;
if (!cmd_parameter_val(argc, argv, "connect", &host)) {
cmd_printf("Need host name\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
if (!cmd_parameter_int(argc, argv, host, &port)) {
cmd_printf("Need port number\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
if (strcmp(host, "NULL") == 0) {
host = NULL;
}
cmd_printf("Host name: %s port: %" PRId32 "\r\n", host, port);
return handle_nsapi_error("TCPSocket::connect()", static_cast<TCPSocket &>(info->socket()).connect(host, port));
} else if (COMMAND_IS("send")) {
return tcp_send_command_handler(info, argc, argv);
} else if (COMMAND_IS("recv")) {
return tcp_recv_command_handler(info, argc, argv);
} else if (COMMAND_IS("start_tcp_receiver_thread")) {
return start_tcp_receiver_thread(info, argc, argv);
} else if (COMMAND_IS("join_tcp_receiver_thread")) {
info->getReceiverThread()->join();
print_data((const uint8_t *)info->getReceiveBuffer(), info->getDataCount());
cmd_printf("received: %d bytes\r\n", info->getRecvTotal());
thread_clean_up(info);
return CMDLINE_RETCODE_SUCCESS;
} else if (COMMAND_IS("start_bg_traffic_thread")) {
return start_bg_traffic_thread(info, argc, argv);
} else if (COMMAND_IS("join_bg_traffic_thread")) {
int bg_thread_success = CMDLINE_RETCODE_SUCCESS;
if (!info->available()) { // Tells that background thread stumbled to an issue and stopped prematurely
bg_thread_success = CMDLINE_RETCODE_FAIL;
}
info->setUnavailable();
info->getReceiverThread()->join();
thread_clean_up(info);
return bg_thread_success;
} else if (COMMAND_IS("setsockopt_keepalive")) {
int32_t seconds;
nsapi_error_t ret;
if (!cmd_parameter_int(argc, argv, "setsockopt_keepalive", &seconds)) {
cmd_printf("Need keep-alive value(0-7200seconds)");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
ret = info->socket().setsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &seconds, sizeof(seconds));
return handle_nsapi_error("TCPSocket::setsockopt()", ret);
} else if (COMMAND_IS("getsockopt_keepalive")) {
int32_t optval;
unsigned optlen = sizeof(optval);
nsapi_error_t ret;
ret = info->socket().getsockopt(NSAPI_SOCKET, NSAPI_KEEPALIVE, &optval, &optlen);
if (optlen != sizeof(int)) {
return CMDLINE_RETCODE_FAIL;
}
if (ret < 0) {
return handle_nsapi_error("TCPSocket::getsockopt()", ret);
}
return handle_nsapi_size_or_error("TCPSocket::getsockopt()", optval);
}
/*
* Commands for TCPServer
* listen, accept
*/
if ((COMMAND_IS("listen") || COMMAND_IS("accept")) && info->type() != SInfo::TCP_SERVER) {
cmd_printf("Not TCPServer\r\n");
return CMDLINE_RETCODE_FAIL;
}
if (COMMAND_IS("listen")) {
int32_t backlog;
if (cmd_parameter_int(argc, argv, "listen", &backlog)) {
return handle_nsapi_error("TCPServer::listen()", static_cast<TCPServer &>(info->socket()).listen(backlog));
} else {
return handle_nsapi_error("TCPServer::listen()", static_cast<TCPServer &>(info->socket()).listen());
}
} else if (COMMAND_IS("accept")) {
SocketAddress addr;
int32_t id;
if (!cmd_parameter_int(argc, argv, "accept", &id)) {
cmd_printf("Need new socket id\r\n");
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
SInfo *new_info = get_sinfo(id);
if (!new_info) {
cmd_printf("Invalid socket id\r\n");
return CMDLINE_RETCODE_FAIL;
}
TCPSocket *new_sock = static_cast<TCPSocket *>(&new_info->socket());
nsapi_error_t ret = static_cast<TCPServer &>(info->socket()).accept(new_sock, &addr);
if (ret == NSAPI_ERROR_OK) {
cmd_printf("TCPServer::accept() new socket sid: %d connection from %s port %d\r\n",
new_info->id(), addr.get_ip_address(), addr.get_port());
}
return handle_nsapi_error("TCPServer::accept()", ret);
}
return CMDLINE_RETCODE_INVALID_PARAMETERS;
}
void print_data(const uint8_t *buf, int len)
{
switch (printing_mode) {
case PRINT_STRING:
print_data_as_string(buf, len, printing_col_width);
break;
case PRINT_HEX:
print_data_as_hex(buf, len, printing_col_width);
break;
case PRINT_DISABLED:
break;
default:
assert(0);
}
}
void print_data_as_string(const uint8_t *buf, int len, int col_width)
{
int printable_bytes;
for (printable_bytes = 0; printable_bytes < len; printable_bytes++) {
if (!isprint(buf[printable_bytes])) {
break;
}
}
cmd_mutex_lock();
cmd_printf("string data, printing %d bytes:\r\n", len);
for (int i = 0; i < printable_bytes; i += col_width) {
if (printable_bytes - i > col_width) {
cmd_printf("%04d: %.*s\r\n", i, col_width, buf + i);
} else {
cmd_printf("%04d: %.*s\r\n", i, printable_bytes - i, buf + i);
}
}
cmd_printf("Printed %d bytes\r\n", printable_bytes);
if (len != printable_bytes) {
cmd_printf("Error! Couldn't print all data. "
"Unprintable character: 0x%02x found at index: %d\r\n",
buf[printable_bytes], printable_bytes);
}
cmd_mutex_unlock();
}
void print_data_as_hex(const uint8_t *buf, int len, int col_width)
{
cmd_mutex_lock();
cmd_printf("hex data, printing %d bytes:\r\n", len);
for (int i = 0; i < len; i += col_width) {
if (len - i > col_width) {
cmd_printf("%04d: %s:\r\n", i, print_array(buf + i, col_width));
} else {
cmd_printf("%04d: %s\r\n", i, print_array(buf + i, len - i));
}
}
cmd_printf("Printed %d bytes\r\n", len);
cmd_mutex_unlock();
}
| 31.761589
| 141
| 0.578294
|
c1728p9
|
4af01049cafe3b9f54048a835cd8666a05a6d00c
| 17,215
|
cpp
|
C++
|
src/LexBase.cpp
|
eXtremal-ik7/config4cpp
|
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
|
[
"MIT"
] | null | null | null |
src/LexBase.cpp
|
eXtremal-ik7/config4cpp
|
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
|
[
"MIT"
] | null | null | null |
src/LexBase.cpp
|
eXtremal-ik7/config4cpp
|
087ee5457c6db2f0ca5d1b12c9b60c44b1fd130d
|
[
"MIT"
] | null | null | null |
//-----------------------------------------------------------------------
// Copyright 2011 Ciaran McHale.
//
// 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's
//--------
#include "LexBase.h"
#include "UidIdentifierDummyProcessor.h"
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <wchar.h>
#include <stdio.h>
namespace CONFIG4CPP_NAMESPACE {
extern "C"
int
CONFIG4CPP_C_PREFIX(keywordInfoCmp)(const void * ptr1, const void * ptr2)
{
const LexBase::KeywordInfo * sas1;
const LexBase::KeywordInfo * sas2;
sas1 = (const LexBase::KeywordInfo *)ptr1;
sas2 = (const LexBase::KeywordInfo *)ptr2;
return strcmp(sas1->m_spelling, sas2->m_spelling);
}
void
LexBase::searchForKeyword(
const char * spelling,
bool & found,
short & symbol)
{
LexBase::KeywordInfo searchItem;
LexBase::KeywordInfo * result = 0;
searchItem.m_spelling = spelling;
if (m_keywordInfoArraySize == 0) {
found = false;
return;
}
result = (LexBase::KeywordInfo *)
bsearch(&searchItem, m_keywordInfoArray, m_keywordInfoArraySize,
sizeof(searchItem),CONFIG4CPP_C_PREFIX(keywordInfoCmp));
if (result == 0) {
found = false;
} else {
found = true;
symbol = result->m_symbol;
}
}
extern "C"
int
CONFIG4CPP_C_PREFIX(funcInfoCmp_c)(const void * ptr1, const void * ptr2)
{
const LexBase::FuncInfo * sas1;
const LexBase::FuncInfo * sas2;
sas1 = (const LexBase::FuncInfo *)ptr1;
sas2 = (const LexBase::FuncInfo *)ptr2;
return strcmp(sas1->m_spelling, sas2->m_spelling);
}
void
LexBase::searchForFunction(
const char * spelling,
bool & found,
short & funcType,
short & symbol)
{
FuncInfo searchItem;
FuncInfo * result = 0;
if (m_funcInfoArraySize == 0) {
found = false;
return;
}
searchItem.m_spelling = spelling;
result = (FuncInfo *)bsearch(&searchItem, m_funcInfoArray,
m_funcInfoArraySize, sizeof(searchItem),
CONFIG4CPP_C_PREFIX(funcInfoCmp_c));
if (result == 0) {
found = false;
} else {
found = true;
funcType = result->m_funcType;
symbol = result->m_symbol;
}
}
//----------------------------------------------------------------------
// Function: Constructor
//
// Description:
//----------------------------------------------------------------------
LexBase::LexBase(
Configuration::SourceType sourceType,
const char * source,
UidIdentifierProcessor * uidIdentifierProcessor)
{
StringBuffer msg;
//--------
// Initialize state for the multi-byte functions in the C library.
//--------
memset(&m_mbtowcState, 0, sizeof(mbstate_t));
m_keywordInfoArray = 0;
m_keywordInfoArraySize = 0;
m_funcInfoArray = 0;
m_funcInfoArraySize = 0;
m_uidIdentifierProcessor = uidIdentifierProcessor;
m_amOwnerOfUidIdentifierProcessor = false;
m_sourceType = sourceType;
m_source = source;
m_lineNum = 1;
m_ptr = 0;
m_atEOF = false;
switch (sourceType) {
case Configuration::INPUT_FILE:
if (!m_file.open(source)) {
msg << "cannot open " << source << ": " << strerror(errno);
throw ConfigurationException(msg.c_str());
}
break;
case Configuration::INPUT_STRING:
m_ptr = m_source;
break;
case Configuration::INPUT_EXEC:
if (!execCmd(source, m_execOutput)) {
msg << "cannot parse 'exec#" << source << "': "
<< m_execOutput.c_str();
throw ConfigurationException(msg.c_str());
}
m_ptr = m_execOutput.c_str();
break;
default:
assert(0); // Bug!
break;
}
nextChar(); // initialize m_ch
}
//----------------------------------------------------------------------
// Function: Constructor
//
// Description:
//----------------------------------------------------------------------
LexBase::LexBase(const char * str)
{
StringBuffer msg;
//--------
// Initialize state for the multi-byte functions in the C library.
//--------
memset(&m_mbtowcState, 0, sizeof(mbstate_t));
m_keywordInfoArray = 0;
m_keywordInfoArraySize = 0;
m_funcInfoArray = 0;
m_funcInfoArraySize = 0;
m_uidIdentifierProcessor = new UidIdentifierDummyProcessor();
m_amOwnerOfUidIdentifierProcessor = true;
m_sourceType = Configuration::INPUT_STRING;
m_source = str;
m_lineNum = 1;
m_ptr = m_source;
m_atEOF = false;
nextChar(); // initialize m_ch
}
//----------------------------------------------------------------------
// Function: Destructor
//
// Description:
//----------------------------------------------------------------------
LexBase::~LexBase()
{
if (m_amOwnerOfUidIdentifierProcessor) {
delete m_uidIdentifierProcessor;
}
}
//----------------------------------------------------------------------
// Function: nextByte()
//
// Description: Read the next byte from the input source
//----------------------------------------------------------------------
char
LexBase::nextByte()
{
int ch;
if (m_sourceType == Configuration::INPUT_FILE) {
do {
ch = m_file.getChar();
} while (ch == '\r');
} else {
do {
ch = *m_ptr;
if (ch == '\0') {
ch = EOF;
} else {
m_ptr ++;
}
} while (ch == '\r');
}
m_atEOF = (ch == EOF);
if (m_atEOF) {
ch = 0;
}
return (char)ch;
}
//----------------------------------------------------------------------
// Function: nextChar()
//
// Description: Read the next char from the input file
//----------------------------------------------------------------------
void
LexBase::nextChar()
{
char ch;
int status;
wchar_t wChar;
m_ch.reset();
status = -1;
while (status == -1) {
ch = nextByte();
if (m_atEOF && !m_ch.isEmpty()) {
StringBuffer msg;
msg << "Invalid multi-byte character on line " << m_lineNum;
throw ConfigurationException(msg.c_str());
}
if (m_atEOF) {
//--------
// At EOF. Our work is done.
//--------
break;
}
if (!m_ch.add(ch)) {
StringBuffer msg;
msg << "Invalid multi-byte character on line " << m_lineNum;
throw ConfigurationException(msg.c_str());
}
status = mbrtowc(&wChar, m_ch.c_str(), m_ch.length(), &m_mbtowcState);
if (status == -1 && m_ch.isFull()) {
StringBuffer msg;
msg << "Invalid multi-byte character on line " << m_lineNum;
throw ConfigurationException(msg.c_str());
}
m_ch.setWChar(wChar);
}
if (m_ch == '\n') {
m_lineNum ++;
}
}
//----------------------------------------------------------------------
// Function: nextToken()
//
// Description: Analyse the next token from the input file
//----------------------------------------------------------------------
void
LexBase::nextToken(LexToken &token)
{
StringBuffer spelling;
bool found;
short funcType;
short symbol;
//--------
// Skip leading white space
//--------
while (m_ch.isSpace()) {
nextChar();
}
//--------
// Check for EOF.
//--------
if (m_atEOF) {
if (m_sourceType == Configuration::INPUT_STRING) {
token.reset(LEX_EOF_SYM, m_lineNum, "<end of string>");
} else {
token.reset(LEX_EOF_SYM, m_lineNum, "<end of file>");
}
return;
}
//--------
// Note the line number at the start of the token
//--------
const int lineNum = m_lineNum;
//--------
// Miscellaneous kinds of tokens.
//--------
switch (m_ch.c_str()[0]) {
case '?':
nextChar();
if (m_ch == '=') {
nextChar();
token.reset(LEX_QUESTION_EQUALS_SYM, lineNum, "?=");
} else {
token.reset(LEX_UNKNOWN_SYM, lineNum, spelling.c_str());
}
return;
case '!':
nextChar();
if (m_ch == '=') {
nextChar();
token.reset(LEX_NOT_EQUALS_SYM, lineNum, "!=");
} else {
token.reset(LEX_NOT_SYM, lineNum, "!");
}
return;
case '@':
spelling.append(m_ch.c_str());
nextChar();
while (!m_atEOF && isKeywordChar(m_ch)) {
spelling.append(m_ch.c_str());
nextChar();
}
searchForKeyword(spelling.c_str(), found, symbol);
if (found) {
token.reset(symbol, lineNum, spelling.c_str());
} else {
token.reset(LEX_UNKNOWN_SYM, lineNum, spelling.c_str());
}
return;
case '+':
nextChar();
token.reset(LEX_PLUS_SYM, lineNum, "+");
return;
case '&':
nextChar();
if (m_ch == '&') {
nextChar();
token.reset(LEX_AND_SYM, lineNum, "&&");
} else {
spelling << '&' << m_ch.c_str();
token.reset(LEX_UNKNOWN_SYM, lineNum, spelling.c_str());
}
return;
case '|':
nextChar();
if (m_ch == '|') {
nextChar();
token.reset(LEX_OR_SYM, lineNum, "||");
} else {
spelling << '|' << m_ch.c_str();
token.reset(LEX_UNKNOWN_SYM, lineNum, spelling.c_str());
}
return;
case '=':
nextChar();
if (m_ch == '=') {
nextChar();
token.reset(LEX_EQUALS_EQUALS_SYM, lineNum, "==");
} else {
token.reset(LEX_EQUALS_SYM, lineNum, "=");
}
return;
case ';':
nextChar();
token.reset(LEX_SEMICOLON_SYM, lineNum, ";");
return;
case '[':
nextChar();
token.reset(LEX_OPEN_BRACKET_SYM, lineNum, "[");
return;
case ']':
nextChar();
token.reset(LEX_CLOSE_BRACKET_SYM, lineNum, "]");
return;
case '{':
nextChar();
token.reset(LEX_OPEN_BRACE_SYM, lineNum, "{");
return;
case '}':
nextChar();
token.reset(LEX_CLOSE_BRACE_SYM, lineNum, "}");
return;
case '(':
nextChar();
token.reset(LEX_OPEN_PAREN_SYM, lineNum, "(");
return;
case ')':
nextChar();
token.reset(LEX_CLOSE_PAREN_SYM, lineNum, ")");
return;
case ',':
nextChar();
token.reset(LEX_COMMA_SYM, lineNum, ",");
return;
case '"':
consumeString(token);
return;;
case '<':
nextChar();
if (m_ch != '%') {
token.reset(LEX_UNKNOWN_SYM, lineNum, "<");
return;
}
nextChar(); // skip over '%'
consumeBlockString(token);
return;
case '#':
//--------
// A comment. Consume it and immediately following
// comments (without resorting to recursion).
//--------
while (m_ch == '#') {
//--------
// Skip to the end of line
//--------
while (!m_atEOF && m_ch != '\n') {
nextChar();
}
if (m_ch == '\n') {
nextChar();
}
//--------
// Skip leading white space on the next line
//--------
while (m_ch.isSpace()) {
nextChar();
}
//--------
// Potentially loop around again to consume
// more comment lines that follow immediately.
//--------
}
//--------
// Now use (a guaranteed single level of) recursion
// to obtain the next (non-comment) token.
//--------
nextToken(token);
return;
}
//--------
// Is it a function or identifier?
//--------
if (isIdentifierChar(m_ch)) {
//--------
// Consume all the identifier characters
// but not an immediately following "(", if any
//--------
spelling.append(m_ch.c_str());
nextChar();
while (!m_atEOF && isIdentifierChar(m_ch)) {
spelling.append(m_ch.c_str());
nextChar();
}
//--------
// If "(" follows immediately then it is (supposed to be)
// a function.
//--------
if (m_ch == '(') {
spelling.append(m_ch.c_str());
nextChar();
searchForFunction(spelling.c_str(), found, funcType, symbol);
if (found) {
token.reset(symbol, lineNum, spelling.c_str(), funcType);
} else {
token.reset(LEX_UNKNOWN_FUNC_SYM, lineNum, spelling.c_str());
}
return;
}
//--------
// It's not a function so it looks like an identifier.
// Better check it's a legal identifier.
//--------
if (strcmp(spelling.c_str(), ".") == 0) {
token.reset(LEX_SOLE_DOT_IDENT_SYM, lineNum, spelling.c_str());
} else if (strstr(spelling.c_str(), "..") != 0) {
token.reset(LEX_TWO_DOTS_IDENT_SYM, lineNum, spelling.c_str());
} else {
try {
m_uidIdentifierProcessor->expand(spelling);
token.resetWithOwnership(LEX_IDENT_SYM, lineNum, spelling);
} catch (const ConfigurationException &) {
token.resetWithOwnership(LEX_ILLEGAL_IDENT_SYM, lineNum,
spelling);
}
}
return;
}
//--------
// None of the above
//--------
spelling << m_ch.c_str();
nextChar();
token.reset(LEX_UNKNOWN_SYM, lineNum, spelling.c_str());
}
//----------------------------------------------------------------------
// Function: consumeBlockString()
//
// Description: Consume a string from the input file and return the
// relevant token.
//----------------------------------------------------------------------
void
LexBase::consumeBlockString(LexToken &token)
{
StringBuffer spelling;
MBChar prevCh;
int lineNum;
//--------
// Note the line number at the start of the string
//--------
lineNum = m_lineNum;
//--------
// Consume chars until we get to "%>"
//--------
prevCh = ' ';
while (!(prevCh == '%' && m_ch == '>')) {
if (m_atEOF) {
token.reset(LEX_BLOCK_STRING_WITH_EOF_SYM, lineNum,
spelling.c_str());
return;
}
spelling << m_ch.c_str();
prevCh = m_ch;
nextChar();
}
//--------
// Spelling contains the string followed by '%'.
// Remove that unwanted terminating character.
//--------
spelling.deleteLastChar();
nextChar(); // consumer the '>'
//--------
// At the end of the string.
//--------
token.resetWithOwnership(LEX_STRING_SYM, lineNum, spelling);
return;
}
//----------------------------------------------------------------------
// Function: consumeString()
//
// Description: Consume a string from the input file and return the
// relevant token.
//----------------------------------------------------------------------
void
LexBase::consumeString(LexToken &token)
{
StringBuffer spelling;
StringBuffer msg;
assert(m_ch == '"');
//--------
// Note the line number at the start of the string
//--------
const int lineNum = m_lineNum;
//--------
// Consume chars until we get to the end of the sting
//--------
nextChar();
while (m_ch != '"') {
if (m_atEOF || m_ch.c_str()[0] == '\n') {
token.reset(LEX_STRING_WITH_EOL_SYM, lineNum, spelling.c_str());
return;
}
switch (m_ch.c_str()[0]) {
case '%':
//--------
// Escape char in string
//--------
nextChar();
if (m_atEOF || m_ch.c_str()[0] == '\n') {
token.reset(LEX_STRING_WITH_EOL_SYM, lineNum, spelling.c_str());
return;
}
switch (m_ch.c_str()[0]) {
case 't':
spelling << '\t';
break;
case 'n':
spelling << '\n';
break;
case '%':
spelling << '%';
break;
case '"':
spelling << '"';
break;
default:
msg << "Invalid escape sequence (%" << m_ch.c_str()[0]
<< ") in string on line " << m_lineNum;
throw ConfigurationException(msg.c_str());
}
break;
default:
//--------
// Typical char in string
//--------
spelling << m_ch.c_str();
break;
}
nextChar();
}
nextChar(); // consume the terminating double-quote char
//--------
// At the end of the string.
//--------
token.resetWithOwnership(LEX_STRING_SYM, lineNum, spelling);
return;
}
//----------------------------------------------------------------------
// Function: isKeywordChar()
//
// Description: Determine if the parameter is a char that can appear
// in a keyword (after the initial "@").
//----------------------------------------------------------------------
bool
LexBase::isKeywordChar(const MBChar & mbCh)
{
wchar_t wCh;
wCh = mbCh.getWChar();
if ('A' <= wCh && wCh <= 'Z') { return true; }
if ('a' <= wCh && wCh <= 'z') { return true; }
return false;
}
//----------------------------------------------------------------------
// Function: isIdentifierChar()
//
// Description: Determine if the parameter is a char that can appear
// in an identifier.
//----------------------------------------------------------------------
bool
LexBase::isIdentifierChar(const MBChar & mbCh)
{
wchar_t wCh;
bool result;
wCh = mbCh.getWChar();
result = (::iswalpha(wCh) != 0) // letter
|| (::iswdigit(wCh) != 0) // digit
|| mbCh == '-' // dash
|| mbCh == '_' // underscore
|| mbCh == '.' // dot
|| mbCh == ':' // For C++ nested names, e.g., Foo::Bar
|| mbCh == '$' // For mangled names of Java nested classes
|| mbCh == '?' // For Ruby identifiers, e.g., found?
|| mbCh == '/' // For URLs, e.g., http://foo.com/bar/
|| mbCh == '\\' // For Windows directory names
;
return result;
}
}; // namespace CONFIG4CPP_NAMESPACE
| 23.326558
| 73
| 0.5605
|
eXtremal-ik7
|
4af02a5b0bec8809fda94987e4977de395d29240
| 2,658
|
cpp
|
C++
|
src/walker.cpp
|
markosej11/turtlebot3_walker
|
5a7e25367588f969383631da62c078abe08b472a
|
[
"MIT"
] | null | null | null |
src/walker.cpp
|
markosej11/turtlebot3_walker
|
5a7e25367588f969383631da62c078abe08b472a
|
[
"MIT"
] | null | null | null |
src/walker.cpp
|
markosej11/turtlebot3_walker
|
5a7e25367588f969383631da62c078abe08b472a
|
[
"MIT"
] | null | null | null |
/**
* @Copyright 2021 Markose Jacob
* @file walker.cpp
* @author Markose Jacob
* @date 11/28/2021
*
* @brief Walker class
*
* @section LICENSE
*
* MIT License
* Copyright (c) 2021 Markose Jacob
* 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.
*
* @section DESCRIPTION
*
* Class implementation
*
*/
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <sensor_msgs/LaserScan.h>
#include "geometry_msgs/Twist.h"
#include "walker.hpp"
void hw13::Walker::laserCallback(const sensor_msgs::LaserScan::ConstPtr& data) {
distance = data->ranges[180];
ROS_INFO_STREAM("Distance: " << distance);
}
hw13::Walker::Walker(ros::NodeHandle node) {
// ROS subscriber to LaserScan
ros::Subscriber laserSubscriber = node.subscribe("/scan", 1000,
&Walker::laserCallback, this);
// ROS publisher to velocity topic
ros::Publisher velocityPublisher =
node.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
// Looprate of 4 Hz
ros::Rate rate(4);
while (ros::ok()) {
// Define twist msg
geometry_msgs::Twist twist;
// Initialize to all zeros
twist.linear.x = 0.0;
twist.linear.y = 0.0;
twist.linear.z = 0.0;
twist.angular.x = 0.0;
twist.angular.y = 0.0;
twist.angular.z = 0.0;
if (distance > 0.45) {
ROS_INFO_STREAM("Moving forward ...");
twist.linear.x = -0.12;
} else {
ROS_INFO_STREAM("Rotating ...");
twist.angular.z = 1.4;
}
velocityPublisher.publish(twist);
ros::spinOnce();
rate.sleep();
}
}
| 31.642857
| 81
| 0.665538
|
markosej11
|
4af31509a5c6a6bdeba357e3ca82e07c42757ce9
| 6,467
|
cpp
|
C++
|
test/misc/ut_prng.cpp
|
PascalLG/zinc-cpp
|
560d51a6b7ccd60e4dcf3b0fd132a9bb56f72911
|
[
"MIT"
] | 1
|
2021-04-07T11:03:57.000Z
|
2021-04-07T11:03:57.000Z
|
test/misc/ut_prng.cpp
|
PascalLG/zinc-cpp
|
560d51a6b7ccd60e4dcf3b0fd132a9bb56f72911
|
[
"MIT"
] | null | null | null |
test/misc/ut_prng.cpp
|
PascalLG/zinc-cpp
|
560d51a6b7ccd60e4dcf3b0fd132a9bb56f72911
|
[
"MIT"
] | null | null | null |
//========================================================================
// Zinc - Unit Testing
// Copyright (c) 2020, Pascal Levy
//
// 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 <array>
#include <iostream>
#include "gtest/gtest.h"
#include "misc/prng.h"
//--------------------------------------------------------------
// Test the PRNG, sequence 1.
//--------------------------------------------------------------
TEST(PRNG, Sequence1) {
prng & g = prng::instance();
g.seed(1234u);
static std::array<uint32_t, 128> expected = {
0x31076B2F, 0x7F66E2D3, 0x9F428526, 0xD15DDC35, 0x700EECCC, 0x9CB35D74, 0xC90D4298, 0xC577D7F9,
0xC7AC7E8F, 0xDC54DAB1, 0x45C8A117, 0x269024E9, 0x46C65C9A, 0x32D2201E, 0xCD477EAB, 0xD0AE849E,
0xF5489EEC, 0x28A81F7C, 0xE03D1F1A, 0x1DBB3576, 0x5B99E9BA, 0x034DE878, 0x80413770, 0x7CA11DDC,
0xAEF76D45, 0x54BD6D50, 0xB673A3C9, 0xCD79C97F, 0x5EC8C0F6, 0x192709FE, 0x8FAA8DAF, 0x0E559632,
0x80CA0EF0, 0x715256FB, 0x0386544C, 0x05AB3925, 0xC5D7F722, 0x4A6D2FA6, 0xE1F4C5FA, 0x3F13B4C3,
0x5D692AE7, 0xBD005C8B, 0x9D8A9A80, 0xE3A452E9, 0x134C2F4B, 0xFCB52950, 0x5E6B4003, 0x1E10C502,
0xEEE24513, 0x64CEEB8C, 0xA6C0B7C1, 0x73E619CB, 0x65AF1173, 0x89C40E6B, 0xC9EA37FA, 0xCA6635D1,
0x511C2C0E, 0x77410CF3, 0x916EE9C7, 0x6F71EF3C, 0xDE7F21EA, 0x91C95A6B, 0x6FA90FAE, 0xF8215B9C,
0xCD598C51, 0x0A61E357, 0x24CDE70D, 0x8C519074, 0xB44A7260, 0x766B6B8C, 0xB45F70C5, 0x60607BFD,
0x3802C271, 0x53F20BDF, 0xECC41FE5, 0xD0436E9F, 0x713022F9, 0xA58473FC, 0xE8C8EE59, 0x0C242454,
0x0F4FA82D, 0xFEB58A10, 0x2F2D7029, 0xB071BF48, 0x0C1F79B8, 0xEDF6B8EC, 0xACC4FF46, 0xEB09AFB8,
0x98395456, 0xF9AD5FAC, 0x888703DA, 0x65A1EBD3, 0x0B17492F, 0x433B76B1, 0x8FBA1412, 0x6E1E6655,
0x546526AE, 0xC3B849E2, 0x80C26F25, 0x9987F56D, 0x1CA51B26, 0x14B8F087, 0x9B710BE4, 0xB45D06C3,
0x90E1BF85, 0x29FCC6EE, 0x01BB4A2F, 0x08480BF6, 0x9E10A8F4, 0x5401A976, 0xE980E2AF, 0x794EE38F,
0xCA5FCA22, 0x116E000A, 0xFDF90D1C, 0x61F95404, 0xF5740852, 0x1E599067, 0xCABE2959, 0xE575C937,
0x490634EB, 0xC3A9B94E, 0x9FFA8A97, 0x601A89B2, 0x7A645AF9, 0x069BC23E, 0x3217C4B7, 0xE8126954,
};
for (uint32_t x: expected) {
ASSERT_EQ(x, g.next());
}
}
//--------------------------------------------------------------
// Test the PRNG, sequence 2.
//--------------------------------------------------------------
TEST(PRNG, Sequence2) {
prng & g = prng::instance();
g.seed(56789u);
static std::array<uint32_t, 128> expected = {
0xCBE05A0F, 0x88D5FA24, 0xBD3CEEE0, 0x16AFF7CB, 0x09419667, 0x6BA97454, 0xF07A396B, 0xC8B70A55,
0x2D9643CC, 0x1C01261C, 0x483E97BD, 0x272ADCFA, 0xF676A561, 0x63E0BE1B, 0x0C4598E4, 0x7C584BBA,
0xA20A800A, 0xC243F2DB, 0x3836DD02, 0x99F0A0D7, 0x4C8E1008, 0xD6B8278E, 0xFC1E66F4, 0x68CD5167,
0xEA9E70E8, 0x72F91E20, 0x2214373B, 0x7F2D8A81, 0x2A7BFBA4, 0x2F961159, 0xDC93A084, 0x97FC9BB6,
0x04A7D38A, 0x173916E8, 0x6B40178F, 0x44DC490E, 0x81159EAF, 0x362DFD98, 0xDED0C0CB, 0xB1A9E1B2,
0x980BAB9E, 0xC25FA1FB, 0x0822B4EA, 0x8E52796D, 0x738AA9FE, 0x4E196FCA, 0x8997070B, 0x56475A4D,
0xEFE31CF5, 0x5E3DB07A, 0x0BF57F75, 0xD053476F, 0xFF3C7999, 0xDEFC2901, 0x1288EE6A, 0xD1E1B4DD,
0xE27AC7B1, 0x40BA5E7B, 0x350DAE8D, 0xC51CAEE2, 0xAC731672, 0x915E2EE0, 0x3050E290, 0x67CE7651,
0x4BF73555, 0xE48936D7, 0x6DAAE689, 0x9CB3A791, 0xF40392FA, 0xC1D37FA5, 0x13284090, 0xC4C60596,
0xE350A597, 0x9D88F323, 0xF5CD1EAE, 0x8394EC48, 0x38B91D03, 0x9B392E6A, 0xED6A8574, 0x8C52DF1F,
0x74B4B259, 0x3C9C5039, 0xABA15618, 0xD9B25606, 0x67BBECF3, 0x26A3EAD3, 0xDD85BF52, 0xA7B8F4A1,
0xD8BE0F54, 0x0FA86A68, 0xB1AA53F4, 0xD21D48D1, 0x44C8430F, 0xB6BCF3F9, 0x9D768E3E, 0xE217A1B6,
0x410E2423, 0x39206DE5, 0x9ED633CF, 0xF958EBDC, 0x5805A06C, 0x0F561750, 0x6DCF8E7A, 0xA02B35E1,
0x28514AF0, 0x09F0EE99, 0x8C0B2EA7, 0x9F699731, 0xF5129E42, 0x5332DE50, 0xFB1D3754, 0x357C7681,
0x809FDD2E, 0x08FFE150, 0x1AADD862, 0x3A330E24, 0xAE99E729, 0xB270BBD6, 0xC674C01D, 0xAFF9C413,
0x03A2C548, 0x59CFF8D6, 0xCE8BC1FF, 0x02DB4C2D, 0xEF884378, 0x866C96E6, 0x19ACC02A, 0xDD1D34D7,
};
for (uint32_t x: expected) {
ASSERT_EQ(x, g.next());
}
}
//--------------------------------------------------------------
// Test the statistical distribution.
//--------------------------------------------------------------
TEST(PRNG, Statistics) {
prng & g = prng::instance();
g.seed();
const int N = 1000000;
std::array<unsigned int, 256> histo = { 0 };
for (size_t i = 0; i < N / 4; i++) {
uint32_t v = g.next();
histo[v & 255]++;
histo[(v >> 8) & 255]++;
histo[(v >> 16) & 255]++;
histo[(v >> 24) & 255]++;
}
double t = 0.0, s = 0.0;
for (size_t i = 0; i < 256; i++) {
double x = static_cast<double>(histo[i]);
s += i * x;
t += x * x;
}
double average = s / N;
EXPECT_GE(average, 127.25);
EXPECT_LE(average, 128.75);
double khi = (256.0 * t / N) - N;
EXPECT_GE(khi, 256.0 - 2.0 * sqrt(256.0)); // may fail sometimes...
EXPECT_LE(khi, 256.0 + 2.0 * sqrt(256.0));
}
//========================================================================
| 49.746154
| 111
| 0.640173
|
PascalLG
|
4afa96f08d7729d972cae38c04048b5527503392
| 17,631
|
cpp
|
C++
|
cpp/tests/column/column_view_shallow_test.cpp
|
karthikeyann/cudf
|
a00466fe30ce6618e8f790ea1337875558867512
|
[
"Apache-2.0"
] | 3
|
2020-09-25T21:45:41.000Z
|
2020-09-28T01:51:57.000Z
|
cpp/tests/column/column_view_shallow_test.cpp
|
karthikeyann/cudf
|
a00466fe30ce6618e8f790ea1337875558867512
|
[
"Apache-2.0"
] | 1
|
2020-09-26T01:22:44.000Z
|
2020-09-26T02:25:41.000Z
|
cpp/tests/column/column_view_shallow_test.cpp
|
karthikeyann/cudf
|
a00466fe30ce6618e8f790ea1337875558867512
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright (c) 2021, NVIDIA CORPORATION.
*
* 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 <cudf/column/column_view.hpp>
#include <cudf/null_mask.hpp>
#include <cudf/types.hpp>
#include <cudf/utilities/traits.hpp>
#include <cudf_test/base_fixture.hpp>
#include <cudf_test/column_utilities.hpp>
#include <cudf_test/column_wrapper.hpp>
#include <cudf_test/cudf_gtest.hpp>
#include <cudf_test/type_lists.hpp>
#include <thrust/iterator/counting_iterator.h>
#include <memory>
#include <type_traits>
// fixed_width, dict, string, list, struct
template <typename T, std::enable_if_t<cudf::is_fixed_width<T>()>* = nullptr>
std::unique_ptr<cudf::column> example_column()
{
auto begin = thrust::make_counting_iterator(1);
auto end = thrust::make_counting_iterator(16);
return cudf::test::fixed_width_column_wrapper<T>(begin, end).release();
}
template <typename T, std::enable_if_t<cudf::is_dictionary<T>()>* = nullptr>
std::unique_ptr<cudf::column> example_column()
{
return cudf::test::dictionary_column_wrapper<std::string>(
{"fff", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "", ""}, {1, 1, 1, 1, 1, 1, 1, 1, 0})
.release();
}
template <typename T,
std::enable_if_t<std::is_same_v<T, std::string> or
std::is_same_v<T, cudf::string_view>>* = nullptr>
std::unique_ptr<cudf::column> example_column()
{
return cudf::test::strings_column_wrapper(
{"fff", "aaa", "ddd", "bbb", "ccc", "ccc", "ccc", "", ""})
.release();
}
template <typename T, std::enable_if_t<std::is_same_v<T, cudf::list_view>>* = nullptr>
std::unique_ptr<cudf::column> example_column()
{
return cudf::test::lists_column_wrapper<int>({{1, 2, 3}, {4, 5}, {}, {6, 7, 8}}).release();
}
template <typename T, std::enable_if_t<std::is_same_v<T, cudf::struct_view>>* = nullptr>
std::unique_ptr<cudf::column> example_column()
{
auto begin = thrust::make_counting_iterator(1);
auto end = thrust::make_counting_iterator(16);
auto member_0 = cudf::test::fixed_width_column_wrapper<int32_t>(begin, end);
auto member_1 = cudf::test::fixed_width_column_wrapper<int32_t>(begin + 10, end + 10);
return cudf::test::structs_column_wrapper({member_0, member_1}).release();
}
template <typename T>
struct ColumnViewShallowTests : public cudf::test::BaseFixture {
};
using AllTypes = cudf::test::Concat<cudf::test::AllTypes, cudf::test::CompoundTypes>;
TYPED_TEST_SUITE(ColumnViewShallowTests, AllTypes);
// Test for fixed_width, dict, string, list, struct
// column_view, column_view = same hash.
// column_view, make a copy = same hash.
// new column_view from column = same hash
// column_view, copy column = diff hash
// column_view, diff column = diff hash.
//
// column_view old, update data + new column_view = same hash.
// column_view old, add null_mask + new column_view = diff hash.
// column_view old, update nulls + new column_view = same hash.
// column_view old, set_null_count + new column_view = same hash.
//
// column_view, sliced[0, size) = same hash (for split too)
// column_view, sliced[n:) = diff hash (for split too)
// column_view, bit_cast = diff hash
//
// mutable_column_view, column_view = same hash
// mutable_column_view, modified mutable_column_view = same hash
//
// update the children column data = same hash
// update the children column_views = diff hash
TYPED_TEST(ColumnViewShallowTests, shallow_hash_basic)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// same = same hash
{
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view));
}
// copy column_view = same hash
{
auto col_view_copy = col_view;
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_copy));
}
// new column_view from column = same hash
{
auto col_view_new = cudf::column_view{*col};
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new));
}
// copy column = diff hash
{
auto col_new = std::make_unique<cudf::column>(*col);
auto col_view_copy = col_new->view();
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_copy));
}
// column_view, diff column = diff hash.
{
auto col_diff = example_column<TypeParam>();
auto col_view_diff = cudf::column_view{*col_diff};
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_diff));
}
}
TYPED_TEST(ColumnViewShallowTests, shallow_hash_update_data)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// update data + new column_view = same hash.
{
// update data by modifying some bits: fixed_width, string, dict, list, struct
if constexpr (cudf::is_fixed_width<TypeParam>()) {
// Update data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head());
cudf::set_null_mask(data, 2, 64, true);
} else {
// Update child(0).data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head());
cudf::set_null_mask(data, 2, 64, true);
}
auto col_view_new = cudf::column_view{*col};
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new));
}
// add null_mask + new column_view = diff hash.
{
col->set_null_mask(cudf::create_null_mask(col->size(), cudf::mask_state::ALL_VALID));
auto col_view_new = cudf::column_view{*col};
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_new));
col_view_new.null_count();
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_view_new));
auto col_view_new2 = cudf::column_view{*col};
EXPECT_EQ(shallow_hash(col_view_new), shallow_hash(col_view_new2));
}
col_view = cudf::column_view{*col}; // updating after adding null_mask
// update nulls + new column_view = same hash.
{
cudf::set_null_mask(col->mutable_view().null_mask(), 2, 4, false);
auto col_view_new = cudf::column_view{*col};
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new));
}
// set_null_count + new column_view = same hash. set_null_count(UNKNOWN_NULL_COUNT)
{
col->set_null_count(cudf::UNKNOWN_NULL_COUNT);
auto col_view_new = cudf::column_view{*col};
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new));
col->set_null_count(col->size());
auto col_view_new2 = cudf::column_view{*col};
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_view_new2));
}
}
TYPED_TEST(ColumnViewShallowTests, shallow_hash_slice)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// column_view, sliced[0, size) = same hash (for split too)
{
auto col_sliced = cudf::slice(col_view, {0, col_view.size()});
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_sliced[0]));
auto col_split = cudf::split(col_view, {0});
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_split[0]));
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_split[1]));
}
// column_view, sliced[n:] = diff hash (for split too)
{
auto col_sliced = cudf::slice(col_view, {1, col_view.size()});
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_sliced[0]));
auto col_split = cudf::split(col_view, {1});
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_split[0]));
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_split[1]));
}
// column_view, col copy sliced[0, 0) = same hash (empty column)
{
auto col_new = std::make_unique<cudf::column>(*col);
auto col_new_view = col_new->view();
auto col_sliced = cudf::slice(col_view, {0, 0, 1, 1, col_view.size(), col_view.size()});
auto col_new_sliced = cudf::slice(col_new_view, {0, 0, 1, 1, col_view.size(), col_view.size()});
EXPECT_EQ(shallow_hash(col_sliced[0]), shallow_hash(col_sliced[1]));
EXPECT_EQ(shallow_hash(col_sliced[1]), shallow_hash(col_sliced[2]));
EXPECT_EQ(shallow_hash(col_sliced[0]), shallow_hash(col_new_sliced[0]));
EXPECT_EQ(shallow_hash(col_sliced[1]), shallow_hash(col_new_sliced[1]));
EXPECT_EQ(shallow_hash(col_sliced[2]), shallow_hash(col_new_sliced[2]));
}
// column_view, bit_cast = diff hash
{
if constexpr (std::is_integral_v<TypeParam> and not std::is_same_v<TypeParam, bool>) {
using newType = std::conditional_t<std::is_signed_v<TypeParam>,
std::make_unsigned_t<TypeParam>,
std::make_signed_t<TypeParam>>;
auto new_type = cudf::data_type(cudf::type_to_id<newType>());
auto col_bitcast = cudf::bit_cast(col_view, new_type);
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_bitcast));
}
}
}
TYPED_TEST(ColumnViewShallowTests, shallow_hash_mutable)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// mutable_column_view, column_view = same hash
{
auto col_mutable = cudf::mutable_column_view{*col};
EXPECT_EQ(shallow_hash(col_mutable), shallow_hash(col_view));
}
// mutable_column_view, modified mutable_column_view = same hash
// update the children column data = same hash
{
auto col_mutable = cudf::mutable_column_view{*col};
if constexpr (cudf::is_fixed_width<TypeParam>()) {
// Update data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head());
cudf::set_null_mask(data, 1, 32, false);
} else {
// Update child(0).data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head());
cudf::set_null_mask(data, 1, 32, false);
}
EXPECT_EQ(shallow_hash(col_view), shallow_hash(col_mutable));
auto col_mutable_new = cudf::mutable_column_view{*col};
EXPECT_EQ(shallow_hash(col_mutable), shallow_hash(col_mutable_new));
}
// update the children column_views = diff hash
{
if constexpr (cudf::is_nested<TypeParam>()) {
col->child(0).set_null_mask(
cudf::create_null_mask(col->child(0).size(), cudf::mask_state::ALL_NULL));
auto col_child_updated = cudf::mutable_column_view{*col};
EXPECT_NE(shallow_hash(col_view), shallow_hash(col_child_updated));
}
}
}
TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_basic)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// same = same hash
{
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view));
}
// copy column_view = same hash
{
auto col_view_copy = col_view;
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_copy));
}
// new column_view from column = same hash
{
auto col_view_new = cudf::column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new));
}
// copy column = diff hash
{
auto col_new = std::make_unique<cudf::column>(*col);
auto col_view_copy = col_new->view();
EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_copy));
}
// column_view, diff column = diff hash.
{
auto col_diff = example_column<TypeParam>();
auto col_view_diff = cudf::column_view{*col_diff};
EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_diff));
}
}
TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_update_data)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// update data + new column_view = same hash.
{
// update data by modifying some bits: fixed_width, string, dict, list, struct
if constexpr (cudf::is_fixed_width<TypeParam>()) {
// Update data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head());
cudf::set_null_mask(data, 2, 64, true);
} else {
// Update child(0).data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head());
cudf::set_null_mask(data, 2, 64, true);
}
auto col_view_new = cudf::column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new));
}
// add null_mask + new column_view = diff hash.
{
col->set_null_mask(cudf::create_null_mask(col->size(), cudf::mask_state::ALL_VALID));
auto col_view_new = cudf::column_view{*col};
EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_new));
col_view_new.null_count();
EXPECT_FALSE(is_shallow_equivalent(col_view, col_view_new));
auto col_view_new2 = cudf::column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_view_new, col_view_new2));
}
col_view = cudf::column_view{*col}; // updating after adding null_mask
// update nulls + new column_view = same hash.
{
cudf::set_null_mask(col->mutable_view().null_mask(), 2, 4, false);
auto col_view_new = cudf::column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new));
}
// set_null_count + new column_view = same hash. set_null_count(UNKNOWN_NULL_COUNT)
{
col->set_null_count(cudf::UNKNOWN_NULL_COUNT);
auto col_view_new = cudf::column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new));
col->set_null_count(col->size());
auto col_view_new2 = cudf::column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_view, col_view_new2));
}
}
TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_slice)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// column_view, sliced[0, size) = same hash (for split too)
{
auto col_sliced = cudf::slice(col_view, {0, col_view.size()});
EXPECT_TRUE(is_shallow_equivalent(col_view, col_sliced[0]));
auto col_split = cudf::split(col_view, {0});
EXPECT_FALSE(is_shallow_equivalent(col_view, col_split[0]));
EXPECT_TRUE(is_shallow_equivalent(col_view, col_split[1]));
}
// column_view, sliced[n:] = diff hash (for split too)
{
auto col_sliced = cudf::slice(col_view, {1, col_view.size()});
EXPECT_FALSE(is_shallow_equivalent(col_view, col_sliced[0]));
auto col_split = cudf::split(col_view, {1});
EXPECT_FALSE(is_shallow_equivalent(col_view, col_split[0]));
EXPECT_FALSE(is_shallow_equivalent(col_view, col_split[1]));
}
// column_view, col copy sliced[0, 0) = same hash (empty column)
{
auto col_new = std::make_unique<cudf::column>(*col);
auto col_new_view = col_new->view();
auto col_sliced = cudf::slice(col_view, {0, 0, 1, 1, col_view.size(), col_view.size()});
auto col_new_sliced = cudf::slice(col_new_view, {0, 0, 1, 1, col_view.size(), col_view.size()});
EXPECT_TRUE(is_shallow_equivalent(col_sliced[0], col_sliced[1]));
EXPECT_TRUE(is_shallow_equivalent(col_sliced[1], col_sliced[2]));
EXPECT_TRUE(is_shallow_equivalent(col_sliced[0], col_new_sliced[0]));
EXPECT_TRUE(is_shallow_equivalent(col_sliced[1], col_new_sliced[1]));
EXPECT_TRUE(is_shallow_equivalent(col_sliced[2], col_new_sliced[2]));
}
// column_view, bit_cast = diff hash
{
if constexpr (std::is_integral_v<TypeParam> and not std::is_same_v<TypeParam, bool>) {
using newType = std::conditional_t<std::is_signed_v<TypeParam>,
std::make_unsigned_t<TypeParam>,
std::make_signed_t<TypeParam>>;
auto new_type = cudf::data_type(cudf::type_to_id<newType>());
auto col_bitcast = cudf::bit_cast(col_view, new_type);
EXPECT_FALSE(is_shallow_equivalent(col_view, col_bitcast));
}
}
}
TYPED_TEST(ColumnViewShallowTests, is_shallow_equivalent_mutable)
{
using namespace cudf::detail;
auto col = example_column<TypeParam>();
auto col_view = cudf::column_view{*col};
// mutable_column_view, column_view = same hash
{
auto col_mutable = cudf::mutable_column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_mutable, col_view));
}
// mutable_column_view, modified mutable_column_view = same hash
// update the children column data = same hash
{
auto col_mutable = cudf::mutable_column_view{*col};
if constexpr (cudf::is_fixed_width<TypeParam>()) {
// Update data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->mutable_view().head());
cudf::set_null_mask(data, 1, 32, false);
} else {
// Update child(0).data
auto data = reinterpret_cast<cudf::bitmask_type*>(col->child(0).mutable_view().head());
cudf::set_null_mask(data, 1, 32, false);
}
EXPECT_TRUE(is_shallow_equivalent(col_view, col_mutable));
auto col_mutable_new = cudf::mutable_column_view{*col};
EXPECT_TRUE(is_shallow_equivalent(col_mutable, col_mutable_new));
}
// update the children column_views = diff hash
{
if constexpr (cudf::is_nested<TypeParam>()) {
col->child(0).set_null_mask(
cudf::create_null_mask(col->child(0).size(), cudf::mask_state::ALL_NULL));
auto col_child_updated = cudf::mutable_column_view{*col};
EXPECT_FALSE(is_shallow_equivalent(col_view, col_child_updated));
}
}
}
| 39.799097
| 100
| 0.695309
|
karthikeyann
|
4afd9707cacc4094c122440407dc12cf6711e195
| 11,682
|
cpp
|
C++
|
diploidizeSNPlog.cpp
|
YourePrettyGood/VariantCallingSimulations
|
3b21879450779ca78c936b961700ceab803daecb
|
[
"MIT"
] | 1
|
2021-02-15T15:36:55.000Z
|
2021-02-15T15:36:55.000Z
|
diploidizeSNPlog.cpp
|
YourePrettyGood/VariantCallingSimulations
|
3b21879450779ca78c936b961700ceab803daecb
|
[
"MIT"
] | null | null | null |
diploidizeSNPlog.cpp
|
YourePrettyGood/VariantCallingSimulations
|
3b21879450779ca78c936b961700ceab803daecb
|
[
"MIT"
] | null | null | null |
/**********************************************************************************
* diploidizeSNPlog.cpp *
* Written by Patrick Reilly *
* Version 1.0 written 2017/01/23 *
* Description: *
* *
* Syntax: diploidizeSNPlog [haploid 1 merged SNP log] [haploid 2 merged SNP log] *
**********************************************************************************/
#include <iostream>
#include <fstream>
#include <string>
#include <getopt.h>
#include <cctype>
#include <vector>
#include <map>
#include <sstream>
#include <array>
//Define constants for getopt:
#define no_argument 0
#define required_argument 1
#define optional_argument 2
//Version:
#define VERSION "1.0"
//Usage/help:
#define USAGE "diploidizeSNPlog\nUsage:\n diploidizeSNPlog -i [FASTA .fai] -a [haploid 1 merged SNP log] -b [haploid 2 merged SNP log]\n"
using namespace std;
vector<string> splitString(string line_to_split, char delimiter) {
vector<string> line_vector;
string element;
istringstream line_to_split_stream(line_to_split);
while (getline(line_to_split_stream, element, delimiter)) {
line_vector.push_back(element);
}
return line_vector;
}
long baseToLong(string &base) {
switch(base[0]) {
case 'A':
case 'a':
return 0;
case 'C':
case 'c':
return 1;
case 'G':
case 'g':
return 2;
case 'T':
case 't':
return 3;
default:
return 4;
}
}
long degenerateBases(long a, long b) {
if (a == b) { //Homozygous
return a;
} else if (a > 3 || b > 3) { //Either is an N
return 4;
} else if ((a == 0 && b == 1) || (a == 1 && b == 0)) { //Het A/C
return 5; //M
} else if ((a == 0 && b == 2) || (a == 2 && b == 0)) { //Het A/G
return 6; //R
} else if ((a == 0 && b == 3) || (a == 3 && b == 0)) { //Het A/T
return 7; //W
} else if ((a == 1 && b == 2) || (a == 2 && b == 1)) { //Het C/G
return 8; //S
} else if ((a == 1 && b == 3) || (a == 3 && b == 1)) { //Het C/T
return 9; //Y
} else if ((a == 2 && b == 3) || (a == 3 && b == 2)) { //Het G/T
return 10; //K
} else {
return 4;
}
}
int main(int argc, char **argv) {
//Numbers to bases map:
char int2bases[] = {'A', 'C', 'G', 'T', 'N', 'M', 'R', 'W', 'S', 'Y', 'K'};
//Log file paths:
string branch1snplog_path, branch2snplog_path, fai_path;
//Option for debugging:
bool debug = 0;
//Variables for getopt_long:
int optchar;
int structindex = 0;
extern int optind;
//Create the struct used for getopt:
const struct option longoptions[] {
{"input_fai", required_argument, 0, 'i'},
{"hap1_snp_log", required_argument, 0, 'a'},
{"hap2_snp_log", required_argument, 0, 'b'},
{"debug", no_argument, 0, 'd'},
{"version", no_argument, 0, 'v'},
{"help", no_argument, 0, 'h'}
};
//Read in the options:
while ((optchar = getopt_long(argc, argv, "i:a:b:dvh", longoptions, &structindex)) > -1) {
switch(optchar) {
case 'i':
cerr << "Using FASTA .fai index: " << optarg << endl;
fai_path = optarg;
break;
case 'a':
cerr << "Using haploid 1 merged SNP log: " << optarg << endl;
branch1snplog_path = optarg;
break;
case 'b':
cerr << "Using haploid 2 merged SNP log: " << optarg << endl;
branch2snplog_path = optarg;
break;
case 'd':
cerr << "Debugging mode enabled." << endl;
debug = 1;
break;
case 'v':
cerr << "diploidizeSNPlog version " << VERSION << endl;
return 0;
break;
case 'h':
cerr << USAGE;
return 0;
break;
default:
cerr << "Unknown option " << (unsigned char)optchar << " supplied." << endl;
cerr << USAGE;
return 1;
break;
}
}
//Ignore positional arguments
if (optind < argc) {
cerr << "Ignoring extra positional arguments starting at " << argv[optind++] << endl;
}
//Check that log paths are set:
if (branch1snplog_path.empty() || branch2snplog_path.empty() || fai_path.empty()) {
cerr << "Missing one of the input logs. Quitting." << endl;
return 2;
}
//Open the FASTA .fai index:
ifstream fasta_fai;
fasta_fai.open(fai_path);
if (!fasta_fai) {
cerr << "Error opening FASTA .fai index file " << fai_path << ". Quitting." << endl;
return 3;
}
//Read in the scaffold order from the .fai file:
vector<string> scaffolds;
string failine;
while (getline(fasta_fai, failine)) {
vector<string> line_vector;
line_vector = splitString(failine, '\t');
scaffolds.push_back(line_vector[0]);
}
fasta_fai.close();
//Open the haploid 1 merged SNP log:
ifstream branch1_snp_log;
branch1_snp_log.open(branch1snplog_path);
if (!branch1_snp_log) {
cerr << "Error opening haploid 1 merged SNP log " << branch1snplog_path << ". Quitting." << endl;
return 5;
}
//Open the haploid 2 merged SNP log:
ifstream branch2_snp_log;
branch2_snp_log.open(branch2snplog_path);
if (!branch2_snp_log) {
cerr << "Error opening haploid 2 merged SNP log " << branch2snplog_path << ". Quitting." << endl;
branch1_snp_log.close();
return 6;
}
//Read branch 1 log into map (keyed by scaffold) of vectors of 3-element arrays (pos, oldallele, newallele):
cerr << "Reading haploid 1 merged SNP log " << branch1snplog_path << endl;
map<string, vector<array<long, 3>>> branch1_log;
string b1line;
while (getline(branch1_snp_log, b1line)) {
vector<string> line_vector;
line_vector = splitString(b1line, '\t');
long oldallele = baseToLong(line_vector[2]);
long newallele = baseToLong(line_vector[3]);
if (debug && (oldallele > 3 || newallele > 3)) {
cerr << "Found non-ACGT base in branch 1 SNP log at " << line_vector[0] << " position " << line_vector[1] << endl;
}
array<long, 3> log_record;
log_record[0] = stoul(line_vector[1]);
log_record[1] = oldallele;
log_record[2] = newallele;
branch1_log[line_vector[0]].push_back(log_record);
}
branch1_snp_log.close();
cerr << "Done reading haploid 1 merged SNP log" << endl;
//Read branch 2 log into map (keyed by scaffold) of vectors of 3-element arrays (pos, oldallele, newallele):
cerr << "Reading haploid 2 merged SNP log " << branch2snplog_path << endl;
map<string, vector<array<long, 3>>> branch2_log;
string b2line;
while (getline(branch2_snp_log, b2line)) {
vector<string> line_vector;
line_vector = splitString(b2line, '\t');
long oldallele = baseToLong(line_vector[2]);
long newallele = baseToLong(line_vector[3]);
if (debug && (oldallele > 3 || newallele > 3)) {
cerr << "Found non-ACGT base in branch 1 SNP log at " << line_vector[0] << " position " << line_vector[1] << endl;
}
array<long, 3> log_record;
log_record[0] = stoul(line_vector[1]);
log_record[1] = oldallele;
log_record[2] = newallele;
branch2_log[line_vector[0]].push_back(log_record);
}
branch2_snp_log.close();
cerr << "Done reading haploid 2 merged SNP log" << endl;
//Now iterate over scaffolds, outputting diploidized SNPs at any sites where either haploid deviates from ref:
cerr << "Diploidizing SNP logs" << endl;
for (auto scaffold_iterator = scaffolds.begin(); scaffold_iterator != scaffolds.end(); ++scaffold_iterator) {
if (branch1_log.count(*scaffold_iterator) == 0) {
if (branch2_log.count(*scaffold_iterator) > 0) { //Scaffold is only represented in one of the two haploids
//Output haploid 2/ref degenerate base:
for (auto b2_iterator = branch2_log[*scaffold_iterator].begin(); b2_iterator != branch2_log[*scaffold_iterator].end(); ++b2_iterator) {
cout << *scaffold_iterator << '\t' << (*b2_iterator)[0] << '\t' << int2bases[(*b2_iterator)[1]] << '\t' << int2bases[degenerateBases((*b2_iterator)[2], (*b2_iterator)[1])] << endl;
}
}
} else if (branch2_log.count(*scaffold_iterator) == 0) { //Scaffold must be represented in haploid 1
//Output haploid 1/ref degenerate base
for (auto b1_iterator = branch1_log[*scaffold_iterator].begin(); b1_iterator != branch1_log[*scaffold_iterator].end(); ++b1_iterator) {
cout << *scaffold_iterator << '\t' << (*b1_iterator)[0] << '\t' << int2bases[(*b1_iterator)[1]] << '\t' << int2bases[degenerateBases((*b1_iterator)[2], (*b1_iterator)[1])] << endl;
}
} else { //Scaffold is represented in both haploids, so diploidize the scaffold
auto b1_iterator = branch1_log[*scaffold_iterator].begin();
auto b2_iterator = branch2_log[*scaffold_iterator].begin();
while (b1_iterator != branch1_log[*scaffold_iterator].end() && b2_iterator != branch2_log[*scaffold_iterator].end()) {
if ((*b1_iterator)[0] < (*b2_iterator)[0]) {
//Output haploid 1/ref degenerate base:
cout << *scaffold_iterator << '\t' << (*b1_iterator)[0] << '\t' << int2bases[(*b1_iterator)[1]] << '\t' << int2bases[degenerateBases((*b1_iterator)[2], (*b1_iterator)[1])] << endl;
++b1_iterator;
} else if ((*b1_iterator)[0] > (*b2_iterator)[0]) {
//Output haploid 2/ref degenerate base:
cout << *scaffold_iterator << '\t' << (*b2_iterator)[0] << '\t' << int2bases[(*b2_iterator)[1]] << '\t' << int2bases[degenerateBases((*b2_iterator)[2], (*b2_iterator)[1])] << endl;
++b2_iterator;
} else {
//Check that ref alleles match:
if ((*b1_iterator)[1] != (*b2_iterator)[1]) {
cerr << "Old alleles for site " << (*b1_iterator)[0] << " on scaffold " << *scaffold_iterator << " do not match between haploids." << endl;
cerr << "Haploid 1 says " << int2bases[(*b1_iterator)[1]] << " while haploid 2 says " << int2bases[(*b2_iterator)[1]] << endl;
}
//Diploidize the SNP:
cout << *scaffold_iterator << '\t' << (*b1_iterator)[0] << '\t' << int2bases[(*b1_iterator)[1]] << '\t' << int2bases[degenerateBases((*b1_iterator)[2], (*b2_iterator)[2])] << endl;
++b1_iterator;
++b2_iterator;
}
}
//Output the remainder of the scaffold from whichever branch still hasn't reached its end:
while (b1_iterator != branch1_log[*scaffold_iterator].end()) {
cout << *scaffold_iterator << '\t' << (*b1_iterator)[0] << '\t' << int2bases[(*b1_iterator)[1]] << '\t' << int2bases[degenerateBases((*b1_iterator)[2], (*b1_iterator)[1])] << endl;
++b1_iterator;
}
while (b2_iterator != branch2_log[*scaffold_iterator].end()) {
cout << *scaffold_iterator << '\t' << (*b2_iterator)[0] << '\t' << int2bases[(*b2_iterator)[1]] << '\t' << int2bases[degenerateBases((*b2_iterator)[2], (*b2_iterator)[1])] << endl;
++b2_iterator;
}
}
}
cerr << "Done diploidizing SNP logs" << endl;
return 0;
}
| 40.846154
| 195
| 0.555128
|
YourePrettyGood
|
4afe40388e78839d3c18eb7ba8bfa532b4ed6d53
| 1,209
|
cpp
|
C++
|
ARDUINO_CODE/Bluetooth.cpp
|
Allabakshu-shaik/Mercedes-POC
|
b338c471870830ba4b4fb26e4dc1097e0882a8e2
|
[
"MIT"
] | 46
|
2020-01-08T16:38:46.000Z
|
2022-03-30T21:08:07.000Z
|
ARDUINO_CODE/Bluetooth.cpp
|
Allabakshu-shaik/Mercedes-POC
|
b338c471870830ba4b4fb26e4dc1097e0882a8e2
|
[
"MIT"
] | 2
|
2020-03-28T08:26:29.000Z
|
2020-08-06T10:52:57.000Z
|
ARDUINO_CODE/Bluetooth.cpp
|
Allabakshu-shaik/Mercedes-POC
|
b338c471870830ba4b4fb26e4dc1097e0882a8e2
|
[
"MIT"
] | 9
|
2020-03-13T20:53:02.000Z
|
2021-08-31T08:50:20.000Z
|
#include "Bluetooth.h"
bool BLUETOOTH::isConnected = false;
#ifdef ARDUINO_MEGA
BLUETOOTH::BLUETOOTH() {
Serial1.begin(9600);
Serial1.clearWriteError();
}
char* BLUETOOTH::read_message() {
memset(buffer, 0x00, sizeof(buffer));
if (Serial1.available()) {
uint8_t len = Serial1.read();
Serial1.readBytes(buffer, len);
this->isConnected = true;
DPRINTLN(BT_REC_STR+String(buffer));
}
return buffer;
}
void BLUETOOTH::write_message(const char* msg, uint8_t len = 0) {
for(uint8_t i = 0; i < len; i++) {
Serial1.write(msg[i]);
}
}
#else
BLUETOOTH::BLUETOOTH(uint8_t rx, uint8_t tx) {
bt = new SoftwareSerial(tx, rx);
bt->begin(9600);
bt->clearWriteError();
}
char* BLUETOOTH::read_message() {
memset(buffer, 0x00, sizeof(buffer));
if (bt->available()) {
this->isConnected = true;
uint8_t len = bt->read();
bt->readBytes(buffer, len);
DPRINTLN(BT_REC_STR+String(buffer));
}
return buffer;
}
void BLUETOOTH::write_message(const char* msg, uint8_t len = 0) {
for(uint8_t i = 0; i < len; i++) {
bt->write(msg[i]);
}
bt->write('\r');
bt->flush();
}
#endif
| 22.388889
| 65
| 0.603805
|
Allabakshu-shaik
|
ab00784b9802f57a9c460c2c8dca85543846a516
| 16,515
|
cpp
|
C++
|
src/ReportWindow.cpp
|
fantoro/CapitalBe
|
0d5f7056a61e71693b1ef85b5024c9ce0894ab2f
|
[
"MIT"
] | 2
|
2017-05-17T07:18:05.000Z
|
2018-02-28T13:51:47.000Z
|
src/ReportWindow.cpp
|
fantoro/CapitalBe
|
0d5f7056a61e71693b1ef85b5024c9ce0894ab2f
|
[
"MIT"
] | 26
|
2016-12-20T12:28:52.000Z
|
2022-03-30T06:00:03.000Z
|
src/ReportWindow.cpp
|
fantoro/CapitalBe
|
0d5f7056a61e71693b1ef85b5024c9ce0894ab2f
|
[
"MIT"
] | 13
|
2015-01-28T15:26:06.000Z
|
2020-10-26T06:03:42.000Z
|
#include "ReportWindow.h"
#include <GridLayoutBuilder.h>
#include <LayoutBuilder.h>
#include <View.h>
#include <StringView.h>
#include <Bitmap.h>
#include <TranslationUtils.h>
#include "ReportGrid.h"
#include "DateBox.h"
#include "StickyDrawButton.h"
#include "Layout.h"
#include "TimeSupport.h"
#include "ObjectList.h"
#include "Database.h"
#include "ColumnTypes.h"
#include "HelpButton.h"
#include "Preferences.h"
#include "MsgDefs.h"
int compare_stringitem(const void *item1, const void *item2);
enum
{
M_REPORT_CASH_FLOW='csfl',
M_REPORT_NET_WORTH,
M_REPORT_TRANSACTIONS,
M_REPORT_BUDGET,
M_START_DATE_CHANGED,
M_END_DATE_CHANGED,
M_CATEGORIES_CHANGED,
M_SUBTOTAL_NONE,
M_SUBTOTAL_MONTH,
M_SUBTOTAL_QUARTER,
M_SUBTOTAL_YEAR,
M_TOGGLE_ACCOUNT,
M_TOGGLE_GRAPH
};
ReportWindow::ReportWindow(BRect frame)
: BWindow(frame,TRANSLATE("Reports"), B_DOCUMENT_WINDOW, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS),
fSubtotalMode(SUBTOTAL_NONE),
fReportMode(REPORT_CASH_FLOW),
fStartDate(GetCurrentYear()),
fEndDate(GetCurrentDate()),
fTitleFont(be_bold_font),
fHeaderFont(be_plain_font)
{
BString temp;
fHeaderFont.SetFace(B_ITALIC_FACE);
BView *view = new BView("back", B_WILL_DRAW);
BLayoutBuilder::Group<>(this, B_VERTICAL, 0.0f)
.SetInsets(0)
.Add(view)
.End();
view->SetViewColor(240,240,240);
BGroupLayout *reportsLayout = new BGroupLayout(B_VERTICAL, 0);
BGroupLayout *accountsLayout = new BGroupLayout(B_VERTICAL, 0);
BGroupLayout *subtotalLayout = new BGroupLayout(B_VERTICAL, 0);
BGroupLayout *categoriesLayout = new BGroupLayout(B_VERTICAL, 0);
BGroupLayout *layout_ = new BGroupLayout(B_VERTICAL, 1.0f);
BLayoutBuilder::Group<>(view, B_HORIZONTAL)
.SetInsets(10)
.AddGroup(B_VERTICAL, 1.0f)
.Add(reportsLayout, 1)
.Add(accountsLayout, 5)
.Add(subtotalLayout, 1)
.Add(categoriesLayout, 5)
.End()
.Add(layout_)
.End();
BMenu *reportmenu = new BMenu(TRANSLATE("Reports"));
reportmenu->SetLabelFromMarked(true);
// TODO: Re-enable the Budget report
// reportmenu->AddItem(new BMenuItem(TRANSLATE("Budget"), new BMessage(M_REPORT_BUDGET)));
temp << TRANSLATE("Income") << " / " << TRANSLATE("Spending");
reportmenu->AddItem(new BMenuItem(temp.String(), new BMessage(M_REPORT_CASH_FLOW)));
reportmenu->AddItem(new BMenuItem(TRANSLATE("Total Worth"), new BMessage(M_REPORT_NET_WORTH)));
reportmenu->AddItem(new BMenuItem(TRANSLATE("Transactions"), new BMessage(M_REPORT_TRANSACTIONS)));
reportmenu->SetRadioMode(true);
reportmenu->ItemAt(0L)->SetMarked(true);
fReportMode = REPORT_BUDGET;
BRect r(10,10,reportmenu->StringWidth(temp.String())+45,60);
temp = TRANSLATE("Reports"); temp += ": ";
BStringView *sv = new BStringView("reportsv",temp.String());
reportsLayout->AddView(sv);
fReportField = new BMenuField("reportfield","",reportmenu);
reportsLayout->AddView(fReportField);
temp = TRANSLATE("Accounts"); temp += ": ";
sv = new BStringView("accountsv",temp.String());
accountsLayout->AddView(sv);
fAccountList = new BListView("reportaccountlist",B_MULTIPLE_SELECTION_LIST);
BScrollView *scrollview = new BScrollView("accountscroller",fAccountList,0,
false,true);
accountsLayout->AddView(scrollview);
// This is disabled because otherwise the report is rendered once for each
// account added when the report window is shown initially
// fAccountList->SetSelectionMessage(new BMessage(M_TOGGLE_ACCOUNT));
temp = TRANSLATE("Subtotal"); temp += ":";
sv = new BStringView("subtotalsv",temp.String());
subtotalLayout->AddView(sv);
BMenu *subtotalmenu = new BMenu(TRANSLATE("Subtotal"));
subtotalmenu->AddItem(new BMenuItem(TRANSLATE("None"),new BMessage(M_SUBTOTAL_NONE)));
subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Month"),new BMessage(M_SUBTOTAL_MONTH)));
subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Quarter"),new BMessage(M_SUBTOTAL_QUARTER)));
subtotalmenu->AddItem(new BMenuItem(TRANSLATE("Year"),new BMessage(M_SUBTOTAL_YEAR)));
subtotalmenu->SetLabelFromMarked(true);
subtotalmenu->SetRadioMode(true);
subtotalmenu->ItemAt(0)->SetMarked(true);
fSubtotalField = new BMenuField("subtotalfield","",subtotalmenu);
subtotalLayout->AddView(fSubtotalField);
prefsLock.Lock();
BString reporthelp = gAppPath;
prefsLock.Unlock();
reporthelp << "helpfiles/" << gCurrentLanguage->Name() << "/Report Window Help";
HelpButton *help = new HelpButton("reporthelp", reporthelp.String());
temp = TRANSLATE("Categories"); temp += ": ";
sv = new BStringView("catsv",temp.String());
categoriesLayout->AddView(sv);
fCategoryList = new BListView("reportcattlist",B_MULTIPLE_SELECTION_LIST,
B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE | B_NAVIGABLE);
fCategoryScroller = new BScrollView("catscroller",fCategoryList,0,false,true);
categoriesLayout->AddView(fCategoryScroller);
fCategoryList->SetSelectionMessage(new BMessage(M_CATEGORIES_CHANGED));
fCategoryList->SetInvocationMessage(new BMessage(M_CATEGORIES_CHANGED));
BString datestring;
gDefaultLocale.DateToString(GetCurrentYear(),datestring);
temp = TRANSLATE("Starting Date"); temp += ": ";
fStartDateBox = new DateBox("startdate",temp.String(),datestring.String(),
new BMessage(M_START_DATE_CHANGED));
fStartDateBox->SetDate(GetCurrentYear());
// fStartDateBox->SetEscapeCancel(true);
layout_->AddView(fStartDateBox);
fStartDateBox->GetFilter()->SetMessenger(new BMessenger(this));
gDefaultLocale.DateToString(GetCurrentDate(),datestring);
temp = TRANSLATE("Ending Date"); temp += ": ";
fEndDateBox = new DateBox("enddate",temp.String(),datestring.String(),
new BMessage(M_END_DATE_CHANGED));
fEndDateBox->SetDate(GetCurrentDate());
layout_->AddView(fEndDateBox);
fEndDateBox->GetFilter()->SetMessenger(new BMessenger(this));
BBitmap *up, *down;
BRect brect(0,0,16,16);
up = BTranslationUtils::GetBitmap('PNG ',"BarGraphUp.png");
if(!up)
up = new BBitmap(brect,B_RGB32);
down = BTranslationUtils::GetBitmap('PNG ',"BarGraphDown.png");
if(!down)
down = new BBitmap(brect,B_RGB32);
brect.OffsetTo(Bounds().right - 10 - brect.Width(),10 +
((fEndDateBox->Frame().Height() - 16)/2) );
fGraphButton = new StickyDrawButton(brect,"graphbutton",up,down,
new BMessage(M_TOGGLE_GRAPH),
B_FOLLOW_TOP | B_FOLLOW_RIGHT,B_WILL_DRAW);
// view->AddChild(fGraphButton);
// TODO: This needs to be unhidden when graph support is finally added
fGraphButton->Hide();
fGridView = new BColumnListView("gridview",B_WILL_DRAW, B_FANCY_BORDER);
layout_->AddView(fGridView);
layout_->AddItem(BGridLayoutBuilder(0.0f, 0.0f)
.Add(BSpaceLayoutItem::CreateGlue(), 0, 0)
.Add(help, 1, 0)
);
// Configuring to make it look good and not like a grid
fGridView->SetColumnFlags(B_ALLOW_COLUMN_RESIZE);
fGridView->SetSortingEnabled(false);
fGridView->SetEditMode(false);
rgb_color white = { 255,255,255,255 };
fGridView->SetColor(B_COLOR_BACKGROUND,white);
fGridView->SetColor(B_COLOR_ROW_DIVIDER,fGridView->Color(B_COLOR_BACKGROUND));
fGridView->SetColor(B_COLOR_SELECTION,fGridView->Color(B_COLOR_BACKGROUND));
fGridView->SetColor(B_COLOR_NON_FOCUS_SELECTION,fGridView->Color(B_COLOR_BACKGROUND));
fGridView->SetColor(B_COLOR_SEPARATOR_BORDER,fGridView->Color(B_COLOR_BACKGROUND));
fGridView->SetColor(B_COLOR_SEPARATOR_LINE,fGridView->Color(B_COLOR_BACKGROUND));
fGraphView = new BView(r,"As Graph",B_FOLLOW_ALL,B_WILL_DRAW);
// view->AddChild(fGraphView);
fGraphView->Hide();
gDatabase.AddObserver(this);
for(int32 i=0; i<gDatabase.CountAccounts(); i++)
{
Account *acc = gDatabase.AccountAt(i);
if(!acc)
continue;
AddAccount(acc);
}
fAccountList->SortItems(compare_stringitem);
fCategoryList->SortItems(compare_stringitem);
for(int32 i=0; i<fAccountList->CountItems(); i++)
{
BStringItem *item = (BStringItem*)fAccountList->ItemAt(i);
if(!item)
continue;
Account *itemaccount = gDatabase.AccountByName(item->Text());
if(itemaccount && (!itemaccount->IsClosed()))
fAccountList->Select(i,true);
}
// fAccountList->Select(0,fAccountList->CountItems()-1,true);
fCategoryList->Select(0,fCategoryList->CountItems()-1,true);
// Set up the scrollbars
CalcCategoryString();
fReportField->MakeFocus(true);
fAccountList->SetSelectionMessage(new BMessage(M_TOGGLE_ACCOUNT));
}
void ReportWindow::HandleNotify(const uint64 &value, const BMessage *msg)
{
Lock();
if(value & WATCH_ACCOUNT)
{
Account *acc;
if(msg->FindPointer("item",(void**)&acc)!=B_OK)
{
Unlock();
return;
}
if(value & WATCH_CREATE)
{
AddAccount(acc);
}
else
if(value & WATCH_DELETE)
{
}
else
if(value & WATCH_RENAME)
{
}
else
if(value & WATCH_CHANGE)
{
}
}
else
if(value & WATCH_TRANSACTION)
{
}
RenderReport();
Unlock();
}
void ReportWindow::MessageReceived(BMessage *msg)
{
switch(msg->what)
{
case M_PREVIOUS_FIELD:
{
if(fStartDateBox->ChildAt(0)->IsFocus())
fCategoryList->MakeFocus();
else
if(fEndDateBox->ChildAt(0)->IsFocus())
fStartDateBox->MakeFocus();
break;
}
case M_NEXT_FIELD:
{
if(fStartDateBox->ChildAt(0)->IsFocus())
fEndDateBox->MakeFocus();
else
if(fEndDateBox->ChildAt(0)->IsFocus())
fGridView->MakeFocus();
break;
}
case M_REPORT_CASH_FLOW:
{
fReportMode = REPORT_CASH_FLOW;
RenderReport();
break;
}
case M_REPORT_NET_WORTH:
{
fReportMode = REPORT_NET_WORTH;
RenderReport();
break;
}
case M_REPORT_TRANSACTIONS:
{
fReportMode = REPORT_TRANSACTIONS;
RenderReport();
break;
}
case M_REPORT_BUDGET:
{
fReportMode = REPORT_BUDGET;
RenderReport();
break;
}
case M_SUBTOTAL_NONE:
{
fSubtotalMode = SUBTOTAL_NONE;
RenderReport();
break;
}
case M_SUBTOTAL_MONTH:
{
fSubtotalMode = SUBTOTAL_MONTH;
RenderReport();
break;
}
case M_SUBTOTAL_QUARTER:
{
fSubtotalMode = SUBTOTAL_QUARTER;
RenderReport();
break;
}
case M_SUBTOTAL_YEAR:
{
fSubtotalMode = SUBTOTAL_YEAR;
RenderReport();
break;
}
case M_START_DATE_CHANGED:
{
time_t temp;
if(gDefaultLocale.StringToDate(fStartDateBox->Text(),temp)==B_OK)
{
fStartDate = temp;
if(fStartDate > fEndDate)
fStartDate = fEndDate;
RenderReport();
}
else
{
ShowAlert(TRANSLATE("Capital Be didn't understand the date you entered."),
TRANSLATE(
"Capital Be understands lots of different ways of entering dates. "
"Apparently, this wasn't one of them. You'll need to change how you "
"entered this date. Sorry."));
fStartDateBox->MakeFocus(true);
break;
}
BString formatted;
gDefaultLocale.DateToString(fStartDate,formatted);
fStartDateBox->SetText(formatted.String());
break;
}
case M_END_DATE_CHANGED:
{
time_t temp;
if(gDefaultLocale.StringToDate(fEndDateBox->Text(),temp)==B_OK)
{
fEndDate = temp;
if(fStartDate > fEndDate)
fStartDate = fEndDate;
RenderReport();
}
else
{
ShowAlert(TRANSLATE("Capital Be didn't understand the date you entered."),
TRANSLATE(
"Capital Be understands lots of different ways of entering dates. "
"Apparently, this wasn't one of them. You'll need to change how you "
"entered this date. Sorry."));
fEndDateBox->MakeFocus(true);
break;
}
BString formatted;
gDefaultLocale.DateToString(fEndDate,formatted);
fEndDateBox->SetText(formatted.String());
break;
}
case M_CATEGORIES_CHANGED:
{
CalcCategoryString();
RenderReport();
break;
}
case M_TOGGLE_ACCOUNT:
{
RenderReport();
break;
}
case M_TOGGLE_GRAPH:
{
if(fGridView->IsHidden())
{
fGridView->Show();
fGraphView->Hide();
}
else
{
fGridView->Hide();
fGraphView->Show();
}
break;
}
default:
BWindow::MessageReceived(msg);
}
}
void ReportWindow::FrameResized(float w, float h)
{
BScrollBar *bar = fCategoryScroller->ScrollBar(B_VERTICAL);
if(fCategoryList->CountItems())
{
float itemheight = fCategoryList->ItemAt(0)->Height();
float itemrange = (fCategoryList->CountItems()+1) * itemheight;
if(itemrange < fCategoryScroller->Frame().Height())
bar->SetRange(0,0);
else
bar->SetRange(0,itemrange - fCategoryScroller->Frame().Height());
float big, small;
bar->GetSteps(&small, &big);
big = (int32)(fCategoryScroller->Frame().Height() * .9);
bar->SetSteps(small,big);
}
else
bar->SetRange(0,0);
FixGridScrollbar();
}
void ReportWindow::AddAccount(Account *acc)
{
if(!acc)
return;
acc->AddObserver(this);
AccountItem *accountitem = new AccountItem(acc);
fAccountList->AddItem(accountitem);
BString command = "select category from account_";
command << acc->GetID() << ";";
CppSQLite3Query query = gDatabase.DBQuery(command.String(),"ReportWindow::AddAccount");
while(!query.eof())
{
BString catstr = DeescapeIllegalCharacters(query.getStringField(0));
if(catstr.CountChars()<1)
{
query.nextRow();
continue;
}
// Make sure that the category is not already in the list.
BStringItem *existing = NULL;
for(int32 k=0; k<fCategoryList->CountItems(); k++)
{
BStringItem *item = (BStringItem*)fCategoryList->ItemAt(k);
if(!item)
continue;
if(catstr.ICompare(item->Text())==0)
{
existing = item;
break;
}
}
if(existing)
{
query.nextRow();
continue;
}
fCategoryList->AddItem(new BStringItem(catstr.String()));
query.nextRow();
}
}
void ReportWindow::FixGridScrollbar(void)
{
BScrollBar *bar = fGridView->ScrollBar(B_VERTICAL);
if (!bar)
return;
BRow *row = fGridView->RowAt(0);
if(!row)
return;
float itemrange = (fGridView->CountRows()+3) * row->Height();;
if(itemrange < fGridView->Frame().Height() - B_H_SCROLL_BAR_HEIGHT)
bar->SetRange(0,0);
else
bar->SetRange(0,itemrange - fGridView->Frame().Height());
float big, small;
bar->GetSteps(&small, &big);
big = (int32)(fGridView->Frame().Height() * .9);
bar->SetSteps(small,big);
}
/*
void ReportWindow::CalcAccountString(void)
{
// Compile list of selected accounts
fAccountString = "";
for(int32 i=0; i<gDatabase.CountAccounts(); i++)
{
AccountItem *accitem = (AccountItem*)fAccountList->ItemAt(i);
if(accitem && accitem->IsSelected())
{
if(fAccountString.CountChars()>0)
fAccountString << ",account_" << accitem->account->GetID();
else
fAccountString << "account_" << accitem->account->GetID();
}
}
}
*/
void ReportWindow::CalcCategoryString(void)
{
// Compile list of selected categories
fCategoryString = "";
for(int32 i=0; i<fCategoryList->CountItems(); i++)
{
BStringItem *catitem = (BStringItem*)fCategoryList->ItemAt(i);
if(catitem && catitem->IsSelected())
{
if(fCategoryString.CountChars()>0)
fCategoryString << ",'" << EscapeIllegalCharacters(catitem->Text()) << "'";
else
fCategoryString << "'" << EscapeIllegalCharacters(catitem->Text()) << "'";
}
}
}
void ReportWindow::RenderReport(void)
{
fGridView->Clear();
BColumn *column = fGridView->ColumnAt(0);
while(column)
{
fGridView->RemoveColumn(column);
delete column;
column = fGridView->ColumnAt(0);
}
if(fAccountList->CountItems()<1 || fAccountList->CurrentSelection()<0)
return;
switch(fReportMode)
{
case REPORT_CASH_FLOW:
{
ComputeCashFlow();
break;
}
case REPORT_NET_WORTH:
{
ComputeNetWorth();
break;
}
case REPORT_TRANSACTIONS:
{
ComputeTransactions();
break;
}
case REPORT_BUDGET:
{
ComputeBudget();
break;
}
default:
break;
}
FixGridScrollbar();
}
bool ReportWindow::QuitRequested(void)
{
// We need to remove this window's observer object from each account's notifier, or else
// we will crash the app after closing the window and selecting an account
for (int32 i = 0; i < gDatabase.CountAccounts(); i++)
{
Account *acc = gDatabase.AccountAt(i);
if(!acc)
continue;
acc->RemoveObserver(this);
}
gDatabase.RemoveObserver(this);
return true;
}
int compare_stringitem(const void *item1, const void *item2)
{
BListItem *listitem1 = *((BListItem**)item1);
BListItem *listitem2 = *((BListItem**)item2);
BStringItem *stritem1=(BStringItem *)listitem1;
BStringItem *stritem2=(BStringItem *)listitem2;
int len1 = (stritem1 && stritem1->Text()) ? strlen(stritem1->Text()) : 0;
int len2 = (stritem2&& stritem2->Text()) ? strlen(stritem2->Text()) : 0;
if(len1 < 1)
{
return (len2 < 1) ? 0 : 1;
}
else
if(len2 < 1)
{
return (len1 < 1) ? 0 : -1;
}
return strcmp(stritem1->Text(),stritem2->Text());
}
| 25.252294
| 111
| 0.706146
|
fantoro
|
ab02beb9d486873696b0937874ecc7c4d546deb7
| 2,124
|
cpp
|
C++
|
src/ArucoHandler.cpp
|
bobribbon/team_scheire_OK
|
e40c52a681e31bd3a0209f11e4de2268cc2d55e1
|
[
"MIT"
] | null | null | null |
src/ArucoHandler.cpp
|
bobribbon/team_scheire_OK
|
e40c52a681e31bd3a0209f11e4de2268cc2d55e1
|
[
"MIT"
] | null | null | null |
src/ArucoHandler.cpp
|
bobribbon/team_scheire_OK
|
e40c52a681e31bd3a0209f11e4de2268cc2d55e1
|
[
"MIT"
] | null | null | null |
/*
* Interactieve OK
* Jeroen Lassche (j.lassche@bravis.nl)
*
* Fork van het project:
* Immersief, interactief operatiekwartier
* door Team Scheire, Imec en Jan Everaert
* https://github.com/imec-int/team_scheire_OK
*/
#include "ArucoHandler.hpp"
#include "ofxOpenCv.h"
#include "ofxCv.h"
#include "ofxAruco.h"
/*
* Teken oppervlaktes op de gevonden markers.
*/
void ArucoHandler::draw(MarkerHandler *markerHandler, SurfaceHandler *surfaceHandler, int mode)
{
vector<aruco::Marker> markers;
framebuffer.begin();
ofClear(0, 0, 0, 0);
// teken camera
if (mode & MODE_SHOW_CAMERA)
{
camera.draw(0, 0, ofGetWidth(), ofGetHeight());
}
markers = aruco.getMarkers();
for (int i = 0; i < markerHandler->visibleMarkersId.size(); i++)
{
Marker marker = markerHandler->get(markerHandler->visibleMarkersId.at(i));
aruco.begin(i);
// teken sufaces
if (marker.id != MARKER_UNKNOWN)
{
if (mode & MODE_EDIT && markerHandler->selectedMarkerId == marker.id)
{
surfaceHandler->draw(marker, true);
}
else
{
surfaceHandler->draw(marker);
}
}
// teken marker
if (mode & MODE_SHOW_MARKERS)
{
markerHandler->draw(marker);
}
aruco.end();
}
framebuffer.end();
framebuffer.draw(0, 0);
return;
}
/*
* Verkrijg zichtbare markers id's.
* Geeft een vector van ints terug met de gevonden id's.
*/
vector<int> ArucoHandler::getVisibleMarkersIds(void)
{
vector<aruco::Marker> arucoMarkers;
vector<int> ids;
arucoMarkers = aruco.getMarkers();
for (int i = 0; i < arucoMarkers.size(); i++)
{
ids.push_back(arucoMarkers.at(i).id);
}
return ids;
}
/*
* Stel ofxAruco in.
*/
void ArucoHandler::setup(string dataPath)
{
camera.setDeviceID(0);
camera.initGrabber(WIDTH, HEIGHT);
aruco.setup(dataPath + "intrinsics.int", camera.getWidth(), camera.getHeight());
framebuffer.allocate(WIDTH, HEIGHT);
return;
}
/*
* Update camera.
*/
void ArucoHandler::update(int mode)
{
if (mode & MODE_TRACK)
{
camera.update();
if (camera.isFrameNew())
{
camera.getPixelsRef().mirror(true, false);
aruco.detectBoards(camera.getPixels());
}
}
return;
}
| 17.848739
| 95
| 0.679379
|
bobribbon
|
ab073e642a41c91e273bab92f031deae626bb8b4
| 11,387
|
cpp
|
C++
|
src/plugins/ExampleSensor/ExampleSensor.cpp
|
SchademanK/Ookala
|
9a5112e1d3067d589c150fb9c787ae36801a67dc
|
[
"MIT"
] | null | null | null |
src/plugins/ExampleSensor/ExampleSensor.cpp
|
SchademanK/Ookala
|
9a5112e1d3067d589c150fb9c787ae36801a67dc
|
[
"MIT"
] | null | null | null |
src/plugins/ExampleSensor/ExampleSensor.cpp
|
SchademanK/Ookala
|
9a5112e1d3067d589c150fb9c787ae36801a67dc
|
[
"MIT"
] | null | null | null |
// --------------------------------------------------------------------------
// $Id: ExampleSensor.cpp 135 2008-12-19 00:49:58Z omcf $
// --------------------------------------------------------------------------
// Copyright (c) 2008 Hewlett-Packard Development Company, L.P.
//
// 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __linux__
#include <unistd.h>
#include <usb.h>
#elif WIN32
#include <windows.h>
#endif
#include <algorithm>
#include <iostream>
#include "Sensor.h"
#include "PluginChain.h"
//ExampleSensor - headers ----------------------------------------------------
#include "ExampleSensor.h"
// ----------------------------------
BEGIN_PLUGIN_REGISTER(1)
PLUGIN_REGISTER(0, Ookala::ExampleSensor)
END_PLUGIN_REGISTER
// ----------------------------------
// ==================================
//
// ExampleSensor
//
// ----------------------------------
Ookala::ExampleSensor::ExampleSensor():
Sensor()
{
setName("ExampleSensor");
mDeviceOpen = false;
mNextSensorKey = 1;
mReadScreenRefresh = false;
}
// ----------------------------------
//
Ookala::ExampleSensor::ExampleSensor(const ExampleSensor &src):
Sensor(src)
{
mDeviceOpen = src.mDeviceOpen;
mNextSensorKey = src.mNextSensorKey;
mDeviceKey = src.mDeviceKey;
mReadScreenRefresh = src.mReadScreenRefresh;
}
// ----------------------------------
//
// virtual
Ookala::ExampleSensor::~ExampleSensor()
{
// If we're left with an open device, close it.
if (mDeviceOpen) {
// XXX: Close the device handle.
std::cout << " disposing of open sensor\n";
mDeviceOpen = false;
}
}
// ----------------------------
//
Ookala::ExampleSensor &
Ookala::ExampleSensor::operator=(const ExampleSensor &src)
{
if (this != &src) {
Sensor::operator=(src);
mNextSensorKey = src.mNextSensorKey;
mDeviceOpen = src.mDeviceOpen;
mDeviceKey = src.mDeviceKey;
mReadScreenRefresh = src.mReadScreenRefresh;
}
return *this;
}
// ----------------------------------
//
// virtual
std::vector<uint32_t>
Ookala::ExampleSensor::sensors()
{
std::vector<uint32_t> devices;
setErrorString("");
if (mDeviceOpen) {
devices.push_back(mDeviceKey);
}
return devices;
}
// ----------------------------------
//
// virtual
bool
Ookala::ExampleSensor::measureYxy(Yxy &value,
PluginChain *chain /* = NULL */,
uint32_t sensorId /* = 0 */)
{
DictOptions opts;
setErrorString("");
if (!getDictOptions(opts, chain)) {
return false;
}
// Update the calibration, in case someone changed
// it out from under us.
// XXX: Choose the calibration matrix, based on what's selected
// in opts.calibration
std::cout << " measureXY: selecting calibration matrix...\n";
// XXX: Choose the display type (e.g. LCD, CRT, etc) base
// on the value in opts.displayType
std::cout << " measureXY: setup LCD or CRT...\n";
// XXX: Choose the integration time based on the value in
// opts.integrationTime
std::cout << " measureXY: integration time applied...\n";
// XXX: Finally, read a measurement in cd/m&2 into the value
// parameter.
std::cout << " measureXY: reading measurement Yxy (candela)...\n";
// XXX: Return measured value
value.Y = (double) 1.0; // Simulate (dummy) values
value.x = (double) 0.312779;
value.y = (double) 0.329183;
std::cout <<
" measureXY: read (dummy) values Yxy (1.0, 0.31, 0.32) ...\n";
if (chain) {
chain->setUiYxy("Ui::measured_Yxy", value);
}
return true;
}
// ----------------------------------
//
// virtual
std::vector<uint32_t>
Ookala::ExampleSensor::actionNeeded(
PluginChain *chain /* = NULL */,
uint32_t sensorId /* = 0 */)
{
std::vector<uint32_t> actions;
DictOptions opts;
setErrorString("");
if (getDictOptions(opts, chain)) {
// XXX: See if we need to do anything based on our options.
// For example, if opts.displayType indicates CRT,
// we might want to do:
// actions.push_back(SENSOR_ACTION_MEASURE_REFRESH).
// or for LCD:
// actions.push_back(SENSOR_ACTION_DARK_READING).
// YMMV.
}
if (!mDeviceOpen) {
actions.push_back(SENSOR_ACTION_DETECT);
}
return actions;
}
// ----------------------------------
//
// virtual
bool
Ookala::ExampleSensor::actionTaken(uint32_t actionKey,
PluginChain *chain /* = NULL */,
uint32_t sensorId /* = 0 */)
{
setErrorString("");
switch (actionKey) {
// Here we need to probe for attached devices.
case SENSOR_ACTION_DETECT:
if (mDeviceOpen) {
// XXX: Close the device if it's already open
std::cout << " actionTaken: open sensor closed...\n";
mDeviceOpen = false;
}
// XXX: Open the device
std::cout << " actionTaken: detect and open sensor device...\n";
// XXX: And check that it's what we're expecting
std::cout << " actionTaken: confirm state...\n";
// Simulate open (dummy) sensor succeeded
mDeviceOpen = true;
break;
case SENSOR_ACTION_DARK_READING:
// XXX: Establish a dark reading point
std::cout << " actionTaken: conduct Dark Reading...\n";
break;
case SENSOR_ACTION_MEASURE_REFRESH:
// XXX: Measure the refresh rate of monitor (CRT)
std::cout << " actionTaken: conduct Refresh Reading (CRT)...\n";
// Simulate refresh (dummy) action succeeded
mReadScreenRefresh = true;
break;
default:
return false;
break;
}
return true;
}
// ----------------------------------
//
// Given a chain, lookup it's dict and pull out things that
// we care about:
//
// ExampleSensor::displayType [STRING] {lcd, crt}
// ExampleSensor::integrationTime [INT] Number of seconds to measure
// ExampleSensor::calibrationIdx [INT] Override the calibration
// matrix choice based on
// displayType.
// Can be 0-3.
//
// protected
bool
Ookala::ExampleSensor::getDictOptions(DictOptions &opts,
PluginChain *chain)
{
Dict *chainDict = NULL;
DictItem *item = NULL;
StringDictItem *stringItem = NULL;
IntDictItem *intItem = NULL;
DoubleDictItem *doubleItem = NULL;
std::string displayType;
// XXX: Set default values based on the appropriate types
opts.displayType = 0; // XXX:
opts.integrationTime = 1;
opts.calibration = 0; // XXX:
std::cout << " DictOptions: setup base defaults...\n";
if (!chain) {
std::cout << " DictOptions: no chain detected...\n";
return false;
}
chainDict = chain->getDict();
// Pull out the display type, and set a default calibration to match
item = chainDict->get("ExampleSensor::displayType");
if (item) {
stringItem = dynamic_cast<StringDictItem *>(item);
if (stringItem) {
displayType = stringItem->get();
std::transform(displayType.begin(), displayType.end(),
displayType.begin(),
#ifdef _WIN32
tolower);
#else
(int(*)(int))std::tolower);
#endif
if (displayType == "lcd") {
// XXX: Set opts.displayType to LCD and opts.calibration
// to something that makes sense.
opts.displayType = 0; // XXX:
opts.calibration = 0; // XXX:
std::cout << " DictOptions: setup LCD parameters...\n";
} else if (displayType == "crt") {
// XXX: Set opts.displayType to CRT and opts.calibration
// to something that makes sense.
opts.displayType = 0; // XXX:
opts.calibration = 0; // XXX:
std::cout << " DictOptions: setup CRT parameters...\n";
} else {
setErrorString( std::string("Unknown display type: ") +
displayType + std::string("."));
std::cout << " DictOptions: detected Unknown DisplayType...\n";
return false;
}
}
}
// Pull out an integration time, in seconds
item = chainDict->get("ExampleSensor::integrationTime");
if (item) {
doubleItem = dynamic_cast<DoubleDictItem *>(item);
if (doubleItem) {
opts.integrationTime = doubleItem->get();
std::cout << " DictOptions: IntegrationTime set" <<
opts.integrationTime << "\n";;
}
}
// Finally, get a calibration setting
item = chainDict->get("ExampleSensor::calibrationIdx");
if (item) {
intItem = dynamic_cast<IntDictItem *>(item);
if (intItem) {
// XXX: Check range
if ((intItem->get() < 0) || (intItem->get() > 3)) {
setErrorString(
"Invalid calibration setting for ExampleSensor::calibration.");
return false;
}
// XXX: Translate the integer that we get from intItem->get()
// to the appropriate value in opts.calibration.
// This may just need to be a cast.
opts.calibration = intItem->get();
std::cout << " DictOptions: Calibration Index set" <<
opts.calibration << "\n";;
}
}
return true;
}
| 27.977887
| 80
| 0.530517
|
SchademanK
|
ab08e3b9474e22d9d69ffee51a4f1ba6252a60de
| 3,781
|
cpp
|
C++
|
engine/camera.cpp
|
meifuku/AFGEngine
|
21e356eaf293dcaa0eea5823914bbc5c8ae7a85a
|
[
"MS-PL"
] | 8
|
2021-03-04T23:41:02.000Z
|
2022-01-06T01:07:01.000Z
|
engine/camera.cpp
|
meifuku/AFGEngine
|
21e356eaf293dcaa0eea5823914bbc5c8ae7a85a
|
[
"MS-PL"
] | null | null | null |
engine/camera.cpp
|
meifuku/AFGEngine
|
21e356eaf293dcaa0eea5823914bbc5c8ae7a85a
|
[
"MS-PL"
] | 2
|
2021-09-14T09:48:51.000Z
|
2021-12-10T08:54:57.000Z
|
#include "camera.h"
#include "window.h"
#include <glad/glad.h>
#include <glm/ext/matrix_transform.hpp>
#include <glm/vec3.hpp>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <fixed_point.h>
FixedPoint interpolate(FixedPoint x, FixedPoint min, FixedPoint max, FixedPoint length) {
x = x/length;
return (max-min)*x*x*x * (FixedPoint(3) - FixedPoint(2) * x) + min;
}
const FixedPoint stageWidth(300);
const FixedPoint stageHeight(225);
Camera::Camera(float _maxScale) :
scale(1.f),
widthBoundary(internalWidth),
heightBoundary(internalHeight),
limitRatioX(FixedPoint(6)/FixedPoint(7)),
limitRatioY(FixedPoint(2)/FixedPoint(3))
{
if(_maxScale*(internalWidth/2.f)>(float)stageWidth)
maxScale = (stageWidth*2.f)/(float)internalWidth;
else
maxScale = _maxScale;
//No support for tall stages.
}
Camera& Camera::operator=(const Camera& c)
{
center = c.center;
centerTarget = c.centerTarget;
scale = c.scale;
scaleTimer = c.scaleTimer;
shakeTime = c.shakeTime;
return *this;
}
Camera::Camera() : Camera(1.1f)
{
}
void Camera::SetShakeTime(int time)
{
if(time > shakeTime)
shakeTime = time;
}
glm::mat4 Camera::Calculate(Point2d<FixedPoint> p1, Point2d<FixedPoint> p2)
{
Point2d<FixedPoint> dif = p2 - p1;
const FixedPoint distToScroll(100,0);
//Zooms out when the distance between points is larger than the screen's h-ratio.
FixedPoint targetScale = 1.f;
FixedPoint scaleX, scaleY;
if(dif.x.abs() > FixedPoint(widthBoundary*limitRatioX))
{
scaleX = dif.x.abs()/(widthBoundary*limitRatioX);
}
if(dif.y.abs() > FixedPoint(heightBoundary*limitRatioY))
{
scaleY = FixedPoint(0.75)+dif.y.abs()/(FixedPoint(4)*heightBoundary*limitRatioY);
}
auto biggerScale = std::max(scaleX, scaleY);
if(biggerScale > targetScale)
targetScale = biggerScale;
if(targetScale > maxScale)
targetScale = maxScale;
if(targetScale < scale)
{
if(scaleTimer <= 0)
{
scale = interpolate(FixedPoint(scaleTimer+512),targetScale,scale,512);
}
--scaleTimer;
}
else
{
scale = targetScale;
scaleTimer = 20;
}
dif.x.value >>= 1;
dif.y.value >>= 1;
auto rightmost = std::max(p1.x, p2.x);
auto leftmost = std::min(p1.x, p2.x);
if(rightmost > distToScroll + centerTarget.x)
{
centerTarget.x = rightmost-distToScroll;
if(leftmost < -distToScroll + centerTarget.x)
centerTarget.x.value = p1.x.value + (dif.x.value);
}
else if(leftmost < -distToScroll + centerTarget.x)
centerTarget.x = leftmost+distToScroll;
centerTarget.y = p1.y + dif.y;
centerTarget.y -= 64;
if(centerTarget.y < 0)
centerTarget.y = 0;
center.x += (centerTarget.x - center.x)*0.35;
center.y += (centerTarget.y - center.y)*0.25;
if(GetWallPos(camera::leftWall) <= -stageWidth)
center.x = -stageWidth + widthBoundary*scale/FixedPoint(2);
else if(GetWallPos(camera::rightWall) >= stageWidth)
center.x = stageWidth - widthBoundary*scale/FixedPoint(2);
centerYShake = center.y;
if(shakeTime > 0)
{
centerYShake += 3*abs((shakeTime % 4) - 1);
--shakeTime;
}
if(centerYShake > 450-(internalHeight)*(float)scale)
{
centerYShake = 450-(internalHeight)*(float)scale;
centerYShake -= abs((shakeTime % 4) - 1); //Shake backwards
}
glm::mat4 view(1);
view = glm::translate(view, glm::vec3(internalWidth/2.f, 0.f, 0.f));
view = glm::scale(view, glm::vec3(1.f/(float)scale, 1.f/(float)scale, 1.f));
view = glm::translate(view, glm::vec3(-center.x, -centerYShake, 0.f));
return view;
}
FixedPoint Camera::GetWallPos(int which)
{
switch(which)
{
case camera::leftWall:
return center.x - widthBoundary*scale/FixedPoint(2);
case camera::rightWall:
return center.x + widthBoundary*scale/FixedPoint(2);
}
return 0;
}
centerScale Camera::GetCameraCenterScale()
{
return {center.x, centerYShake, scale};
}
| 23.93038
| 89
| 0.699815
|
meifuku
|
ab09711bbd4ba9463609fd235e39c4f3f4968994
| 3,126
|
cpp
|
C++
|
Source/OverlordProject/Materials/SkinnedDiffuseMaterial.cpp
|
TomvanWaas/OvercookedImitation
|
895b98ff23b026bafc24267c8707d68870a2ac58
|
[
"MIT"
] | null | null | null |
Source/OverlordProject/Materials/SkinnedDiffuseMaterial.cpp
|
TomvanWaas/OvercookedImitation
|
895b98ff23b026bafc24267c8707d68870a2ac58
|
[
"MIT"
] | null | null | null |
Source/OverlordProject/Materials/SkinnedDiffuseMaterial.cpp
|
TomvanWaas/OvercookedImitation
|
895b98ff23b026bafc24267c8707d68870a2ac58
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "SkinnedDiffuseMaterial.h"
#include "ContentManager.h"
#include "TextureData.h"
#include "ModelComponent.h"
#include "ModelAnimator.h"
ID3DX11EffectShaderResourceVariable* SkinnedDiffuseMaterial::m_pDiffuseSRVvariable = nullptr;
ID3DX11EffectMatrixVariable* SkinnedDiffuseMaterial::m_pBoneTransforms = nullptr;
ID3DX11EffectVectorVariable* SkinnedDiffuseMaterial::m_pColorVariable = nullptr;
ID3DX11EffectScalarVariable* SkinnedDiffuseMaterial::m_pUseTextureVariable = nullptr;
SkinnedDiffuseMaterial::SkinnedDiffuseMaterial() : Material(L"./Resources/Effects/PosNormTex3D_Skinned.fx"),
m_pDiffuseTexture(nullptr)
, m_Color({1,1,1,1})
, m_UseDiffuseTexture(false)
{}
void SkinnedDiffuseMaterial::SetDiffuseTexture(const std::wstring& assetFile)
{
m_pDiffuseTexture = ContentManager::Load<TextureData>(assetFile);
m_UseDiffuseTexture = true;
}
void SkinnedDiffuseMaterial::LoadEffectVariables()
{
if (!m_pDiffuseSRVvariable)
{
m_pDiffuseSRVvariable = GetEffect()->GetVariableByName("gDiffuseMap")->AsShaderResource();
if (!m_pDiffuseSRVvariable->IsValid())
{
Logger::LogWarning(L"SkinnedDiffuseMaterial::LoadEffectVariables() > \'gDiffuseMap\' variable not found!");
m_pDiffuseSRVvariable = nullptr;
}
}
if (!m_pColorVariable)
{
m_pColorVariable = GetEffect()->GetVariableByName("gColor")->AsVector();
if (!m_pColorVariable->IsValid())
{
Logger::LogWarning(L"SkinnedDiffuseMaterial::LoadEffectVariables() > \'gColor\' variable not found!");
m_pColorVariable = nullptr;
}
}
if (!m_pUseTextureVariable)
{
m_pUseTextureVariable = GetEffect()->GetVariableByName("gUseDiffuseMap")->AsScalar();
if (!m_pUseTextureVariable->IsValid())
{
Logger::LogWarning(L"SkinnedDiffuseMaterial::LoadEffectVariables() > \'gUseDiffuseMap\' variable not found!");
m_pUseTextureVariable = nullptr;
}
}
//Create a link to the gBones variable
if (!m_pBoneTransforms)
{
m_pBoneTransforms = GetEffect()->GetVariableByName("gBones")->AsMatrix();
if (!m_pBoneTransforms->IsValid())
{
Logger::LogWarning(L"SkinnedDiffuseMaterial::LoadEffectVariables() > \'gBones\' variable not found!");
m_pBoneTransforms = nullptr;
}
}
}
void SkinnedDiffuseMaterial::UpdateEffectVariables(const GameContext& gameContext, ModelComponent* pModelComponent)
{
UNREFERENCED_PARAMETER(gameContext);
UNREFERENCED_PARAMETER(pModelComponent);
if (m_pDiffuseTexture && m_pDiffuseSRVvariable)
{
m_pDiffuseSRVvariable->SetResource(m_pDiffuseTexture->GetShaderResourceView());
}
//Set the matrix array (BoneTransforms of the ModelAnimator)}
if (m_pBoneTransforms != nullptr && pModelComponent != nullptr && pModelComponent->HasAnimator())
{
auto ts = pModelComponent->GetAnimator()->GetBoneTransforms();
m_pBoneTransforms->SetMatrixArray((const float*)ts.data(), NULL, ts.size());
}
if (m_pColorVariable)
{
m_pColorVariable->SetFloatVector((float*)&m_Color);
}
if (m_pUseTextureVariable)
{
m_pUseTextureVariable->SetBool(m_UseDiffuseTexture);
}
}
| 31.897959
| 116
| 0.746321
|
TomvanWaas
|
ab0eccd9c949ddbf0bce9ecf7a0959643641effa
| 258
|
hpp
|
C++
|
libng/core/src/libng_core/libcxx/map.hpp
|
gapry/libng
|
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
|
[
"MIT"
] | null | null | null |
libng/core/src/libng_core/libcxx/map.hpp
|
gapry/libng
|
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
|
[
"MIT"
] | null | null | null |
libng/core/src/libng_core/libcxx/map.hpp
|
gapry/libng
|
8fbf927e5bb73f105bddbb618430d3e1bf2cf877
|
[
"MIT"
] | null | null | null |
#pragma once
#include <third_party/eastl/eastl.hpp>
namespace libng::libcxx {
template<class KEY, class VALUE>
class map {
public:
};
} // namespace libng::libcxx
namespace libng {
template<class KEY, class VALUE>
using Map = eastl::map<KEY, VALUE>;
}
| 13.578947
| 38
| 0.717054
|
gapry
|
ab1c39c3d5de4d3afd619d5508b34ddcc950b773
| 952
|
cpp
|
C++
|
item.cpp
|
RichardVN/train-escape-game
|
a177276b2993288f85e8b1079c1ca2dc8babbd91
|
[
"MIT"
] | null | null | null |
item.cpp
|
RichardVN/train-escape-game
|
a177276b2993288f85e8b1079c1ca2dc8babbd91
|
[
"MIT"
] | null | null | null |
item.cpp
|
RichardVN/train-escape-game
|
a177276b2993288f85e8b1079c1ca2dc8babbd91
|
[
"MIT"
] | null | null | null |
/*****************************************************************
** Program name: item.cpp
** Author: Richard Nguyen
** Date: 12/10/19
** Description: Contains member function definitions for the class
item.
******************************************************************/
#include "item.hpp"
// **********************
// Default constructor *
// **********************
item::item()
{
}
// **********************
// Setter Functions *
// **********************
void item::setQuantity(int quantity)
{
this -> quantity = quantity;
}
void item::setName(string name)
{
this -> name = name;
}
void item::setDescription(string description)
{
this -> description = description;
}
// **********************
// Getter functions *
// **********************
string item::getName()
{
return this -> name;
}
string item::getDescription()
{
return this -> description;
}
int item::getQuantity()
{
return this -> quantity;
}
| 17
| 67
| 0.462185
|
RichardVN
|
ab1cb62e1a59da716cc933d10f92e439dd2db2b4
| 17,422
|
cc
|
C++
|
arcane/src/arcane/impl/ParallelExchanger.cc
|
cedricga91/framework
|
143eeccb5bf375df4a3f11b888681f84f60380c6
|
[
"Apache-2.0"
] | 16
|
2021-09-20T12:37:01.000Z
|
2022-03-18T09:19:14.000Z
|
arcane/src/arcane/impl/ParallelExchanger.cc
|
cedricga91/framework
|
143eeccb5bf375df4a3f11b888681f84f60380c6
|
[
"Apache-2.0"
] | 66
|
2021-09-17T13:49:39.000Z
|
2022-03-30T16:24:07.000Z
|
arcane/src/arcane/impl/ParallelExchanger.cc
|
cedricga91/framework
|
143eeccb5bf375df4a3f11b888681f84f60380c6
|
[
"Apache-2.0"
] | 11
|
2021-09-27T16:48:55.000Z
|
2022-03-23T19:06:56.000Z
|
// -*- tab-width: 2; indent-tabs-mode: nil; coding: utf-8-with-signature -*-
//-----------------------------------------------------------------------------
// Copyright 2000-2022 CEA (www.cea.fr) IFPEN (www.ifpenergiesnouvelles.com)
// See the top-level COPYRIGHT file for details.
// SPDX-License-Identifier: Apache-2.0
//-----------------------------------------------------------------------------
/*---------------------------------------------------------------------------*/
/* ParallelExchanger.cc (C) 2000-2022 */
/* */
/* Echange d'informations entre processeurs. */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
#include "arcane/impl/ParallelExchanger.h"
#include "arcane/utils/NotSupportedException.h"
#include "arcane/utils/FatalErrorException.h"
#include "arcane/utils/PlatformUtils.h"
#include "arcane/MathUtils.h"
#include "arcane/IParallelMng.h"
#include "arcane/SerializeBuffer.h"
#include "arcane/SerializeMessage.h"
#include "arcane/Timer.h"
#include "arcane/ISerializeMessageList.h"
#include <algorithm>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace Arcane
{
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ParallelExchanger::
ParallelExchanger(IParallelMng* pm)
: ParallelExchanger(makeRef(pm))
{
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ParallelExchanger::
ParallelExchanger(Ref<IParallelMng> pm)
: TraceAccessor(pm->traceMng())
, m_parallel_mng(pm)
, m_timer(pm->timerMng(),"ParallelExchangerTimer",Timer::TimerReal)
{
String use_collective_str = platform::getEnvironmentVariable("ARCANE_PARALLEL_EXCHANGER_USE_COLLECTIVE");
if (use_collective_str=="1" || use_collective_str=="TRUE")
m_exchange_mode = EM_Collective;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ParallelExchanger::
~ParallelExchanger()
{
for( auto* buf : m_comms_buf )
delete buf;
m_comms_buf.clear();
delete m_own_send_message;
delete m_own_recv_message;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
IParallelMng* ParallelExchanger::
parallelMng() const
{
return m_parallel_mng.get();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
bool ParallelExchanger::
initializeCommunicationsMessages()
{
Int32 nb_send_rank = m_send_ranks.size();
UniqueArray<Int32> gather_input_send_ranks(nb_send_rank+1);
gather_input_send_ranks[0] = nb_send_rank;
std::copy(std::begin(m_send_ranks),std::end(m_send_ranks),
std::begin(gather_input_send_ranks)+1);
IntegerUniqueArray gather_output_send_ranks;
Integer nb_rank = m_parallel_mng->commSize();
m_parallel_mng->allGatherVariable(gather_input_send_ranks,
gather_output_send_ranks);
m_recv_ranks.clear();
Integer total_comm_rank = 0;
Int32 my_rank = m_parallel_mng->commRank();
{
Integer gather_index = 0;
for( Integer i=0; i<nb_rank; ++i ){
Integer nb_comm = gather_output_send_ranks[gather_index];
total_comm_rank += nb_comm;
++gather_index;
for( Integer z=0; z<nb_comm; ++z ){
Integer current_rank = gather_output_send_ranks[gather_index+z];
if (current_rank==my_rank)
m_recv_ranks.add(i);
}
gather_index += nb_comm;
}
}
if (total_comm_rank==0)
return true;
_initializeCommunicationsMessages();
return false;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
initializeCommunicationsMessages(Int32ConstArrayView recv_ranks)
{
m_recv_ranks.resize(recv_ranks.size());
m_recv_ranks.copy(recv_ranks);
_initializeCommunicationsMessages();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
_initializeCommunicationsMessages()
{
if (m_verbosity_level>=1){
info() << "ParallelExchanger " << m_name << " : nb_send=" << m_send_ranks.size()
<< " nb_recv=" << m_recv_ranks.size();
if (m_verbosity_level>=2){
info() << "ParallelExchanger " << m_name << " : send=" << m_send_ranks;
info() << "ParallelExchanger " << m_name << " : recv=" << m_recv_ranks;
}
}
Int32 my_rank = m_parallel_mng->commRank();
for( Int32 msg_rank : m_send_ranks ){
auto* comm = new SerializeMessage(my_rank,msg_rank,ISerializeMessage::MT_Send);
// Il ne sert à rien de s'envoyer des messages.
// (En plus ca fait planter certaines versions de MPI...)
if (my_rank==msg_rank)
m_own_send_message = comm;
else
m_comms_buf.add(comm);
m_send_serialize_infos.add(comm);
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
processExchange()
{
ParallelExchangerOptions options;
options.setExchangeMode(static_cast<ParallelExchangerOptions::eExchangeMode>(m_exchange_mode));
processExchange(options);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
processExchange(const ParallelExchangerOptions& options)
{
if (m_verbosity_level>=1)
info() << "ParallelExchanger " << m_name << ": ProcessExchange (begin)"
<< " date=" << platform::getCurrentDateTime();
{
Timer::Sentry sentry(&m_timer);
_processExchange(options);
}
if (m_verbosity_level>=1)
info() << "ParallelExchanger " << m_name << ": ProcessExchange (end)"
<< " total_time=" << m_timer.lastActivationTime();
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
_processExchange(const ParallelExchangerOptions& options)
{
if (m_verbosity_level>=1){
Int64 total_size = 0;
for( SerializeMessage* comm : m_send_serialize_infos ){
Int64 message_size = comm->trueSerializer()->totalSize();
total_size += message_size;
if (m_verbosity_level>=2)
info() << "Send rank=" << comm->destination() << " size=" << message_size;
}
info() << "ParallelExchanger " << m_name << ": ProcessExchange"
<< " total_size=" << total_size << " nb_message=" << m_comms_buf.size();
}
bool use_all_to_all = false;
if (options.exchangeMode())
use_all_to_all = true;
// TODO: traiter le cas EM_Auto
// Génère les infos pour chaque processeur de qui on va recevoir
// des entités
Int32 my_rank = m_parallel_mng->commRank();
for( Int32 msg_rank : m_recv_ranks ){
auto* comm = new SerializeMessage(my_rank,msg_rank,ISerializeMessage::MT_Recv);
// Il ne sert à rien de s'envoyer des messages.
// (En plus ca fait planter certaines versions de MPI...)
if (my_rank==msg_rank)
m_own_recv_message = comm;
else
m_comms_buf.add(comm);
m_recv_serialize_infos.add(comm);
}
if (use_all_to_all)
_processExchangeCollective();
else{
Int32 max_pending = options.maxPendingMessage();
if (max_pending>0)
_processExchangeWithControl(max_pending);
else
m_parallel_mng->processMessages(m_comms_buf);
if (m_own_send_message && m_own_recv_message){
m_own_recv_message->serializer()->copy(m_own_send_message->serializer());
}
}
// Récupère les infos de chaque receveur
for( SerializeMessage* comm : m_recv_serialize_infos )
comm->serializer()->setMode(ISerializer::ModeGet);
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
_processExchangeCollective()
{
info() << "Using collective exchange in ParallelExchanger";
IParallelMng* pm = m_parallel_mng.get();
Int32 nb_rank = pm->commSize();
Int32UniqueArray send_counts(nb_rank,0);
Int32UniqueArray send_indexes(nb_rank,0);
Int32UniqueArray recv_counts(nb_rank,0);
Int32UniqueArray recv_indexes(nb_rank,0);
// D'abord, détermine pour chaque proc le nombre d'octets à envoyer
for( SerializeMessage* comm : m_send_serialize_infos ){
auto* sbuf = comm->trueSerializer();
Span<Byte> val_buf = sbuf->globalBuffer();
Int32 rank = comm->destRank();
send_counts[rank] = arcaneCheckArraySize(val_buf.size());
}
// Fait un AllToAll pour connaitre combien de valeurs je dois recevoir des autres.
{
Timer::SimplePrinter sp(traceMng(),"ParallelExchanger: sending sizes with AllToAll");
pm->allToAll(send_counts,recv_counts,1);
}
// Détermine le nombre total d'infos à envoyer et recevoir
// TODO: En cas débordement, il faudrait le faire en plusieurs morceaux
// ou alors revenir aux échanges point à point.
Int32 total_send = 0;
Int32 total_recv = 0;
Int64 int64_total_send = 0;
Int64 int64_total_recv = 0;
for( Integer i=0; i<nb_rank; ++i ){
send_indexes[i] = total_send;
recv_indexes[i] = total_recv;
total_send += send_counts[i];
total_recv += recv_counts[i];
int64_total_send += send_counts[i];
int64_total_recv += recv_counts[i];
}
// Vérifie qu'on ne déborde pas.
if (int64_total_send!=total_send)
ARCANE_FATAL("Message to send is too big size={0} max=2^31",int64_total_send);
if (int64_total_recv!=total_recv)
ARCANE_FATAL("Message to receive is too big size={0} max=2^31",int64_total_recv);
ByteUniqueArray send_buf(total_send);
ByteUniqueArray recv_buf(total_recv);
bool is_verbose = (m_verbosity_level>=1);
if (m_verbosity_level>=2){
for( Integer i=0; i<nb_rank; ++i ){
if (send_counts[i]!=0 || recv_counts[i]!=0)
info() << "INFOS: rank=" << i << " send_count=" << send_counts[i]
<< " send_idx=" << send_indexes[i]
<< " recv_count=" << recv_counts[i]
<< " recv_idx=" << recv_indexes[i];
}
}
// Copie dans send_buf les infos des sérialisers.
for( SerializeMessage* comm : m_send_serialize_infos ){
auto* sbuf = comm->trueSerializer();
Span<Byte> val_buf = sbuf->globalBuffer();
Int32 rank = comm->destRank();
if (is_verbose)
info() << "SEND rank=" << rank << " size=" << send_counts[rank]
<< " idx=" << send_indexes[rank]
<< " buf_size=" << val_buf.size();
ByteArrayView dest_buf(send_counts[rank],&send_buf[send_indexes[rank]]);
dest_buf.copy(val_buf);
}
if (is_verbose)
info() << "AllToAllVariable total_send=" << total_send
<< " total_recv=" << total_recv;
{
Timer::SimplePrinter sp(traceMng(),"ParallelExchanger: sending values with AllToAll");
pm->allToAllVariable(send_buf,send_counts,send_indexes,recv_buf,recv_counts,recv_indexes);
}
// Recopie les données reçues dans le message correspondant.
for( SerializeMessage* comm : m_recv_serialize_infos ){
auto* sbuf = comm->trueSerializer();
Int32 rank = comm->destRank();
if (is_verbose)
info() << "RECV rank=" << rank << " size=" << recv_counts[rank]
<< " idx=" << recv_indexes[rank];
ByteArrayView orig_buf(recv_counts[rank],&recv_buf[recv_indexes[rank]]);
sbuf->preallocate(orig_buf.size());
sbuf->globalBuffer().copy(orig_buf);
sbuf->setFromSizes();
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ISerializeMessage* ParallelExchanger::
messageToSend(Integer i)
{
return m_send_serialize_infos[i];
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
ISerializeMessage* ParallelExchanger::
messageToReceive(Integer i)
{
return m_recv_serialize_infos[i];
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
setVerbosityLevel(Int32 v)
{
if (v<0)
v = 0;
m_verbosity_level = v;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
void ParallelExchanger::
setName(const String& name)
{
m_name = name;
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
namespace
{
class SortFunctor
{
public:
/*!
* \brief Operateur de tri des messages.
*
* Le tri se fait comme suit:
* - d'abord prend 1 rang sur nb_phase pour éviter que tous les messages
* aillent sur les mêmes noeuds (car on suppose que les rangs consécutifs sont
* sur les mêmes noeuds)
* - ensuite tri sur le rang de destination
* - enfin poste les réceptions avant les envois.
*/
bool operator()(const ISerializeMessage* a,const ISerializeMessage* b)
{
const int nb_phase = 4;
int phase1 = a->destination().value() % nb_phase;
int phase2 = b->destination().value() % nb_phase;
if (phase1 != phase2)
return phase1<phase2;
if (a->destination() != b->destination())
return a->destination() < b->destination();
if (a->isSend() != b->isSend())
return (a->isSend() ? false : true);
return a->source() < b->source();
}
};
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/*!
* \brief Echange avec contrôle du nombre maximum de messages en vol.
*/
void ParallelExchanger::
_processExchangeWithControl(Int32 max_pending_message)
{
// L'ensemble des messages sont dans 'm_comms_buf'.
// On les recopie dans 'sorted_messages' pour qu'ils soient triés.
auto message_list {m_parallel_mng->createSerializeMessageListRef()};
UniqueArray<ISerializeMessage*> sorted_messages(m_comms_buf);
std::sort(sorted_messages.begin(),sorted_messages.end(),SortFunctor{});
Integer position = 0;
// Il faut au moins ajouter un minimum de messages pour ne pas avoir de blocage.
// A priori le minimum est 2 pour qu'il y est au moins un receive et un send
// mais il est préférable de mettre plus pour ne pas trop dégrader les performances.
max_pending_message = math::max(4,max_pending_message);
Integer nb_message = sorted_messages.size();
Integer nb_to_add = max_pending_message;
Int32 verbosity_level = m_verbosity_level;
if (verbosity_level>=1)
info() << "ParallelExchanger " << m_name << " : process exchange WITH CONTROL"
<< " nb_message=" << nb_message << " max_pending=" << max_pending_message;
while(position<nb_message){
for( Integer i=0; i<nb_to_add; ++i ){
if (position>=nb_message)
break;
ISerializeMessage* message = sorted_messages[position];
if (verbosity_level>=2)
info() << "Add Message p=" << position << " is_send?=" << message->isSend() << " source=" << message->source()
<< " dest=" << message->destination();
message_list->addMessage(message);
++position;
}
// S'il ne reste plus de messages, alors on fait un WaitAll pour attendre*
// que les messages restants soient tous terminés.
if (position>=nb_message){
message_list->waitMessages(Parallel::WaitAll);
break;
}
// Le nombre de messages terminés indique combien de message il faudra
// ajouter à la liste pour la prochaine itération.
Integer nb_done = message_list->waitMessages(Parallel::WaitSome);
if (verbosity_level>=2)
info() << "Wait nb_done=" << nb_done;
if (nb_done==(-1))
nb_done = max_pending_message;
nb_to_add = nb_done;
}
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
Ref<IParallelExchanger>
createParallelExchangerImpl(Ref<IParallelMng> pm)
{
return makeRef<IParallelExchanger>(new ParallelExchanger(pm));
}
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
} // End namespace Arcane
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
| 34.844
| 118
| 0.534554
|
cedricga91
|
ab1d46e1e554441470b0df611f84f6d6ccc9d2b0
| 4,548
|
cpp
|
C++
|
src/core/states/euclidean.cpp
|
jcarpent/crocoddyl
|
155999999f1fbd0c5760875584c540e2bc13645b
|
[
"BSD-3-Clause"
] | 1
|
2019-12-21T12:11:15.000Z
|
2019-12-21T12:11:15.000Z
|
src/core/states/euclidean.cpp
|
boyali/crocoddyl
|
155999999f1fbd0c5760875584c540e2bc13645b
|
[
"BSD-3-Clause"
] | null | null | null |
src/core/states/euclidean.cpp
|
boyali/crocoddyl
|
155999999f1fbd0c5760875584c540e2bc13645b
|
[
"BSD-3-Clause"
] | null | null | null |
///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (C) 2018-2019, LAAS-CNRS
// Copyright note valid unless otherwise stated in individual files.
// All rights reserved.
///////////////////////////////////////////////////////////////////////////////
#include "crocoddyl/core/states/euclidean.hpp"
namespace crocoddyl {
StateVector::StateVector(const std::size_t& nx) : StateAbstract(nx, nx) {}
StateVector::~StateVector() {}
Eigen::VectorXd StateVector::zero() const { return Eigen::VectorXd::Zero(nx_); }
Eigen::VectorXd StateVector::rand() const { return Eigen::VectorXd::Random(nx_); }
void StateVector::diff(const Eigen::Ref<const Eigen::VectorXd>& x0, const Eigen::Ref<const Eigen::VectorXd>& x1,
Eigen::Ref<Eigen::VectorXd> dxout) const {
if (static_cast<std::size_t>(x0.size()) != nx_) {
throw std::invalid_argument("x0 has wrong dimension (it should be " + std::to_string(nx_) + ")");
}
if (static_cast<std::size_t>(x1.size()) != nx_) {
throw std::invalid_argument("x1 has wrong dimension (it should be " + std::to_string(nx_) + ")");
}
if (static_cast<std::size_t>(dxout.size()) != ndx_) {
throw std::invalid_argument("dxout has wrong dimension (it should be " + std::to_string(ndx_) + ")");
}
dxout = x1 - x0;
}
void StateVector::integrate(const Eigen::Ref<const Eigen::VectorXd>& x, const Eigen::Ref<const Eigen::VectorXd>& dx,
Eigen::Ref<Eigen::VectorXd> xout) const {
if (static_cast<std::size_t>(x.size()) != nx_) {
throw std::invalid_argument("x has wrong dimension (it should be " + std::to_string(nx_) + ")");
}
if (static_cast<std::size_t>(dx.size()) != ndx_) {
throw std::invalid_argument("dx has wrong dimension (it should be " + std::to_string(ndx_) + ")");
}
if (static_cast<std::size_t>(xout.size()) != nx_) {
throw std::invalid_argument("xout has wrong dimension (it should be " + std::to_string(nx_) + ")");
}
xout = x + dx;
}
void StateVector::Jdiff(const Eigen::Ref<const Eigen::VectorXd>&, const Eigen::Ref<const Eigen::VectorXd>&,
Eigen::Ref<Eigen::MatrixXd> Jfirst, Eigen::Ref<Eigen::MatrixXd> Jsecond,
Jcomponent firstsecond) const {
assert(is_a_Jcomponent(firstsecond) && ("firstsecond must be one of the Jcomponent {both, first, second}"));
if (firstsecond == first || firstsecond == both) {
if (static_cast<std::size_t>(Jfirst.rows()) != ndx_ || static_cast<std::size_t>(Jfirst.cols()) != ndx_) {
throw std::invalid_argument("Jfirst has wrong dimension (it should be " + std::to_string(ndx_) + "," +
std::to_string(ndx_) + ")");
}
Jfirst.setZero();
Jfirst.diagonal() = Eigen::VectorXd::Constant(ndx_, -1.);
}
if (firstsecond == second || firstsecond == both) {
if (static_cast<std::size_t>(Jsecond.rows()) != ndx_ || static_cast<std::size_t>(Jsecond.cols()) != ndx_) {
throw std::invalid_argument("Jsecond has wrong dimension (it should be " + std::to_string(ndx_) + "," +
std::to_string(ndx_) + ")");
}
Jsecond.setZero();
Jsecond.diagonal() = Eigen::VectorXd::Constant(ndx_, 1.);
}
}
void StateVector::Jintegrate(const Eigen::Ref<const Eigen::VectorXd>&, const Eigen::Ref<const Eigen::VectorXd>&,
Eigen::Ref<Eigen::MatrixXd> Jfirst, Eigen::Ref<Eigen::MatrixXd> Jsecond,
Jcomponent firstsecond) const {
assert(is_a_Jcomponent(firstsecond) && ("firstsecond must be one of the Jcomponent {both, first, second}"));
if (firstsecond == first || firstsecond == both) {
if (static_cast<std::size_t>(Jfirst.rows()) != ndx_ || static_cast<std::size_t>(Jfirst.cols()) != ndx_) {
throw std::invalid_argument("Jfirst has wrong dimension (it should be " + std::to_string(ndx_) + "," +
std::to_string(ndx_) + ")");
}
Jfirst.setZero();
Jfirst.diagonal() = Eigen::VectorXd::Constant(ndx_, 1.);
}
if (firstsecond == second || firstsecond == both) {
if (static_cast<std::size_t>(Jsecond.rows()) != ndx_ || static_cast<std::size_t>(Jsecond.cols()) != ndx_) {
throw std::invalid_argument("Jsecond has wrong dimension (it should be " + std::to_string(ndx_) + "," +
std::to_string(ndx_) + ")");
}
Jsecond.setZero();
Jsecond.diagonal() = Eigen::VectorXd::Constant(ndx_, 1.);
}
}
} // namespace crocoddyl
| 48.382979
| 116
| 0.600484
|
jcarpent
|
ab1d6e29f2ebf95f883847c77c2eb8515c8a5c10
| 3,108
|
cpp
|
C++
|
test/zisa/unit_test/reconstruction/weno_ao.cpp
|
1uc/ZisaFVM
|
75fcedb3bece66499e011228a39d8a364b50fd74
|
[
"MIT"
] | null | null | null |
test/zisa/unit_test/reconstruction/weno_ao.cpp
|
1uc/ZisaFVM
|
75fcedb3bece66499e011228a39d8a364b50fd74
|
[
"MIT"
] | null | null | null |
test/zisa/unit_test/reconstruction/weno_ao.cpp
|
1uc/ZisaFVM
|
75fcedb3bece66499e011228a39d8a364b50fd74
|
[
"MIT"
] | 1
|
2021-08-24T11:52:51.000Z
|
2021-08-24T11:52:51.000Z
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#include <numeric>
#include <zisa/grid/grid.hpp>
#include <zisa/reconstruction/weno_ao.hpp>
#include <zisa/testing/testing_framework.hpp>
#include <zisa/unit_test/grid/test_grid_factory.hpp>
#include <zisa/unit_test/reconstruction/hybrid_weno.hpp>
TEST_CASE("WENO_AO API", "[weno_ao][math]") {
SECTION("compatibility with std::vector") {
SECTION("push_back") {
auto grid = zisa::load_grid(zisa::TestGridFactory::small());
auto params
= zisa::HybridWENOParams({{{1}, {"c"}, {2.0}}, {1.0}, 1e-10, 4.0});
auto rc = std::vector<zisa::WENO_AO>();
for (auto i : cell_indices(*grid)) {
rc.emplace_back(grid, i, params);
}
REQUIRE(rc.size() == grid->n_cells);
for (decltype(rc.size()) i = 0; i < rc.size(); ++i) {
const auto &approx = rc[i];
auto exact = zisa::WENO_AO(grid, i, params);
REQUIRE(approx == exact);
}
}
}
}
TEST_CASE("WENO_AO; reconstruct smooth", "[weno_ao][math]") {
auto grid_names = std::vector<std::string>{
zisa::TestGridFactory::unit_square_with_halo(1),
zisa::TestGridFactory::unit_square_with_halo(2)};
double eps = 1e-10;
double s = 4.0;
using interval_t = std::tuple<double, double>;
auto cases
= std::vector<std::tuple<interval_t, bool, zisa::HybridWENOParams>>{
{{0.8, 1.15}, true, {{{1}, {"c"}, {2.0}}, {1.0}, eps, s}},
{{0.8, 1.15}, true, {{{1}, {"b"}, {2.0}}, {1.0}, eps, s}},
{{1.8, 2.2}, false, {{{2}, {"c"}, {2.0}}, {1.0}, eps, s}},
{{1.8, 2.2}, false, {{{2}, {"b"}, {2.0}}, {1.0}, eps, s}},
{{2.8, 3.25}, false, {{{3}, {"c"}, {2.0}}, {1.0}, eps, s}},
{{2.8, 3.25}, false, {{{3}, {"b"}, {2.0}}, {1.0}, eps, s}},
{{3.8, 4.4}, false, {{{4}, {"c"}, {2.0}}, {1.0}, eps, s}}};
cases.push_back({{2.9, 3.3},
true,
{{{3, 2, 2, 2}, {"c", "b", "b", "b"}, {3.0, 1.5, 1.5, 1.5}},
{100.0, 1.0, 1.0, 1.0},
eps,
s}});
// The reason for the second order convergence is the linear weights. They
// allow too much pollution from the second order stencils.
cases.push_back({{2.0, 3.8},
false, /* empirically is not non-oscillatory */
{{{4, 2, 2, 2}, {"c", "b", "b", "b"}, {2.0, 1.5, 1.5, 1.5}},
{10.0, 1.0, 1.0, 1.0},
eps,
s}});
// Which can be remedied by increasing the central weight.
cases.push_back({{3.8, 4.4},
true,
{{{4, 2, 2, 2}, {"c", "b", "b", "b"}, {2.0, 1.5, 1.5, 1.5}},
{1000.0, 1.0, 1.0, 1.0},
eps,
s}});
for (auto &[expected_rate, is_stable, params] : cases) {
zisa::test_hybrid_weno_convergence<zisa::WENO_AO>(
grid_names, expected_rate, params, 2);
if (is_stable) {
zisa::test_hybrid_weno_stability<zisa::WENO_AO>(grid_names, params, 2);
}
}
}
| 34.533333
| 79
| 0.500644
|
1uc
|
ab1eadd0371c04f108dbb19000c1643ee01cd840
| 1,361
|
cpp
|
C++
|
Source/10.0.18362.0/ucrt/misc/terminate.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 2
|
2021-01-27T10:19:30.000Z
|
2021-02-09T06:24:30.000Z
|
Source/10.0.18362.0/ucrt/misc/terminate.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | null | null | null |
Source/10.0.18362.0/ucrt/misc/terminate.cpp
|
825126369/UCRT
|
8853304fdc2a5c216658d08b6dbbe716aa2a7b1f
|
[
"MIT"
] | 1
|
2021-01-27T10:19:36.000Z
|
2021-01-27T10:19:36.000Z
|
//
// terminate.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// The terminate handler
//
#include <corecrt_internal.h>
#include <corecrt_terminate.h>
static terminate_handler __cdecl get_terminate_or_default(
__acrt_ptd const* const ptd
) throw()
{
return ptd->_terminate ? ptd->_terminate : &abort;
}
extern "C" terminate_handler __cdecl _get_terminate()
{
return get_terminate_or_default(__acrt_getptd());
}
extern "C" terminate_handler __cdecl set_terminate(
terminate_handler const new_handler
)
{
__acrt_ptd* const ptd = __acrt_getptd();
terminate_handler const old_handler = get_terminate_or_default(ptd);
ptd->_terminate = new_handler;
return old_handler;
}
extern "C" void __cdecl terminate()
{
terminate_handler const handler = __acrt_getptd()->_terminate;
if (handler)
{
// Note: We cannot allow any exceptions to propagate from a user-
// registered terminate handler, so if any structured exception escapes
// the user handler we abort.
__try
{
handler();
}
__except(EXCEPTION_EXECUTE_HANDLER)
{
; // Deliberately do nothing
}
}
// If the terminate handler returned, faulted, or otherwise failed to end
// execution, we will do it:
abort();
}
| 22.683333
| 79
| 0.667891
|
825126369
|
ab21d08280b6968b4027ceb8afaa35b34d30d51d
| 1,596
|
cpp
|
C++
|
QtBiVis/ccell.cpp
|
Archi0/QtBicVis
|
c6cd7f456fcf0ac9d2222ef60a2b5621089cb065
|
[
"MIT"
] | 1
|
2019-10-05T15:17:06.000Z
|
2019-10-05T15:17:06.000Z
|
QtBiVis/ccell.cpp
|
Archi0/QtBicVis
|
c6cd7f456fcf0ac9d2222ef60a2b5621089cb065
|
[
"MIT"
] | 1
|
2016-10-18T21:17:22.000Z
|
2016-10-18T21:17:22.000Z
|
QtBiVis/ccell.cpp
|
Archi0/QtBiVis
|
c6cd7f456fcf0ac9d2222ef60a2b5621089cb065
|
[
"MIT"
] | null | null | null |
#include "ccell.h"
CCell::CCell()
{
sValue = "";
sNumbers = "";
bState =false;
// m_pRect = new QRectF(0,0,8,8);
// setFlags(ItemIsSelectable);
}
QString CCell::getSValue() const
{
return sValue;
}
void CCell::setSValue(const QString &value)
{
sValue = value;
}
void CCell::setState(bool s)
{
bState = s;
}
void CCell::select()
{
QPixmap* pix;
if(!bState)
{
pix = new QPixmap(10,10);
pix->fill(Qt::red);
bState = true;
this->setPixmap(*pix);
}
}
void CCell::unselect()
{
QPixmap* pix;
if(bState)
{
pix = new QPixmap(10,10);
pix->fill(m_color);
bState = false;
this->setPixmap(*pix);
}
}
void CCell::mousePressEvent(QGraphicsSceneMouseEvent *e)
{
emit selected(this);
}
QString CCell::getSNumbers() const
{
return sNumbers;
}
bool CCell::getState() const
{
return bState;
}
void CCell::setSNumbers(const QString &value)
{
sNumbers = value;
}
int CCell::getNIndex() const
{
return nIndex;
}
void CCell::setNIndex(int value)
{
nIndex = value;
}
QColor CCell::getColor() const
{
return m_color;
}
void CCell::setColor(const QColor &color)
{
m_color = color;
}
/*
void CCell::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPen pen(cLineColor);
if (option->state & QStyle::State_Selected) {
pen.setStyle(Qt::DotLine);
pen.setWidth(2);
emit selected();
}
painter->setPen(pen);
painter->setBrush(cBgColor);
painter->drawRect(*m_pRect);
}*/
| 14.642202
| 93
| 0.602757
|
Archi0
|
ab2eb0045b69e1139d620b90e58fa6fb3e80a166
| 431
|
cpp
|
C++
|
05-loops/5.22-drawing-a-right-triangle/trang-solution.cpp
|
trangnart/cis22a
|
498a7b37d12a13efa7749849dc95d9892d1786be
|
[
"MIT"
] | 2
|
2020-09-04T22:06:06.000Z
|
2020-09-09T04:00:25.000Z
|
05-loops/5.22-drawing-a-right-triangle/trang-solution.cpp
|
trangnart/cis22a
|
498a7b37d12a13efa7749849dc95d9892d1786be
|
[
"MIT"
] | 14
|
2020-08-24T01:44:36.000Z
|
2021-01-01T08:44:17.000Z
|
05-loops/5.22-drawing-a-right-triangle/trang-solution.cpp
|
trangnart/cis22a
|
498a7b37d12a13efa7749849dc95d9892d1786be
|
[
"MIT"
] | 1
|
2020-09-04T22:13:13.000Z
|
2020-09-04T22:13:13.000Z
|
#include <iostream>
using namespace std;
int main() {
char triangleChar;
int triangleHeight;
cout << "Enter a character:" << endl;
cin >> triangleChar;
cout << "Enter triangle height:" << endl;
cin >> triangleHeight;
cout << endl;
for (int i = 0; i <= triangleHeight; ++i) {
for (int j = 0; j < i; ++j) {
cout << triangleChar << " ";
}
cout << endl;
}
return 0;
}
| 18.73913
| 46
| 0.529002
|
trangnart
|
ab3bb6b00c3541cad8a469b3d29d17898e40ae9f
| 800
|
cpp
|
C++
|
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Penalty_TSPTW.cpp
|
BaiChunhui-9803/bch_sc2_OFEC
|
d50211b27df5a51a953a2475b6c292d00cbfeff6
|
[
"MIT"
] | null | null | null |
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Penalty_TSPTW.cpp
|
BaiChunhui-9803/bch_sc2_OFEC
|
d50211b27df5a51a953a2475b6c292d00cbfeff6
|
[
"MIT"
] | null | null | null |
project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/Penalty_TSPTW.cpp
|
BaiChunhui-9803/bch_sc2_OFEC
|
d50211b27df5a51a953a2475b6c292d00cbfeff6
|
[
"MIT"
] | null | null | null |
#include "./INCLUDE/LKH.h"
#include "./INCLUDE/Segment.h"
namespace LKH {
GainType LKHAlg::Penalty_TSPTW()
{
Node *N = Depot, *NextN;
GainType Sum = 0, P = 0;
int Forward = SUCC(N)->Id != N->Id + DimensionSaved;
do {
if (N->Id <= DimensionSaved) {
if (Sum < N->Earliest)
Sum = N->Earliest;
else if (Sum > N->Latest &&
(P += Sum - N->Latest) > CurrentPenalty)
return CurrentPenalty + 1;
NextN = Forward ? SUCC(N) : PREDD(N);
}
NextN = Forward ? SUCC(N) : PREDD(N);
Sum += ((this->*C)(N, NextN) - N->Pi - NextN->Pi) / Precision;
} while ((N = NextN) != Depot);
if (Sum > Depot->Latest &&
((P += Sum - Depot->Latest) > CurrentPenalty ||
(P == CurrentPenalty && CurrentGain <= 0)))
return CurrentPenalty + (CurrentGain > 0);
return P;
}
}
| 28.571429
| 65
| 0.57125
|
BaiChunhui-9803
|
ab3f6a9aa9c131e7936a28e0735e9bd970780118
| 7,538
|
cpp
|
C++
|
dynamic/wrappers/cell_based/AbstractCellBasedSimulation3_3.cppwg.cpp
|
jmsgrogan/PyChaste
|
48a9863d2c941c71e47ecb72e917b477ba5c1413
|
[
"FTL"
] | 6
|
2017-02-04T16:10:53.000Z
|
2021-07-01T08:03:16.000Z
|
dynamic/wrappers/cell_based/AbstractCellBasedSimulation3_3.cppwg.cpp
|
jmsgrogan/PyChaste
|
48a9863d2c941c71e47ecb72e917b477ba5c1413
|
[
"FTL"
] | 6
|
2017-06-22T08:50:41.000Z
|
2019-12-15T20:17:29.000Z
|
dynamic/wrappers/cell_based/AbstractCellBasedSimulation3_3.cppwg.cpp
|
jmsgrogan/PyChaste
|
48a9863d2c941c71e47ecb72e917b477ba5c1413
|
[
"FTL"
] | 3
|
2017-05-15T21:33:58.000Z
|
2019-10-27T21:43:07.000Z
|
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <set>
#include <vector>
#include <string>
#include <map>
#include "SmartPointers.hpp"
#include "UblasIncludes.hpp"
#include "AbstractCellBasedSimulation.hpp"
#include "AbstractCellBasedSimulation3_3.cppwg.hpp"
namespace py = pybind11;
typedef AbstractCellBasedSimulation<3,3 > AbstractCellBasedSimulation3_3;
PYBIND11_DECLARE_HOLDER_TYPE(T, boost::shared_ptr<T>);
typedef unsigned int unsignedint;
class AbstractCellBasedSimulation3_3_Overloads : public AbstractCellBasedSimulation3_3{
public:
using AbstractCellBasedSimulation3_3::AbstractCellBasedSimulation;
void OutputSimulationParameters(::out_stream & rParamsFile) override {
PYBIND11_OVERLOAD_PURE(
void,
AbstractCellBasedSimulation3_3,
OutputSimulationParameters,
rParamsFile);
}
void WriteVisualizerSetupFile() override {
PYBIND11_OVERLOAD(
void,
AbstractCellBasedSimulation3_3,
WriteVisualizerSetupFile,
);
}
unsigned int DoCellBirth() override {
PYBIND11_OVERLOAD(
unsignedint,
AbstractCellBasedSimulation3_3,
DoCellBirth,
);
}
void SetupSolve() override {
PYBIND11_OVERLOAD(
void,
AbstractCellBasedSimulation3_3,
SetupSolve,
);
}
bool StoppingEventHasOccurred() override {
PYBIND11_OVERLOAD(
bool,
AbstractCellBasedSimulation3_3,
StoppingEventHasOccurred,
);
}
void UpdateCellPopulation() override {
PYBIND11_OVERLOAD(
void,
AbstractCellBasedSimulation3_3,
UpdateCellPopulation,
);
}
void UpdateCellLocationsAndTopology() override {
PYBIND11_OVERLOAD_PURE(
void,
AbstractCellBasedSimulation3_3,
UpdateCellLocationsAndTopology,
);
}
void OutputAdditionalSimulationSetup(::out_stream & rParamsFile) override {
PYBIND11_OVERLOAD_PURE(
void,
AbstractCellBasedSimulation3_3,
OutputAdditionalSimulationSetup,
rParamsFile);
}
};
void register_AbstractCellBasedSimulation3_3_class(py::module &m){
py::class_<AbstractCellBasedSimulation3_3 , AbstractCellBasedSimulation3_3_Overloads , boost::shared_ptr<AbstractCellBasedSimulation3_3 > >(m, "AbstractCellBasedSimulation3_3")
.def(py::init<::AbstractCellPopulation<3, 3> &, bool, bool >(), py::arg("rCellPopulation"), py::arg("deleteCellPopulationInDestructor") = false, py::arg("initialiseCells") = true)
.def(
"GetNodeLocation",
(::std::vector<double, std::allocator<double> >(AbstractCellBasedSimulation3_3::*)(unsigned int const &)) &AbstractCellBasedSimulation3_3::GetNodeLocation,
" " , py::arg("rNodeIndex") )
.def(
"GetDt",
(double(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetDt,
" " )
.def(
"GetNumBirths",
(unsigned int(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetNumBirths,
" " )
.def(
"GetNumDeaths",
(unsigned int(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetNumDeaths,
" " )
.def(
"GetOutputDirectory",
(::std::string(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetOutputDirectory,
" " )
.def(
"SetDt",
(void(AbstractCellBasedSimulation3_3::*)(double)) &AbstractCellBasedSimulation3_3::SetDt,
" " , py::arg("dt") )
.def(
"SetEndTime",
(void(AbstractCellBasedSimulation3_3::*)(double)) &AbstractCellBasedSimulation3_3::SetEndTime,
" " , py::arg("endTime") )
.def(
"SetOutputDirectory",
(void(AbstractCellBasedSimulation3_3::*)(::std::string)) &AbstractCellBasedSimulation3_3::SetOutputDirectory,
" " , py::arg("outputDirectory") )
.def(
"SetSamplingTimestepMultiple",
(void(AbstractCellBasedSimulation3_3::*)(unsigned int)) &AbstractCellBasedSimulation3_3::SetSamplingTimestepMultiple,
" " , py::arg("samplingTimestepMultiple") )
.def(
"SetNoBirth",
(void(AbstractCellBasedSimulation3_3::*)(bool)) &AbstractCellBasedSimulation3_3::SetNoBirth,
" " , py::arg("noBirth") )
.def(
"SetUpdateCellPopulationRule",
(void(AbstractCellBasedSimulation3_3::*)(bool)) &AbstractCellBasedSimulation3_3::SetUpdateCellPopulationRule,
" " , py::arg("updateCellPopulation") )
.def(
"GetUpdateCellPopulationRule",
(bool(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetUpdateCellPopulationRule,
" " )
.def(
"AddCellKiller",
(void(AbstractCellBasedSimulation3_3::*)(::boost::shared_ptr<AbstractCellKiller<3> >)) &AbstractCellBasedSimulation3_3::AddCellKiller,
" " , py::arg("pCellKiller") )
.def(
"RemoveAllCellKillers",
(void(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::RemoveAllCellKillers,
" " )
.def(
"AddSimulationModifier",
(void(AbstractCellBasedSimulation3_3::*)(::boost::shared_ptr<AbstractCellBasedSimulationModifier<3, 3> >)) &AbstractCellBasedSimulation3_3::AddSimulationModifier,
" " , py::arg("pSimulationModifier") )
.def(
"Solve",
(void(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::Solve,
" " )
.def(
"rGetCellPopulation",
(::AbstractCellPopulation<3, 3> &(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::rGetCellPopulation,
" " , py::return_value_policy::reference_internal)
.def(
"rGetCellPopulation",
(::AbstractCellPopulation<3, 3> const &(AbstractCellBasedSimulation3_3::*)() const ) &AbstractCellBasedSimulation3_3::rGetCellPopulation,
" " , py::return_value_policy::reference_internal)
.def(
"GetOutputDivisionLocations",
(bool(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetOutputDivisionLocations,
" " )
.def(
"SetOutputDivisionLocations",
(void(AbstractCellBasedSimulation3_3::*)(bool)) &AbstractCellBasedSimulation3_3::SetOutputDivisionLocations,
" " , py::arg("outputDivisionLocations") )
.def(
"GetOutputCellVelocities",
(bool(AbstractCellBasedSimulation3_3::*)()) &AbstractCellBasedSimulation3_3::GetOutputCellVelocities,
" " )
.def(
"SetOutputCellVelocities",
(void(AbstractCellBasedSimulation3_3::*)(bool)) &AbstractCellBasedSimulation3_3::SetOutputCellVelocities,
" " , py::arg("outputCellVelocities") )
.def(
"OutputSimulationParameters",
(void(AbstractCellBasedSimulation3_3::*)(::out_stream &)) &AbstractCellBasedSimulation3_3::OutputSimulationParameters,
" " , py::arg("rParamsFile") )
;
}
| 42.829545
| 187
| 0.62762
|
jmsgrogan
|
ab3fb3eee8890f5201f17ecd0f5f0f6a7e1a5513
| 6,328
|
cpp
|
C++
|
source/RAIIGen/Generator/OpenGLESGenerator.cpp
|
Unarmed1000/RAIIGen
|
2516ab5949c1fb54ca1b6e51e5e99e15ecfebbfb
|
[
"BSD-3-Clause"
] | 8
|
2016-11-02T14:08:51.000Z
|
2021-03-25T02:00:00.000Z
|
source/RAIIGen/Generator/OpenGLESGenerator.cpp
|
Unarmed1000/RAIIGen
|
2516ab5949c1fb54ca1b6e51e5e99e15ecfebbfb
|
[
"BSD-3-Clause"
] | 4
|
2016-08-23T12:37:17.000Z
|
2016-09-30T01:58:20.000Z
|
source/RAIIGen/Generator/OpenGLESGenerator.cpp
|
Unarmed1000/RAIIGen
|
2516ab5949c1fb54ca1b6e51e5e99e15ecfebbfb
|
[
"BSD-3-Clause"
] | null | null | null |
//***************************************************************************************************************************************************
//* BSD 3-Clause License
//*
//* Copyright (c) 2016, Rene Thrane
//* 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.
//* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
//* software without specific prior written permission.
//*
//* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//***************************************************************************************************************************************************
#include <RAIIGen/Generator/OpenGLESGenerator.hpp>
#include <RAIIGen/Generator/FunctionNamePair.hpp>
#include <RAIIGen/Generator/MatchedFunctionPair.hpp>
#include <RAIIGen/CaseUtil.hpp>
#include <RAIIGen/Capture.hpp>
#include <FslBase/Exceptions.hpp>
#include <FslBase/IO/File.hpp>
#include <FslBase/String/StringUtil.hpp>
#include <algorithm>
#include <array>
#include <iostream>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace Fsl;
namespace MB
{
namespace
{
const auto CREATE_FUNCTION = "glGen";
const auto DESTROY_FUNCTION = "glDelete";
const auto TYPE_NAME_PREFIX = "GL";
const auto FUNCTION_NAME_PREFIX = "gl";
// gl_enum, not good
const auto ERRORCODE_TYPE_NAME = "";
const auto DEFAULT_VALUE = "VK_NULL_HANDLE";
const std::vector<FunctionNamePair> g_functionPairs{
FunctionNamePair(CREATE_FUNCTION, DESTROY_FUNCTION),
};
// Manual matches for methods that don't follow 'standard' patterns
const std::vector<FunctionNamePair> g_manualFunctionMatches{
// Pipelines are destroyed with vkDestroyPipeline
// FunctionNamePair("vkCreateGraphicsPipelines", "vkDestroyPipeline"),
};
const std::vector<RAIIClassCustomization> g_arrayRAIIClassCustomization{};
const std::vector<ClassFunctionAbsorb> g_classFunctionAbsorbtion{};
const std::unordered_map<std::string, RAIIClassMethodOverrides> g_classMethodOverride = {};
const std::vector<std::string> g_forceNullParameter{
//"VkAllocationCallbacks"
};
const std::vector<FunctionGuard> g_functionGuards{};
const std::vector<BlackListEntry> g_functionNameBlacklist{};
const std::vector<BlackListEntry> g_enumNameBlacklist{};
const std::vector<BlackListEntry> g_enumMemberBlacklist{};
const std::vector<FunctionParameterNameOverride> g_functionParameterNameOverride{};
const std::vector<FunctionParameterTypeOverride> g_functionParameterTypeOverride{};
const std::unordered_map<std::string, std::string> g_typeDefaultValues = {
//{ "VkBuffer", DEFAULT_VALUE },
//{ "VkBufferView", DEFAULT_VALUE },
//{ "VkCommandBuffer", DEFAULT_VALUE },
//{ "VkCommandPool", DEFAULT_VALUE },
//{ "VkDebugReportCallbackEXT", DEFAULT_VALUE },
//{ "VkDescriptorPool", DEFAULT_VALUE },
//{ "VkDescriptorSet", DEFAULT_VALUE },
//{ "VkDescriptorSetLayout", DEFAULT_VALUE },
//{ "VkDevice", DEFAULT_VALUE },
//{ "VkDeviceMemory", DEFAULT_VALUE },
//{ "VkEvent", DEFAULT_VALUE },
//{ "VkFence", DEFAULT_VALUE },
//{ "VkFramebuffer", DEFAULT_VALUE },
//{ "VkImage", DEFAULT_VALUE },
//{ "VkImageView", DEFAULT_VALUE },
//{ "VkInstance", DEFAULT_VALUE },
//{ "VkPipeline", DEFAULT_VALUE },
//{ "VkPipelineCache", DEFAULT_VALUE },
//{ "VkPipelineLayout", DEFAULT_VALUE },
//{ "VkQueryPool", DEFAULT_VALUE },
//{ "VkRenderPass", DEFAULT_VALUE },
//{ "VkSampler", DEFAULT_VALUE },
//{ "VkSemaphore", DEFAULT_VALUE },
//{ "VkShaderModule", DEFAULT_VALUE },
//{ "VkSurfaceKHR", DEFAULT_VALUE },
//{ "VkSwapchainKHR", DEFAULT_VALUE },
};
const std::vector<TypeNameAliasEntry> g_typeNameAliases = {};
}
OpenGLESGenerator::OpenGLESGenerator(const Capture& capture, const BasicConfig& basicConfig, const Fsl::IO::Path& templateRoot,
const Fsl::IO::Path& dstPath)
: SimpleGenerator(capture,
SimpleGeneratorConfig(basicConfig, g_functionPairs, g_manualFunctionMatches, g_arrayRAIIClassCustomization,
g_classFunctionAbsorbtion, g_classMethodOverride, g_typeDefaultValues, g_forceNullParameter,
g_functionGuards, g_functionNameBlacklist, g_enumNameBlacklist, g_enumMemberBlacklist,
g_typeNameAliases, TYPE_NAME_PREFIX,
FUNCTION_NAME_PREFIX, ERRORCODE_TYPE_NAME, false, false),
templateRoot, dstPath)
{
}
CaptureConfig OpenGLESGenerator::GetCaptureConfig()
{
std::deque<std::string> filters;
filters.push_back(CREATE_FUNCTION);
filters.push_back(DESTROY_FUNCTION);
return CaptureConfig(TYPE_NAME_PREFIX, filters, g_functionParameterNameOverride, g_functionParameterTypeOverride, true);
}
}
| 41.090909
| 149
| 0.670512
|
Unarmed1000
|
ab41f97a3c93b5a3104c6e622cd441a024888c7a
| 524
|
hxx
|
C++
|
lang/Language.hxx
|
JeneLitsch/lang-get
|
9c11f12112b59539a954c804ba121c2dd513684e
|
[
"MIT"
] | null | null | null |
lang/Language.hxx
|
JeneLitsch/lang-get
|
9c11f12112b59539a954c804ba121c2dd513684e
|
[
"MIT"
] | null | null | null |
lang/Language.hxx
|
JeneLitsch/lang-get
|
9c11f12112b59539a954c804ba121c2dd513684e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <unordered_map>
#include <string>
#include <string_view>
#include <memory>
namespace lang {
class Language {
public:
const std::string find(const std::string & key) const;
void insert(const std::string & key, const std::string & text);
private:
std::unordered_map<std::string, std::string> table;
};
void set(std::shared_ptr<Language> language);
const std::string get(const char * key);
const std::string get(const std::string & key);
const std::string get(const std::string_view key);
}
| 27.578947
| 65
| 0.715649
|
JeneLitsch
|
ab4293a0f786f79d3cbf809561fbb99ba9b51d64
| 1,071
|
hpp
|
C++
|
sprout/iterator/remove_if_iterator.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | 1
|
2020-02-04T05:16:01.000Z
|
2020-02-04T05:16:01.000Z
|
sprout/iterator/remove_if_iterator.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | null | null | null |
sprout/iterator/remove_if_iterator.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | null | null | null |
#ifndef SPROUT_ITERATOR_REMOVE_IF_ITERATOR_HPP
#define SPROUT_ITERATOR_REMOVE_IF_ITERATOR_HPP
#include <sprout/config.hpp>
#include <sprout/iterator/filter_iterator.hpp>
namespace sprout {
//
// remove_if_filter
//
template<typename Predicate>
class remove_if_filter {
public:
typedef bool result_type;
private:
Predicate pred_;
public:
explicit SPROUT_CONSTEXPR remove_if_filter(Predicate pred)
: pred_(pred)
{}
template<typename U>
SPROUT_CONSTEXPR bool operator()(U const& value) const {
return !pred_(value);
}
};
//
// make_remove_if_iterator
//
template<typename Predicate, typename Iterator>
inline SPROUT_CONSTEXPR sprout::filter_iterator<sprout::remove_if_filter<Predicate>, Iterator>
make_remove_if_iterator(Predicate pred, Iterator it, Iterator last = Iterator()) {
return sprout::filter_iterator<sprout::remove_if_filter<Predicate>, Iterator>(
sprout::remove_if_filter<Predicate>(pred), it, last
);
}
} // namespace sprout
#endif // SPROUT_ITERATOR_REMOVE_IF_ITERATOR_HPP
| 26.775
| 96
| 0.744164
|
osyo-manga
|
ab4a881d65a6e50bcc24d2037844e8ed2b0c91e3
| 786
|
cpp
|
C++
|
10815 Andy's First Dictionary.cpp
|
zihadboss/UVA-Solutions
|
020fdcb09da79dc0a0411b04026ce3617c09cd27
|
[
"Apache-2.0"
] | 86
|
2016-01-20T11:36:50.000Z
|
2022-03-06T19:43:14.000Z
|
10815 Andy's First Dictionary.cpp
|
Mehedishihab/UVA-Solutions
|
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
|
[
"Apache-2.0"
] | null | null | null |
10815 Andy's First Dictionary.cpp
|
Mehedishihab/UVA-Solutions
|
474fe3d9d9ba574b97fd40ca5abb22ada95654a1
|
[
"Apache-2.0"
] | 113
|
2015-12-04T06:40:57.000Z
|
2022-02-11T02:14:28.000Z
|
#include <iostream>
#include <set>
#include <string>
using namespace std;
inline bool IsLowerCharacter(char c)
{
return c >= 'a' && c <= 'z';
}
int main()
{
string in;
set<string> words;
while (cin >> in)
{
int size = in.size();
string current = "";
for (int i = 0; i < size; ++i)
{
char c = tolower(in[i]);
if (IsLowerCharacter(c))
current += c;
else if (current != "")
{
words.insert(current);
current = "";
}
}
if (current != "")
words.insert(current);
}
for (set<string>::iterator iter = words.begin(); iter != words.end(); ++iter)
cout << *iter << '\n';
}
| 20.153846
| 81
| 0.433842
|
zihadboss
|
ab4bf87dfe24be850b0134f28f82323b4ae73334
| 1,338
|
cpp
|
C++
|
xc_PZ.cpp
|
f-fathurrahman/ffr-pspw-dft-c
|
5e673e33385eb467d99fcd992b350614c2709740
|
[
"MIT"
] | 1
|
2018-05-17T09:01:12.000Z
|
2018-05-17T09:01:12.000Z
|
xc_PZ.cpp
|
f-fathurrahman/ffr-pspw-dft-c
|
5e673e33385eb467d99fcd992b350614c2709740
|
[
"MIT"
] | null | null | null |
xc_PZ.cpp
|
f-fathurrahman/ffr-pspw-dft-c
|
5e673e33385eb467d99fcd992b350614c2709740
|
[
"MIT"
] | null | null | null |
// eFeFeR, December 2011
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void xc_PZ(double *rho, double *vxc, double &Exc, int NNR)
{
const double A = -0.1423;
const double B = 1.0529;
const double C = 0.3334;
const double a = 0.0311;
const double b = -0.0480;
const double c = 0.0020;
const double d = -0.0116;
const double SMALL=1.e-13;
double ax, r, ux, uc, ex, ec, rs, rrs, bpr, rsl;
int i;
Exc = 0.0;
ax = -(3.0/4.0)*pow(3.0/2.0/M_PI,2.0/3.0);
for(i=0; i<NNR; i++) {
r = rho[i];
//
if(r < -0.1) { // Is this safe?
printf("***WARNING: Negative electron density: %18.10f\n", r);
//abort();
}
//
else if(r <= SMALL) {
ux = 0.0;
uc = 0.0;
ec = 0.0;
ex = 0.0;
}
//
else {
rs = pow( 3.0/(4.0*M_PI*r), 1.0/3.0);
rrs = sqrt(rs);
// Exchange
ex = ax/rs;
ux = 4.0/3.0*ex;
// Correlation for rs >= 1
if(rs >= 1.0) {
bpr = 1.0 + B*rrs + C*rs;
ec = A/bpr;
uc = (1.0 + 7.0/6.0*B*rrs + 4.0/3.0*C*rs)*ec/bpr;
}
// Correlation for rs < 1
else {
rsl = log(rs);
ec = a*rsl + b + c*rs*rsl + d*rs;
uc = (2.0*d - c)/3.0*rs + b-a/3.0 + a*rsl + 2.0*c/3.0*rs*rsl;
}
}
vxc[i] = ux + uc;
Exc = Exc + r*(ex + ec);
}
}
| 20.584615
| 69
| 0.457399
|
f-fathurrahman
|
ab4d5e5d8c20136f62f2dbe5e8b5ae3f0ea720b4
| 1,454
|
hpp
|
C++
|
src/LuminoEngine/src/Shader/ShaderManager.hpp
|
infinnie/Lumino
|
921caabdbcb91528a2aac290e31d650628bc3bed
|
[
"MIT"
] | null | null | null |
src/LuminoEngine/src/Shader/ShaderManager.hpp
|
infinnie/Lumino
|
921caabdbcb91528a2aac290e31d650628bc3bed
|
[
"MIT"
] | null | null | null |
src/LuminoEngine/src/Shader/ShaderManager.hpp
|
infinnie/Lumino
|
921caabdbcb91528a2aac290e31d650628bc3bed
|
[
"MIT"
] | null | null | null |
#pragma once
#ifdef _WIN32
#include <d3dcompiler.h>
#endif
#include <LuminoEngine/Shader/Common.hpp>
#include "../Base/RefObjectCache.hpp"
namespace ln {
namespace detail {
class GraphicsManager;
#ifdef _WIN32
typedef HRESULT(WINAPI* PFN_D3DCompile2)(
LPCVOID pSrcData,
SIZE_T SrcDataSize,
LPCSTR pSourceName,
const D3D_SHADER_MACRO* pDefines,
ID3DInclude* pInclude,
LPCSTR pEntrypoint,
LPCSTR pTarget,
UINT Flags1,
UINT Flags2,
UINT SecondaryDataFlags,
LPCVOID pSecondaryData,
SIZE_T SecondaryDataSize,
ID3DBlob** ppCode,
ID3DBlob** ppErrorMsgs
);
#endif
class ShaderManager
: public RefObject
{
public:
struct Settings
{
GraphicsManager* graphicsManager = nullptr;
};
ShaderManager();
virtual ~ShaderManager();
void init(const Settings& settings);
void dispose();
Ref<Shader> loadShader(const StringRef& filePath);
GraphicsManager* graphicsManager() const { return m_graphicsManager; }
const std::vector<std::pair<std::string, std::string>>& builtinShaderList() const { return m_builtinShaderList; }
#ifdef _WIN32
PFN_D3DCompile2 D3DCompile2 = nullptr;
#endif
private:
GraphicsManager* m_graphicsManager;
std::vector<std::pair<std::string, std::string>> m_builtinShaderList;
ObjectCache<String, Shader> m_shaderCache;
#ifdef _WIN32
HMODULE m_hD3DCompilerDLL;
#endif
};
} // namespace detail
} // namespace ln
| 22.030303
| 117
| 0.715956
|
infinnie
|
ab5727322eef21d72eef2a063a1f9fe70fadb375
| 4,905
|
hpp
|
C++
|
dart/dynamics/TemplatedJacobianNode.hpp
|
axeisghost/DART6motionBlur
|
23387b0422bf95b75a113dbf5facc5f10d4a3305
|
[
"BSD-2-Clause"
] | 4
|
2021-02-20T15:59:42.000Z
|
2022-03-25T04:04:21.000Z
|
dart/dynamics/TemplatedJacobianNode.hpp
|
axeisghost/DART6motionBlur
|
23387b0422bf95b75a113dbf5facc5f10d4a3305
|
[
"BSD-2-Clause"
] | 1
|
2021-04-14T04:12:48.000Z
|
2021-04-14T04:12:48.000Z
|
dart/dynamics/TemplatedJacobianNode.hpp
|
axeisghost/DART6motionBlur
|
23387b0422bf95b75a113dbf5facc5f10d4a3305
|
[
"BSD-2-Clause"
] | 2
|
2019-10-29T12:41:16.000Z
|
2021-03-22T16:38:27.000Z
|
/*
* Copyright (c) 2015-2016, Humanoid Lab, Georgia Tech Research Corporation
* Copyright (c) 2015-2017, Graphics Lab, Georgia Tech Research Corporation
* Copyright (c) 2016-2017, Personal Robotics Lab, Carnegie Mellon University
* All rights reserved.
*
* This file is provided under the following "BSD-style" License:
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef DART_DYNAMICS_TEMPLATEDJACOBIANENTITY_HPP_
#define DART_DYNAMICS_TEMPLATEDJACOBIANENTITY_HPP_
#include "dart/dynamics/JacobianNode.hpp"
namespace dart {
namespace dynamics {
/// TemplatedJacobianNode provides a curiously recurring template pattern
/// implementation of the various JacobianNode non-caching functions. These
/// functions are easily distinguished because they return by value instead of
/// returning by const reference.
///
/// This style of implementation allows BodyNode and EndEffector to share the
/// implementations of these various auxiliary Jacobian functions without any
/// penalty from dynamic overload resolution.
template <class NodeType>
class TemplatedJacobianNode : public JacobianNode
{
public:
// Documentation inherited
math::Jacobian getJacobian(
const Frame* _inCoordinatesOf) const override final;
// Documentation inherited
math::Jacobian getJacobian(
const Eigen::Vector3d& _offset) const override final;
// Documentation inherited
math::Jacobian getJacobian(
const Eigen::Vector3d& _offset,
const Frame* _inCoordinatesOf) const override final;
// Documentation inherited
math::Jacobian getWorldJacobian(
const Eigen::Vector3d& _offset) const override final;
// Documentation inherited
math::LinearJacobian getLinearJacobian(
const Frame* _inCoordinatesOf = Frame::World()) const override final;
// Documentation inherited
math::LinearJacobian getLinearJacobian(
const Eigen::Vector3d& _offset,
const Frame* _inCoordinatesOf = Frame::World()) const override final;
// Documentation inherited
math::AngularJacobian getAngularJacobian(
const Frame* _inCoordinatesOf = Frame::World()) const override final;
// Documentation inherited
math::Jacobian getJacobianSpatialDeriv(
const Frame* _inCoordinatesOf) const override final;
// Documentation inherited
math::Jacobian getJacobianSpatialDeriv(
const Eigen::Vector3d& _offset) const override final;
// Documentation inherited
math::Jacobian getJacobianSpatialDeriv(
const Eigen::Vector3d& _offset,
const Frame* _inCoordinatesOf) const override final;
// Documentation inherited
math::Jacobian getJacobianClassicDeriv(
const Frame* _inCoordinatesOf) const override final;
// Documentation inherited
math::Jacobian getJacobianClassicDeriv(
const Eigen::Vector3d& _offset,
const Frame* _inCoordinatesOf = Frame::World()) const override final;
// Documentation inherited
math::LinearJacobian getLinearJacobianDeriv(
const Frame* _inCoordinatesOf = Frame::World()) const override final;
// Documentation inherited
math::LinearJacobian getLinearJacobianDeriv(
const Eigen::Vector3d& _offset,
const Frame* _inCoordinatesOf = Frame::World()) const override final;
// Documentation inherited
math::AngularJacobian getAngularJacobianDeriv(
const Frame* _inCoordinatesOf = Frame::World()) const override final;
protected:
/// Constructor
TemplatedJacobianNode(BodyNode* bn);
};
} // namespace dynamics
} // namespace dart
#include "dart/dynamics/detail/TemplatedJacobianNode.hpp"
#endif // DART_DYNAMICS_TEMPLATEDJACOBIANENTITY_HPP_
| 37.442748
| 78
| 0.759429
|
axeisghost
|
ab63318049c59604c4202e5c0c01e64d6bb57272
| 23,362
|
cpp
|
C++
|
src/lib/sema/SemanticAnalyzer.cpp
|
LittleLaGi/p2llvm
|
549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3
|
[
"MIT"
] | null | null | null |
src/lib/sema/SemanticAnalyzer.cpp
|
LittleLaGi/p2llvm
|
549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3
|
[
"MIT"
] | null | null | null |
src/lib/sema/SemanticAnalyzer.cpp
|
LittleLaGi/p2llvm
|
549b82c2e89c2cc1324a3d8b8d7760bb96ba0ba3
|
[
"MIT"
] | null | null | null |
#include "sema/SemanticAnalyzer.hpp"
#include "sema/error.hpp"
#include "visitor/AstNodeInclude.hpp"
#include <algorithm>
#include <cassert>
static constexpr const char *kRedeclaredSymbolErrorMessage =
"symbol '%s' is redeclared";
void SemanticAnalyzer::visit(ProgramNode &p_program) {
m_symbol_manager.pushGlobalScope();
m_context_stack.push(SemanticContext::kGlobal);
m_returned_type_stack.push(p_program.getTypePtr());
auto success = m_symbol_manager.addSymbol(
p_program.getName(), SymbolEntry::KindEnum::kProgramKind,
p_program.getTypePtr(), static_cast<Constant *>(nullptr));
if (!success) {
logSemanticError(p_program.getLocation(), kRedeclaredSymbolErrorMessage,
p_program.getNameCString());
m_has_error = true;
}
p_program.visitChildNodes(*this);
p_program.setSymbolTable(m_symbol_manager.getCurrentTable());
m_returned_type_stack.pop();
m_context_stack.pop();
m_symbol_manager.popGlobalScope();
}
void SemanticAnalyzer::visit(DeclNode &p_decl) {
p_decl.visitChildNodes(*this);
}
SymbolEntry::KindEnum
SemanticAnalyzer::determineVarKind(const VariableNode &p_variable) {
if (isInForLoop()) {
return SymbolEntry::KindEnum::kLoopVarKind;
}
if (isInFunction()) {
return SymbolEntry::KindEnum::kParameterKind;
}
// global or local
return p_variable.getConstantPtr() ? SymbolEntry::KindEnum::kConstantKind
: SymbolEntry::KindEnum::kVariableKind;
}
SymbolEntry *SemanticAnalyzer::addSymbol(const VariableNode &p_variable) {
auto kind = determineVarKind(p_variable);
auto *entry = m_symbol_manager.addSymbol(p_variable.getName(), kind,
p_variable.getTypePtr(),
p_variable.getConstantPtr());
if (!entry) {
logSemanticError(p_variable.getLocation(),
kRedeclaredSymbolErrorMessage,
p_variable.getNameCString());
m_has_error = true;
}
return entry;
}
static bool validateDimensions(const VariableNode &p_variable) {
bool has_error = false;
auto validate_dimension = [&](const auto dimension) {
if (dimension == 0) {
logSemanticError(p_variable.getLocation(),
"'%s' declared as an array with an index that is "
"not greater than 0",
p_variable.getNameCString());
has_error = true;
}
};
for_each(p_variable.getTypePtr()->getDimensions().begin(),
p_variable.getTypePtr()->getDimensions().end(),
validate_dimension);
return !has_error;
}
void SemanticAnalyzer::visit(VariableNode &p_variable) {
auto *entry = addSymbol(p_variable);
p_variable.visitChildNodes(*this);
if (entry && !validateDimensions(p_variable)) {
m_error_entry_set.insert(entry);
m_has_error = true;
}
}
void SemanticAnalyzer::visit(ConstantValueNode &p_constant_value) {
p_constant_value.setInferredType(
p_constant_value.getTypePtr()->getStructElementType(0));
}
void SemanticAnalyzer::visit(FunctionNode &p_function) {
auto success = m_symbol_manager.addSymbol(
p_function.getName(), SymbolEntry::KindEnum::kFunctionKind,
p_function.getTypePtr(), &p_function.getParameters());
if (!success) {
logSemanticError(p_function.getLocation(),
kRedeclaredSymbolErrorMessage,
p_function.getNameCString());
m_has_error = true;
}
m_symbol_manager.pushScope();
m_context_stack.push(SemanticContext::kFunction);
m_returned_type_stack.push(p_function.getTypePtr());
auto visit_ast_node = [this](auto &ast_node) { ast_node->accept(*this); };
for_each(p_function.getParameters().begin(),
p_function.getParameters().end(), visit_ast_node);
// directly visit the body to prevent pushing duplicate scope
m_context_stack.push(SemanticContext::kLocal);
p_function.visitBodyChildNodes(*this);
m_context_stack.pop();
p_function.setSymbolTable(m_symbol_manager.getCurrentTable());
m_returned_type_stack.pop();
m_context_stack.pop();
m_symbol_manager.popScope();
}
void SemanticAnalyzer::visit(CompoundStatementNode &p_compound_statement) {
m_symbol_manager.pushScope();
m_context_stack.push(SemanticContext::kLocal);
p_compound_statement.visitChildNodes(*this);
p_compound_statement.setSymbolTable(m_symbol_manager.getCurrentTable());
m_context_stack.pop();
m_symbol_manager.popScope();
}
static bool validatePrintTarget(const PrintNode &p_print) {
const auto *const target_type_ptr = p_print.getTarget().getInferredType();
if (!target_type_ptr) {
return false;
}
if (!target_type_ptr->isScalar()) {
logSemanticError(p_print.getTarget().getLocation(),
"expression of print statement must be scalar type");
return false;
}
return true;
}
void SemanticAnalyzer::visit(PrintNode &p_print) {
p_print.visitChildNodes(*this);
if (!validatePrintTarget(p_print)) {
m_has_error = true;
}
}
static bool validateOperandsInArithmeticOp(const Operator op,
const PType *const p_left_type,
const PType *const p_right_type) {
if (op == Operator::kPlusOp && p_left_type->isString() &&
p_right_type->isString()) {
return true;
}
if ((p_left_type->isInteger() || p_left_type->isReal()) &&
(p_right_type->isInteger() || p_right_type->isReal())) {
return true;
}
return false;
}
static bool validateOperandsInModOp(const PType *const p_left_type,
const PType *const p_right_type) {
return p_left_type->isInteger() && p_right_type->isInteger();
}
static bool validateOperandsInBooleanOp(const PType *const p_left_type,
const PType *const p_right_type) {
return p_left_type->isBool() && p_right_type->isBool();
}
static bool validateOperandsInRelationalOp(const PType *const p_left_type,
const PType *const p_right_type) {
return (p_left_type->isInteger() || p_left_type->isReal()) &&
(p_right_type->isInteger() || p_right_type->isReal());
}
static bool validateBinaryOperands(BinaryOperatorNode &p_bin_op) {
const auto *left_type_ptr = p_bin_op.getLeftOperand().getInferredType();
const auto *right_type_ptr = p_bin_op.getRightOperand().getInferredType();
if (left_type_ptr == nullptr || right_type_ptr == nullptr) {
return false;
}
switch (p_bin_op.getOp()) {
case Operator::kPlusOp:
case Operator::kMinusOp:
case Operator::kMultiplyOp:
case Operator::kDivideOp:
if (validateOperandsInArithmeticOp(p_bin_op.getOp(), left_type_ptr,
right_type_ptr)) {
return true;
}
break;
case Operator::kModOp:
if (validateOperandsInModOp(left_type_ptr, right_type_ptr)) {
return true;
}
break;
case Operator::kAndOp:
case Operator::kOrOp:
if (validateOperandsInBooleanOp(left_type_ptr, right_type_ptr)) {
return true;
}
break;
case Operator::kLessOp:
case Operator::kLessOrEqualOp:
case Operator::kEqualOp:
case Operator::kGreaterOp:
case Operator::kGreaterOrEqualOp:
case Operator::kNotEqualOp:
if (validateOperandsInRelationalOp(left_type_ptr, right_type_ptr)) {
return true;
}
break;
default:
assert(false && "unknown binary op or unary op");
}
logSemanticError(p_bin_op.getLocation(),
"invalid operands to binary operator '%s' ('%s' and '%s')",
p_bin_op.getOpCString(), left_type_ptr->getPTypeCString(),
right_type_ptr->getPTypeCString());
return false;
}
static void setBinaryOpInferredType(BinaryOperatorNode &p_bin_op) {
switch (p_bin_op.getOp()) {
case Operator::kPlusOp:
case Operator::kMinusOp:
case Operator::kMultiplyOp:
case Operator::kDivideOp:
if (p_bin_op.getLeftOperand().getInferredType()->isString()) {
p_bin_op.setInferredType(
new PType(PType::PrimitiveTypeEnum::kStringType));
return;
}
if (p_bin_op.getLeftOperand().getInferredType()->isReal() ||
p_bin_op.getRightOperand().getInferredType()->isReal()) {
p_bin_op.setInferredType(
new PType(PType::PrimitiveTypeEnum::kRealType));
return;
}
case Operator::kModOp:
p_bin_op.setInferredType(
new PType(PType::PrimitiveTypeEnum::kIntegerType));
return;
case Operator::kAndOp:
case Operator::kOrOp:
p_bin_op.setInferredType(
new PType(PType::PrimitiveTypeEnum::kBoolType));
return;
case Operator::kLessOp:
case Operator::kLessOrEqualOp:
case Operator::kEqualOp:
case Operator::kGreaterOp:
case Operator::kGreaterOrEqualOp:
case Operator::kNotEqualOp:
p_bin_op.setInferredType(
new PType(PType::PrimitiveTypeEnum::kBoolType));
return;
default:
assert(false && "unknown binary op or unary op");
}
}
void SemanticAnalyzer::visit(BinaryOperatorNode &p_bin_op) {
p_bin_op.visitChildNodes(*this);
if (!validateBinaryOperands(p_bin_op)) {
m_has_error = true;
return;
}
setBinaryOpInferredType(p_bin_op);
}
static bool validateUnaryOperand(const UnaryOperatorNode &p_un_op) {
const auto *const operand_type = p_un_op.getOperand().getInferredType();
if (!operand_type) {
return false;
}
switch (p_un_op.getOp()) {
case Operator::kNegOp:
if (operand_type->isInteger() || operand_type->isReal()) {
return true;
}
break;
case Operator::kNotOp:
if (operand_type->isBool()) {
return true;
}
break;
default:
assert(false && "unknown binary op or unary op");
}
logSemanticError(p_un_op.getLocation(),
"invalid operand to unary operator '%s' ('%s')",
p_un_op.getOpCString(), operand_type->getPTypeCString());
return false;
}
static void setUnaryOpInferredType(UnaryOperatorNode &p_un_op) {
switch (p_un_op.getOp()) {
case Operator::kNegOp:
p_un_op.setInferredType(new PType(
p_un_op.getOperand().getInferredType()->getPrimitiveType()));
return;
case Operator::kNotOp:
p_un_op.setInferredType(new PType(PType::PrimitiveTypeEnum::kBoolType));
return;
default:
assert(false && "unknown binary op or unary op");
}
}
void SemanticAnalyzer::visit(UnaryOperatorNode &p_un_op) {
p_un_op.visitChildNodes(*this);
if (!validateUnaryOperand(p_un_op)) {
m_has_error = true;
return;
}
setUnaryOpInferredType(p_un_op);
}
static const SymbolEntry *
checkSymbolExistence(const SymbolManager &p_symbol_manager,
const std::string &p_name, const Location &p_location) {
const auto *entry = p_symbol_manager.lookup(p_name);
if (entry == nullptr) {
logSemanticError(p_location, "use of undeclared symbol '%s'",
p_name.c_str());
}
return entry;
}
static bool validateFunctionInvocationKind(
const SymbolEntry::KindEnum kind,
const FunctionInvocationNode &p_func_invocation) {
if (kind != SymbolEntry::KindEnum::kFunctionKind) {
logSemanticError(p_func_invocation.getLocation(),
"call of non-function symbol '%s'",
p_func_invocation.getNameCString());
return false;
}
return true;
}
static bool validateArguments(const SymbolEntry *const p_entry,
const FunctionInvocationNode &p_func_invocation) {
const auto ¶meters = *p_entry->getAttribute().parameters();
const auto &arguments = p_func_invocation.getArguments();
if (arguments.size() != FunctionNode::getParametersNum(parameters)) {
logSemanticError(p_func_invocation.getLocation(),
"too few/much arguments provided for function '%s'",
p_func_invocation.getNameCString());
return false;
}
FunctionInvocationNode::ExprNodes::const_iterator argument_iter =
arguments.begin();
for (const auto ¶meter : parameters) {
const auto &variables = parameter->getVariables();
for (const auto &variable : variables) {
auto *expr_type_ptr = (*argument_iter)->getInferredType();
if (!expr_type_ptr) {
return false;
}
if (!expr_type_ptr->compare(variable->getTypePtr())) {
logSemanticError(
(*argument_iter)->getLocation(),
"incompatible type passing '%s' to parameter of type '%s'",
expr_type_ptr->getPTypeCString(),
variable->getTypePtr()->getPTypeCString());
return false;
}
argument_iter++;
}
}
return true;
}
static void
setFuncInvocationInferredType(FunctionInvocationNode &p_func_invocation,
const SymbolEntry *p_entry) {
p_func_invocation.setInferredType(
new PType(p_entry->getTypePtr()->getPrimitiveType()));
}
void SemanticAnalyzer::visit(FunctionInvocationNode &p_func_invocation) {
p_func_invocation.visitChildNodes(*this);
const SymbolEntry *entry = nullptr;
if ((entry = checkSymbolExistence(
m_symbol_manager, p_func_invocation.getName(),
p_func_invocation.getLocation())) == nullptr) {
m_has_error = true;
return;
}
if (!validateFunctionInvocationKind(entry->getKind(), p_func_invocation)) {
m_has_error = true;
return;
}
if (!validateArguments(entry, p_func_invocation)) {
m_has_error = true;
return;
}
setFuncInvocationInferredType(p_func_invocation, entry);
}
static bool validateVariableKind(const SymbolEntry::KindEnum kind,
const VariableReferenceNode &p_variable_ref) {
if (kind != SymbolEntry::KindEnum::kParameterKind &&
kind != SymbolEntry::KindEnum::kVariableKind &&
kind != SymbolEntry::KindEnum::kLoopVarKind &&
kind != SymbolEntry::KindEnum::kConstantKind) {
logSemanticError(p_variable_ref.getLocation(),
"use of non-variable symbol '%s'",
p_variable_ref.getNameCString());
return false;
}
return true;
}
static bool
validateArrayReference(const VariableReferenceNode &p_variable_ref) {
for (const auto &index : p_variable_ref.getIndices()) {
if (index->getInferredType() == nullptr) {
return false;
}
if (!index->getInferredType()->isInteger()) {
logSemanticError(index->getLocation(),
"index of array reference must be an integer");
return false;
}
}
return true;
}
static bool
validateArraySubscriptNum(const PType *p_var_type,
const VariableReferenceNode &p_variable_ref) {
if (p_variable_ref.getIndices().size() >
p_var_type->getDimensions().size()) {
logSemanticError(p_variable_ref.getLocation(),
"there is an over array subscript on '%s'",
p_variable_ref.getNameCString());
return false;
}
return true;
}
void SemanticAnalyzer::visit(VariableReferenceNode &p_variable_ref) {
p_variable_ref.visitChildNodes(*this);
const SymbolEntry *entry = nullptr;
if ((entry =
checkSymbolExistence(m_symbol_manager, p_variable_ref.getName(),
p_variable_ref.getLocation())) == nullptr) {
return;
}
if (!validateVariableKind(entry->getKind(), p_variable_ref)) {
return;
}
if (m_error_entry_set.find(const_cast<SymbolEntry *>(entry)) !=
m_error_entry_set.end()) {
return;
}
if (!validateArrayReference(p_variable_ref)) {
return;
}
if (!validateArraySubscriptNum(entry->getTypePtr(), p_variable_ref)) {
return;
}
p_variable_ref.setInferredType(entry->getTypePtr()->getStructElementType(
p_variable_ref.getIndices().size()));
}
static bool validateAssignmentLvalue(const AssignmentNode &p_assignment,
const SymbolManager &p_symbol_manager,
const bool is_in_for_loop) {
const auto &lvalue = p_assignment.getLvalue();
const auto *const lvalue_type_ptr = lvalue.getInferredType();
if (!lvalue_type_ptr) {
return false;
}
if (!lvalue_type_ptr->isScalar()) {
logSemanticError(lvalue.getLocation(),
"array assignment is not allowed");
return false;
}
const auto *const entry = p_symbol_manager.lookup(lvalue.getName());
if (entry->getKind() == SymbolEntry::KindEnum::kConstantKind) {
logSemanticError(lvalue.getLocation(),
"cannot assign to variable '%s' which is a constant",
lvalue.getNameCString());
return false;
}
if (!is_in_for_loop &&
entry->getKind() == SymbolEntry::KindEnum::kLoopVarKind) {
logSemanticError(lvalue.getLocation(),
"the value of loop variable cannot be modified inside "
"the loop body");
return false;
}
return true;
}
static bool validateAssignmentExpr(const AssignmentNode &p_assignment) {
const auto &expr = p_assignment.getExpr();
const auto *const expr_type_ptr = expr.getInferredType();
if (!expr_type_ptr) {
return false;
}
if (!expr_type_ptr->isScalar()) {
logSemanticError(expr.getLocation(), "array assignment is not allowed");
return false;
}
const auto *const lvalue_type_ptr =
p_assignment.getLvalue().getInferredType();
if (!lvalue_type_ptr->compare(expr_type_ptr)) {
logSemanticError(p_assignment.getLocation(),
"assigning to '%s' from incompatible type '%s'",
lvalue_type_ptr->getPTypeCString(),
expr_type_ptr->getPTypeCString());
return false;
}
return true;
}
void SemanticAnalyzer::visit(AssignmentNode &p_assignment) {
p_assignment.visitChildNodes(*this);
if (!validateAssignmentLvalue(p_assignment, m_symbol_manager,
isInForLoop())) {
m_has_error = true;
return;
}
if (!validateAssignmentExpr(p_assignment)) {
m_has_error = true;
return;
}
}
static bool validateReadTarget(const ReadNode &p_read,
const SymbolManager &p_symbol_manager) {
const auto *const target_type_ptr = p_read.getTarget().getInferredType();
if (!target_type_ptr) {
return false;
}
if (!target_type_ptr->isScalar()) {
logSemanticError(
p_read.getTarget().getLocation(),
"variable reference of read statement must be scalar type");
return false;
}
const auto *const entry =
p_symbol_manager.lookup(p_read.getTarget().getName());
assert(entry && "Shouldn't reach here. This should be catched during the"
"visits of child nodes");
if (entry->getKind() == SymbolEntry::KindEnum::kConstantKind ||
entry->getKind() == SymbolEntry::KindEnum::kLoopVarKind) {
logSemanticError(p_read.getTarget().getLocation(),
"variable reference of read statement cannot be a "
"constant or loop variable");
return false;
}
return true;
}
void SemanticAnalyzer::visit(ReadNode &p_read) {
p_read.visitChildNodes(*this);
if (!validateReadTarget(p_read, m_symbol_manager)) {
m_has_error = true;
}
}
static bool validateConditionExpr(const ExpressionNode &p_condition) {
const auto *const type_ptr = p_condition.getInferredType();
if (!type_ptr) {
return false;
}
if (!type_ptr->isBool()) {
logSemanticError(p_condition.getLocation(),
"the expression of condition must be boolean type");
return false;
}
return true;
}
void SemanticAnalyzer::visit(IfNode &p_if) {
p_if.visitChildNodes(*this);
if (!validateConditionExpr(p_if.getCondition())) {
m_has_error = true;
}
}
void SemanticAnalyzer::visit(WhileNode &p_while) {
p_while.visitChildNodes(*this);
if (!validateConditionExpr(p_while.getCondition())) {
m_has_error = true;
}
}
static bool validateForLoopBound(const ForNode &p_for) {
auto initial_value = p_for.getLowerBound().getConstantPtr()->integer();
auto condition_value = p_for.getUpperBound().getConstantPtr()->integer();
if (initial_value >= condition_value) {
logSemanticError(p_for.getLocation(),
"the lower bound and upper bound of iteration count "
"must be in the incremental order");
return false;
}
return true;
}
void SemanticAnalyzer::visit(ForNode &p_for) {
m_symbol_manager.pushScope();
m_context_stack.push(SemanticContext::kForLoop);
p_for.visitChildNodes(*this);
if (!validateForLoopBound(p_for)) {
m_has_error = true;
}
p_for.setSymbolTable(m_symbol_manager.getCurrentTable());
m_context_stack.pop();
m_symbol_manager.popScope();
}
static bool validateReturnValueType(const ExpressionNode &p_retval,
const PType *const p_expected_return_type) {
const auto *const retval_type_ptr = p_retval.getInferredType();
if (!retval_type_ptr) {
return false;
}
if (!p_expected_return_type->compare(retval_type_ptr)) {
logSemanticError(p_retval.getLocation(),
"return '%s' from a function with return type '%s'",
retval_type_ptr->getPTypeCString(),
p_expected_return_type->getPTypeCString());
return false;
}
return true;
}
void SemanticAnalyzer::visit(ReturnNode &p_return) {
p_return.visitChildNodes(*this);
const auto *const expected_return_type_ptr = m_returned_type_stack.top();
if (expected_return_type_ptr->isVoid()) {
logSemanticError(p_return.getLocation(),
"program/procedure should not return a value");
m_has_error = true;
return;
}
if (!validateReturnValueType(p_return.getReturnValue(),
expected_return_type_ptr)) {
m_has_error = true;
return;
}
}
| 31.741848
| 80
| 0.62653
|
LittleLaGi
|
036814d1a97748599afba9b31b875766beed3e52
| 1,204
|
cpp
|
C++
|
networkit/cpp/io/ThrillGraphBinaryWriter.cpp
|
tsapko3628/networkit
|
2953c9f30b676f930e301953f00f014c47edcf69
|
[
"MIT"
] | 1
|
2019-08-15T10:35:07.000Z
|
2019-08-15T10:35:07.000Z
|
networkit/cpp/io/ThrillGraphBinaryWriter.cpp
|
tsapko3628/networkit
|
2953c9f30b676f930e301953f00f014c47edcf69
|
[
"MIT"
] | null | null | null |
networkit/cpp/io/ThrillGraphBinaryWriter.cpp
|
tsapko3628/networkit
|
2953c9f30b676f930e301953f00f014c47edcf69
|
[
"MIT"
] | null | null | null |
/*
* ThrillGraphBinaryWriter.hpp
*
* @author Michael Hamann <michael.hamann@kit.edu>
*/
#include <fstream>
#include <networkit/io/ThrillGraphBinaryWriter.hpp>
namespace NetworKit {
void ThrillGraphBinaryWriter::write(const Graph &G, const std::string &path) {
if (G.upperNodeIdBound() > std::numeric_limits<uint32_t>::max()) {
throw std::runtime_error("Thrill binary graphs only support graphs with up to 2^32-1 nodes.");
}
std::ofstream out_stream(path, std::ios::trunc | std::ios::binary);
std::vector<uint32_t> neighbors;
for (node u = 0; u < G.upperNodeIdBound(); ++u) {
neighbors.clear();
if (G.hasNode(u)) {
G.forEdgesOf(u, [&](node v) {
if (u <= v) {
neighbors.push_back(v);
}
});
}
size_t deg = neighbors.size();
// Write variable length int for the degree
if(!deg) {
out_stream << uint8_t(0);
}
while(deg) {
size_t u = deg & 0x7F;
deg >>= 7;
out_stream << uint8_t(u | (deg ? 0x80 : 0));
}
for (uint32_t v : neighbors) {
// write neighbor as little endian
for (size_t i = 0; i < sizeof(uint32_t); ++i) {
out_stream << uint8_t(v);
v >>= 8;
}
}
}
out_stream.close();
}
} // namespace NetworKit
| 20.758621
| 96
| 0.620432
|
tsapko3628
|
0368abdcaa74444faedefb6f776d1dc78de63cb1
| 1,946
|
hpp
|
C++
|
modules/viewer/src/Viewer/gmPointListModel.hpp
|
GraphMIC/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 43
|
2016-04-11T11:34:05.000Z
|
2022-03-31T03:37:57.000Z
|
modules/viewer/src/Viewer/gmPointListModel.hpp
|
kevinlq/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 1
|
2016-05-17T12:58:16.000Z
|
2016-05-17T12:58:16.000Z
|
modules/viewer/src/Viewer/gmPointListModel.hpp
|
kevinlq/GraphMIC
|
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
|
[
"BSD-3-Clause"
] | 14
|
2016-05-13T20:23:16.000Z
|
2021-12-20T10:33:19.000Z
|
#pragma once
#include "gmViewerExport.hpp"
#include "mitkDataNode.h"
#include "mitkPointSet.h"
#include <QAbstractListModel>
namespace gm
{
namespace ViewItem
{
class GM_VIEWER_EXPORT PointListModel: public QAbstractListModel
{
Q_OBJECT
protected:
mitk::DataNode* m_pointSetNode;
unsigned int m_pointSetModifiedObserverTag;
unsigned int m_pointSetDeletedObserverTag;
int m_timeStep;
public:
PointListModel( mitk::DataNode* = NULL, int t = 0, QObject* parent = 0 );
~PointListModel();
int rowCount( const QModelIndex& parent = QModelIndex() ) const override;
QVariant data(const QModelIndex& index, int role) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
auto setPointSetNode(mitk::DataNode* pointSetNode) -> void;
auto getPointSet() -> const mitk::PointSet*;
auto setTimeStep(int t) -> void;
auto getTimeStep() -> const int;
auto onPointSetChanged(const itk::EventObject &e) -> void;
auto onPointSetDeleted(const itk::EventObject &e) -> void;
auto getPointForModelIndex(const QModelIndex &index, mitk::PointSet::PointType &p, mitk::PointSet::PointIdentifier &id) const -> bool;
auto getModelIndexForPointID(mitk::PointSet::PointIdentifier id, QModelIndex &index) const -> bool ;
public slots:
void moveSelectedPointUp();
void moveSelectedPointDown();
void removeSelectedPoint();
signals:
void signalUpdateSelection();
protected:
auto observeNewPointSet(mitk::DataNode* pointSetNode) -> void;
auto checkForPointSetInNode(mitk::DataNode* node) const -> mitk::PointSet::Pointer;
};
}
}
| 39.714286
| 146
| 0.63001
|
GraphMIC
|
036a8c4921bc8c9deb1b7043bd6ebf94059d9ef3
| 2,525
|
cpp
|
C++
|
Visual Mercutio/zModelBP/PSS_RiskProbabilityContainer.cpp
|
Jeanmilost/Visual-Mercutio
|
f079730005b6ce93d5e184bb7c0893ccced3e3ab
|
[
"MIT"
] | 1
|
2022-01-31T06:24:24.000Z
|
2022-01-31T06:24:24.000Z
|
Visual Mercutio/zModelBP/PSS_RiskProbabilityContainer.cpp
|
Jeanmilost/Visual-Mercutio
|
f079730005b6ce93d5e184bb7c0893ccced3e3ab
|
[
"MIT"
] | 2
|
2021-04-11T15:50:42.000Z
|
2021-06-05T08:23:04.000Z
|
Visual Mercutio/zModelBP/PSS_RiskProbabilityContainer.cpp
|
Jeanmilost/Visual-Mercutio
|
f079730005b6ce93d5e184bb7c0893ccced3e3ab
|
[
"MIT"
] | 2
|
2021-01-08T00:55:18.000Z
|
2022-01-31T06:24:18.000Z
|
/****************************************************************************
* ==> PSS_RiskProbabilityContainer ----------------------------------------*
****************************************************************************
* Description : Provides a risk probability container *
* Developer : Processsoft *
****************************************************************************/
#include "stdafx.h"
#include "PSS_RiskProbabilityContainer.h"
// processsoft
#include "zBaseLib\PSS_TextFile.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
//---------------------------------------------------------------------------
// PSS_RiskProbabilityContainer
//---------------------------------------------------------------------------
PSS_RiskProbabilityContainer::PSS_RiskProbabilityContainer() :
CObject()
{}
//---------------------------------------------------------------------------
PSS_RiskProbabilityContainer::~PSS_RiskProbabilityContainer()
{
RemoveAllElements();
}
//---------------------------------------------------------------------------
BOOL PSS_RiskProbabilityContainer::LoadFile(const CString& fileName)
{
if (fileName.IsEmpty())
return FALSE;
m_FileName = fileName;
PSS_TextFile textFile;
if (!textFile.OpenRead(m_FileName))
return FALSE;
BOOL endReached = FALSE;
CString text;
while (!endReached)
{
textFile >> text;
if (!text.IsEmpty())
m_Set.Add(text);
else
endReached = TRUE;
}
textFile.CloseFile();
return TRUE;
}
//---------------------------------------------------------------------------
CString PSS_RiskProbabilityContainer::GetFileName() const
{
return m_FileName;
}
//---------------------------------------------------------------------------
CStringArray* PSS_RiskProbabilityContainer::GetElementsArray()
{
return &m_Set;
}
//---------------------------------------------------------------------------
CString PSS_RiskProbabilityContainer::GetElementAt(std::size_t index) const
{
if (index < GetElementCount())
return m_Set.GetAt(index);
return _T("");
}
//---------------------------------------------------------------------------
void PSS_RiskProbabilityContainer::RemoveAllElements()
{
m_Set.RemoveAll();
}
//---------------------------------------------------------------------------
| 29.705882
| 78
| 0.406337
|
Jeanmilost
|
036b71e2cb216c6ba9b3abdfebc3a217827c5242
| 1,078
|
cpp
|
C++
|
tests/Helpers/Helpers.cpp
|
matheuspf/handy
|
3c33c2bfc947567d1be483cf1b5ad63716479357
|
[
"MIT"
] | 4
|
2018-08-06T12:26:43.000Z
|
2020-09-11T09:59:07.000Z
|
tests/Helpers/Helpers.cpp
|
matheuspf/Handy
|
3c33c2bfc947567d1be483cf1b5ad63716479357
|
[
"MIT"
] | 2
|
2020-03-24T00:57:46.000Z
|
2021-02-02T04:53:27.000Z
|
tests/Helpers/Helpers.cpp
|
matheuspf/Handy
|
3c33c2bfc947567d1be483cf1b5ad63716479357
|
[
"MIT"
] | 1
|
2017-12-05T18:33:22.000Z
|
2017-12-05T18:33:22.000Z
|
#include "handy/Helpers/Helpers.h"
#include "gtest/gtest.h"
#include <fstream>
#include <sstream>
#include <vector>
namespace
{
TEST(HelpersTest, IsInheritedTest)
{
struct A {};
struct B : A {};
struct C {};
struct D : B {};
EXPECT_EQ((handy::IsInherited<B, A>::value), true);
EXPECT_EQ((handy::IsInherited<C, A>::value), false);
EXPECT_EQ((handy::IsInherited<C, B>::value), false);
EXPECT_EQ((handy::IsInherited<D, B>::value), true);
EXPECT_EQ((handy::IsInherited<D, A>::value), true);
EXPECT_EQ((handy::IsInherited<A, A>::value), true);
EXPECT_EQ((handy::IsInherited<B, B>::value), true);
EXPECT_EQ((handy::IsInherited<C, C>::value), true);
EXPECT_EQ((handy::IsInherited<D, D>::value), true);
}
TEST(HelpersTest, GetArgTest)
{
EXPECT_EQ((std::is_same<handy::GetArg_t<1, int, char, double>, char>::value), true);
EXPECT_EQ((std::is_same<handy::GetArg_t<0, int, char, double>, char>::value), false);
EXPECT_EQ((std::is_same<handy::GetArg_t<2, int, char, double>, double>::value), true);
}
}
| 21.56
| 90
| 0.636364
|
matheuspf
|
0371babcf570722a9dbfa507437e132a9ae3af21
| 10,211
|
cpp
|
C++
|
tests/Unit/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Test_KerrSchild.cpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | 1
|
2018-10-01T06:07:16.000Z
|
2018-10-01T06:07:16.000Z
|
tests/Unit/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Test_KerrSchild.cpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | 4
|
2018-06-04T20:26:40.000Z
|
2018-07-27T14:54:55.000Z
|
tests/Unit/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/Test_KerrSchild.cpp
|
macedo22/spectre
|
97b2b7ae356cf86830258cb5f689f1191fdb6ddd
|
[
"MIT"
] | null | null | null |
// Distributed under the MIT License.
// See LICENSE.txt for details.
#include "Framework/TestingFramework.hpp"
#include <algorithm>
#include <array>
#include <cstddef>
#include <limits>
#include <string>
#include <type_traits>
#include "DataStructures/DataBox/Prefixes.hpp"
#include "DataStructures/DataVector.hpp"
#include "DataStructures/Tensor/EagerMath/Magnitude.hpp"
#include "DataStructures/Tensor/Tensor.hpp"
#include "Framework/TestCreation.hpp"
#include "Framework/TestHelpers.hpp"
#include "Helpers/PointwiseFunctions/AnalyticSolutions/GeneralRelativity/VerifyGrSolution.hpp"
#include "Helpers/PointwiseFunctions/AnalyticSolutions/TestHelpers.hpp"
#include "NumericalAlgorithms/LinearOperators/PartialDerivatives.tpp"
#include "PointwiseFunctions/AnalyticSolutions/GeneralRelativity/KerrSchild.hpp"
#include "PointwiseFunctions/GeneralRelativity/Tags.hpp"
#include "Utilities/ConstantExpressions.hpp"
#include "Utilities/MakeWithValue.hpp"
#include "Utilities/TMPL.hpp"
#include "Utilities/TaggedTuple.hpp"
// IWYU pragma: no_forward_declare Tags::deriv
namespace {
template <typename Frame, typename DataType>
tnsr::I<DataType, 3, Frame> spatial_coords(
const DataType& used_for_size) noexcept {
auto x = make_with_value<tnsr::I<DataType, 3, Frame>>(used_for_size, 0.0);
get<0>(x) = 1.32;
get<1>(x) = 0.82;
get<2>(x) = 1.24;
return x;
}
template <typename Frame, typename DataType>
void test_schwarzschild(const DataType& used_for_size) noexcept {
// Schwarzschild solution is:
// H = M/r
// l_mu = (1,x/r,y/r,z/r)
// lapse = (1+2M/r)^{-1/2}
// d_lapse = (1+2M/r)^{-3/2}(Mx^i/r^3)
// shift^i = (2Mx^i/r^2) / lapse^2
// g_{ij} = delta_{ij} + 2 M x_i x_j/r^3
// d_i H = -Mx_i/r^3
// d_i l_j = delta_{ij}/r - x^i x^j/r^3
// d_k g_ij = -6M x_i x_j x_k/r^5 + 2 M x_i delta_{kj}/r^3
// + 2 M x_j delta_{ki}/r^3
// Parameters for KerrSchild solution
const double mass = 1.01;
const std::array<double, 3> spin{{0.0, 0.0, 0.0}};
const std::array<double, 3> center{{0.0, 0.0, 0.0}};
const auto x = spatial_coords<Frame>(used_for_size);
const double t = 1.3;
// Evaluate solution
gr::Solutions::KerrSchild solution(mass, spin, center);
const auto vars = solution.variables(
x, t, typename gr::Solutions::KerrSchild::tags<DataType, Frame>{});
const auto& lapse = get<gr::Tags::Lapse<DataType>>(vars);
const auto& dt_lapse = get<Tags::dt<gr::Tags::Lapse<DataType>>>(vars);
const auto& d_lapse =
get<typename gr::Solutions::KerrSchild::DerivLapse<DataType, Frame>>(
vars);
const auto& shift = get<gr::Tags::Shift<3, Frame, DataType>>(vars);
const auto& d_shift =
get<typename gr::Solutions::KerrSchild::DerivShift<DataType, Frame>>(
vars);
const auto& dt_shift =
get<Tags::dt<gr::Tags::Shift<3, Frame, DataType>>>(vars);
const auto& g = get<gr::Tags::SpatialMetric<3, Frame, DataType>>(vars);
const auto& dt_g =
get<Tags::dt<gr::Tags::SpatialMetric<3, Frame, DataType>>>(vars);
const auto& d_g = get<
typename gr::Solutions::KerrSchild::DerivSpatialMetric<DataType, Frame>>(
vars);
// Check those quantities that should be zero.
const auto zero = make_with_value<DataType>(x, 0.);
CHECK(dt_lapse.get() == zero);
for (size_t i = 0; i < 3; ++i) {
CHECK(dt_shift.get(i) == zero);
for (size_t j = 0; j < 3; ++j) {
CHECK(dt_g.get(i, j) == zero);
}
}
const DataType r = get(magnitude(x));
const DataType one_over_r_squared = 1.0 / square(r);
const DataType one_over_r_cubed = 1.0 / cube(r);
const DataType one_over_r_fifth = one_over_r_squared * one_over_r_cubed;
auto expected_lapse = make_with_value<Scalar<DataType>>(x, 0.0);
get(expected_lapse) = 1.0 / sqrt(1.0 + 2.0 * mass / r);
CHECK_ITERABLE_APPROX(lapse, expected_lapse);
auto expected_d_lapse = make_with_value<tnsr::i<DataType, 3, Frame>>(x, 0.0);
for (size_t i = 0; i < 3; ++i) {
expected_d_lapse.get(i) =
mass * x.get(i) * one_over_r_cubed * cube(get(lapse));
}
CHECK_ITERABLE_APPROX(d_lapse, expected_d_lapse);
auto expected_shift = make_with_value<tnsr::I<DataType, 3, Frame>>(x, 0.0);
for (size_t i = 0; i < 3; ++i) {
expected_shift.get(i) =
2.0 * mass * x.get(i) * one_over_r_squared * square(get(lapse));
}
CHECK_ITERABLE_APPROX(shift, expected_shift);
auto expected_d_shift = make_with_value<tnsr::iJ<DataType, 3, Frame>>(x, 0.0);
for (size_t j = 0; j < 3; ++j) {
expected_d_shift.get(j, j) =
2.0 * mass * one_over_r_squared * square(get(lapse));
for (size_t i = 0; i < 3; ++i) {
expected_d_shift.get(j, i) -=
4.0 * mass * x.get(j) * x.get(i) * square(one_over_r_squared) *
square(get(lapse)) * (1 - mass / r * square(get(lapse)));
}
}
CHECK_ITERABLE_APPROX(d_shift, expected_d_shift);
auto expected_g = make_with_value<tnsr::ii<DataType, 3, Frame>>(x, 0.0);
for (size_t i = 0; i < 3; ++i) {
for (size_t j = i; j < 3; ++j) {
expected_g.get(i, j) =
2.0 * mass * x.get(i) * x.get(j) * one_over_r_cubed;
}
expected_g.get(i, i) += 1.0;
}
CHECK_ITERABLE_APPROX(g, expected_g);
auto expected_d_g = make_with_value<tnsr::ijj<DataType, 3, Frame>>(x, 0.0);
for (size_t k = 0; k < 3; ++k) {
for (size_t i = 0; i < 3; ++i) {
for (size_t j = i; j < 3; ++j) { // Symmetry
expected_d_g.get(k, i, j) =
-6.0 * mass * x.get(i) * x.get(j) * x.get(k) * one_over_r_fifth;
if (k == j) {
expected_d_g.get(k, i, j) += 2.0 * mass * x.get(i) * one_over_r_cubed;
}
if (k == i) {
expected_d_g.get(k, i, j) += 2.0 * mass * x.get(j) * one_over_r_cubed;
}
}
}
}
CHECK_ITERABLE_APPROX(d_g, expected_d_g);
}
template <typename Frame, typename DataType>
void test_tag_retrieval(const DataType& used_for_size) noexcept {
// Parameters for KerrSchild solution
const double mass = 1.234;
const std::array<double, 3> spin{{0.1, -0.2, 0.3}};
const std::array<double, 3> center{{1.0, 2.0, 3.0}};
const auto x = spatial_coords<Frame>(used_for_size);
const double t = 1.3;
// Evaluate solution
const gr::Solutions::KerrSchild solution(mass, spin, center);
TestHelpers::AnalyticSolutions::test_tag_retrieval(
solution, x, t,
typename gr::Solutions::KerrSchild::template tags<DataType, Frame>{});
}
template <typename Frame>
void test_einstein_solution() noexcept {
// Parameters
// ...for KerrSchild solution
const double mass = 1.7;
const std::array<double, 3> spin{{0.1, 0.2, 0.3}};
const std::array<double, 3> center{{0.3, 0.2, 0.4}};
// ...for grid
const std::array<double, 3> lower_bound{{0.82, 1.24, 1.32}};
const double time = -2.8;
gr::Solutions::KerrSchild solution(mass, spin, center);
TestHelpers::VerifyGrSolution::verify_consistency(
solution, time, tnsr::I<double, 3, Frame>{lower_bound}, 0.01, 1.0e-10);
if constexpr (std::is_same_v<Frame, ::Frame::Inertial>) {
// Don't look at time-independent solution in other than the inertial
// frame.
const size_t grid_size = 8;
const std::array<double, 3> upper_bound{{0.8, 1.22, 1.30}};
TestHelpers::VerifyGrSolution::verify_time_independent_einstein_solution(
solution, grid_size, lower_bound, upper_bound,
std::numeric_limits<double>::epsilon() * 1.e5);
}
}
void test_serialize() noexcept {
gr::Solutions::KerrSchild solution(3.0, {{0.2, 0.3, 0.2}}, {{0.0, 3.0, 4.0}});
test_serialization(solution);
}
void test_copy_and_move() noexcept {
gr::Solutions::KerrSchild solution(3.0, {{0.2, 0.3, 0.2}}, {{0.0, 3.0, 4.0}});
test_copy_semantics(solution);
auto solution_copy = solution;
// clang-tidy: std::move of trivially copyable type
test_move_semantics(std::move(solution), solution_copy); // NOLINT
}
void test_construct_from_options() {
const auto created = TestHelpers::test_creation<gr::Solutions::KerrSchild>(
"Mass: 0.5\n"
"Spin: [0.1,0.2,0.3]\n"
"Center: [1.0,3.0,2.0]");
CHECK(created ==
gr::Solutions::KerrSchild(0.5, {{0.1, 0.2, 0.3}}, {{1.0, 3.0, 2.0}}));
}
} // namespace
SPECTRE_TEST_CASE("Unit.PointwiseFunctions.AnalyticSolutions.Gr.KerrSchild",
"[PointwiseFunctions][Unit]") {
test_copy_and_move();
test_serialize();
test_construct_from_options();
test_schwarzschild<Frame::Inertial>(DataVector(5));
test_schwarzschild<Frame::Inertial>(0.0);
test_tag_retrieval<Frame::Inertial>(DataVector(5));
test_tag_retrieval<Frame::Inertial>(0.0);
test_einstein_solution<Frame::Inertial>();
test_schwarzschild<Frame::Grid>(DataVector(5));
test_schwarzschild<Frame::Grid>(0.0);
test_tag_retrieval<Frame::Grid>(DataVector(5));
test_tag_retrieval<Frame::Grid>(0.0);
test_einstein_solution<Frame::Grid>();
}
// [[OutputRegex, Spin magnitude must be < 1]]
SPECTRE_TEST_CASE("Unit.PointwiseFunctions.AnalyticSolutions.Gr.KerrSchildSpin",
"[PointwiseFunctions][Unit]") {
ERROR_TEST();
gr::Solutions::KerrSchild solution(1.0, {{1.0, 1.0, 1.0}}, {{0.0, 0.0, 0.0}});
}
// [[OutputRegex, Mass must be non-negative]]
SPECTRE_TEST_CASE("Unit.PointwiseFunctions.AnalyticSolutions.Gr.KerrSchildMass",
"[PointwiseFunctions][Unit]") {
ERROR_TEST();
gr::Solutions::KerrSchild solution(-1.0, {{0.0, 0.0, 0.0}},
{{0.0, 0.0, 0.0}});
}
// [[OutputRegex, In string:.*At line 2 column 9:.Value -0.5 is below the lower
// bound of 0]]
SPECTRE_TEST_CASE("Unit.PointwiseFunctions.AnalyticSolutions.Gr.KerrSchildOptM",
"[PointwiseFunctions][Unit]") {
ERROR_TEST();
TestHelpers::test_creation<gr::Solutions::KerrSchild>(
"Mass: -0.5\n"
"Spin: [0.1,0.2,0.3]\n"
"Center: [1.0,3.0,2.0]");
}
// [[OutputRegex, In string:.*At line 2 column 3:.Spin magnitude must be < 1]]
SPECTRE_TEST_CASE("Unit.PointwiseFunctions.AnalyticSolutions.Gr.KerrSchildOptS",
"[PointwiseFunctions][Unit]") {
ERROR_TEST();
TestHelpers::test_creation<gr::Solutions::KerrSchild>(
"Mass: 0.5\n"
"Spin: [1.1,0.9,0.3]\n"
"Center: [1.0,3.0,2.0]");
}
| 36.730216
| 94
| 0.652042
|
macedo22
|
037310778e911323870cd8107f3ecc37a31bddd0
| 639
|
cpp
|
C++
|
core/bookmarks/cbookmark.cpp
|
VioletGiraffe/FasterThanSight
|
f23d2e4a3e4f8abcee3d4691dbb35a0823da56e3
|
[
"MIT"
] | 34
|
2016-06-13T18:38:54.000Z
|
2022-02-21T00:04:54.000Z
|
core/bookmarks/cbookmark.cpp
|
probonopd/FasterThanSight
|
f23d2e4a3e4f8abcee3d4691dbb35a0823da56e3
|
[
"MIT"
] | 54
|
2016-05-20T07:38:51.000Z
|
2019-03-15T17:23:09.000Z
|
core/bookmarks/cbookmark.cpp
|
probonopd/FasterThanSight
|
f23d2e4a3e4f8abcee3d4691dbb35a0823da56e3
|
[
"MIT"
] | 11
|
2016-12-19T13:14:24.000Z
|
2022-02-20T23:58:25.000Z
|
#include "cbookmark.h"
#include "assert/advanced_assert.h"
DISABLE_COMPILER_WARNINGS
#include <QStringBuilder>
#include <QStringList>
RESTORE_COMPILER_WARNINGS
CBookmark::CBookmark(const QString & serializedBookmark)
{
const QStringList components = serializedBookmark.split(';');
assert_and_return_r(components.size() == 2, );
filePath = components[0];
wordIndex = (size_t)components[1].toULongLong();
}
CBookmark::CBookmark(const QString& path, const size_t position) : filePath(path), wordIndex(position)
{
}
QString CBookmark::toString() const
{
return filePath % ';' % QString::number(wordIndex);
}
| 24.576923
| 103
| 0.733959
|
VioletGiraffe
|
03738de4a35439a2089b392e1772330b8a3225b7
| 2,439
|
cpp
|
C++
|
tc 160+/DequeSort.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 3
|
2015-05-25T06:24:37.000Z
|
2016-09-10T07:58:00.000Z
|
tc 160+/DequeSort.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | null | null | null |
tc 160+/DequeSort.cpp
|
ibudiselic/contest-problem-solutions
|
88082981b4d87da843472e3ca9ed5f4c42b3f0aa
|
[
"BSD-2-Clause"
] | 5
|
2015-05-25T06:24:40.000Z
|
2021-08-19T19:22:29.000Z
|
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
#include <utility>
using namespace std;
class DequeSort {
public:
int minDeques(vector <int> data) {
vector< pair<int, int> > v;
v.push_back(make_pair(data[0], data[0]));
for (int i=1; i<(int)data.size(); ++i) {
bool done = false;
for (int j=0; j<(int)v.size(); ++j) {
int l = v[j].first;
int r = v[j].second;
if (data[i]>l && data[i]<r)
continue;
l = min(l, data[i]);
r = max(r, data[i]);
bool ok = true;
for (int k=i+1; k<(int)data.size(); ++k)
if (data[k]>l && data[k]<r) {
ok = false;
break;
}
if (ok) {
v[j].first = l;
v[j].second = r;
done = true;
break;
}
}
if (!done)
v.push_back(make_pair(data[i], data[i]));
}
return v.size();
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {50, 45, 55, 60, 65,
40, 70, 35, 30, 75}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, minDeques(Arg0)); }
void test_case_1() { int Arr0[] = {3, 6, 0, 9, 5, 4}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 2; verify_case(1, Arg1, minDeques(Arg0)); }
void test_case_2() { int Arr0[] = {0, 2, 1, 4, 3, 6, 5, 8, 7, 9}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; verify_case(2, Arg1, minDeques(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
DequeSort ___test;
___test.run_test(-1);
}
// END CUT HERE
| 31.675325
| 309
| 0.540795
|
ibudiselic
|
037688bd186cf13ba183f3656aa337b6fa8ad0f1
| 5,072
|
cpp
|
C++
|
nau/src/nau/scene/iScene.cpp
|
Khirion/nau
|
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
|
[
"MIT"
] | 29
|
2015-09-16T22:28:30.000Z
|
2022-03-11T02:57:36.000Z
|
nau/src/nau/scene/iScene.cpp
|
Khirion/nau
|
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
|
[
"MIT"
] | 1
|
2017-03-29T13:32:58.000Z
|
2017-03-31T13:56:03.000Z
|
nau/src/nau/scene/iScene.cpp
|
Khirion/nau
|
47a2ad8e0355a264cd507da5e7bba1bf7abbff95
|
[
"MIT"
] | 10
|
2015-10-15T14:20:15.000Z
|
2022-02-17T10:37:29.000Z
|
#include "nau/scene/iScene.h"
#include "nau.h"
#include "nau/math/matrix.h"
using namespace nau::math;
using namespace nau::scene;
bool
IScene::Init() {
// MAT4
Attribs.add(Attribute(TRANSFORM, "TRANSFORM", Enums::MAT4, true));
// VEC4
Attribs.add(Attribute(SCALE, "SCALE", Enums::DataType::VEC4, false, new vec4(1.0f, 1.0f, 1.0f, 1.0f)));
Attribs.add(Attribute(TRANSLATE, "TRANSLATE", Enums::DataType::VEC4, false, new vec4(0.0f, 0.0f, 0.0f, 0.0f)));
Attribs.add(Attribute(ROTATE, "ROTATE", Enums::DataType::VEC4, false, new vec4(0.0f, 1.0f, 0.0f, 0.0f)));
// VEC3
Attribs.add(Attribute(BB_MAX, "BB_MAX", Enums::DataType::VEC3, true, new vec3(-1.0f, -1.0f, -1.0f)));
Attribs.add(Attribute(BB_MIN, "BB_MIN", Enums::DataType::VEC3, true, new vec3(1.0f, 1.0f, 1.0f)));
Attribs.add(Attribute(BB_CENTER, "BB_CENTER", Enums::DataType::VEC3, true, new vec3(0.0f, 0.0f, 0.0f)));
// ENUM
Attribs.add(Attribute(TRANSFORM_ORDER, "TRANSFORM_ORDER", Enums::ENUM, false, new NauInt(T_R_S)));
Attribs.listAdd("TRANSFORM_ORDER", "T_R_S", T_R_S);
Attribs.listAdd("TRANSFORM_ORDER", "T_S_R", T_S_R);
Attribs.listAdd("TRANSFORM_ORDER", "R_T_S", R_T_S);
Attribs.listAdd("TRANSFORM_ORDER", "R_S_T", R_S_T);
Attribs.listAdd("TRANSFORM_ORDER", "S_R_T", S_R_T);
Attribs.listAdd("TRANSFORM_ORDER", "S_T_R", S_T_R);
// UINT
Attribs.add(Attribute(TRIANGLE_COUNT, "TRIANGLE_COUNT", Enums::DataType::UINT, true, new NauUInt(0)));
//#ifndef _WINDLL
NAU->registerAttributes("SCENE", &Attribs);
//#endif
return true;
}
AttribSet &
IScene::GetAttribs() {
return Attribs;
}
AttribSet IScene::Attribs;
bool IScene::Inited = Init();
void
IScene::updateTransform() {
mat4 tis;
switch (m_EnumProps[TRANSFORM_ORDER]) {
case T_R_S:
tis.setIdentity();
tis.translate(m_Float4Props[TRANSLATE].x, m_Float4Props[TRANSLATE].y, m_Float4Props[TRANSLATE].z);
tis.rotate(m_Float4Props[ROTATE].w, m_Float4Props[ROTATE].x, m_Float4Props[ROTATE].y, m_Float4Props[ROTATE].z);
tis.scale(m_Float4Props[SCALE].x, m_Float4Props[SCALE].y, m_Float4Props[SCALE].z);
break;
case T_S_R:
tis.setIdentity();
tis.translate(m_Float4Props[TRANSLATE].x, m_Float4Props[TRANSLATE].y, m_Float4Props[TRANSLATE].z);
tis.scale(m_Float4Props[SCALE].x, m_Float4Props[SCALE].y, m_Float4Props[SCALE].z);
tis.rotate(m_Float4Props[ROTATE].w, m_Float4Props[ROTATE].x, m_Float4Props[ROTATE].y, m_Float4Props[ROTATE].z);
break;
case R_T_S:
tis.setIdentity();
tis.rotate(m_Float4Props[ROTATE].w, m_Float4Props[ROTATE].x, m_Float4Props[ROTATE].y, m_Float4Props[ROTATE].z);
tis.translate(m_Float4Props[TRANSLATE].x, m_Float4Props[TRANSLATE].y, m_Float4Props[TRANSLATE].z);
tis.scale(m_Float4Props[SCALE].x, m_Float4Props[SCALE].y, m_Float4Props[SCALE].z);
break;
case R_S_T:
tis.setIdentity();
tis.rotate(m_Float4Props[ROTATE].w, m_Float4Props[ROTATE].x, m_Float4Props[ROTATE].y, m_Float4Props[ROTATE].z);
tis.scale(m_Float4Props[SCALE].x, m_Float4Props[SCALE].y, m_Float4Props[SCALE].z);
tis.translate(m_Float4Props[TRANSLATE].x, m_Float4Props[TRANSLATE].y, m_Float4Props[TRANSLATE].z);
break;
case S_R_T:
tis.setIdentity();
tis.scale(m_Float4Props[SCALE].x, m_Float4Props[SCALE].y, m_Float4Props[SCALE].z);
tis.rotate(m_Float4Props[ROTATE].w, m_Float4Props[ROTATE].x, m_Float4Props[ROTATE].y, m_Float4Props[ROTATE].z);
tis.translate(m_Float4Props[TRANSLATE].x, m_Float4Props[TRANSLATE].y, m_Float4Props[TRANSLATE].z);
break;
case S_T_R:
tis.setIdentity();
tis.scale(m_Float4Props[SCALE].x, m_Float4Props[SCALE].y, m_Float4Props[SCALE].z);
tis.translate(m_Float4Props[TRANSLATE].x, m_Float4Props[TRANSLATE].y, m_Float4Props[TRANSLATE].z);
tis.rotate(m_Float4Props[ROTATE].w, m_Float4Props[ROTATE].x, m_Float4Props[ROTATE].y, m_Float4Props[ROTATE].z);
break;
}
setTransform(tis);
std::shared_ptr<nau::event_::IEventData> e3 = nau::event_::EventFactory::Create("String");
std::string * name = new std::string(m_Name);
e3->setData(name);
delete name;
EVENTMANAGER->notifyEvent("SCENE_TRANSFORM", "SCENE", "", e3);
}
void
IScene::setPropf4(Float4Property prop, vec4& aVec) {
switch (prop) {
case SCALE:
case ROTATE:
case TRANSLATE:
m_Float4Props[prop] = aVec;
updateTransform();
break;
default:
AttributeValues::setPropf4(prop, aVec);
}
}
void
IScene::setPrope(EnumProperty prop, int v) {
switch (prop) {
case TRANSFORM_ORDER:
m_EnumProps[prop] = v;
updateTransform();
break;
default:
AttributeValues::setPrope(prop, v);
}
}
vec3 &
IScene::getPropf3(Float3Property prop) {
switch (prop) {
case BB_MIN: m_Float3Props[BB_MIN] = getBoundingVolume().getMin();
return m_Float3Props[BB_MIN];
case BB_MAX: m_Float3Props[BB_MAX] = getBoundingVolume().getMax();
return m_Float3Props[BB_MAX];
case BB_CENTER: m_Float3Props[BB_CENTER] = getBoundingVolume().getCenter();
return m_Float3Props[BB_CENTER];
default: return AttributeValues::getPropf3(prop);
}
}
const std::string &
IScene::getClassName() {
return m_Type;
}
void nau::scene::IScene::recompile() {
m_Compiled = false;
compile();
}
| 30.554217
| 113
| 0.728312
|
Khirion
|
0378c4d26e1cb319d8fd740c05e8c3b7f6dbf715
| 6,573
|
cpp
|
C++
|
include/types/image.cpp
|
nathanmullenax83/rhizome
|
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
|
[
"MIT"
] | 1
|
2020-07-11T14:53:38.000Z
|
2020-07-11T14:53:38.000Z
|
include/types/image.cpp
|
nathanmullenax83/rhizome
|
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
|
[
"MIT"
] | 1
|
2020-07-04T16:45:49.000Z
|
2020-07-04T16:45:49.000Z
|
include/types/image.cpp
|
nathanmullenax83/rhizome
|
e7410341fdc4d38ab5aaecc55c94d3ac6efd51da
|
[
"MIT"
] | null | null | null |
#include "image.hpp"
namespace rhizome {
namespace types {
void image_demo() {
std::cout << "Image Demo." << std::endl;
Image x;
x.set_size(500,500);
x.checker_board( 16,16, Color(1,1,1,1), Color(1,0,0,1));
x.save_png("test.png");
Image y;
y.freeimage_load("include/image/back.png");
y.freeimage_save("withfreeimage.png");
}
Image::~Image() {
}
void Image::set_size( size_t width, size_t height ) {
this->width = width;
this->height = height;
while( pixels.size() < width*height ) {
pixels.push_back( Color() );
}
}
void Image::open_png_alpha( string const &path ) {
png::image< png::rgba_pixel > image( path.c_str() );
size_t height = image.get_height();
size_t width = image.get_width();
set_size(width,height);
for(size_t y=0; y<height; ++y) {
for(size_t x=0; x<width; ++x) {
png::rgba_pixel p = image[y][x];
pixels[x+y*width] = Color(p.red/256.0,p.green/256.0,p.blue/256.0,p.alpha/256.0 );
}
}
}
void Image::open_png( string const &path ) {
png::image< png::rgb_pixel > image(path.c_str());
size_t height = image.get_height();
size_t width = image.get_width();
set_size(width,height);
for(size_t y=0; y<height; ++y) {
for(size_t x=0; x<width; ++x) {
png::rgb_pixel p = image[y][x];
Color &d = pixels[x+y*width];
d.r = rhizome::types::clamp(p.red/256.0);
d.g = rhizome::types::clamp(p.green/256.0);
d.b = rhizome::types::clamp(p.blue/256.0);
d.a = 1.0;
}
}
}
void Image::save_png_alpha( string const &path ) {
png::image< png::rgba_pixel > im(height,width);
for(size_t y=0; y<height; ++y) {
for(size_t x=0; x<width; ++x) {
png::rgba_pixel p;
p.red = std::floor(pixels[x+y*width].r*256.0);
p.green = std::floor(pixels[x+y*width].g*256.0);
p.blue = std::floor(pixels[x+y*width].b*256.0);
p.alpha = std::floor(pixels[x+y*width].a*256.0);
im[y][x] = p;
}
}
im.write(path.c_str());
}
void Image::save_png( string const &path ) {
png::image< png::rgb_pixel > im( height, width );
for(size_t y=0; y<height; ++y) {
for(size_t x=0; x<width; ++x) {
png::rgb_pixel p;
Color c = pixels[x+y*width];
p.red = std::floor(c.r*256.0);
p.green = std::floor(c.g*256.0);
p.blue = std::floor(c.b*256.0);
im[y][x] = p;
}
}
im.write( path.c_str() );
}
void Image::pset( size_t x, size_t y, Color const &c ) {
pixels[x + y*width] = c;
}
rhizome::types::Color
Image::pget( size_t x, size_t y ) {
return pixels[x+y*width];
}
void Image::checker_board( size_t h, size_t w, Color const &a, Color const &b ) {
for(size_t y=0; y<height; ++y) {
for(size_t x=0; x<width; ++x) {
pset(x,y,(y/h + x/w)%2==0 ? a : b );
}
}
}
rhizome::types::Color
from_quad( RGBQUAD const &q ) {
rhizome::types::Color c;
c.r = q.rgbRed/255.0;
c.g = q.rgbGreen/255.0;
c.b = q.rgbBlue/255.0;
return c;
}
RGBQUAD from_color( rhizome::types::Color const &c) {
RGBQUAD q;
q.rgbRed = (unsigned char) std::floor( 255.0*c.r );
q.rgbGreen = (unsigned char) std::floor( 255.0*c.g );
q.rgbBlue = (unsigned char) std::floor( 255.0*c.b );
return q;
}
bool
Image::freeimage_load( string const &path ) {
fipImage im;
if(im.load( path.c_str() )) {
set_size(im.getWidth(), im.getHeight());
for(size_t y=0; y<im.getHeight(); ++y) {
for(size_t x=0; x<im.getWidth(); ++x) {
RGBQUAD color;
im.getPixelColor(x,y,&color);
if( x==y && x==250 ) {
std::cout << ((int)color.rgbGreen) <<"\n";
}
pset( x,y, from_quad(color));
}
}
return true;
} else {
throw runtime_error("freeimage_load: could not load image");
}
}
void
Image::freeimage_save( string const &path ) {
fipImage im;
im.setSize(FREE_IMAGE_TYPE::FIT_BITMAP,width,height,8);
for(size_t y=0; y<height; ++y) {
for(size_t x=0; x<width; ++x) {
RGBQUAD q;
q = from_color(pget(x,y));
if( x==y && x==250 ) {
std::cout << ((int)q.rgbGreen)<<"\n";
}
im.setPixelColor(x,y,&q);
}
}
if( !FreeImage_Save(FIF_PNG,im, path.c_str()) ) {
throw runtime_error("Couldn't save image.");
}
}
void
Image::serialize_to( size_t level, ostream &out ) const {
(void) level;
out << "Image";
throw runtime_error("Not implemented.");
}
Thing *
Image::clone() const {
Image *copy = new Image(*this);
return copy;
}
string
Image::rhizome_type() const {
return "Image";
}
bool
Image::has_interface(string const &w) {
return (w==rhizome_type()||w=="Thing");
}
Thing *
Image::invoke( Thing *context, string const &method, Thing *arg ) {
(void)method;(void)arg;(void)context;
throw runtime_error("Nothing to invoke.");
}
}
}
| 33.030151
| 101
| 0.42492
|
nathanmullenax83
|
03857f744a5c019760a1a6de89003afbd4abe00b
| 8,545
|
cpp
|
C++
|
lazy-code/Teensy4LazyBoard/src/MessageManagement.cpp
|
william-redenbaugh/lazy-board
|
945d2c4c59a560141ee37f4d4eff84014eb997d7
|
[
"MIT"
] | 3
|
2020-06-07T04:09:27.000Z
|
2020-08-19T04:33:06.000Z
|
lazy-code/Teensy4LazyBoard/src/MessageManagement.cpp
|
william-redenbaugh/lazy-board
|
945d2c4c59a560141ee37f4d4eff84014eb997d7
|
[
"MIT"
] | 4
|
2020-06-09T18:15:44.000Z
|
2020-08-31T22:00:24.000Z
|
lazy-code/Teensy4LazyBoard/src/MessageManagement.cpp
|
william-redenbaugh/lazy-board
|
945d2c4c59a560141ee37f4d4eff84014eb997d7
|
[
"MIT"
] | null | null | null |
/*
Author: William Redenbaugh
Last Edit Date: 7/3/2020
*/
#include "MessageManagement.hpp"
/**************************************************************************/
/*!
@brief Starts up our serial interface for doing message management stuff
*/
/**************************************************************************/
void MessageManagement::begin(void){
// Doesn't really matter what we put in here
// It's always running at 12 megabits anyway!
Serial.begin(115200);
}
/**************************************************************************/
/*!
@brief Serial message unpacker the message management class. Will then connect data to other message unpacking functions.
*/
/**************************************************************************/
bool MessageManagement::run(void){
if(Serial.available() >= 16){
// Scoping the serial read and decoding so that it gets
// popped off the stack asap.
uint8_t message_instr_arr[16];
// Popping off the oldest 16 bytes of information
// for the message instruction data.
for(uint8_t i = 0; i < 16; i++)
message_instr_arr[i] = Serial.read();
// Message instruction unpacking
// Message unpacking instructions.
pb_istream_t msg_in = pb_istream_from_buffer(message_instr_arr, 16);
pb_decode(&msg_in, MessageData_fields, &this->latest_message_data);
return true;
}
return false;
}
/**************************************************************************/
/*!
@brief Serial message unpacker the message management class. Will then connect data to other message unpacking functions.
@returns MessageData information
*/
/**************************************************************************/
MessageData_MessageType MessageManagement::latest_message_enum(void){
return this->latest_message_data.message_type;
}
/**************************************************************************/
/*!
@returns the latest boolean value of the return message.
*/
/**************************************************************************/
bool MessageManagement::latest_return_message(void){
return this->latest_message_data.return_message;
}
/**************************************************************************/
/*!
@returns the latest size value of the return message.
*/
/**************************************************************************/
int32_t MessageManagement::return_message_size(void){
return this->latest_message_data.message_size;
}
/**************************************************************************/
/*!
@brief Unpacks message general instruction enumerated types.
*/
/**************************************************************************/
void MessageManagement::process_general_instructions(void){
// Array with latest package information.
uint8_t general_instr_buff[this->latest_message_data.message_size];
// Get latest data off serial device.
for(uint8_t i = 0; i < this->latest_message_data.message_size; i++)
general_instr_buff[i] = Serial.read();
pb_istream_t msg_in = pb_istream_from_buffer(general_instr_buff, this->latest_message_data.message_size);
pb_decode(&msg_in, GeneralInstructions_fields, &this->general_instructions);
}
/**************************************************************************/
/*!
@brief Processes keybinding information.
*/
/**************************************************************************/
void MessageManagement::process_keybinding_information(void){
uint8_t keybinding_buff[this->latest_message_data.message_size];
// Get latest data off serial device.
for(uint8_t i = 0; i < this->latest_message_data.message_size; i++)
keybinding_buff[i] = Serial.read();
pb_istream_t msg_in = pb_istream_from_buffer(keybinding_buff, this->latest_message_data.message_size);
pb_decode(&msg_in, ProgramKeybindings_fields, &this->latest_keybinding_info);
}
/**************************************************************************/
/*!
@returns latest keybinding information. should be called after process_keybinding_informatio()
*/
/**************************************************************************/
ProgramKeybindings MessageManagement::get_keybinding_information(void){
return this->latest_keybinding_info;
}
/**************************************************************************/
/*!
@returns latest image flash information. Should be called after the "process_image_data()" function
*/
/**************************************************************************/
ImageFlash MessageManagement::image_data_instructions(void){
return this->latest_image_flash_data;
}
/**************************************************************************/
/*!
@brief processes our latest image instruction data.
@note This does not process the actual image information, that data should still be in the Serial buffer. Might be changed later.
*/
/**************************************************************************/
void MessageManagement::process_image_data(void){
uint8_t image_data_buff [this->latest_message_data.message_size];
// Deserialize our instructions.
for(uint8_t i = 0; i < this->latest_message_data.message_size; i++)
image_data_buff[i] = Serial.read();
pb_istream_t msg_in = pb_istream_from_buffer(image_data_buff, this->latest_message_data.message_size);
pb_decode(&msg_in, ImageFlash_fields, &this->latest_image_flash_data);
}
/**************************************************************************/
/*!
@brief Processes rgb instructions
*/
/**************************************************************************/
void MessageManagement::process_rgb_instructions(void){
uint8_t rgb_data_buff[this->latest_message_data.message_size];
// Get latest data off serial device.
for(uint8_t i = 0; i < this->latest_message_data.message_size; i++)
rgb_data_buff[i] = Serial.read();
pb_istream_t msg_in = pb_istream_from_buffer(rgb_data_buff, this->latest_message_data.message_size);
pb_decode(&msg_in, GeneralRGBData_fields, &this->latest_general_rgb_data);
}
/**************************************************************************/
/*!
@returns latest keybinding information. should be called after process_keybinding_informatio()
*/
/**************************************************************************/
GeneralRGBData MessageManagement::get_rgb_general_instructions(void){
return latest_general_rgb_data;
}
/**************************************************************************/
/*!
@returns The latest general instruction data, should be called right after we know we got new general instruction data.
*/
/**************************************************************************/
GeneralInstructions_MainInstrEnum MessageManagement::get_latest_general_instructions(void){
this->process_general_instructions();
return this->general_instructions.main_instructions;
}
/**************************************************************************/
/*!
@brief Tests to make sure that protbuffer serialization and deserialization is working properly.
@returns boolean value that test was successful.
*/
/**************************************************************************/
bool MessageManagement::testing_message_protobuffers(void){
MessageData message_data_out;
message_data_out.message_size = 32;
message_data_out.message_type = MessageData_MessageType_GENERAL_INSTRUCTIONS;
// Put data into serialized format.
uint8_t buffer[16];
memset(buffer, 0, sizeof(buffer));
pb_ostream_t msg_out = pb_ostream_from_buffer(buffer, sizeof(buffer));
pb_encode(&msg_out, MessageData_fields, &message_data_out);
// Unpack serialsed data.
pb_istream_t msg_in = pb_istream_from_buffer(buffer, sizeof(buffer));
MessageData message_data_in;
pb_decode(&msg_in, MessageData_fields, &message_data_in);
if(message_data_in.message_size == message_data_out.message_size && message_data_in.message_type == message_data_out.message_type)
return true;
return false;
}
| 42.512438
| 135
| 0.536337
|
william-redenbaugh
|
03878367d1516b142bd72beac2ad6a9f334095d0
| 1,391
|
cpp
|
C++
|
numerical_methods/qr_decomposition.cpp
|
dvijaymanohar/C-Plus-Plus
|
c987381c25858f08d0fe9301712ab6c1a10b433f
|
[
"MIT"
] | null | null | null |
numerical_methods/qr_decomposition.cpp
|
dvijaymanohar/C-Plus-Plus
|
c987381c25858f08d0fe9301712ab6c1a10b433f
|
[
"MIT"
] | null | null | null |
numerical_methods/qr_decomposition.cpp
|
dvijaymanohar/C-Plus-Plus
|
c987381c25858f08d0fe9301712ab6c1a10b433f
|
[
"MIT"
] | null | null | null |
/**
* @file
* \brief Program to compute the [QR
* decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a given
* matrix.
* \author [Krishna Vedala](https://github.com/kvedala)
*/
#include <array>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include "./qr_decompose.h"
using qr_algorithm::qr_decompose;
using qr_algorithm::operator<<;
/**
* main function
*/
int main(void)
{
unsigned int ROWS, COLUMNS;
std::cout << "Enter the number of rows and columns: ";
std::cin >> ROWS >> COLUMNS;
std::cout << "Enter matrix elements row-wise:\n";
std::valarray<std::valarray<double>> A(ROWS);
std::valarray<std::valarray<double>> Q(ROWS);
std::valarray<std::valarray<double>> R(COLUMNS);
for (int i = 0; i < std::max(ROWS, COLUMNS); i++)
{
if (i < ROWS)
{
A[i] = std::valarray<double>(COLUMNS);
Q[i] = std::valarray<double>(COLUMNS);
}
if (i < COLUMNS)
{
R[i] = std::valarray<double>(COLUMNS);
}
}
for (int i = 0; i < ROWS; i++)
for (int j = 0; j < COLUMNS; j++) { std::cin >> A[i][j]; }
std::cout << A << "\n";
clock_t t1 = clock();
qr_decompose(A, &Q, &R);
double dtime = static_cast<double>(clock() - t1) / CLOCKS_PER_SEC;
std::cout << Q << "\n";
std::cout << R << "\n";
std::cout << "Time taken to compute: " << dtime << " sec\n ";
return 0;
}
| 23.576271
| 76
| 0.588066
|
dvijaymanohar
|
0387a307cd2e5a042924d2516566ba5618be1686
| 29
|
hpp
|
C++
|
src/boost_icl_set.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_icl_set.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_icl_set.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/icl/set.hpp>
| 14.5
| 28
| 0.724138
|
miathedev
|
0389994bab6e2f4250852f92faced8ab6ab7fe9b
| 4,025
|
cpp
|
C++
|
cppwinrt/Scenario5_TimeZone.cpp
|
lyahdav/CppWinRtUwpSandbox
|
aad073b768031589cb1165ce8e95cdf8897e35f6
|
[
"MIT"
] | 2,504
|
2019-05-07T06:56:42.000Z
|
2022-03-31T19:37:59.000Z
|
cppwinrt/Scenario5_TimeZone.cpp
|
lyahdav/CppWinRtUwpSandbox
|
aad073b768031589cb1165ce8e95cdf8897e35f6
|
[
"MIT"
] | 314
|
2019-05-08T16:56:30.000Z
|
2022-03-21T07:13:45.000Z
|
cppwinrt/Scenario5_TimeZone.cpp
|
lyahdav/CppWinRtUwpSandbox
|
aad073b768031589cb1165ce8e95cdf8897e35f6
|
[
"MIT"
] | 2,219
|
2019-05-07T00:47:26.000Z
|
2022-03-30T21:12:31.000Z
|
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "pch.h"
#include "Scenario5_TimeZone.h"
#include "Scenario5_TimeZone.g.cpp"
using namespace winrt;
using namespace Windows::Foundation;
using namespace Windows::Globalization;
using namespace Windows::UI::Xaml;
namespace
{
void ReportCalendarData(std::wostream& results, Calendar const& calendar)
{
// Display individual date/time elements.
results <<
L"In " << std::wstring_view(calendar.GetTimeZone()) <<
L" time zone: " << std::wstring_view(calendar.DayOfWeekAsSoloString()) <<
L" " << std::wstring_view(calendar.MonthAsSoloString()) <<
L" " << std::wstring_view(calendar.DayAsPaddedString(2)) <<
L", " << std::wstring_view(calendar.YearAsString()) <<
L" " << std::wstring_view(calendar.HourAsPaddedString(2)) <<
L":" << std::wstring_view(calendar.MinuteAsPaddedString(2)) <<
L":" << std::wstring_view(calendar.SecondAsPaddedString(2)) <<
L" " << std::wstring_view(calendar.PeriodAsString()) <<
L" " << std::wstring_view(calendar.TimeZoneAsString(3)) <<
L"\n";
}
}
namespace winrt::SDKTemplate::implementation
{
Scenario5_TimeZone::Scenario5_TimeZone()
{
InitializeComponent();
}
void Scenario5_TimeZone::ShowResults_Click(IInspectable const&, RoutedEventArgs const&)
{
// This scenario illustrates time zone support in Windows.Globalization.Calendar class
// Displayed time zones in addition to the local time zone.
std::array timeZones{ L"UTC", L"America/New_York", L"Asia/Kolkata" };
// Store results here.
std::wostringstream results;
// Create default Calendar object
Calendar calendar;
hstring localTimeZone = calendar.GetTimeZone();
// Show current time in local time zone
results << L"Current date and time:\n";
ReportCalendarData(results, calendar);
results << L"\n";
// Show current time in additional time zones
for (auto&& timeZone : timeZones)
{
calendar.ChangeTimeZone(timeZone);
ReportCalendarData(results, calendar);
}
results << L"\n";
// Change back to local time zone
calendar.ChangeTimeZone(localTimeZone);
// Show a time on 14th day of second month of next year.
// Note the effect of daylight saving time on the results.
results << L"Same time on 14th day of second month of next year:\n";
calendar.AddYears(1); calendar.Month(2); calendar.Day(14);
ReportCalendarData(results, calendar);
for (auto&& timeZone : timeZones)
{
calendar.ChangeTimeZone(timeZone);
ReportCalendarData(results, calendar);
}
results << L"\n";
// Change back to local time zone
calendar.ChangeTimeZone(localTimeZone);
// Show a time on 14th day of tenth month of next year.
// Note the effect of daylight saving time on the results.
results << L"Same time on 14th day of tenth month of next year:\n";
calendar.AddMonths(8);
ReportCalendarData(results, calendar);
for (auto&& timeZone : timeZones)
{
calendar.ChangeTimeZone(timeZone);
ReportCalendarData(results, calendar);
}
results << L"\n";
// Display the results
OutputTextBlock().Text(results.str());
}
}
| 36.926606
| 95
| 0.59354
|
lyahdav
|
038bcc76f8b5878b30a9e9afed1879afa03d5161
| 98
|
hpp
|
C++
|
day07/part2.hpp
|
Moremar/advent_of_code_2016
|
dea264671fc2c31baa42b1282751dfd1ae071a7d
|
[
"Apache-2.0"
] | null | null | null |
day07/part2.hpp
|
Moremar/advent_of_code_2016
|
dea264671fc2c31baa42b1282751dfd1ae071a7d
|
[
"Apache-2.0"
] | null | null | null |
day07/part2.hpp
|
Moremar/advent_of_code_2016
|
dea264671fc2c31baa42b1282751dfd1ae071a7d
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "part1.hpp"
namespace Part2 {
int solve(const vector<IPv7> &ipv7s);
}
| 12.25
| 41
| 0.683673
|
Moremar
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.