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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5806a5ead19491e1c86e80cb17d2578fdb96bea8
| 2,431
|
cpp
|
C++
|
src/border.cpp
|
Arian8j2/YourCraft
|
6afe4e50afe678e2d38b60e816adf0a9d320f01a
|
[
"MIT"
] | 4
|
2021-03-02T21:02:51.000Z
|
2021-11-19T22:16:05.000Z
|
src/border.cpp
|
Arian8j2/YourCraft
|
6afe4e50afe678e2d38b60e816adf0a9d320f01a
|
[
"MIT"
] | null | null | null |
src/border.cpp
|
Arian8j2/YourCraft
|
6afe4e50afe678e2d38b60e816adf0a9d320f01a
|
[
"MIT"
] | null | null | null |
#include "border.h"
#include "player.h"
CBorder::CBorder(CGameContext* pGameContext): m_pGameContext(pGameContext){
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
float aVerticies[] = {
-0.5f, 0.5f, 0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, 0.5f, -0.5f,
-0.5f, 0.5f, 0.5f,
-0.5f, -0.5f, 0.5f,
-0.5f, -0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, 0.5f, 0.5f,
0.5f, -0.5f, 0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, 0.5f, -0.5f,
0.5f, 0.5f, -0.5f,
0.5f, -0.5f, -0.5f,
-0.5f, -0.5f, -0.5f
};
glBufferData(GL_ARRAY_BUFFER, sizeof(aVerticies), aVerticies, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, false, sizeof(float)*3, 0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(float)*3, 0);
glEnableVertexAttribArray(1);
glLineWidth(1.5f);
}
void CBorder::Render(glm::vec3& Pos){
glUseProgram(m_pGameContext->GetBlockProgram());
static uint32_t s_BlockPosUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uBlockPos");
static uint32_t s_PlayerViewUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uView");
static uint32_t s_ProjectionUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uProjection");
static uint32_t s_ColorUniform = glGetUniformLocation(m_pGameContext->GetBlockProgram(), "uColor");
glm::mat4 MatPos(1.0f);
MatPos[3] = glm::vec4(Pos, 1.0f);
static glm::mat4 s_Projection = glm::perspective(glm::radians((float) m_pGameContext->GetSettingValue("fov").GetInt()), (float)m_pGameContext->m_Width / m_pGameContext->m_Height, 0.101f, 100.0f);
glBindVertexArray(m_VAO);
glUniformMatrix4fv(s_BlockPosUniform, 1, 0, glm::value_ptr(MatPos));
glUniformMatrix4fv(s_PlayerViewUniform, 1, 0, glm::value_ptr(m_pGameContext->GetPlayer()->m_View));
glUniformMatrix4fv(s_ProjectionUniform, 1, 0, glm::value_ptr(s_Projection));
glUniform3f(s_ColorUniform, 0.0f, 0.0f, 0.0f);
glBindVertexArray(m_VAO);
for(int i=0; i < 4; i++)
glDrawArrays(GL_LINE_LOOP, i*4, 4);
}
CBorder::~CBorder(){
glDeleteVertexArrays(1, &m_VAO);
glDeleteBuffers(1, &m_VBO);
}
| 33.30137
| 199
| 0.640889
|
Arian8j2
|
580b0dd7cdf7930b6cb85c6e67947634df7d42a1
| 4,742
|
hpp
|
C++
|
engine/source/public/core/anton_crt.hpp
|
kociap/GameEngine
|
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
|
[
"MIT"
] | 12
|
2019-01-02T11:13:19.000Z
|
2020-06-02T10:58:20.000Z
|
engine/source/public/core/anton_crt.hpp
|
kociap/GameEngine
|
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
|
[
"MIT"
] | null | null | null |
engine/source/public/core/anton_crt.hpp
|
kociap/GameEngine
|
ff5f1ca589df5b44887c3383919a73bbe0ab05a0
|
[
"MIT"
] | 1
|
2020-04-03T11:54:53.000Z
|
2020-04-03T11:54:53.000Z
|
#pragma once
#if defined(_WIN64)
#define ANTON_NOEXCEPT
#define ANTON_CRT_IMPORT __declspec(dllimport)
#define size_t unsigned long long
#else
#define ANTON_NOEXCEPT noexcept
#define ANTON_CRT_IMPORT
#define size_t unsigned long int
#endif
// C Runtime Forward Declarations
extern "C" {
// stddef.h
#ifndef offsetof
#define offsetof(s,m) __builtin_offsetof(s,m)
#endif
// time.h
struct timespec;
// math.h
ANTON_CRT_IMPORT float powf(float, float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float sqrtf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float cbrtf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float roundf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float floorf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float ceilf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float modff(float, float*) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float sinf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float cosf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float tanf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float asinf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float acosf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float atanf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float atan2f(float, float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float expf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float logf(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float log10f(float) ANTON_NOEXCEPT;
ANTON_CRT_IMPORT float log2f(float) ANTON_NOEXCEPT;
// string.h
// memset, memmove, memcpy, strlen don't use dllimport on win.
void* memset(void* dest, int value, size_t count);
void* memcpy(void* dest, void const* src, size_t count);
void* memmove(void* dest, void const* src, size_t count);
int memcmp(void const* lhs, void const* rhs, size_t count);
size_t strlen(char const* string);
// stdlib.h
ANTON_CRT_IMPORT float strtof(char const*, char**);
ANTON_CRT_IMPORT double strtod(char const*, char**);
ANTON_CRT_IMPORT long long strtoll(char const*, char**, int base);
ANTON_CRT_IMPORT unsigned long long strtoull(char const*, char**, int base);
// stdio.h
#if defined(_WIN64)
#ifndef _FILE_DEFINED
#define _FILE_DEFINED
typedef struct _iobuf {
void* _Placeholder;
} FILE;
#endif
ANTON_CRT_IMPORT FILE* __acrt_iob_func(unsigned _Ix);
#define stdin (__acrt_iob_func(0))
#define stdout (__acrt_iob_func(1))
#define stderr (__acrt_iob_func(2))
#else
#ifndef __FILE_defined
#define __FILE_defined 1
typedef struct _IO_FILE FILE;
#endif
extern FILE* stdin;
extern FILE* stdout;
extern FILE* stderr;
#endif
#define SEEK_SET 0
#define SEEK_CUR 1
#define SEEK_END 2
#define EOF (-1)
#if defined(_WIN64)
#define ANTON_CRT_STDIO_NOEXCEPT
#else
#define ANTON_CRT_STDIO_NOEXCEPT noexcept
#endif
ANTON_CRT_IMPORT FILE* fopen(char const* filename, char const* modes);
ANTON_CRT_IMPORT FILE* freopen(char const* filename, char const* mode, FILE* stream);
ANTON_CRT_IMPORT int fclose(FILE* stream);
ANTON_CRT_IMPORT int fflush(FILE* stream);
ANTON_CRT_IMPORT void setbuf(FILE* stream, char* buffer) ANTON_CRT_STDIO_NOEXCEPT;
ANTON_CRT_IMPORT int setvbuf(FILE* stream, char* buffer, int mode, size_t size) ANTON_CRT_STDIO_NOEXCEPT;
ANTON_CRT_IMPORT size_t fread(void* buffer, size_t size, size_t count, FILE* stream);
ANTON_CRT_IMPORT size_t fwrite(void const* buffer, size_t size, size_t count, FILE* stream);
ANTON_CRT_IMPORT int fgetc(FILE* stream);
ANTON_CRT_IMPORT char* fgets(char*, int count, FILE* stream);
ANTON_CRT_IMPORT char* gets(char* string);
ANTON_CRT_IMPORT int getchar(void);
ANTON_CRT_IMPORT int fputc(int ch, FILE* stream);
ANTON_CRT_IMPORT int fputs(char const* string, FILE* stream);
ANTON_CRT_IMPORT int puts(char const* string);
ANTON_CRT_IMPORT int putchar(int ch);
ANTON_CRT_IMPORT int ungetc(int ch, FILE* stream);
ANTON_CRT_IMPORT long ftell(FILE* stream);
ANTON_CRT_IMPORT int fseek(FILE* stream, long offset, int origin);
ANTON_CRT_IMPORT void rewind(FILE* stream);
ANTON_CRT_IMPORT int ferror(FILE* stream) ANTON_CRT_STDIO_NOEXCEPT;
ANTON_CRT_IMPORT int feof(FILE* stream) ANTON_CRT_STDIO_NOEXCEPT;
ANTON_CRT_IMPORT void clearerr(FILE* stream) ANTON_CRT_STDIO_NOEXCEPT;
#undef ANTON_CRT_STDIO_NOEXCEPT
}
// C++ Runtime Forward Declarations
void* operator new(size_t size, void*) noexcept;
void operator delete(void* ptr, void* place) noexcept;
#undef ANTON_CRT_IMPORT
#undef size_t
| 34.362319
| 109
| 0.715943
|
kociap
|
580b1ef2bd4ec2ab59c00d0adbdb9f9e5d84f163
| 26,436
|
cpp
|
C++
|
ros/src/computing/perception/detection/fusion_tools/packages/range_vision_fusion/src/range_vision_fusion.cpp
|
AftermathK/Autoware
|
88a1f088eba5878d88e95ecb88cd9389a4bad4b3
|
[
"BSD-3-Clause"
] | 2
|
2019-01-29T10:50:56.000Z
|
2021-12-20T07:20:13.000Z
|
ros/src/computing/perception/detection/fusion_tools/packages/range_vision_fusion/src/range_vision_fusion.cpp
|
ShawnSchaerer/Autoware
|
c2ba68b4e9f42136e6f055a9cd278dcebdcbab17
|
[
"BSD-3-Clause"
] | null | null | null |
ros/src/computing/perception/detection/fusion_tools/packages/range_vision_fusion/src/range_vision_fusion.cpp
|
ShawnSchaerer/Autoware
|
c2ba68b4e9f42136e6f055a9cd278dcebdcbab17
|
[
"BSD-3-Clause"
] | 2
|
2019-01-29T10:51:00.000Z
|
2020-09-13T04:52:44.000Z
|
/*
* Copyright (c) 2018, Nagoya University
* 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 Autoware 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.
********************
* v1.0: amc-nu (abrahammonrroy@yahoo.com)
*
* range_vision_fusion_node.cpp
*
* Created on: July, 05th, 2018
*/
#include "range_vision_fusion/range_vision_fusion.h"
cv::Point3f
RosRangeVisionFusionApp::TransformPoint(const geometry_msgs::Point &in_point, const tf::StampedTransform &in_transform)
{
tf::Vector3 tf_point(in_point.x, in_point.y, in_point.z);
tf::Vector3 tf_point_t = in_transform * tf_point;
return cv::Point3f(tf_point_t.x(), tf_point_t.y(), tf_point_t.z());
}
cv::Point2i
RosRangeVisionFusionApp::ProjectPoint(const cv::Point3f &in_point)
{
auto u = int(in_point.x * fx_ / in_point.z + cx_);
auto v = int(in_point.y * fy_ / in_point.z + cy_);
return cv::Point2i(u, v);
}
autoware_msgs::DetectedObject
RosRangeVisionFusionApp::TransformObject(const autoware_msgs::DetectedObject &in_detection,
const tf::StampedTransform& in_transform)
{
autoware_msgs::DetectedObject t_obj = in_detection;
tf::Vector3 in_pos(in_detection.pose.position.x,
in_detection.pose.position.y,
in_detection.pose.position.z);
tf::Quaternion in_quat(in_detection.pose.orientation.x,
in_detection.pose.orientation.y,
in_detection.pose.orientation.w,
in_detection.pose.orientation.z);
tf::Vector3 in_pos_t = in_transform * in_pos;
tf::Quaternion in_quat_t = in_transform * in_quat;
t_obj.pose.position.x = in_pos_t.x();
t_obj.pose.position.y = in_pos_t.y();
t_obj.pose.position.z = in_pos_t.z();
t_obj.pose.orientation.x = in_quat_t.x();
t_obj.pose.orientation.y = in_quat_t.y();
t_obj.pose.orientation.z = in_quat_t.z();
t_obj.pose.orientation.w = in_quat_t.w();
return t_obj;
}
bool
RosRangeVisionFusionApp::IsObjectInImage(const autoware_msgs::DetectedObject &in_detection)
{
cv::Point3f image_space_point = TransformPoint(in_detection.pose.position, camera_lidar_tf_);
cv::Point2i image_pixel = ProjectPoint(image_space_point);
return (image_pixel.x >= 0)
&& (image_pixel.x < image_size_.width)
&& (image_pixel.y >= 0)
&& (image_pixel.y < image_size_.height)
&& (image_space_point.z > 0);
}
cv::Rect RosRangeVisionFusionApp::ProjectDetectionToRect(const autoware_msgs::DetectedObject &in_detection)
{
cv::Rect projected_box;
Eigen::Vector3f pos;
pos << in_detection.pose.position.x,
in_detection.pose.position.y,
in_detection.pose.position.z;
Eigen::Quaternionf rot(in_detection.pose.orientation.w,
in_detection.pose.orientation.x,
in_detection.pose.orientation.y,
in_detection.pose.orientation.z);
std::vector<double> dims = {in_detection.dimensions.x,
in_detection.dimensions.y,
in_detection.dimensions.z};
jsk_recognition_utils::Cube cube(pos, rot, dims);
Eigen::Affine3f range_vision_tf;
tf::transformTFToEigen(camera_lidar_tf_, range_vision_tf);
jsk_recognition_utils::Vertices vertices = cube.transformVertices(range_vision_tf);
std::vector<cv::Point> polygon;
for (auto &vertex : vertices)
{
cv::Point p = ProjectPoint(cv::Point3f(vertex.x(), vertex.y(), vertex.z()));
polygon.push_back(p);
}
projected_box = cv::boundingRect(polygon);
return projected_box;
}
void
RosRangeVisionFusionApp::TransformRangeToVision(const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections,
autoware_msgs::DetectedObjectArray &out_in_cv_range_detections,
autoware_msgs::DetectedObjectArray &out_out_cv_range_detections)
{
out_in_cv_range_detections.header = in_range_detections->header;
out_in_cv_range_detections.objects.clear();
out_out_cv_range_detections.header = in_range_detections->header;
out_out_cv_range_detections.objects.clear();
for (size_t i= 0; i < in_range_detections->objects.size(); i++)
{
if(IsObjectInImage(in_range_detections->objects[i]))
{
out_in_cv_range_detections.objects.push_back(in_range_detections->objects[i]);
}
else
{
out_out_cv_range_detections.objects.push_back(in_range_detections->objects[i]);
}
}
}
void
RosRangeVisionFusionApp::CalculateObjectFeatures(autoware_msgs::DetectedObject &in_out_object, bool in_estimate_pose)
{
float min_x=std::numeric_limits<float>::max();float max_x=-std::numeric_limits<float>::max();
float min_y=std::numeric_limits<float>::max();float max_y=-std::numeric_limits<float>::max();
float min_z=std::numeric_limits<float>::max();float max_z=-std::numeric_limits<float>::max();
float average_x = 0, average_y = 0, average_z = 0, length, width, height;
pcl::PointXYZ centroid, min_point, max_point, average_point;
std::vector<cv::Point2f> object_2d_points;
pcl::PointCloud<pcl::PointXYZ> in_cloud;
pcl::fromROSMsg(in_out_object.pointcloud, in_cloud);
for (const auto &point : in_cloud.points)
{
average_x+=point.x; average_y+=point.y; average_z+=point.z;
centroid.x += point.x; centroid.y += point.y; centroid.z += point.z;
if(point.x<min_x) min_x = point.x;
if(point.y<min_y) min_y = point.y;
if(point.z<min_z) min_z = point.z;
if(point.x>max_x) max_x = point.x;
if(point.y>max_y) max_y = point.y;
if(point.z>max_z) max_z = point.z;
cv::Point2f pt;
pt.x = point.x;
pt.y = point.y;
object_2d_points.push_back(pt);
}
min_point.x = min_x; min_point.y = min_y; min_point.z = min_z;
max_point.x = max_x; max_point.y = max_y; max_point.z = max_z;
if (in_cloud.points.size() > 0)
{
centroid.x /= in_cloud.points.size();
centroid.y /= in_cloud.points.size();
centroid.z /= in_cloud.points.size();
average_x /= in_cloud.points.size();
average_y /= in_cloud.points.size();
average_z /= in_cloud.points.size();
}
average_point.x = average_x; average_point.y = average_y; average_point.z = average_z;
length = max_point.x - min_point.x;
width = max_point.y - min_point.y;
height = max_point.z - min_point.z;
geometry_msgs::PolygonStamped convex_hull;
std::vector<cv::Point2f> hull_points;
if (object_2d_points.size() > 0)
cv::convexHull(object_2d_points, hull_points);
convex_hull.header = in_out_object.header;
for (size_t i = 0; i < hull_points.size() + 1 ; i++)
{
geometry_msgs::Point32 point;
point.x = hull_points[i%hull_points.size()].x;
point.y = hull_points[i%hull_points.size()].y;
point.z = min_point.z;
convex_hull.polygon.points.push_back(point);
}
for (size_t i = 0; i < hull_points.size() + 1 ; i++)
{
geometry_msgs::Point32 point;
point.x = hull_points[i%hull_points.size()].x;
point.y = hull_points[i%hull_points.size()].y;
point.z = max_point.z;
convex_hull.polygon.points.push_back(point);
}
double rz = 0;
if (in_estimate_pose)
{
cv::RotatedRect box = cv::minAreaRect(hull_points);
rz = box.angle*3.14/180;
in_out_object.pose.position.x = box.center.x;
in_out_object.pose.position.y = box.center.y;
in_out_object.dimensions.x = box.size.width;
in_out_object.dimensions.y = box.size.height;
}
in_out_object.convex_hull = convex_hull;
in_out_object.pose.position.x = min_point.x + length/2;
in_out_object.pose.position.y = min_point.y + width/2;
in_out_object.pose.position.z = min_point.z + height/2;
in_out_object.dimensions.x = ((length<0)?-1*length:length);
in_out_object.dimensions.y = ((width<0)?-1*width:width);
in_out_object.dimensions.z = ((height<0)?-1*height:height);
tf::Quaternion quat = tf::createQuaternionFromRPY(0.0, 0.0, rz);
tf::quaternionTFToMsg(quat, in_out_object.pose.orientation);
}
autoware_msgs::DetectedObject RosRangeVisionFusionApp::MergeObjects(const autoware_msgs::DetectedObject &in_object_a,
const autoware_msgs::DetectedObject & in_object_b)
{
autoware_msgs::DetectedObject object_merged;
object_merged = in_object_b;
pcl::PointCloud<pcl::PointXYZ> cloud_a, cloud_b, cloud_merged;
if (!in_object_a.pointcloud.data.empty())
pcl::fromROSMsg(in_object_a.pointcloud, cloud_a);
if (!in_object_b.pointcloud.data.empty())
pcl::fromROSMsg(in_object_b.pointcloud, cloud_b);
cloud_merged = cloud_a + cloud_b;
sensor_msgs::PointCloud2 cloud_msg;
pcl::toROSMsg(cloud_merged, cloud_msg);
cloud_msg.header = object_merged.pointcloud.header;
object_merged.pointcloud = cloud_msg;
return object_merged;
}
double RosRangeVisionFusionApp::GetDistanceToObject(const autoware_msgs::DetectedObject &in_object)
{
return sqrt(in_object.dimensions.x*in_object.dimensions.x +
in_object.dimensions.y*in_object.dimensions.y +
in_object.dimensions.z*in_object.dimensions.z);
}
autoware_msgs::DetectedObjectArray
RosRangeVisionFusionApp::FuseRangeVisionDetections(const autoware_msgs::DetectedObjectArray::ConstPtr &in_vision_detections,
const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections)
{
autoware_msgs::DetectedObjectArray range_in_cv;
autoware_msgs::DetectedObjectArray range_out_cv;
TransformRangeToVision(in_range_detections, range_in_cv, range_out_cv);
autoware_msgs::DetectedObjectArray fused_objects;
fused_objects.header = in_range_detections->header;
std::vector< std::vector<size_t> > vision_range_assignments (in_vision_detections->objects.size());
std::vector< long > vision_range_closest (in_vision_detections->objects.size());
for (size_t i = 0; i < in_vision_detections->objects.size(); i++)
{
auto vision_object = in_vision_detections->objects[i];
cv::Rect vision_rect(vision_object.x, vision_object.y,
vision_object.width, vision_object.height);
int vision_rect_area = vision_rect.area();
long closest_index = -1;
double closest_distance = std::numeric_limits<double>::max();
for (size_t j = 0; j < range_in_cv.objects.size(); j++)
{
double current_distance = GetDistanceToObject(range_in_cv.objects[j]);
cv::Rect range_rect = ProjectDetectionToRect(range_in_cv.objects[j]);
int range_rect_area = range_rect.area();
cv::Rect overlap = range_rect & vision_rect;
if ( (overlap.area() > range_rect_area*overlap_threshold_)
|| (overlap.area() > vision_rect_area*overlap_threshold_)
)
{
vision_range_assignments[i].push_back(j);
range_in_cv.objects[j].score = vision_object.score;
range_in_cv.objects[j].label = vision_object.label;
range_in_cv.objects[j].color = vision_object.color;
range_in_cv.objects[j].image_frame = vision_object.image_frame;
range_in_cv.objects[j].x = vision_object.x;
range_in_cv.objects[j].y = vision_object.y;
range_in_cv.objects[j].width = vision_object.width;
range_in_cv.objects[j].height = vision_object.height;
range_in_cv.objects[j].angle = vision_object.angle;
if(current_distance < closest_distance)
{
closest_index = j;
closest_distance = current_distance;
}
}
}
vision_range_closest[i] = closest_index;
}
std::vector<bool> used_range_detections(range_in_cv.objects.size(), false);
//only assign the closest
for(size_t i = 0; i < vision_range_assignments.size(); i++)
{
if(!range_in_cv.objects.empty() && vision_range_closest[i] >= 0)
{
used_range_detections[i] = true;
fused_objects.objects.push_back(range_in_cv.objects[vision_range_closest[i]]);
}
}
/*
for(size_t i = 0; i < vision_range_assignments.size(); i++)
{
autoware_msgs::DetectedObject merged_object = range_in_cv.objects[0];
for(const auto& range_detection_idx: vision_range_assignments[i])
{
if(merged_object.label == range_in_cv.objects[range_detection_idx].label)
{
used_range_detections[range_detection_idx] = true;
merged_object = MergeObjects(merged_object, range_in_cv.objects[range_detection_idx]);
}
}
if(!vision_range_assignments[i].empty())
{
CalculateObjectFeatures(merged_object, true);
fused_objects.objects.push_back(merged_object);
}
}*/
//add objects outside image
for(size_t i=0; i < range_out_cv.objects.size(); i++)
{
fused_objects.objects.push_back(range_out_cv.objects[i]);
}
return fused_objects;
}
void
RosRangeVisionFusionApp::SyncedDetectionsCallback(const autoware_msgs::DetectedObjectArray::ConstPtr &in_vision_detections,
const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections)
{
autoware_msgs::DetectedObjectArray fusion_objects;
jsk_recognition_msgs::BoundingBoxArray fused_boxes;
visualization_msgs::MarkerArray fused_objects_labels;
if (nullptr == in_vision_detections ||
nullptr == in_range_detections)
{
ROS_INFO("[%s] Empty Detections, check that vision and range detectors are running and publishing.", __APP_NAME__);
if (empty_frames_ > 5)
{
publisher_fused_objects_.publish(fusion_objects);
publisher_fused_boxes_.publish(fused_boxes);
publisher_fused_text_.publish(fused_objects_labels);
empty_frames_++;
}
return;
}
if (!camera_lidar_tf_ok_)
{
camera_lidar_tf_ = FindTransform(image_frame_id_,
in_range_detections->header.frame_id);
}
if(
!camera_lidar_tf_ok_ ||
!camera_info_ok_)
{
ROS_INFO("[%s] Missing Camera-LiDAR TF or CameraInfo", __APP_NAME__);
return;
}
fusion_objects = FuseRangeVisionDetections(in_vision_detections, in_range_detections);
fused_boxes = ObjectsToBoxes(fusion_objects);
fused_objects_labels = ObjectsToMarkers(fusion_objects);
publisher_fused_objects_.publish(fusion_objects);
publisher_fused_boxes_.publish(fused_boxes);
publisher_fused_text_.publish(fused_objects_labels);
empty_frames_ = 0;
vision_detections_ = nullptr;
range_detections_ = nullptr;
}
visualization_msgs::MarkerArray
RosRangeVisionFusionApp::ObjectsToMarkers(const autoware_msgs::DetectedObjectArray &in_objects)
{
visualization_msgs::MarkerArray final_markers;
for(const autoware_msgs::DetectedObject& object : in_objects.objects)
{
if (object.label != "unknown")
{
visualization_msgs::Marker marker;
marker.header = in_objects.header;
marker.ns = "range_vision_fusion";
marker.id = object.id;
marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING;
marker.scale.z = 1.0;
marker.text = object.label;
marker.pose.position = object.pose.position;
marker.pose.position.z += 1.5;
marker.color.r = 1.0;
marker.color.g = 1.0;
marker.color.b = 1.0;
marker.color.a = 1.0;
marker.scale.x = 1.5;
marker.scale.y = 1.5;
marker.scale.z = 1.5;
marker.lifetime = ros::Duration(0.1);
final_markers.markers.push_back(marker);
}
}
return final_markers;
}
jsk_recognition_msgs::BoundingBoxArray
RosRangeVisionFusionApp::ObjectsToBoxes(const autoware_msgs::DetectedObjectArray &in_objects)
{
jsk_recognition_msgs::BoundingBoxArray final_boxes;
final_boxes.header = in_objects.header;
for(const autoware_msgs::DetectedObject& object : in_objects.objects)
{
jsk_recognition_msgs::BoundingBox box;
box.header = in_objects.header;
box.label = object.id;
box.dimensions = object.dimensions;
box.pose = object.pose;
box.value = object.score;
final_boxes.boxes.push_back(box);
}
return final_boxes;
}
void
RosRangeVisionFusionApp::VisionDetectionsCallback(const autoware_msgs::DetectedObjectArray::ConstPtr &in_vision_detections)
{
if (!processing_ && !in_vision_detections->objects.empty())
{
processing_ = true;
vision_detections_ = in_vision_detections;
SyncedDetectionsCallback(in_vision_detections, range_detections_);
processing_ = false;
}
}
void
RosRangeVisionFusionApp::RangeDetectionsCallback(const autoware_msgs::DetectedObjectArray::ConstPtr &in_range_detections)
{
if (!processing_ && !in_range_detections->objects.empty())
{
processing_ = true;
range_detections_ = in_range_detections;
SyncedDetectionsCallback(vision_detections_, in_range_detections);
processing_ = false;
}
}
void RosRangeVisionFusionApp::ImageCallback(const sensor_msgs::Image::ConstPtr &in_image_msg)
{
if(!camera_info_ok_)
return;
cv_bridge::CvImagePtr cv_image = cv_bridge::toCvCopy(in_image_msg, "bgr8");
cv::Mat in_image = cv_image->image;
cv::Mat undistorted_image;
cv::undistort(in_image, image_, camera_instrinsics_, distortion_coefficients_);
};
void
RosRangeVisionFusionApp::IntrinsicsCallback(const sensor_msgs::CameraInfo &in_message)
{
image_size_.height = in_message.height;
image_size_.width = in_message.width;
camera_instrinsics_ = cv::Mat(3, 3, CV_64F);
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
camera_instrinsics_.at<double>(row, col) = in_message.K[row * 3 + col];
}
}
distortion_coefficients_ = cv::Mat(1, 5, CV_64F);
for (int col = 0; col < 5; col++)
{
distortion_coefficients_.at<double>(col) = in_message.D[col];
}
fx_ = static_cast<float>(in_message.P[0]);
fy_ = static_cast<float>(in_message.P[5]);
cx_ = static_cast<float>(in_message.P[2]);
cy_ = static_cast<float>(in_message.P[6]);
intrinsics_subscriber_.shutdown();
camera_info_ok_ = true;
image_frame_id_ = in_message.header.frame_id;
ROS_INFO("[%s] CameraIntrinsics obtained.", __APP_NAME__);
}
tf::StampedTransform
RosRangeVisionFusionApp::FindTransform(const std::string &in_target_frame, const std::string &in_source_frame)
{
tf::StampedTransform transform;
ROS_INFO("%s - > %s", in_source_frame.c_str(), in_target_frame.c_str());
camera_lidar_tf_ok_ = false;
try
{
transform_listener_->lookupTransform(in_target_frame, in_source_frame, ros::Time(0), transform);
camera_lidar_tf_ok_ = true;
ROS_INFO("[%s] Camera-Lidar TF obtained", __APP_NAME__);
}
catch (tf::TransformException &ex)
{
ROS_ERROR("[%s] %s", __APP_NAME__, ex.what());
}
return transform;
}
void
RosRangeVisionFusionApp::InitializeRosIo(ros::NodeHandle &in_private_handle)
{
//get params
std::string camera_info_src, detected_objects_vision;
std::string detected_objects_range, fused_topic_str = "/detection/combined_objects", fused_boxes_str = "/detection/combined_objects_boxes";
std::string fused_text_str = "detection/combined_objects_labels";
std::string name_space_str = ros::this_node::getNamespace();
bool sync_topics = false;
ROS_INFO("[%s] This node requires: Registered TF(Lidar-Camera), CameraInfo, Vision and Range Detections being published.", __APP_NAME__);
in_private_handle.param<std::string>("detected_objects_range", detected_objects_range, "/detection/lidar_objects");
ROS_INFO("[%s] detected_objects_range: %s", __APP_NAME__, detected_objects_range.c_str());
in_private_handle.param<std::string>("detected_objects_vision", detected_objects_vision, "/detection/vision_objects");
ROS_INFO("[%s] detected_objects_vision: %s", __APP_NAME__, detected_objects_vision.c_str());
in_private_handle.param<std::string>("camera_info_src", camera_info_src, "/camera_info");
ROS_INFO("[%s] camera_info_src: %s", __APP_NAME__, camera_info_src.c_str());
in_private_handle.param<double>("overlap_threshold", overlap_threshold_, 0.5);
ROS_INFO("[%s] overlap_threshold: %f", __APP_NAME__, overlap_threshold_);
in_private_handle.param<bool>("sync_topics", sync_topics, false);
ROS_INFO("[%s] sync_topics: %d", __APP_NAME__, sync_topics);
if (name_space_str != "/")
{
if (name_space_str.substr(0, 2) == "//")
{
name_space_str.erase(name_space_str.begin());
}
camera_info_src = name_space_str + camera_info_src;
}
//generate subscribers and sychronizers
ROS_INFO("[%s] Subscribing to... %s", __APP_NAME__, camera_info_src.c_str());
intrinsics_subscriber_ = in_private_handle.subscribe(camera_info_src,
1,
&RosRangeVisionFusionApp::IntrinsicsCallback, this);
/*image_subscriber_ = in_private_handle.subscribe("/image_raw",
1,
&RosRangeVisionFusionApp::ImageCallback, this);*/
ROS_INFO("[%s] Subscribing to... %s", __APP_NAME__, detected_objects_vision.c_str());
ROS_INFO("[%s] Subscribing to... %s", __APP_NAME__, detected_objects_range.c_str());
if (!sync_topics)
{
detections_range_subscriber_ = in_private_handle.subscribe(detected_objects_vision,
1,
&RosRangeVisionFusionApp::VisionDetectionsCallback, this);
detections_vision_subscriber_ = in_private_handle.subscribe(detected_objects_range,
1,
&RosRangeVisionFusionApp::RangeDetectionsCallback, this);
}
else
{
vision_filter_subscriber_ = new message_filters::Subscriber<autoware_msgs::DetectedObjectArray>(node_handle_,
detected_objects_vision, 1);
range_filter_subscriber_ = new message_filters::Subscriber<autoware_msgs::DetectedObjectArray>(node_handle_,
detected_objects_range, 1);
detections_synchronizer_ =
new message_filters::Synchronizer<SyncPolicyT>(SyncPolicyT(10),
*vision_filter_subscriber_,
*range_filter_subscriber_);
detections_synchronizer_->registerCallback(boost::bind(&RosRangeVisionFusionApp::SyncedDetectionsCallback, this, _1, _2));
}
publisher_fused_objects_ = node_handle_.advertise<autoware_msgs::DetectedObjectArray>(fused_topic_str, 1);
publisher_fused_boxes_ = node_handle_.advertise<jsk_recognition_msgs::BoundingBoxArray>(fused_boxes_str, 1);
publisher_fused_text_ = node_handle_.advertise<visualization_msgs::MarkerArray>(fused_text_str, 1);
ROS_INFO("[%s] Publishing fused objects in %s", __APP_NAME__, fused_topic_str.c_str());
ROS_INFO("[%s] Publishing fused boxes in %s", __APP_NAME__, fused_boxes_str.c_str());
}
void
RosRangeVisionFusionApp::Run()
{
ros::NodeHandle private_node_handle("~");
tf::TransformListener transform_listener;
transform_listener_ = &transform_listener;
InitializeRosIo(private_node_handle);
ROS_INFO("[%s] Ready. Waiting for data...", __APP_NAME__);
ros::spin();
ROS_INFO("[%s] END", __APP_NAME__);
}
RosRangeVisionFusionApp::RosRangeVisionFusionApp()
{
camera_lidar_tf_ok_ = false;
camera_info_ok_ = false;
processing_ = false;
image_frame_id_ = "";
overlap_threshold_ = 0.5;
empty_frames_ = 0;
}
| 38.536443
| 143
| 0.657475
|
AftermathK
|
580e5521d0785f546d139ffb54c95b1adb627e16
| 8,138
|
cc
|
C++
|
src/resolver/assignment_validation_test.cc
|
haocxy/mirror-googlesource-dawn-tint
|
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
|
[
"Apache-2.0"
] | null | null | null |
src/resolver/assignment_validation_test.cc
|
haocxy/mirror-googlesource-dawn-tint
|
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
|
[
"Apache-2.0"
] | null | null | null |
src/resolver/assignment_validation_test.cc
|
haocxy/mirror-googlesource-dawn-tint
|
44a0adf9b47c22a7b2f392f30aaf59811f56d6ee
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2021 The Tint 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 "src/resolver/resolver.h"
#include "gmock/gmock.h"
#include "src/ast/struct_block_decoration.h"
#include "src/resolver/resolver_test_helper.h"
#include "src/sem/storage_texture_type.h"
namespace tint {
namespace resolver {
namespace {
using ResolverAssignmentValidationTest = ResolverTest;
TEST_F(ResolverAssignmentValidationTest, ReadOnlyBuffer) {
// [[block]] struct S { m : i32 };
// [[group(0), binding(0)]]
// var<storage,read> a : S;
auto* s = Structure("S", {Member("m", ty.i32())},
{create<ast::StructBlockDecoration>()});
Global(Source{{12, 34}}, "a", ty.Of(s), ast::StorageClass::kStorage,
ast::Access::kRead,
ast::DecorationList{
create<ast::BindingDecoration>(0),
create<ast::GroupDecoration>(0),
});
WrapInFunction(Assign(Source{{56, 78}}, MemberAccessor("a", "m"), 1));
EXPECT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(),
"56:78 error: cannot store into a read-only type 'ref<storage, "
"i32, read>'");
}
TEST_F(ResolverAssignmentValidationTest, AssignIncompatibleTypes) {
// {
// var a : i32 = 2;
// a = 2.3;
// }
auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2));
auto* assign = Assign(Source{{12, 34}}, "a", 2.3f);
WrapInFunction(var, assign);
ASSERT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'");
}
TEST_F(ResolverAssignmentValidationTest,
AssignCompatibleTypesInBlockStatement_Pass) {
// {
// var a : i32 = 2;
// a = 2
// }
auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2));
WrapInFunction(var, Assign("a", 2));
ASSERT_TRUE(r()->Resolve()) << r()->error();
}
TEST_F(ResolverAssignmentValidationTest,
AssignIncompatibleTypesInBlockStatement_Fail) {
// {
// var a : i32 = 2;
// a = 2.3;
// }
auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2));
WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2.3f));
ASSERT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'");
}
TEST_F(ResolverAssignmentValidationTest,
AssignIncompatibleTypesInNestedBlockStatement_Fail) {
// {
// {
// var a : i32 = 2;
// a = 2.3;
// }
// }
auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2));
auto* inner_block = Block(Decl(var), Assign(Source{{12, 34}}, "a", 2.3f));
auto* outer_block = Block(inner_block);
WrapInFunction(outer_block);
ASSERT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(), "12:34 error: cannot assign 'f32' to 'i32'");
}
TEST_F(ResolverAssignmentValidationTest, AssignToScalar_Fail) {
// var my_var : i32 = 2;
// 1 = my_var;
auto* var = Var("my_var", ty.i32(), ast::StorageClass::kNone, Expr(2));
WrapInFunction(var, Assign(Expr(Source{{12, 34}}, 1), "my_var"));
EXPECT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(), "12:34 error: cannot assign to value of type 'i32'");
}
TEST_F(ResolverAssignmentValidationTest, AssignCompatibleTypes_Pass) {
// var a : i32 = 2;
// a = 2
auto* var = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2));
WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2));
EXPECT_TRUE(r()->Resolve()) << r()->error();
}
TEST_F(ResolverAssignmentValidationTest,
AssignCompatibleTypesThroughAlias_Pass) {
// alias myint = i32;
// var a : myint = 2;
// a = 2
auto* myint = Alias("myint", ty.i32());
auto* var = Var("a", ty.Of(myint), ast::StorageClass::kNone, Expr(2));
WrapInFunction(var, Assign(Source{{12, 34}}, "a", 2));
EXPECT_TRUE(r()->Resolve()) << r()->error();
}
TEST_F(ResolverAssignmentValidationTest,
AssignCompatibleTypesInferRHSLoad_Pass) {
// var a : i32 = 2;
// var b : i32 = 3;
// a = b;
auto* var_a = Var("a", ty.i32(), ast::StorageClass::kNone, Expr(2));
auto* var_b = Var("b", ty.i32(), ast::StorageClass::kNone, Expr(3));
WrapInFunction(var_a, var_b, Assign(Source{{12, 34}}, "a", "b"));
EXPECT_TRUE(r()->Resolve()) << r()->error();
}
TEST_F(ResolverAssignmentValidationTest, AssignThroughPointer_Pass) {
// var a : i32;
// let b : ptr<function,i32> = &a;
// *b = 2;
const auto func = ast::StorageClass::kFunction;
auto* var_a = Var("a", ty.i32(), func, Expr(2));
auto* var_b = Const("b", ty.pointer<int>(func), AddressOf(Expr("a")));
WrapInFunction(var_a, var_b, Assign(Source{{12, 34}}, Deref("b"), 2));
EXPECT_TRUE(r()->Resolve()) << r()->error();
}
TEST_F(ResolverAssignmentValidationTest, AssignToConstant_Fail) {
// {
// let a : i32 = 2;
// a = 2
// }
auto* var = Const("a", ty.i32(), Expr(2));
WrapInFunction(var, Assign(Expr(Source{{12, 34}}, "a"), 2));
EXPECT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(),
"12:34 error: cannot assign to const\nnote: 'a' is declared here:");
}
TEST_F(ResolverAssignmentValidationTest, AssignNonConstructible_Handle) {
// var a : texture_storage_1d<rgba8unorm, read>;
// var b : texture_storage_1d<rgba8unorm, read>;
// a = b;
auto make_type = [&] {
return ty.storage_texture(ast::TextureDimension::k1d,
ast::ImageFormat::kRgba8Unorm,
ast::Access::kRead);
};
Global("a", make_type(), ast::StorageClass::kNone,
ast::DecorationList{
create<ast::BindingDecoration>(0),
create<ast::GroupDecoration>(0),
});
Global("b", make_type(), ast::StorageClass::kNone,
ast::DecorationList{
create<ast::BindingDecoration>(1),
create<ast::GroupDecoration>(0),
});
WrapInFunction(Assign(Source{{56, 78}}, "a", "b"));
EXPECT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(),
"56:78 error: storage type of assignment must be constructible");
}
TEST_F(ResolverAssignmentValidationTest, AssignNonConstructible_Atomic) {
// [[block]] struct S { a : atomic<i32>; };
// [[group(0), binding(0)]] var<storage, read_write> v : S;
// v.a = v.a;
auto* s = Structure("S", {Member("a", ty.atomic(ty.i32()))},
{create<ast::StructBlockDecoration>()});
Global(Source{{12, 34}}, "v", ty.Of(s), ast::StorageClass::kStorage,
ast::Access::kReadWrite,
ast::DecorationList{
create<ast::BindingDecoration>(0),
create<ast::GroupDecoration>(0),
});
WrapInFunction(Assign(Source{{56, 78}}, MemberAccessor("v", "a"),
MemberAccessor("v", "a")));
EXPECT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(),
"56:78 error: storage type of assignment must be constructible");
}
TEST_F(ResolverAssignmentValidationTest, AssignNonConstructible_RuntimeArray) {
// [[block]] struct S { a : array<f32>; };
// [[group(0), binding(0)]] var<storage, read_write> v : S;
// v.a = v.a;
auto* s = Structure("S", {Member("a", ty.array(ty.f32()))},
{create<ast::StructBlockDecoration>()});
Global(Source{{12, 34}}, "v", ty.Of(s), ast::StorageClass::kStorage,
ast::Access::kReadWrite,
ast::DecorationList{
create<ast::BindingDecoration>(0),
create<ast::GroupDecoration>(0),
});
WrapInFunction(Assign(Source{{56, 78}}, MemberAccessor("v", "a"),
MemberAccessor("v", "a")));
EXPECT_FALSE(r()->Resolve());
EXPECT_EQ(r()->error(),
"56:78 error: storage type of assignment must be constructible");
}
} // namespace
} // namespace resolver
} // namespace tint
| 31.789063
| 80
| 0.613664
|
haocxy
|
580f60d9c3c1917c611b3c85574dd8ded30a22fe
| 957
|
cpp
|
C++
|
LeetCode/RemoveLinkedListElements.cpp
|
SelvorWhim/competitive
|
b9daaf21920d6f7669dc0c525e903949f4e33b62
|
[
"Unlicense"
] | null | null | null |
LeetCode/RemoveLinkedListElements.cpp
|
SelvorWhim/competitive
|
b9daaf21920d6f7669dc0c525e903949f4e33b62
|
[
"Unlicense"
] | null | null | null |
LeetCode/RemoveLinkedListElements.cpp
|
SelvorWhim/competitive
|
b9daaf21920d6f7669dc0c525e903949f4e33b62
|
[
"Unlicense"
] | null | null | null |
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* it = head;
ListNode* newHead = NULL;
ListNode* lastValid = NULL;
while (it != NULL) {
if (it->val != val) {
if (newHead == NULL) {
newHead = it;
}
if (lastValid == NULL) {
lastValid = it;
} else {
lastValid = lastValid->next;
}
}
else if (it->val == val && lastValid != NULL) {
lastValid->next = it->next;
} // if (it->val == val && lastValid == NULL), the node is effectively skipped in the new list
it = it->next;
}
return newHead;
}
};
| 28.147059
| 106
| 0.440961
|
SelvorWhim
|
5810aa11c2c678e2dba12e500ef70300a1a9781d
| 5,699
|
cpp
|
C++
|
tests/sshmanager_clitest.cpp
|
lilithean/XtalOpt
|
9ebc125e6014b27e72a04fb62c8820c7b9670c61
|
[
"BSD-3-Clause"
] | 23
|
2017-09-01T04:35:02.000Z
|
2022-01-16T13:51:17.000Z
|
tests/sshmanager_clitest.cpp
|
lilithean/XtalOpt
|
9ebc125e6014b27e72a04fb62c8820c7b9670c61
|
[
"BSD-3-Clause"
] | 20
|
2017-08-29T15:29:46.000Z
|
2022-01-20T09:10:59.000Z
|
tests/sshmanager_clitest.cpp
|
lilithean/XtalOpt
|
9ebc125e6014b27e72a04fb62c8820c7b9670c61
|
[
"BSD-3-Clause"
] | 21
|
2017-06-15T03:11:34.000Z
|
2022-02-28T05:20:44.000Z
|
/**********************************************************************
SSHManager - SSHManagerTest class provides unit testing for the
SSHManager class
Copyright (C) 2010-2011 David C. Lonie
This source code is released under the New BSD License, (the "License").
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 <globalsearch/sshmanager_cli.h>
#include <QString>
#include <QTemporaryFile>
#include <QtTest>
#define NUM_CONN 5
using namespace GlobalSearch;
class SSHManagerCLITest : public QObject
{
Q_OBJECT
private:
SSHManagerCLI* manager;
// Create a local directory structure:
// [tmp path]/sshtesttmp/
// testfile1
// newdir/
// testfile2
QStringList m_dirLayout;
QDir m_localTempDir;
QString m_remoteDir;
QString m_localNewDir;
QString m_testfile1Contents;
QString m_testfile2Contents;
private slots:
/**
* Called before the first test function is executed.
*/
void initTestCase();
/**
* Called after the last test function is executed.
*/
void cleanupTestCase();
/**
* Called before each test function is executed.
*/
void init();
/**
* Called after every test function.
*/
void cleanup();
// Tests
void lockAllAndExecute();
void copyThreads();
};
void SSHManagerCLITest::initTestCase()
{
// Create a local directory structure:
// [tmp path]/sshtesttmp/
// testfile1
// newdir/
// testfile2
m_remoteDir = ".sshtmpdir";
m_dirLayout << m_remoteDir + "/testfile1" << m_remoteDir + "/newdir/"
<< m_remoteDir + "/newdir/testfile2";
m_localTempDir.mkpath(QDir::tempPath() + "/sshtesttmp");
m_localTempDir.mkpath(QDir::tempPath() + "/sshtesttmp/newdir");
m_localTempDir.setPath(QDir::tempPath() + "/sshtesttmp");
m_localNewDir = m_localTempDir.path() + ".new";
// Each testfile is ~1MB
QString buffer(104857, '0');
QFile testfile1(m_localTempDir.path() + "/testfile1");
testfile1.open(QIODevice::WriteOnly);
QTextStream teststream1(&testfile1);
m_testfile1Contents = "This is the first file's contents.\n" + buffer;
teststream1 << m_testfile1Contents;
testfile1.close();
QFile testfile2(m_localTempDir.path() + "/newdir/testfile2");
testfile2.open(QIODevice::WriteOnly);
QTextStream teststream2(&testfile2);
m_testfile2Contents = "and these are the second's.\n" + buffer;
teststream2 << m_testfile2Contents;
testfile2.close();
// Open ssh connection
manager = new SSHManagerCLI();
try {
// Ensure that the following points to a real server, acct, and pw
// combo. Do not commit any changes here! (considering using
// /etc/hosts to map "testserver" to a real server with a
// chroot-jailed acct/pw = "test")
manager->makeConnections("testserver", "test", "test", 22);
} catch (SSHConnection::SSHConnectionException) {
QFAIL("Cannot connect to ssh server. Make sure that the connection opened "
"in initTestCase() points to a valid account on a real host before "
"debugging this failure.");
}
}
void SSHManagerCLITest::cleanupTestCase()
{
QFile::remove(m_localTempDir.path() + "/testfile1");
QFile::remove(m_localTempDir.path() + "/newdir/testfile2");
m_localTempDir.rmdir(m_localTempDir.path() + "/newdir");
m_localTempDir.rmdir(m_localTempDir.path());
QFile::remove(m_localNewDir + "/testfile1");
QFile::remove(m_localNewDir + "/newdir/testfile2");
m_localTempDir.rmdir(m_localNewDir + "/newdir");
m_localTempDir.rmdir(m_localNewDir);
if (manager)
delete manager;
manager = 0;
}
void SSHManagerCLITest::init()
{
}
void SSHManagerCLITest::cleanup()
{
}
void SSHManagerCLITest::lockAllAndExecute()
{
QList<SSHConnection*> list;
for (int i = 0; i < NUM_CONN; i++) {
list.append(manager->getFreeConnection());
}
QString command = "expr 2 + 4";
QString stdout_str, stderr_str;
SSHConnection* conn;
int ec;
for (int i = 0; i < NUM_CONN; i++) {
conn = list.at(i);
QVERIFY(conn->execute(command, stdout_str, stderr_str, ec));
QCOMPARE(ec, 0);
QCOMPARE(stdout_str, QString("6\n"));
QVERIFY(stderr_str.isEmpty());
}
for (int i = 0; i < NUM_CONN; i++) {
manager->unlockConnection(list.at(i));
}
}
class CopyThread : public QThread
{
public:
CopyThread(SSHManager* m, const QString& f, const QString& t)
: QThread(0), manager(m), from(f), to(t)
{
}
void run()
{
SSHConnection* conn = manager->getFreeConnection();
conn->copyDirectoryToServer(from, to);
conn->removeRemoteDirectory(to);
manager->unlockConnection(conn);
}
private:
SSHManager* manager;
QString from, to;
};
void SSHManagerCLITest::copyThreads()
{
QList<CopyThread*> list;
for (int i = 0; i < NUM_CONN * 20; ++i) {
CopyThread* ct = new CopyThread(manager, m_localTempDir.path(),
m_remoteDir + QString::number(i + 1));
list.append(ct);
}
QBENCHMARK
{
for (int i = 0; i < list.size(); ++i) {
list.at(i)->start();
}
for (int i = 0; i < list.size(); ++i) {
list.at(i)->wait();
qDebug() << "Thread " << i + 1 << " of " << list.size() << " finished.";
}
}
}
QTEST_MAIN(SSHManagerCLITest)
#include "sshmanager_clitest.moc"
| 26.882075
| 79
| 0.640814
|
lilithean
|
5812d55e1d9e9bdc8296acf6f0576ecef0cc8bcc
| 379
|
cpp
|
C++
|
src/geometry/segment.cpp
|
teyrana/quadtree
|
4172ad2f2e36414caebf80013a3d32e6df200945
|
[
"MIT"
] | null | null | null |
src/geometry/segment.cpp
|
teyrana/quadtree
|
4172ad2f2e36414caebf80013a3d32e6df200945
|
[
"MIT"
] | 1
|
2019-08-24T17:31:50.000Z
|
2019-08-24T17:31:50.000Z
|
src/geometry/segment.cpp
|
teyrana/quadtree
|
4172ad2f2e36414caebf80013a3d32e6df200945
|
[
"MIT"
] | null | null | null |
// The MIT License
// (c) 2019 Daniel Williams
#include <cmath>
#include "geometry/point.hpp"
#include "geometry/segment.hpp"
using terrain::geometry::Point;
using terrain::geometry::Segment;
Segment::Segment() {}
Segment::Segment(const Point& _start, const Point& _end):
start(_start), end(_end)
{}
void Segment::clear(){
this->start.clear();
this->end.clear();
}
| 16.478261
| 57
| 0.691293
|
teyrana
|
5812ea4aec3da9e3cc16952c7e4ca4c632a044d7
| 19,054
|
cpp
|
C++
|
test/auto/ListModel/ListModelTest.cpp
|
ericzh86/ModelsModule
|
e1f263420e5e54ac280d1c61485ccb6a0a625129
|
[
"MIT"
] | 8
|
2019-12-11T08:52:37.000Z
|
2021-08-04T03:42:55.000Z
|
test/auto/ListModel/ListModelTest.cpp
|
ericzh86/ModelsModule
|
e1f263420e5e54ac280d1c61485ccb6a0a625129
|
[
"MIT"
] | null | null | null |
test/auto/ListModel/ListModelTest.cpp
|
ericzh86/ModelsModule
|
e1f263420e5e54ac280d1c61485ccb6a0a625129
|
[
"MIT"
] | 1
|
2020-04-16T07:07:50.000Z
|
2020-04-16T07:07:50.000Z
|
#include "ListModelTest.h"
#include <QtCore>
#include <QtTest>
#include "QCxxListModel.h"
#include "ListModelTester.h"
// Macros
#define InitModel() \
QCxxListModel<QObject *> model; \
model.setCountEnabled(true); \
auto tester = new ListModelTester(&model)
#define VerifyCountSignal(value) QVERIFY(tester->count() == value)
#define VerifyChangedSize(value) QVERIFY(tester->changedSize() == value)
#define VerifyRowsChanged(i, from, to) QVERIFY(tester->isChanged(i, from, to))
ListModelTest::ListModelTest()
{
for (int i = 0; i < 100; ++i) {
objects.append(new QObject(this));
}
}
void ListModelTest::appendListCase()
{
InitModel();
QObjectList list1 { objects[0], objects[1] };
QObjectList list2 { objects[2], objects[3] };
model.append(list1);
VerifyCountSignal(1);
model.append(list2);
VerifyCountSignal(2);
QVERIFY(model.count() == 4);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.value(3) == objects[3]);
}
void ListModelTest::prependCase()
{
InitModel();
model.prepend(objects[0]);
VerifyCountSignal(1);
model.prepend(objects[1]);
VerifyCountSignal(2);
model.prepend(objects[2]);
VerifyCountSignal(3);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[2]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[0]);
}
void ListModelTest::appendCase()
{
InitModel();
model.append(objects[0]);
VerifyCountSignal(1);
model.append(objects[1]);
VerifyCountSignal(2);
model.append(objects[2]);
VerifyCountSignal(3);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
}
void ListModelTest::push_frontCase()
{
InitModel();
model.push_front(objects[0]);
VerifyCountSignal(1);
model.push_front(objects[1]);
VerifyCountSignal(2);
model.push_front(objects[2]);
VerifyCountSignal(3);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[2]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[0]);
}
void ListModelTest::push_backCase()
{
InitModel();
model.push_back(objects[0]);
VerifyCountSignal(1);
model.push_back(objects[1]);
VerifyCountSignal(2);
model.push_back(objects[2]);
VerifyCountSignal(3);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
}
void ListModelTest::replaceCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.replace(0, objects[3]);
VerifyCountSignal(0);
QVERIFY(model.value(0) == objects[3]);
model.replace(1, objects[4]);
VerifyCountSignal(0);
QVERIFY(model.value(1) == objects[4]);
model.replace(2, objects[5]);
VerifyCountSignal(0);
QVERIFY(model.value(2) == objects[5]);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[3]);
QVERIFY(model.value(1) == objects[4]);
QVERIFY(model.value(2) == objects[5]);
}
void ListModelTest::insertCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.insert(0, objects[3]);
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[3]);
model.insert(2, objects[4]);
VerifyCountSignal(2);
QVERIFY(model.value(2) == objects[4]);
model.insert(4, objects[5]);
VerifyCountSignal(3);
QVERIFY(model.value(4) == objects[5]);
QVERIFY(model.count() == 6);
QVERIFY(model.value(0) == objects[3]);
QVERIFY(model.value(1) == objects[0]);
QVERIFY(model.value(2) == objects[4]);
QVERIFY(model.value(3) == objects[1]);
QVERIFY(model.value(4) == objects[5]);
QVERIFY(model.value(5) == objects[2]);
}
void ListModelTest::removeOneCase()
{
InitModel();
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
model.append(objects[i]);
}
tester->resetCount();
model.removeOne(objects[0]);
VerifyCountSignal(1);
model.removeOne(objects[2]);
VerifyCountSignal(2);
model.removeOne(objects[4]);
VerifyCountSignal(3);
QVERIFY(model.count() == 9);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[1]);
QVERIFY(model.value(3) == objects[2]);
QVERIFY(model.value(4) == objects[3]);
QVERIFY(model.value(5) == objects[3]);
QVERIFY(model.value(6) == objects[4]);
QVERIFY(model.value(7) == objects[5]);
QVERIFY(model.value(8) == objects[5]);
}
void ListModelTest::removeAllCase()
{
InitModel();
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
model.append(objects[i]);
}
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
model.append(objects[i]);
model.append(objects[i]);
}
tester->resetCount();
model.removeAll(objects[0]);
VerifyCountSignal(1);
model.removeAll(objects[2]);
VerifyCountSignal(2);
model.removeAll(objects[4]);
VerifyCountSignal(3);
QVERIFY(model.count() == 18);
QVERIFY(model.value( 0) == objects[1]);
QVERIFY(model.value( 1) == objects[3]);
QVERIFY(model.value( 2) == objects[5]);
QVERIFY(model.value( 3) == objects[1]);
QVERIFY(model.value( 4) == objects[1]);
QVERIFY(model.value( 5) == objects[3]);
QVERIFY(model.value( 6) == objects[3]);
QVERIFY(model.value( 7) == objects[5]);
QVERIFY(model.value( 8) == objects[5]);
QVERIFY(model.value( 9) == objects[1]);
QVERIFY(model.value(10) == objects[1]);
QVERIFY(model.value(11) == objects[1]);
QVERIFY(model.value(12) == objects[3]);
QVERIFY(model.value(13) == objects[3]);
QVERIFY(model.value(14) == objects[3]);
QVERIFY(model.value(15) == objects[5]);
QVERIFY(model.value(16) == objects[5]);
QVERIFY(model.value(17) == objects[5]);
}
void ListModelTest::pop_frontCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.pop_front();
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[2]);
model.pop_front();
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[2]);
model.pop_front();
VerifyCountSignal(3);
QVERIFY(model.count() == 0);
}
void ListModelTest::pop_backCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.pop_back();
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
model.pop_back();
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
model.pop_back();
VerifyCountSignal(3);
QVERIFY(model.count() == 0);
}
void ListModelTest::removeAtCase()
{
InitModel();
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.removeAt(0);
VerifyCountSignal(1);
model.removeAt(1);
VerifyCountSignal(2);
model.removeAt(2);
VerifyCountSignal(3);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[3]);
QVERIFY(model.value(2) == objects[5]);
}
void ListModelTest::removeFirstCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.removeFirst();
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[2]);
model.removeFirst();
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[2]);
model.removeFirst();
VerifyCountSignal(3);
QVERIFY(model.count() == 0);
}
void ListModelTest::removeLastCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.removeLast();
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
model.removeLast();
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
model.removeLast();
VerifyCountSignal(3);
QVERIFY(model.count() == 0);
}
void ListModelTest::takeAtCase()
{
InitModel();
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
tester->resetCount();
QVERIFY(model.takeAt(0) == objects[0]);
VerifyCountSignal(1);
QVERIFY(model.takeAt(1) == objects[2]);
VerifyCountSignal(2);
QVERIFY(model.takeAt(2) == objects[4]);
VerifyCountSignal(3);
QVERIFY(model.count() == 3);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[3]);
QVERIFY(model.value(2) == objects[5]);
}
void ListModelTest::takeFirstCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
QVERIFY(model.takeFirst() == objects[0]);
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[2]);
QVERIFY(model.takeFirst() == objects[1]);
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[2]);
QVERIFY(model.takeFirst() == objects[2]);
VerifyCountSignal(3);
QVERIFY(model.count() == 0);
}
void ListModelTest::takeLastCase()
{
InitModel();
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
QVERIFY(model.takeLast() == objects[2]);
VerifyCountSignal(1);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.takeLast() == objects[1]);
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.takeLast() == objects[0]);
VerifyCountSignal(3);
QVERIFY(model.count() == 0);
}
void ListModelTest::swapCase()
{
InitModel();
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.swap(0, 1);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[0]);
model.swap(1, 2);
QVERIFY(model.value(1) == objects[2]);
QVERIFY(model.value(2) == objects[0]);
model.swap(4, 5);
QVERIFY(model.value(4) == objects[5]);
QVERIFY(model.value(5) == objects[4]);
VerifyCountSignal(0);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[2]);
QVERIFY(model.value(2) == objects[0]);
QVERIFY(model.value(3) == objects[3]);
QVERIFY(model.value(4) == objects[5]);
QVERIFY(model.value(5) == objects[4]);
QVERIFY(model.count() == 6);
}
void ListModelTest::swapListCase()
{
InitModel();
QObjectList list { objects[0], objects[1], objects[2] };
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.swap(list);
VerifyCountSignal(1);
QVERIFY(list.value(0) == objects[0]);
QVERIFY(list.value(1) == objects[1]);
QVERIFY(list.value(2) == objects[2]);
QVERIFY(list.value(3) == objects[3]);
QVERIFY(list.value(4) == objects[4]);
QVERIFY(list.value(5) == objects[5]);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.count() == 3);
}
void ListModelTest::moveCase()
{
InitModel();
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model.move(0, 1);
QVERIFY(model.value(0) == objects[1]);
QVERIFY(model.value(1) == objects[0]);
model.move(1, 2);
QVERIFY(model.value(1) == objects[2]);
QVERIFY(model.value(2) == objects[0]);
model.move(4, 5);
QVERIFY(model.value(4) == objects[5]);
QVERIFY(model.value(5) == objects[4]);
model.move(5, 4);
QVERIFY(model.value(4) == objects[4]);
QVERIFY(model.value(5) == objects[5]);
model.move(2, 1);
QVERIFY(model.value(1) == objects[0]);
QVERIFY(model.value(2) == objects[2]);
model.move(1, 0);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
VerifyCountSignal(0);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.value(3) == objects[3]);
QVERIFY(model.value(4) == objects[4]);
QVERIFY(model.value(5) == objects[5]);
QVERIFY(model.count() == 6);
}
void ListModelTest::clearCase()
{
InitModel();
int destroies = 0;
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
connect(objects[i], &QObject::destroyed,
this, [&] { ++destroies; });
}
tester->resetCount();
model.clear();
VerifyCountSignal(1);
QTRY_COMPARE(destroies, 0);
QVERIFY(model.count() == 0);
}
void ListModelTest::deleteAllCase()
{
InitModel();
int destroies = 0;
for (int i = 0; i < 6; ++i) {
QObject *o = new QObject(this);
model.append(o);
connect(o, &QObject::destroyed,
this, [&] { ++destroies; });
}
tester->resetCount();
model.deleteAll();
VerifyCountSignal(1);
QTRY_COMPARE(destroies, 6);
QVERIFY(model.count() == 0);
}
void ListModelTest::operatorAssignmentCase()
{
InitModel();
QObjectList list { objects[0], objects[1], objects[2] };
for (int i = 0; i < 6; ++i) {
model.append(objects[i]);
}
tester->resetCount();
model = list;
VerifyCountSignal(1);
QVERIFY(list.value(0) == objects[0]);
QVERIFY(list.value(1) == objects[1]);
QVERIFY(list.value(2) == objects[2]);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.count() == 3);
}
void ListModelTest::operatorAdditionCase()
{
InitModel();
QObjectList list { objects[0], objects[1], objects[2] };
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
list = model + list;
VerifyCountSignal(0);
QVERIFY(list.value(0) == objects[0]);
QVERIFY(list.value(1) == objects[1]);
QVERIFY(list.value(2) == objects[2]);
QVERIFY(list.value(3) == objects[0]);
QVERIFY(list.value(4) == objects[1]);
QVERIFY(list.value(5) == objects[2]);
QVERIFY(list.count() == 6);
}
void ListModelTest::operatorEqualToCase()
{
InitModel();
QObjectList list { objects[0], objects[1], objects[2] };
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
QVERIFY(model == list);
VerifyCountSignal(0);
}
void ListModelTest::operatorNotEqualCase()
{
InitModel();
QObjectList list { objects[1], objects[1], objects[2] };
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
tester->resetCount();
QVERIFY(model != list);
VerifyCountSignal(0);
}
void ListModelTest::operatorAdditionAssignmentListCase()
{
InitModel();
QObjectList list { objects[0], objects[1], objects[2] };
model += list;
VerifyCountSignal(1);
model += list;
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.value(3) == objects[0]);
QVERIFY(model.value(4) == objects[1]);
QVERIFY(model.value(5) == objects[2]);
QVERIFY(model.count() == 6);
}
void ListModelTest::operatorLeftShiftListCase()
{
InitModel();
QObjectList list { objects[0], objects[1], objects[2] };
model << list;
VerifyCountSignal(1);
model << list;
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.value(3) == objects[0]);
QVERIFY(model.value(4) == objects[1]);
QVERIFY(model.value(5) == objects[2]);
QVERIFY(model.count() == 6);
}
void ListModelTest::operatorAdditionAssignmentCase()
{
InitModel();
model += objects[0];
VerifyCountSignal(1);
model += objects[1];
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.count() == 2);
}
void ListModelTest::operatorLeftShiftCase()
{
InitModel();
model << objects[0];
VerifyCountSignal(1);
model << objects[1];
VerifyCountSignal(2);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.count() == 2);
}
void ListModelTest::modelMethodsCase()
{
InitModel();
Q_UNUSED(tester);
QObject *o = (QObject *)1;
for (int i = 0; i < 3; ++i) {
model.append(objects[i]);
}
model.append(nullptr);
model.append(o);
QModelIndex index0 = model.index(0, 0);
QModelIndex index1 = model.index(1, 0);
QModelIndex index2 = model.index(2, 0);
QModelIndex index3 = model.index(3, 0);
QModelIndex index4 = model.index(4, 0);
QModelIndex index5 = model.index(5, 0);
QVERIFY(index0.row() == 0);
QVERIFY(index1.row() == 1);
QVERIFY(index2.row() == 2);
QVERIFY(index3.row() == 3);
QVERIFY(index4.row() == 4);
QVERIFY(index5.row() ==-1);
QVERIFY(index0.column() == 0);
QVERIFY(index1.column() == 0);
QVERIFY(index2.column() == 0);
QVERIFY(index3.column() == 0);
QVERIFY(index4.column() == 0);
QVERIFY(index5.column() ==-1);
QVERIFY(model.value(index0) == objects[0]);
QVERIFY(model.value(index1) == objects[1]);
QVERIFY(model.value(index2) == objects[2]);
QVERIFY(model.value(index3) == nullptr);
QVERIFY(model.value(index4) == o);
QVERIFY(model.value(index5) == nullptr);
QVERIFY(model.value(index0, nullptr) == objects[0]);
QVERIFY(model.value(index1, nullptr) == objects[1]);
QVERIFY(model.value(index2, nullptr) == objects[2]);
QVERIFY(model.value(index3, nullptr) == nullptr);
QVERIFY(model.value(index4, nullptr) == o);
QVERIFY(model.value(index5, nullptr) == nullptr);
QVERIFY(model.value(0) == objects[0]);
QVERIFY(model.value(1) == objects[1]);
QVERIFY(model.value(2) == objects[2]);
QVERIFY(model.value(3) == nullptr);
QVERIFY(model.value(4) == o);
QVERIFY(model.value(5) == nullptr);
QVERIFY(model.value(0, nullptr) == objects[0]);
QVERIFY(model.value(1, nullptr) == objects[1]);
QVERIFY(model.value(2, nullptr) == objects[2]);
QVERIFY(model.value(3, nullptr) == nullptr);
QVERIFY(model.value(4, nullptr) == o);
QVERIFY(model.value(5, nullptr) == nullptr);
}
QTEST_APPLESS_MAIN(ListModelTest)
| 24.118987
| 78
| 0.599139
|
ericzh86
|
58144a8de60ff911068cf63bc3e79d31ea11f2a9
| 1,909
|
cpp
|
C++
|
Sources/AGEngine/Graphic/GraphicElementManager.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 47
|
2015-03-29T09:44:25.000Z
|
2020-11-30T10:05:56.000Z
|
Sources/AGEngine/Graphic/GraphicElementManager.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 313
|
2015-01-01T18:16:30.000Z
|
2015-11-30T07:54:07.000Z
|
Sources/AGEngine/Graphic/GraphicElementManager.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 9
|
2015-06-07T13:21:54.000Z
|
2020-08-25T09:50:07.000Z
|
#include "GraphicElementManager.hpp"
#include "BFC/BFCCullableHandle.hpp"
#include "BFC/BFCBlockManagerFactory.hpp"
#include "Graphic/DRBMeshData.hpp"
#include "AssetManagement/Instance/MeshInstance.hh"
#include "AssetManagement/Instance/MaterialInstance.hh"
#include "Utils/Profiler.hpp"
namespace AGE
{
GraphicElementManager::GraphicElementManager(BFCBlockManagerFactory *factory)
: _bfcBlockManager(factory)
{
AGE_ASSERT(factory != nullptr);
}
BFCCullableHandleGroup GraphicElementManager::addMesh(std::shared_ptr<MeshInstance> mesh, std::shared_ptr<MaterialSetInstance> materialInstance)
{
SCOPE_profile_cpu_function("DRB");
BFCCullableHandleGroup result;
for (auto &submesh : mesh->subMeshs)
{
DRBMesh *drbMesh = nullptr;
if (submesh.isSkinned)
{
auto drbMeshSkeleton = _skinnedMeshPool.create();
drbMesh = drbMeshSkeleton;
}
else
{
drbMesh = _meshPool.create();
}
drbMesh->datas->setVerticesKey(submesh.vertices);
drbMesh->datas->setPainterKey(submesh.painter);
drbMesh->datas->setAABB(submesh.boundingBox);
std::size_t materialIndex = submesh.defaultMaterialIndex < materialInstance->datas.size() ? submesh.defaultMaterialIndex : 0;
auto &material = materialInstance->datas[materialIndex];
// we set the material unique id
drbMesh->material = &material;
BFCCullableHandle resultMesh = _bfcBlockManager->createItem(drbMesh);
result.getHandles().push_back(resultMesh);
}
return result;
}
void GraphicElementManager::removeMesh(BFCCullableHandleGroup &handle)
{
SCOPE_profile_cpu_function("DRB");
for (auto &m : handle.getHandles())
{
if (m.getPtr<DRBMesh>()->getDatas()->hadRenderMode(RenderModes::AGE_SKINNED))
{
_skinnedMeshPool.destroy(m.getPtr());
}
else
{
_meshPool.destroy(m.getPtr());
}
_bfcBlockManager->deleteItem(m);
}
handle.getHandles().clear();
}
}
| 25.118421
| 145
| 0.736511
|
Another-Game-Engine
|
58149e7643a81c744cd4db01b0f21e8558ce657c
| 11,616
|
cpp
|
C++
|
tests/unit/suites/mfx_dispatch/linux/mfx_dispatch_test_cases_plugins.cpp
|
me176c-dev/MediaSDK
|
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
|
[
"MIT"
] | 1
|
2020-09-08T15:30:11.000Z
|
2020-09-08T15:30:11.000Z
|
tests/unit/suites/mfx_dispatch/linux/mfx_dispatch_test_cases_plugins.cpp
|
me176c-dev/MediaSDK
|
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
|
[
"MIT"
] | 1
|
2021-01-21T12:27:39.000Z
|
2021-01-21T12:27:39.000Z
|
tests/unit/suites/mfx_dispatch/linux/mfx_dispatch_test_cases_plugins.cpp
|
me176c-dev/MediaSDK
|
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
|
[
"MIT"
] | 1
|
2020-08-17T21:07:24.000Z
|
2020-08-17T21:07:24.000Z
|
// Copyright (c) 2018-2019 Intel Corporation
//
// 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 "mfx_dispatch_test_main.h"
#include "mfx_dispatch_test_fixtures.h"
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <algorithm>
#include <sstream>
#include "mfx_dispatch_test_mocks.h"
constexpr size_t TEST_PLUGIN_COUNT = 7;
TEST_F(DispatcherPluginsTest, ShouldSearchForPluginsCfgByCorrectPath)
{
MockCallObj& mock = *g_call_obj_ptr;
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"),_)).Times(1);
mfxPluginUID uid{};
std::fill(uid.Data, uid.Data + sizeof(mfxPluginUID), MOCK_PLUGIN_UID_BYTE_BASE);
MFXVideoUSER_Load(session, &uid, 0);
}
TEST_F(DispatcherPluginsTest, ShouldFailIfPluginIsNotFound)
{
MockCallObj& mock = *g_call_obj_ptr;
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(1).WillRepeatedly(Return(nullptr));
EXPECT_CALL(mock, fclose).Times(1);
mfxPluginUID uid{};
std::fill(uid.Data, uid.Data + sizeof(mfxPluginUID), MOCK_PLUGIN_UID_BYTE_BASE);
mfxStatus sts = MFXVideoUSER_Load(session, &uid, 0);
ASSERT_EQ(sts, MFX_ERR_NOT_FOUND);
}
static bool successfully_parsed_at_least_once = false;
// The parameter will determine the order of the plugin to be loaded.
TEST_P(DispatcherPluginsTestParametrized, ShouldLoadFromGoodPluginsCfgCorrectly)
{
MockCallObj& mock = *g_call_obj_ptr;
SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT);
size_t plugin_idx = GetParam();
ASSERT_TRUE(plugin_idx < m_plugin_vec.size());
const PluginParamExtended& plugin = m_plugin_vec[plugin_idx];
if (!successfully_parsed_at_least_once)
{ // The plugin file is only successfully parsed once by the dispatcher,
// and the parsed plugin list is stored as a global variable in the
// dispatcher lib. Therefore, the calls below will only be executed once.
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines));
EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
successfully_parsed_at_least_once = true;
}
EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE));
EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap)));
EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin));
EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1).WillRepeatedly(DoAll(SetArgPointee<1>(plugin), Return(MFX_ERR_NONE)));
EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0);
ASSERT_EQ(sts, MFX_ERR_NONE);
EXPECT_CALL(mock, dlclose).Times(1);
EXPECT_CALL(mock, MFXVideoUSER_Unregister(MOCK_SESSION_HANDLE, plugin.Type)).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
sts = MFXVideoUSER_UnLoad(session, &plugin.PluginUID);
ASSERT_EQ(sts, MFX_ERR_NONE);
}
INSTANTIATE_TEST_CASE_P(EnumeratingPlugins, DispatcherPluginsTestParametrized, ::testing::Range((size_t)0, TEST_PLUGIN_COUNT));
TEST_F(DispatcherPluginsTest, ShouldFailIfPluginHasNoSymbols)
{
MockCallObj& mock = *g_call_obj_ptr;
SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT);
const PluginParamExtended& plugin = m_plugin_vec[0];
if (!successfully_parsed_at_least_once)
{
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines));
EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
successfully_parsed_at_least_once = true;
}
EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE));
EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1);
EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(0);
EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(0);
EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(0);
mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0);
ASSERT_EQ(sts, MFX_ERR_NOT_FOUND);
}
TEST_F(DispatcherPluginsTest, ShouldFailIfPluginIsNotCreated)
{
MockCallObj& mock = *g_call_obj_ptr;
SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT);
const PluginParamExtended& plugin = m_plugin_vec[0];
if (!successfully_parsed_at_least_once)
{
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines));
EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
successfully_parsed_at_least_once = true;
}
EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE));
EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap)));
EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1);
EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(0);
EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(0);
mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0);
ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED);
}
TEST_F(DispatcherPluginsTest, ShouldFailIfUnknownPluginParams)
{
MockCallObj& mock = *g_call_obj_ptr;
SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT);
const PluginParamExtended& plugin = m_plugin_vec[0];
if (!successfully_parsed_at_least_once)
{
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines));
EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
successfully_parsed_at_least_once = true;
}
EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE));
EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap)));
EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin));
EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1);
EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(0);
mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0);
ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED);
}
TEST_F(DispatcherPluginsTest, ShouldFailIfRegisterFailed)
{
MockCallObj& mock = *g_call_obj_ptr;
SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT);
const PluginParamExtended& plugin = m_plugin_vec[0];
if (!successfully_parsed_at_least_once)
{
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines));
EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
successfully_parsed_at_least_once = true;
}
EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE));
EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap)));
EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin));
EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1).WillRepeatedly(DoAll(SetArgPointee<1>(plugin), Return(MFX_ERR_NONE)));
EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(1);
mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0);
ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED);
}
TEST_F(DispatcherPluginsTest, ShouldFailIfUnregisterFailed)
{
MockCallObj& mock = *g_call_obj_ptr;
SetEmulatedPluginsCfgContent(mock, TEST_PLUGIN_COUNT);
const PluginParamExtended& plugin = m_plugin_vec[0];
if (!successfully_parsed_at_least_once)
{
EXPECT_CALL(mock, fopen(StrEq(MFX_PLUGINS_CONF_DIR "/plugins.cfg"), _)).Times(1).WillRepeatedly(Return(MOCK_FILE_DESCRIPTOR));
EXPECT_CALL(mock, fgets(_, _, MOCK_FILE_DESCRIPTOR)).Times(AtLeast(1)).WillRepeatedly(Invoke(&mock, &MockCallObj::FeedEmulatedPluginsCfgLines));
EXPECT_CALL(mock, fclose).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
successfully_parsed_at_least_once = true;
}
EXPECT_CALL(mock, dlopen(StrEq(plugin.Path.c_str()), _)).Times(1).WillRepeatedly(Return(MOCK_DLOPEN_HANDLE));
EXPECT_CALL(mock, dlsym(_, StrEq("CreatePlugin"))).Times(1).WillRepeatedly(Return(reinterpret_cast<void*>(CreatePluginWrap)));
EXPECT_CALL(mock, CreatePlugin(plugin.PluginUID, _)).Times(1).WillRepeatedly(Invoke(&mock, &MockCallObj::ReturnMockPlugin));
EXPECT_CALL(mock, GetPluginParam(mock.m_mock_plugin.pthis, _)).Times(1).WillRepeatedly(DoAll(SetArgPointee<1>(plugin), Return(MFX_ERR_NONE)));
EXPECT_CALL(mock, MFXVideoUSER_Register(MOCK_SESSION_HANDLE, plugin.Type, _)).Times(1).WillRepeatedly(Return(MFX_ERR_NONE));
mfxStatus sts = MFXVideoUSER_Load(session, &plugin.PluginUID, 0);
ASSERT_EQ(sts, MFX_ERR_NONE);
EXPECT_CALL(mock, dlclose).Times(0);
EXPECT_CALL(mock, MFXVideoUSER_Unregister(MOCK_SESSION_HANDLE, plugin.Type)).Times(1);
sts = MFXVideoUSER_UnLoad(session, &plugin.PluginUID);
ASSERT_EQ(sts, MFX_ERR_UNSUPPORTED);
}
| 51.171806
| 152
| 0.758781
|
me176c-dev
|
5816ac5f04c4dae0066ee5aa724582191cca8758
| 1,809
|
cc
|
C++
|
cpp/src/array/maxNumberOfFamilies.cc
|
dacozai/algorithm-diary
|
8ed5e119e4450e92e63276047ef19bbf422c2770
|
[
"MIT"
] | 1
|
2019-10-17T08:34:55.000Z
|
2019-10-17T08:34:55.000Z
|
cpp/src/array/maxNumberOfFamilies.cc
|
dacozai/algorithm-diary
|
8ed5e119e4450e92e63276047ef19bbf422c2770
|
[
"MIT"
] | 1
|
2020-05-24T08:32:13.000Z
|
2020-05-24T08:32:13.000Z
|
cpp/src/array/maxNumberOfFamilies.cc
|
dacozai/algorithm-diary
|
8ed5e119e4450e92e63276047ef19bbf422c2770
|
[
"MIT"
] | null | null | null |
#include "test.h"
#include <unordered_map>
/** Question no 1386 medium Cinema Seat Allocation
* Author : Li-Han, Chen; 陳立瀚
* Date : 22th, March, 2020
* Source : https://leetcode.com/problems/cinema-seat-allocation/
*
* A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above.
*
* Given the array reservedSeats containing the numbers of seats already reserved,
* for example, reservedSeats[i]=[3,8] means the seat located in row 3 and labelled with 8 is already reserved.
*
* Return the maximum number of four-person families you can allocate on the cinema seats.
* A four-person family occupies fours seats in one row, that are next to each other.
* Seats across an aisle (such as [3,3] and [3,4]) are not considered to be next to each other, however,
* It is permissible for the four-person family to be separated by an aisle, but in that case,
* exactly two people have to sit on each side of the aisle.
*
*/
/** Solution
* Runtime 36 ms MeMory 8 MB;
* faster than 65.36%, less than 100.00%
* O(n) ; O(n)
*/
int maxNumberOfFamilies(int n, std::vector<std::vector<int>>& reservedSeats) {
std::unordered_map<int, int> mp;
int ans=2*n;
for (auto seat: reservedSeats) {
int row = seat[0], col = seat[1], bny;
if (mp.find(row) == mp.end()) mp[row] = 7;
int bf = mp[row];
if (col == 4 || col == 5) mp[row]%=2;
else if (col == 6 || col == 7) {
mp[row]>>=2;
mp[row]<<=2;
} else if ((col == 2 || col == 3) && mp[row]>3) mp[row]%=4;
else if (col == 8 || col == 9) {
mp[row]>>=1;
mp[row]<<=1;
} else continue;
if (bf-mp[row] == 0) continue;
else if (bf==7) ans--;
else if (mp[row]==0) ans--;
}
return ans;
}
| 34.788462
| 142
| 0.625207
|
dacozai
|
581bf2d3dbdd0b787a8b7c261d45686e1a88caf5
| 21,350
|
cpp
|
C++
|
Source/Physics/Joint.cpp
|
JesseMader/PlasmaEngine
|
ffda8f76b96e83181cfc1f9ec102c4ad0d7fd131
|
[
"MIT"
] | null | null | null |
Source/Physics/Joint.cpp
|
JesseMader/PlasmaEngine
|
ffda8f76b96e83181cfc1f9ec102c4ad0d7fd131
|
[
"MIT"
] | null | null | null |
Source/Physics/Joint.cpp
|
JesseMader/PlasmaEngine
|
ffda8f76b96e83181cfc1f9ec102c4ad0d7fd131
|
[
"MIT"
] | null | null | null |
// MIT Licensed (see LICENSE.md).
#include "Precompiled.hpp"
namespace Plasma
{
namespace Tags
{
DefineTag(Joint);
}
LightningDefineType(Joint, builder, type)
{
PlasmaBindDocumented();
PlasmaBindDependency(Cog);
PlasmaBindDependency(ObjectLink);
PlasmaBindSetup(SetupMode::DefaultSerialization);
LightningBindGetterSetterProperty(Active);
LightningBindGetterSetterProperty(SendsEvents);
LightningBindGetterSetterProperty(AutoSnaps);
LightningBindGetterSetterProperty(CollideConnected);
LightningBindGetterSetterProperty(MaxImpulse);
LightningBindMethod(GetOtherObject);
LightningBindMethod(GetCog);
PlasmaBindEvent(Events::JointExceedImpulseLimit, JointEvent);
PlasmaBindTag(Tags::Physics);
PlasmaBindTag(Tags::Joint);
}
Joint::Joint()
{
mSolver = nullptr;
mNode = new JointNode();
mNode->mJoint = this;
mFlags.Clear();
}
Joint::~Joint()
{
delete mNode;
}
void Joint::Serialize(Serializer& stream)
{
uint mask = JointFlags::OnIsland | JointFlags::Ghost | JointFlags::Valid | JointFlags::Initialized;
SerializeBits(stream,
mFlags,
JointFlags::Names,
mask,
JointFlags::CollideConnected | JointFlags::Active | JointFlags::SendsEvents);
real MaxImpulse;
if (stream.GetMode() == SerializerMode::Loading)
{
SerializeNameDefault(MaxImpulse, Math::PositiveMax());
SetMaxImpulse(MaxImpulse);
}
else
{
MaxImpulse = GetMaxImpulse();
SerializeNameDefault(MaxImpulse, Math::PositiveMax());
}
}
void Joint::Initialize(CogInitializer& initializer)
{
Space* space = initializer.GetSpace();
mSpace = space->has(PhysicsSpace);
ErrorIf(!mSpace, "Joint's space was invalid.");
}
void Joint::OnAllObjectsCreated(CogInitializer& initializer)
{
// Only do initialization once (can be called again from pulley or gear joint)
if (mFlags.IsSet(JointFlags::Initialized) == true)
return;
mFlags.SetFlag(JointFlags::Initialized);
ConnectThisTo(GetOwner(), Events::ObjectLinkChanged, OnObjectLinkChanged);
ConnectThisTo(GetOwner(), Events::ObjectLinkPointChanged, OnObjectLinkPointChanged);
// Always add to the space. This makes it easier to deal with partially
// invalid joints being destroyed (and the space list is only there for easy
// iteration of joints)
mSpace->AddComponent(this);
// Link up the collider edges to the object link's data.
LinkPair();
// Also wake up the objects we're connected to so that newly created joints
// will work properly.
// @JoshD: Should this only happen when during not object startup so that
// saved asleep objects stay asleep?
Physics::JointHelpers::ForceAwakeJoint(this);
// We were dynamically created so try to compute some logical initial values
bool dynamicallyCreated = (initializer.Flags & CreationFlags::DynamicallyAdded) != 0;
if (dynamicallyCreated)
ComputeInitialConfiguration();
}
void Joint::OnDestroy(uint flags)
{
// Always remove from the space, even if we weren't valid (because we're
// always added)
mSpace->RemoveComponent(this);
// If we were in a partially or completely invalid state then one of our
// colliders doesn't exist. If one of them was valid we could wake it up, but
// there's not really a point as this joint wasn't doing anything. Since it
// wasn't doing anything removing the joint shouldn't cause any change to the
// dynamics of a body and therefore waking it up isn't necessary. Same if we
// weren't active.
if (GetValid() && GetActive())
{
mEdges[0].mCollider->ForceAwake();
mEdges[1].mCollider->ForceAwake();
}
// Unlink from the colliders we were connected to. This also marks the joint
// as not valid just in case any other calls happen that would rely on being
// connected.
UnLinkPair();
}
void Joint::ComponentAdded(BoundType* typeId, Component* component)
{
if (typeId == LightningTypeId(JointLimit))
{
JointLimit* limit = static_cast<JointLimit*>(component);
limit->mAtomIds = GetDefaultLimitIds();
Physics::JointHelpers::ForceAwakeJoint(this);
}
else if (typeId == LightningTypeId(JointMotor))
{
JointMotor* motor = static_cast<JointMotor*>(component);
motor->mAtomIds = GetDefaultMotorIds();
Physics::JointHelpers::ForceAwakeJoint(this);
}
else if (typeId == LightningTypeId(JointSpring))
{
JointSpring* spring = static_cast<JointSpring*>(component);
spring->mAtomIds = GetDefaultSpringIds();
Physics::JointHelpers::ForceAwakeJoint(this);
}
}
void Joint::ComponentRemoved(BoundType* typeId, Component* component)
{
if (typeId == LightningTypeId(JointLimit))
Physics::JointHelpers::ForceAwakeJoint(this);
else if (typeId == LightningTypeId(JointMotor))
Physics::JointHelpers::ForceAwakeJoint(this);
else if (typeId == LightningTypeId(JointSpring))
Physics::JointHelpers::ForceAwakeJoint(this);
}
uint Joint::GetAtomIndexFilterVirtual(uint atomIndex, real& desiredConstraintValue) const
{
desiredConstraintValue = 0;
return 0;
}
void Joint::SetPair(Physics::ColliderPair& pair)
{
mEdges[0].mCollider = pair.mObjects[0];
mEdges[0].mOther = pair.mObjects[1];
mEdges[0].mJoint = this;
mEdges[1].mCollider = pair.mObjects[1];
mEdges[1].mOther = pair.mObjects[0];
mEdges[1].mJoint = this;
// We put not CollideConnected at the front so we can do quick filtering
if (GetCollideConnected())
{
if (pair.mObjects[0] != nullptr)
pair.mObjects[0]->mJointEdges.PushBack(&mEdges[0]);
if (pair.mObjects[1] != nullptr)
pair.mObjects[1]->mJointEdges.PushBack(&mEdges[1]);
}
else
{
if (pair.mObjects[0] != nullptr)
pair.mObjects[0]->mJointEdges.PushFront(&mEdges[0]);
if (pair.mObjects[1] != nullptr)
pair.mObjects[1]->mJointEdges.PushFront(&mEdges[1]);
}
// If either collider didn't exist, then don't become valid
if (pair.mObjects[0] == nullptr || pair.mObjects[1] == nullptr)
return;
SetValid(true);
}
void Joint::LinkPair()
{
ObjectLink* link = GetOwner()->has(ObjectLink);
Cog* objectA = link->GetObjectA();
Cog* objectB = link->GetObjectB();
Collider* collider0 = nullptr;
Collider* collider1 = nullptr;
// Try to find the collider from each object
if (objectA != nullptr)
collider0 = objectA->has(Collider);
if (objectB != nullptr)
collider1 = objectB->has(Collider);
// If we failed to get either collider then set this joint as not currently
// being valid (we can't solve)
if (collider0 == nullptr || collider1 == nullptr)
SetValid(false);
// We do have to set the pair properly so that edges and whatnot can be
// properly traversed and unlinked
ColliderPair pair;
pair.mObjects[0] = collider0;
pair.mObjects[1] = collider1;
SetPair(pair);
}
void Joint::UnLinkPair()
{
typedef InList<Joint, &Joint::SolverLink> JointList;
// Only remove from the island and solver if we're on an island.
if (GetOnIsland())
{
JointList::Unlink(this);
}
// Unlink from both colliders
for (size_t i = 0; i < 2; ++i)
{
if (mEdges[i].mCollider != nullptr)
{
Collider::JointEdgeList::Unlink(&mEdges[i]);
mEdges[i].mCollider = nullptr;
}
}
// We aren't linked to two valid colliders so mark ourself as !Valid
SetValid(false);
}
void Joint::Relink(uint index, Cog* cog)
{
// Get the collider from the input cog
Collider* collider = nullptr;
if (cog != nullptr)
collider = cog->has(Collider);
// Remove ourself from the island we were on (if we were on one)
typedef InList<Joint, &Joint::SolverLink> JointList;
if (GetOnIsland())
{
SetOnIsland(false);
JointList::Unlink(this);
}
EdgeType& mainEdge = mEdges[index];
EdgeType& otherEdge = mEdges[(index + 1) % 2];
// Unlink the old edge but only if that edge was to a
// valid collider (aka the edge hasn't been cleared already).
if (mainEdge.mJoint != nullptr && mainEdge.mCollider != nullptr)
Collider::JointEdgeList::Unlink(&mainEdge);
// Fix the colliders on the edges and add this edge to the new collider
mainEdge.mJoint = this;
mainEdge.mCollider = collider;
otherEdge.mOther = collider;
// If we have a collider then link its edge up
if (collider != nullptr)
collider->mJointEdges.PushBack(&mainEdge);
// If we were in a completely invalid state before being setup and now we're
// in a valid state we need to update valid (but not active, that should only
// ever be changed by the user)
bool isValid = (mainEdge.mCollider != nullptr && otherEdge.mCollider != nullptr);
SetValid(isValid);
// Finally, let joints know that we relinked so any specific joint type
// can respond (pulleys and gears need to hook-up some other pointers)
if (isValid)
SpecificJointRelink(index, collider);
}
void Joint::OnObjectLinkChanged(ObjectLinkEvent* event)
{
Relink(event->EdgeId, event->NewCog);
}
void Joint::OnObjectLinkPointChanged(ObjectLinkPointChangedEvent* e)
{
ObjectLinkPointUpdated(e->mEdgeId, e->mNewLocalPoint);
}
uint Joint::GetActiveFilter() const
{
return mConstraintFilter & FilterFlag;
}
uint Joint::GetDefaultFilter() const
{
return (mConstraintFilter >> DefaultOffset) & FilterFlag;
}
void Joint::ResetFilter()
{
mConstraintFilter &= ~FilterFlag;
mConstraintFilter |= (mConstraintFilter >> DefaultOffset) & FilterFlag;
}
Collider* Joint::GetCollider(uint index) const
{
return mEdges[index].mCollider;
}
Cog* Joint::GetCog(uint index)
{
Collider* collider = mEdges[index].mCollider;
if (collider != nullptr)
return collider->GetOwner();
return nullptr;
}
Cog* Joint::GetOtherObject(Cog* cog)
{
Cog* cog0 = GetCog(0);
Cog* cog1 = GetCog(1);
if (cog0 == cog)
return cog1;
else if (cog1 == cog)
return cog0;
return nullptr;
}
Vec3 Joint::GetLocalPointHelper(const Physics::AnchorAtom& anchor, uint index) const
{
return anchor[index];
}
void Joint::SetLocalPointHelper(Physics::AnchorAtom& anchor, uint index, Vec3Param localPoint)
{
anchor[index] = localPoint;
Physics::JointHelpers::ForceAwakeJoint(this);
ObjectLink* objectLink = GetOwner()->has(ObjectLink);
ErrorIf(objectLink == nullptr, "Joint is missing object link");
objectLink->SetLocalPoint(localPoint, (ObjectLink::ObjectIndex)index);
}
Vec3 Joint::GetWorldPointHelper(const Physics::AnchorAtom& anchor, uint index)
{
Collider* collider = GetCollider(index);
if (collider == nullptr)
return Vec3::cZero;
return Physics::JointHelpers::BodyRToWorldPoint(collider, anchor[index]);
}
void Joint::SetWorldPointAHelper(Physics::AnchorAtom& anchor, Vec3Param worldPoint)
{
// Register side-effect properties
if (OperationQueue::IsListeningForSideEffects())
OperationQueue::RegisterSideEffect(this, "LocalPointA", anchor[0]);
SetWorldPointHelper(anchor, worldPoint, 0);
}
void Joint::SetWorldPointBHelper(Physics::AnchorAtom& anchor, Vec3Param worldPoint)
{
// Register side-effect properties
if (OperationQueue::IsListeningForSideEffects())
OperationQueue::RegisterSideEffect(this, "LocalPointB", anchor[1]);
SetWorldPointHelper(anchor, worldPoint, 1);
}
void Joint::SetWorldPointHelper(Physics::AnchorAtom& anchor, Vec3Param worldPoint, uint index)
{
Collider* collider = GetCollider(index);
if (collider == nullptr)
return;
anchor[index] = Physics::JointHelpers::WorldPointToBodyR(collider, worldPoint);
Physics::JointHelpers::ForceAwakeJoint(this);
ObjectLink* objectLink = GetOwner()->has(ObjectLink);
ErrorIf(objectLink == nullptr, "Joint is missing object link");
objectLink->SetLocalPoint(anchor[index], (ObjectLink::ObjectIndex)index);
}
void Joint::SetWorldPointsHelper(Physics::AnchorAtom& anchor, Vec3Param point)
{
// Register side-effect properties
if (OperationQueue::IsListeningForSideEffects())
{
OperationQueue::RegisterSideEffect(this, "LocalPointA", anchor[0]);
OperationQueue::RegisterSideEffect(this, "LocalPointB", anchor[1]);
}
Collider* collider0 = GetCollider(0);
Collider* collider1 = GetCollider(1);
if (collider0 == nullptr || collider1 == nullptr)
return;
ObjectLink* objectLink = GetOwner()->has(ObjectLink);
ErrorIf(objectLink == nullptr, "Joint is missing object link");
anchor[0] = Physics::JointHelpers::WorldPointToBodyR(collider0, point);
anchor[1] = Physics::JointHelpers::WorldPointToBodyR(collider1, point);
objectLink->SetLocalPointA(anchor[0]);
objectLink->SetLocalPointB(anchor[1]);
Physics::JointHelpers::ForceAwakeJoint(this);
}
void Joint::ObjectLinkPointUpdatedHelper(Physics::AnchorAtom& anchor, size_t edgeIndex, Vec3Param localPoint)
{
anchor[edgeIndex] = localPoint;
Physics::JointHelpers::ForceAwakeJoint(this);
}
Vec3 Joint::GetLocalAxisHelper(const Physics::AxisAtom& axisAtom, uint index) const
{
return axisAtom[index];
}
void Joint::SetLocalAxisHelper(Physics::AxisAtom& axisAtom, uint index, Vec3Param localAxis)
{
if (localAxis == Vec3::cZero)
return;
axisAtom[index] = localAxis;
Physics::JointHelpers::ForceAwakeJoint(this);
}
Vec3 Joint::GetWorldAxisHelper(const Physics::AxisAtom& axisAtom) const
{
// There's no real logical world-space axis if the local space vectors don't
// map to the same value. Just use the local axis from object 0.
Collider* collider0 = GetCollider(0);
if (collider0 == nullptr)
return Vec3::cZero;
return Physics::JointHelpers::BodyToWorldR(collider0, axisAtom[0]);
}
void Joint::SetWorldAxisHelper(Physics::AxisAtom& axisAtom, Vec3Param worldAxis)
{
// Register side-effect properties
if (OperationQueue::IsListeningForSideEffects())
{
OperationQueue::RegisterSideEffect(this, "LocalAxisA", axisAtom[0]);
OperationQueue::RegisterSideEffect(this, "LocalAxisB", axisAtom[1]);
}
Vec3 fixedAxis = worldAxis;
if (fixedAxis == Vec3::cZero)
return;
Collider* collider0 = GetCollider(0);
Collider* collider1 = GetCollider(1);
if (collider0 == nullptr || collider1 == nullptr)
return;
axisAtom[0] = Physics::JointHelpers::WorldToBodyR(collider0, fixedAxis);
axisAtom[1] = Physics::JointHelpers::WorldToBodyR(collider1, fixedAxis);
Physics::JointHelpers::ForceAwakeJoint(this);
}
Quat Joint::GetLocalAngleHelper(const Physics::AngleAtom& angleAtom, uint index) const
{
return angleAtom[index];
}
void Joint::SetLocalAngleHelper(Physics::AngleAtom& angleAtom, uint index, QuatParam localReferenceFrame)
{
angleAtom[index] = localReferenceFrame;
Physics::JointHelpers::ForceAwakeJoint(this);
}
bool Joint::GetShouldBaumgarteBeUsed(uint type) const
{
PhysicsSolverConfig* config = mSolver->mSolverConfig;
ConstraintConfigBlock& block = config->mJointBlocks[type];
JointConfigOverride* configOverride = mNode->mConfigOverride;
// Check for the config override component and use its override if it has one.
if (configOverride != nullptr)
{
if (configOverride->mPositionCorrectionType == ConstraintPositionCorrection::PostStabilization)
return false;
if (configOverride->mPositionCorrectionType == ConstraintPositionCorrection::Baumgarte)
return true;
}
// Check the block type for the given joint. If it specifies one correction
// type then use that.
if (block.GetPositionCorrectionType() == ConstraintPositionCorrection::PostStabilization)
return false;
if (block.GetPositionCorrectionType() == ConstraintPositionCorrection::Baumgarte)
return true;
// Otherwise check the global state.
if (config->mPositionCorrectionType == PhysicsSolverPositionCorrection::PostStabilization)
return false;
return true;
}
real Joint::GetLinearBaumgarte(uint type) const
{
// The baumgarte term is always returned even if we aren't using baumgarte.
// This is because a joint could have a spring on it, in which case we ignore
// the position correction mode and always use baumgarte. Therefore, the code
// that calls this should determine whether or not to apply the baumgarte
// using GetShouldBaumgarteBeUsed (Same for angular baumgarte)
PhysicsSolverConfig* config = mSolver->mSolverConfig;
ConstraintConfigBlock& block = config->mJointBlocks[type];
JointConfigOverride* configOverride = mNode->mConfigOverride;
if (configOverride != nullptr)
return configOverride->mLinearBaumgarte;
return block.mLinearBaumgarte;
}
real Joint::GetAngularBaumgarte(uint type) const
{
// See the comment at the top of GetLinearBaumgarte for why we always return
// the baumgarte value.
PhysicsSolverConfig* config = mSolver->mSolverConfig;
ConstraintConfigBlock& block = config->mJointBlocks[type];
JointConfigOverride* configOverride = mNode->mConfigOverride;
if (configOverride != nullptr)
return configOverride->mAngularBaumgarte;
return block.mAngularBaumgarte;
}
real Joint::GetLinearErrorCorrection(uint type) const
{
PhysicsSolverConfig* config = mSolver->mSolverConfig;
ConstraintConfigBlock& block = config->mJointBlocks[type];
JointConfigOverride* configOverride = mNode->mConfigOverride;
if (configOverride != nullptr)
return configOverride->mLinearErrorCorrection;
return block.mLinearErrorCorrection;
}
real Joint::GetLinearErrorCorrection() const
{
return GetLinearErrorCorrection(GetJointType());
}
real Joint::GetAngularErrorCorrection(uint type) const
{
PhysicsSolverConfig* config = mSolver->mSolverConfig;
ConstraintConfigBlock& block = config->mJointBlocks[type];
JointConfigOverride* configOverride = mNode->mConfigOverride;
if (configOverride != nullptr)
return configOverride->mAngularErrorCorrection;
return block.mAngularErrorCorrection;
}
real Joint::GetAngularErrorCorrection() const
{
return GetAngularErrorCorrection(GetJointType());
}
real Joint::GetSlop() const
{
PhysicsSolverConfig* config = mSolver->mSolverConfig;
ConstraintConfigBlock& block = config->mJointBlocks[GetJointType()];
JointConfigOverride* configOverride = mNode->mConfigOverride;
if (configOverride != nullptr)
return configOverride->mSlop;
return block.mSlop;
}
void Joint::UpdateColliderCachedTransforms()
{
Collider* collider0 = GetCollider(0);
if (collider0 != nullptr)
collider0->UpdateQueue();
Collider* collider1 = GetCollider(1);
if (collider1 != nullptr)
collider1->UpdateQueue();
}
void Joint::ComputeCurrentAnchors(Physics::AnchorAtom& anchors)
{
// Just grab the body points from the object link
ObjectLink* link = GetOwner()->has(ObjectLink);
anchors[0] = link->GetLocalPointA();
anchors[1] = link->GetLocalPointB();
}
void Joint::ComputeCurrentReferenceAngle(Physics::AngleAtom& referenceAngle)
{
ObjectLink* link = GetOwner()->has(ObjectLink);
Cog* cogs[2];
cogs[0] = link->GetObjectA();
cogs[1] = link->GetObjectB();
// Compute the relative angles to make the objects maintain their current
// rotations. This is done by computing the orientation that will align
// the object with the identity (aka the inverse).
for (uint i = 0; i < 2; ++i)
{
Cog* cog = cogs[i];
if (cog != nullptr)
{
Transform* t = cog->has(Transform);
if (t != nullptr)
referenceAngle[i] = t->GetWorldRotation().Inverted();
}
}
}
bool Joint::GetOnIsland() const
{
return mFlags.IsSet(JointFlags::OnIsland);
}
void Joint::SetOnIsland(bool onIsland)
{
mFlags.SetState(JointFlags::OnIsland, onIsland);
}
bool Joint::GetGhost() const
{
return mFlags.IsSet(JointFlags::Ghost);
}
void Joint::SetGhost(bool ghost)
{
mFlags.SetState(JointFlags::Ghost, ghost);
}
bool Joint::GetValid() const
{
return mFlags.IsSet(JointFlags::Valid);
}
void Joint::SetValid(bool valid)
{
mFlags.SetState(JointFlags::Valid, valid);
}
bool Joint::GetActive() const
{
return mFlags.IsSet(JointFlags::Active);
}
void Joint::SetActive(bool active)
{
mFlags.SetState(JointFlags::Active, active);
Physics::JointHelpers::ForceAwakeJoint(this);
}
bool Joint::GetSendsEvents() const
{
return mFlags.IsSet(JointFlags::SendsEvents);
}
void Joint::SetSendsEvents(bool sendsEvents)
{
mFlags.SetState(JointFlags::SendsEvents, sendsEvents);
}
bool Joint::GetAutoSnaps() const
{
return mFlags.IsSet(JointFlags::AutoSnaps);
}
void Joint::SetAutoSnaps(bool autoSnaps)
{
mFlags.SetState(JointFlags::AutoSnaps, autoSnaps);
}
bool Joint::GetCollideConnected() const
{
return mFlags.IsSet(JointFlags::CollideConnected);
}
void Joint::SetCollideConnected(bool collideConnected)
{
mFlags.SetState(JointFlags::CollideConnected, collideConnected);
if (!GetValid())
return;
Collider::JointEdgeList::Unlink(&mEdges[0]);
Collider::JointEdgeList::Unlink(&mEdges[1]);
// By putting not collide connected at the front of each collider's list
// we can only check for not CollideConnected objects and stop once we reach a
// CollideConnected for quick rejection in ShouldCollide
if (collideConnected)
{
mEdges[0].mCollider->mJointEdges.PushBack(&mEdges[0]);
mEdges[1].mCollider->mJointEdges.PushBack(&mEdges[1]);
}
else
{
mEdges[0].mCollider->mJointEdges.PushFront(&mEdges[0]);
mEdges[1].mCollider->mJointEdges.PushFront(&mEdges[1]);
}
}
real Joint::GetMaxImpulse() const
{
if (mMaxImpulse == Math::PositiveMax())
return real(0.0);
return mMaxImpulse;
}
void Joint::SetMaxImpulse(real maxImpulse)
{
if (maxImpulse <= real(0.0))
maxImpulse = Math::PositiveMax();
mMaxImpulse = maxImpulse;
}
} // namespace Plasma
| 28.851351
| 109
| 0.72993
|
JesseMader
|
5820b09759dbd9498493383a041dd42f8a975514
| 3,055
|
cpp
|
C++
|
modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 34
|
2017-05-19T18:10:17.000Z
|
2022-01-04T02:18:13.000Z
|
modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | null | null | null |
modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp
|
psiha/nt2
|
5e829807f6b57b339ca1be918a6b60a2507c54d0
|
[
"BSL-1.0"
] | 7
|
2017-12-02T12:59:17.000Z
|
2021-07-31T12:46:14.000Z
|
//==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#include <boost/simd/bitwise/include/functions/ctz.hpp>
#include <boost/dispatch/functor/meta/call.hpp>
#include <nt2/sdk/unit/tests/relation.hpp>
#include <nt2/sdk/unit/tests/type_expr.hpp>
#include <nt2/sdk/unit/tests/exceptions.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/simd/include/constants/zero.hpp>
#include <boost/simd/include/constants/one.hpp>
#include <boost/simd/include/constants/signmask.hpp>
#include <boost/simd/include/constants/nbmantissabits.hpp>
#include <boost/simd/include/constants/nan.hpp>
#include <boost/simd/include/constants/inf.hpp>
#include <boost/simd/include/constants/minf.hpp>
#include <boost/simd/sdk/config.hpp>
NT2_TEST_CASE_TPL ( ctz_real, BOOST_SIMD_REAL_TYPES)
{
using boost::simd::ctz;
using boost::simd::tag::ctz_;
typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t;
typedef typename boost::dispatch::meta::as_integer<T>::type wished_r_t;
// return type conformity test
NT2_TEST_TYPE_IS(r_t, wished_r_t);
// specific values tests
#ifndef BOOST_SIMD_NO_INVALIDS
NT2_TEST_EQUAL(ctz(boost::simd::Inf<T>()), r_t(boost::simd::Nbmantissabits<T>()));
NT2_TEST_EQUAL(ctz(boost::simd::Minf<T>()), r_t(boost::simd::Nbmantissabits<T>()));
NT2_TEST_EQUAL(ctz(boost::simd::Nan<T>()), r_t(boost::simd::Zero<r_t>()));
#endif
NT2_TEST_ASSERT(ctz(boost::simd::Zero<T>()));
NT2_TEST_EQUAL(ctz(boost::simd::Signmask<T>()), r_t(sizeof(T)*8-1));
} // end of test for real_
NT2_TEST_CASE_TPL ( ctz_signed_int, BOOST_SIMD_INTEGRAL_SIGNED_TYPES)
{
using boost::simd::ctz;
using boost::simd::tag::ctz_;
using boost::simd::Nbmantissabits;
using boost::simd::Signmask;
typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t;
for(std::size_t j=0; j< (sizeof(T)*CHAR_BIT-1); j++)
{
// Test 01111 ... 10000b
T value = ~T(0) & ~((T(1)<<j)-1);
NT2_TEST_EQUAL(ctz( value ), r_t(j));
NT2_TEST_EQUAL(ctz( T(-value) ), r_t(j));
}
NT2_TEST_EQUAL(ctz(Signmask<T>()) , r_t(sizeof(T)*CHAR_BIT-1) );
}
NT2_TEST_CASE_TPL( ctz_unsigned_integer, BOOST_SIMD_UNSIGNED_TYPES )
{
using boost::simd::ctz;
using boost::simd::tag::ctz_;
typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t;
typedef typename boost::dispatch::meta::as_integer<T>::type wished_r_t;
// return type conformity test
NT2_TEST_TYPE_IS(r_t, wished_r_t);
// specific values tests
for(std::size_t j=0; j< sizeof(T)*CHAR_BIT; j++)
{
// Test 1111 ... 10000b
T value = ~T(0) & ~((T(1)<<j)-1);
NT2_TEST_EQUAL(ctz( value ), r_t(j));
}
}
| 36.807229
| 85
| 0.654664
|
psiha
|
582597bde0f8de7e5184d4ae2a3c7b34dd9aa68d
| 1,472
|
cpp
|
C++
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.cpp
|
oxygenxo/openvino
|
a984e7e81bcf4a18138b57632914b5a88815282d
|
[
"Apache-2.0"
] | null | null | null |
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.cpp
|
oxygenxo/openvino
|
a984e7e81bcf4a18138b57632914b5a88815282d
|
[
"Apache-2.0"
] | 29
|
2020-12-08T07:33:34.000Z
|
2022-02-21T13:03:37.000Z
|
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.cpp
|
oxygenxo/openvino
|
a984e7e81bcf4a18138b57632914b5a88815282d
|
[
"Apache-2.0"
] | null | null | null |
// Copyright (C) 2020 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include "low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.hpp"
#include <tuple>
#include <sstream>
#include <string>
#include <vector>
#include <transformations/init_node_info.hpp>
#include "lpt_ngraph_functions/fuse_subtract_to_fake_quantize_function.hpp"
namespace LayerTestsDefinitions {
std::string FuseSubtractToFakeQuantizeTransformation::getTestCaseName(testing::TestParamInfo<FuseSubtractToFakeQuantizeTransformationParams> obj) {
std::string targetDevice;
FuseSubtractToFakeQuantizeTransformationTestValues testValues;
std::tie(targetDevice, testValues) = obj.param;
std::ostringstream result;
result << targetDevice << "_" <<
testValues.actual.dequantization << "_" <<
testValues.actual.fakeQuantizeOnData;
return result.str();
}
void FuseSubtractToFakeQuantizeTransformation::SetUp() {
FuseSubtractToFakeQuantizeTransformationTestValues testValues;
std::tie(targetDevice, testValues) = this->GetParam();
function = ngraph::builder::subgraph::FuseSubtractToFakeQuantizeFunction::get(
testValues.inputShape,
testValues.actual.fakeQuantizeOnData,
testValues.actual.dequantization);
ngraph::pass::InitNodeInfo().run_on_function(function);
}
TEST_P(FuseSubtractToFakeQuantizeTransformation, CompareWithRefImpl) {
Run();
};
} // namespace LayerTestsDefinitions
| 32
| 147
| 0.777853
|
oxygenxo
|
582647cc35bcc66768b5d2a8e9a6c8bd180f1cd2
| 84
|
cc
|
C++
|
transport/MessageUtils.cc
|
ybatrakov/ybtrep
|
f5142b3f4611957537971f8e105ebb9fc911c726
|
[
"Apache-2.0"
] | null | null | null |
transport/MessageUtils.cc
|
ybatrakov/ybtrep
|
f5142b3f4611957537971f8e105ebb9fc911c726
|
[
"Apache-2.0"
] | null | null | null |
transport/MessageUtils.cc
|
ybatrakov/ybtrep
|
f5142b3f4611957537971f8e105ebb9fc911c726
|
[
"Apache-2.0"
] | null | null | null |
#include "MessageUtils.h"
mamaPayloadBridge MessageUtils::payloadBridge = nullptr;
| 21
| 56
| 0.821429
|
ybatrakov
|
5826f170c217ac14e36399a80add561303d113bd
| 3,407
|
cpp
|
C++
|
sources/sfzformat_db.cpp
|
sfztools/sfzfoo
|
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
|
[
"BSD-2-Clause"
] | 3
|
2019-12-31T10:53:03.000Z
|
2021-12-16T22:31:42.000Z
|
sources/sfzformat_db.cpp
|
sfztools/sfzfoo
|
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
|
[
"BSD-2-Clause"
] | 1
|
2020-01-04T01:11:24.000Z
|
2020-01-04T08:40:50.000Z
|
sources/sfzformat_db.cpp
|
sfztools/sfz-opcode-checker
|
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
|
[
"BSD-2-Clause"
] | null | null | null |
#include "sfzformat_db.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <iostream>
#include <fstream>
SfzDb *SfzDb::loadYAML(const ghc::filesystem::path &path)
{
SfzDb db;
db._opcodes.reserve(1024);
YAML::Node doc;
try {
doc = YAML::LoadFile(path);
}
catch (std::exception &ex) {
std::cerr << ex.what() << "\n";
return nullptr;
}
db.processCategories(doc["categories"]);
std::sort(db._opcodes.begin(), db._opcodes.end());
return new SfzDb{std::move(db)};
}
std::string SfzDb::createFatOpcodeRegexp() const
{
std::string re;
re.reserve(32 * 1024);
re.append("(?:");
bool firstOpcode = true;
for (const std::string &opcode : _opcodes) {
if (!firstOpcode)
re.push_back('|');
for (char c : opcode) {
bool isLower = c >= 'a' && c <= 'z';
bool isUpper = c >= 'A' && c <= 'Z';
bool isDigit = c >= '0' && c <= '9';
if (c == 'N' || c == 'X' || c == 'Y' || c == 'Z')
re.append("[0-9]+");
else if (c == '*')
re.append("[a-zA-Z0-9_]+");
else if (isLower || isUpper || isDigit || c == '_' || c == '#')
re.push_back(c);
else {
std::cerr << "Do not know how to handle character in regexp: " << (int)(unsigned char)c << "\n";
return std::string{};
}
}
firstOpcode = false;
}
re.append(")");
return re;
}
void SfzDb::processCategories(YAML::Node categoryList)
{
if (!categoryList.IsSequence())
return;
size_t numCat = categoryList.size();
for (size_t idxCat = 0; idxCat < numCat; ++idxCat) {
YAML::Node category = categoryList[idxCat];
processOpcodes(category["opcodes"]);
processTypes(category["types"]);
}
}
void SfzDb::processTypes(YAML::Node typeList)
{
if (!typeList.IsSequence())
return;
size_t numTypes = typeList.size();
for (size_t idxType = 0; idxType < numTypes; ++idxType) {
YAML::Node type = typeList[idxType];
processOpcodes(type["opcodes"]);
}
}
void SfzDb::processOpcodes(YAML::Node opcodeList)
{
if (!opcodeList.IsSequence())
return;
size_t numOpcodes = opcodeList.size();
for (size_t idxOpcode = 0; idxOpcode < numOpcodes; ++idxOpcode) {
YAML::Node opcode = opcodeList[idxOpcode];
processOpcodeName(opcode["name"].as<std::string>());
processOpcodeAlias(opcode["alias"]);
processOpcodeModulation(opcode["modulation"]);
}
}
void SfzDb::processOpcodeAlias(YAML::Node aliasList)
{
if (!aliasList.IsSequence())
return;
size_t numAliases = aliasList.size();
for (size_t idxAlias = 0; idxAlias < numAliases; ++idxAlias) {
YAML::Node alias = aliasList[idxAlias];
processOpcodeName(alias["name"].as<std::string>());
}
}
void SfzDb::processOpcodeModulation(YAML::Node modulationList)
{
if (!modulationList.IsMap())
return;
for (YAML::const_iterator it = modulationList.begin(), end = modulationList.end();
it != end; ++it)
{
// key: midi_cc, ... (other?)
processOpcodes(it->second);
}
}
void SfzDb::processOpcodeName(const std::string &name)
{
if (_opcodesUnordered.insert(name).second)
_opcodes.emplace_back(name);
}
| 25.051471
| 112
| 0.563546
|
sfztools
|
5827ef3dd8751b2c7cd0a0786c1fec0439b4eabe
| 3,172
|
cpp
|
C++
|
Source/Core/FontFace.cpp
|
Unvanquished/libRocket
|
ba129bb701e6777ac763f279fd8f8cbd8339e38d
|
[
"Unlicense",
"MIT"
] | null | null | null |
Source/Core/FontFace.cpp
|
Unvanquished/libRocket
|
ba129bb701e6777ac763f279fd8f8cbd8339e38d
|
[
"Unlicense",
"MIT"
] | 5
|
2016-07-13T00:50:00.000Z
|
2020-02-08T03:49:05.000Z
|
Source/Core/FontFace.cpp
|
Unvanquished/libRocket
|
ba129bb701e6777ac763f279fd8f8cbd8339e38d
|
[
"Unlicense",
"MIT"
] | 4
|
2015-10-24T11:59:32.000Z
|
2021-12-05T19:15:25.000Z
|
/*
* This source file is part of libRocket, the HTML/CSS Interface Middleware
*
* For the latest information, see http://www.librocket.com
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
*
* 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 "precompiled.h"
#include "FontFace.h"
#include <Rocket/Core/FontFaceHandle.h>
#include <Rocket/Core/Log.h>
namespace Rocket {
namespace Core {
FontFace::FontFace(FT_Face _face, Font::Style _style, Font::Weight _weight, bool _release_stream)
{
face = _face;
style = _style;
weight = _weight;
release_stream = _release_stream;
}
FontFace::~FontFace()
{
for (HandleMap::iterator iterator = handles.begin(); iterator != handles.end(); ++iterator)
{
iterator->second->RemoveReference();
}
ReleaseFace();
}
// Returns the style of the font face.
Font::Style FontFace::GetStyle() const
{
return style;
}
// Returns the weight of the font face.
Font::Weight FontFace::GetWeight() const
{
return weight;
}
// Returns a handle for positioning and rendering this face at the given size.
FontFaceHandle* FontFace::GetHandle(const String& _raw_charset, int size)
{
UnicodeRangeList charset;
HandleMap::iterator iterator = handles.find(size);
if (iterator != handles.end())
{
iterator->second->AddReference();
return iterator->second;
}
// See if this face has been released.
if (face == NULL)
{
Log::Message(Log::LT_WARNING, "Font face has been released, unable to generate new handle.");
return NULL;
}
// Construct and initialise the new handle.
FontFaceHandle* handle = new FontFaceHandle();
if (!handle->Initialise(face, _raw_charset, size))
{
handle->RemoveReference();
return NULL;
}
// Save the handle, and add a reference for the callee. The initial reference will be removed when the font face
// releases it.
handles[size] = handle;
handle->AddReference();
return handle;
}
// Releases the face's FreeType face structure.
void FontFace::ReleaseFace()
{
if (face != NULL)
{
FT_Byte* face_memory = face->stream->base;
FT_Done_Face(face);
if (release_stream)
delete[] face_memory;
face = NULL;
}
}
}
}
| 26.214876
| 113
| 0.729823
|
Unvanquished
|
5829320a442c8eb1dbd064ffecc8acfbdb6fe942
| 3,300
|
cpp
|
C++
|
src/game/client/c_colorcorrectionvolume.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 6
|
2022-01-23T09:40:33.000Z
|
2022-03-20T20:53:25.000Z
|
src/game/client/c_colorcorrectionvolume.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | null | null | null |
src/game/client/c_colorcorrectionvolume.cpp
|
cstom4994/SourceEngineRebuild
|
edfd7f8ce8af13e9d23586318350319a2e193c08
|
[
"MIT"
] | 1
|
2022-02-06T21:05:23.000Z
|
2022-02-06T21:05:23.000Z
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Color correction entity.
//
// $NoKeywords: $
//===========================================================================//
#include "cbase.h"
#include "filesystem.h"
#include "cdll_client_int.h"
#include "materialsystem/MaterialSystemUtil.h"
#include "colorcorrectionmgr.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
//------------------------------------------------------------------------------
// FIXME: This really should inherit from something more lightweight
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// Purpose : Shadow control entity
//------------------------------------------------------------------------------
class C_ColorCorrectionVolume : public C_BaseEntity {
public:
DECLARE_CLASS(C_ColorCorrectionVolume, C_BaseEntity);
DECLARE_CLIENTCLASS();
DECLARE_PREDICTABLE();
C_ColorCorrectionVolume();
virtual ~C_ColorCorrectionVolume();
void OnDataChanged(DataUpdateType_t updateType);
bool ShouldDraw();
void ClientThink();
private:
float m_Weight;
char m_lookupFilename[MAX_PATH];
ClientCCHandle_t m_CCHandle;
};
IMPLEMENT_CLIENTCLASS_DT(C_ColorCorrectionVolume, DT_ColorCorrectionVolume, CColorCorrectionVolume)
RecvPropFloat(RECVINFO(m_Weight)),
RecvPropString(RECVINFO(m_lookupFilename)),
END_RECV_TABLE()
BEGIN_PREDICTION_DATA(C_ColorCorrectionVolume)
DEFINE_PRED_FIELD(m_Weight, FIELD_FLOAT, FTYPEDESC_INSENDTABLE),
END_PREDICTION_DATA()
//------------------------------------------------------------------------------
// Constructor, destructor
//------------------------------------------------------------------------------
C_ColorCorrectionVolume::C_ColorCorrectionVolume() {
m_CCHandle = INVALID_CLIENT_CCHANDLE;
}
C_ColorCorrectionVolume::~C_ColorCorrectionVolume() {
g_pColorCorrectionMgr->RemoveColorCorrection(m_CCHandle);
}
//------------------------------------------------------------------------------
// Purpose :
// Input :
// Output :
//------------------------------------------------------------------------------
void C_ColorCorrectionVolume::OnDataChanged(DataUpdateType_t updateType) {
BaseClass::OnDataChanged(updateType);
if (updateType == DATA_UPDATE_CREATED) {
if (m_CCHandle == INVALID_CLIENT_CCHANDLE) {
char filename[MAX_PATH];
Q_strncpy(filename, m_lookupFilename, MAX_PATH);
m_CCHandle = g_pColorCorrectionMgr->AddColorCorrection(filename);
SetNextClientThink((m_CCHandle != INVALID_CLIENT_CCHANDLE) ? CLIENT_THINK_ALWAYS : CLIENT_THINK_NEVER);
}
}
}
//------------------------------------------------------------------------------
// We don't draw...
//------------------------------------------------------------------------------
bool C_ColorCorrectionVolume::ShouldDraw() {
return false;
}
void C_ColorCorrectionVolume::ClientThink() {
Vector entityPosition = GetAbsOrigin();
g_pColorCorrectionMgr->SetColorCorrectionWeight(m_CCHandle, m_Weight);
}
| 28.947368
| 115
| 0.531212
|
cstom4994
|
582d76a97d660cd80c90c2781b8d143006860485
| 1,667
|
cpp
|
C++
|
src/Platform/android/Application_Android.cpp
|
AmazingCow/MonsterFramework
|
e2cc94012ff3074c20aec2e095ea4242f91aa99e
|
[
"BSD-3-Clause"
] | null | null | null |
src/Platform/android/Application_Android.cpp
|
AmazingCow/MonsterFramework
|
e2cc94012ff3074c20aec2e095ea4242f91aa99e
|
[
"BSD-3-Clause"
] | 2
|
2016-09-27T00:13:22.000Z
|
2016-09-27T00:21:30.000Z
|
src/Platform/android/Application_Android.cpp
|
AmazingCow-Game-Framework/MonsterFramework
|
e2cc94012ff3074c20aec2e095ea4242f91aa99e
|
[
"BSD-3-Clause"
] | null | null | null |
#include "MonsterFramework/include/Platform/Application.h"
//Prevent the file to be compiled in NON Android builds.
#if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID )
//Jni
#include "platform/android/jni/JniHelper.h"
//Usings
USING_NS_MF;
USING_NS_CC;
////////////////////////////////////////////////////////////////////////////////
// CTOR / DTOR //
////////////////////////////////////////////////////////////////////////////////
mf::Application::Application() :
cc::Application()
{
constexpr auto kClassPath = "org/cocos2dx/cpp/AppActivity";
constexpr auto kMethodName = "getApplicationName";
constexpr auto kMethodSig = "()Ljava/lang/String;";
JNIEnv* pEnv;
JavaVM* j_jvm = cc::JniHelper::getJavaVM();
jint j_ret = j_jvm->GetEnv((void**)&pEnv, JNI_VERSION_1_4);
jclass j_class = pEnv->FindClass(kClassPath);
jmethodID j_methodId = pEnv->GetStaticMethodID(j_class, kMethodName, kMethodSig);
jstring j_str = (jstring)pEnv->CallStaticObjectMethod(j_class, j_methodId);
const char* cstr = pEnv->GetStringUTFChars(j_str, JNI_FALSE);
m_appName = cstr;
pEnv->ReleaseStringUTFChars(j_str, cstr); //Release the Java stuff.
}
////////////////////////////////////////////////////////////////////////////////
// Public Methods //
////////////////////////////////////////////////////////////////////////////////
const std::string& mf::Application::getApplicationName() const
{
return m_appName;
}
#endif // ( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ) //
| 34.729167
| 86
| 0.513497
|
AmazingCow
|
5839d0685d548e610c341210d01ab8ac68098520
| 1,151
|
hpp
|
C++
|
src/include/guinsoodb/storage/table/validity_segment.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | 1
|
2021-04-22T05:41:54.000Z
|
2021-04-22T05:41:54.000Z
|
src/include/guinsoodb/storage/table/validity_segment.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | null | null | null |
src/include/guinsoodb/storage/table/validity_segment.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | 1
|
2021-12-12T10:24:57.000Z
|
2021-12-12T10:24:57.000Z
|
//===----------------------------------------------------------------------===//
// GuinsooDB
//
// guinsoodb/storage/table/validity_segment.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "guinsoodb/storage/block.hpp"
#include "guinsoodb/storage/uncompressed_segment.hpp"
#include "guinsoodb/common/types/validity_mask.hpp"
namespace guinsoodb {
class BlockHandle;
class DatabaseInstance;
class SegmentStatistics;
class Vector;
struct VectorData;
class ValiditySegment : public UncompressedSegment {
public:
ValiditySegment(DatabaseInstance &db, idx_t row_start, block_id_t block_id = INVALID_BLOCK);
~ValiditySegment();
public:
void InitializeScan(ColumnScanState &state) override;
void FetchRow(ColumnFetchState &state, row_t row_id, Vector &result, idx_t result_idx) override;
idx_t Append(SegmentStatistics &stats, VectorData &data, idx_t offset, idx_t count) override;
void RevertAppend(idx_t start_row) override;
protected:
void FetchBaseData(ColumnScanState &state, idx_t vector_index, Vector &result) override;
};
} // namespace guinsoodb
| 30.289474
| 97
| 0.67159
|
GuinsooLab
|
5843439eade84033f422e6f86c98ec44d44fd90a
| 4,781
|
cpp
|
C++
|
src/shapes/sphere.cpp
|
guerarda/rt1w
|
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
|
[
"MIT"
] | null | null | null |
src/shapes/sphere.cpp
|
guerarda/rt1w
|
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
|
[
"MIT"
] | null | null | null |
src/shapes/sphere.cpp
|
guerarda/rt1w
|
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
|
[
"MIT"
] | null | null | null |
#include "shapes/sphere.hpp"
#include "rt1w/efloat.hpp"
#include "rt1w/error.h"
#include "rt1w/interaction.hpp"
#include "rt1w/params.hpp"
#include "rt1w/ray.hpp"
#include "rt1w/sampling.hpp"
#include "rt1w/transform.hpp"
#include "rt1w/utils.hpp"
#include "rt1w/value.hpp"
static inline bool SphereQuadratic(const Ray &r,
const v3f &oError,
const v3f &dError,
float radius,
EFloat &t0,
EFloat &t1)
{
EFloat ox = { r.org().x, oError.x };
EFloat oy = { r.org().y, oError.y };
EFloat oz = { r.org().z, oError.z };
EFloat dx = { r.dir().x, dError.x };
EFloat dy = { r.dir().y, dError.y };
EFloat dz = { r.dir().z, dError.z };
EFloat a = dx * dx + dy * dy + dz * dz;
EFloat b = 2.f * (dx * ox + dy * oy + dz * oz);
EFloat c = ox * ox + oy * oy + oz * oz - radius * radius;
return Quadratic(a, b, c, t0, t1);
}
struct _Sphere : Sphere {
_Sphere(const Transform &t, float r) :
m_worldToObj(t),
m_box(Inverse(t)(bounds3f{ -v3f{ r, r, r }, v3f{ r, r, r } })),
m_radius(r)
{}
bool intersect(const Ray &r, Interaction &isect) const override;
bool qIntersect(const Ray &r) const override;
float area() const override { return (float)(4. * Pi * m_radius * m_radius); }
bounds3f bounds() const override { return m_box; }
Transform worldToObj() const override { return m_worldToObj; }
Interaction sample(const v2f &u) const override;
float pdf() const override { return 1.f / area(); }
Interaction sample(const Interaction &ref, const v2f &u) const override;
float pdf(const Interaction &ref, const v3f &wi) const override;
float radius() const override { return m_radius; }
Transform m_worldToObj;
bounds3f m_box;
float m_radius;
};
bool _Sphere::intersect(const Ray &ray, Interaction &isect) const
{
v3f oError, dError;
Ray r = m_worldToObj(ray, oError, dError);
EFloat t0, t1;
if (!SphereQuadratic(r, oError, dError, m_radius, t0, t1)) {
return false;
}
EFloat t = t0.lo() > .0f && t0.hi() < r.max() ? t0 : t1;
if (t.lo() <= .0f || t.hi() >= r.max()) {
return false;
}
isect.t = (float)t;
isect.p = r(isect.t);
isect.n = Normalize(isect.p);
isect.wo = -r.dir();
/* Reproject p onto the sphere */
isect.p *= m_radius / isect.p.length();
isect.error = gamma(5) * Abs(isect.p);
/* Compute sphere uv */
v3f p = isect.n;
double theta = std::acos(Clamp(p.y, -1.0, 1.0));
double phi = std::atan2(p.x, p.z);
phi = phi < .0 ? phi + 2 * Pi : phi;
isect.uv.x = (float)(phi / (2.0 * Pi));
isect.uv.y = (float)(theta / Pi);
/* Compute dp/du & dp/dv */
double d = std::sqrt(p.x * p.x + p.z * p.z);
double sinPhi = p.x / d;
double cosPhi = p.z / d;
isect.dpdu = { (float)(2.0 * Pi * p.z), 0.0, (float)(-2.0 * Pi * p.x) };
isect.dpdv = v3f{ (float)(Pi * p.y * sinPhi),
(float)(Pi * -d),
(float)(Pi * p.y * cosPhi) };
/* Shading Geometry */
isect.shading.n = isect.n;
isect.shading.dpdu = isect.dpdu;
isect.shading.dpdv = isect.dpdv;
isect = Inverse(m_worldToObj)(isect);
return true;
}
bool _Sphere::qIntersect(const Ray &ray) const
{
v3f oError, dError;
Ray r = m_worldToObj(ray, oError, dError);
EFloat t0, t1;
if (SphereQuadratic(r, oError, dError, m_radius, t0, t1)) {
EFloat t = t0.lo() > .0f && t0.hi() < r.max() ? t0 : t1;
if (t.lo() > .0f && t.hi() < r.max()) {
return true;
}
}
return false;
}
Interaction _Sphere::sample(const v2f &u) const
{
Interaction it;
it.p = m_radius * UniformSampleSphere(u);
it.n = Normalize(it.p);
it.p = Mulp(Inverse(m_worldToObj), it.p);
it.n = Muln(Inverse(m_worldToObj), it.n);
return it;
}
Interaction _Sphere::sample(const Interaction &, const v2f &u) const
{
return sample(u);
}
float _Sphere::pdf(const Interaction &ref, const v3f &wi) const
{
Ray r = SpawnRay(ref, wi);
Interaction isect;
if (!intersect(r, isect)) {
return .0f;
}
return DistanceSquared(ref.p, isect.p) / (AbsDot(isect.n, -wi) * area());
}
#pragma mark - Static constructors
sptr<Sphere> Sphere::create(const Transform &worldToObj, float radius)
{
return std::make_shared<_Sphere>(worldToObj, radius);
}
sptr<Sphere> Sphere::create(const sptr<Params> &p)
{
float radius = Params::f32(p, "radius", 1.f);
m44f mat = Params::matrix44f(p, "transform", m44f_identity());
Transform t = Transform(mat);
return Sphere::create(t, radius);
}
| 28.289941
| 82
| 0.568919
|
guerarda
|
5848d8168c31b51e78b0c8ea0422f46dc16cd2a8
| 265
|
cc
|
C++
|
aria/examples/bar.cc
|
gunhoon2/aria
|
5bb0ac5c14c88c14b3078ee4af800aa8ec1aaadf
|
[
"MIT"
] | null | null | null |
aria/examples/bar.cc
|
gunhoon2/aria
|
5bb0ac5c14c88c14b3078ee4af800aa8ec1aaadf
|
[
"MIT"
] | null | null | null |
aria/examples/bar.cc
|
gunhoon2/aria
|
5bb0ac5c14c88c14b3078ee4af800aa8ec1aaadf
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2017, Gunhoon Lee (gunhoon@gmail.com)
#include "aria/examples/bar.h"
#include <iostream>
namespace aria {
Bar::Bar() {
std::cout << "Bar ctor.." << std::endl;
}
Bar::~Bar() {
std::cout << "Bar dtor.." << std::endl;
}
} // namespace aria
| 14.722222
| 54
| 0.592453
|
gunhoon2
|
584abe4a2122eb6e93668529e399634992c7214e
| 1,245
|
hpp
|
C++
|
include/cppurses/widget/widgets/checkbox.hpp
|
jktjkt/CPPurses
|
652d702258db8fab55ae945f7bb38e0b7c29521b
|
[
"MIT"
] | null | null | null |
include/cppurses/widget/widgets/checkbox.hpp
|
jktjkt/CPPurses
|
652d702258db8fab55ae945f7bb38e0b7c29521b
|
[
"MIT"
] | null | null | null |
include/cppurses/widget/widgets/checkbox.hpp
|
jktjkt/CPPurses
|
652d702258db8fab55ae945f7bb38e0b7c29521b
|
[
"MIT"
] | null | null | null |
#ifndef CPPURSES_WIDGET_WIDGETS_CHECKBOX_HPP
#define CPPURSES_WIDGET_WIDGETS_CHECKBOX_HPP
#include <cstddef>
#include <cstdint>
#include <signals/signals.hpp>
#include <cppurses/painter/glyph.hpp>
#include <cppurses/painter/glyph_string.hpp>
#include <cppurses/system/mouse_data.hpp>
#include <cppurses/widget/widget.hpp>
namespace cppurses {
/// On/Off state checkbox, using mouse input.
class Checkbox : public Widget {
public:
explicit Checkbox(Glyph_string title = "", int padding = 3);
void toggle();
bool is_checked() const;
Glyph_string title() const;
// Signals
sig::Signal<void()> checked;
sig::Signal<void()> unchecked;
sig::Signal<void()> toggled;
protected:
bool paint_event() override;
bool mouse_press_event(const Mouse_data& mouse) override;
private:
Glyph empty_box_{L'☐'};
Glyph checked_box_{L'☒'};
bool is_checked_{false};
Glyph_string title_;
int padding_;
};
void check(Checkbox& cb);
void uncheck(Checkbox& cb);
namespace slot {
sig::Slot<void()> toggle(Checkbox& cb);
sig::Slot<void()> check(Checkbox& cb);
sig::Slot<void()> uncheck(Checkbox& cb);
} // namespace slot
} // namespace cppurses
#endif // CPPURSES_WIDGET_WIDGETS_CHECKBOX_HPP
| 23.490566
| 64
| 0.713253
|
jktjkt
|
584e170ebe14efc0400153eaa30cdc1b49e1a7d8
| 2,666
|
cpp
|
C++
|
cpp/tests/openpaltests/src/ManagedPointerTestSuite.cpp
|
SensusDA/opendnp3
|
c9aab97279fa7461155fd583d3955853b3ad99a0
|
[
"Apache-2.0"
] | null | null | null |
cpp/tests/openpaltests/src/ManagedPointerTestSuite.cpp
|
SensusDA/opendnp3
|
c9aab97279fa7461155fd583d3955853b3ad99a0
|
[
"Apache-2.0"
] | null | null | null |
cpp/tests/openpaltests/src/ManagedPointerTestSuite.cpp
|
SensusDA/opendnp3
|
c9aab97279fa7461155fd583d3955853b3ad99a0
|
[
"Apache-2.0"
] | null | null | null |
/**
* Licensed to Green Energy Corp (www.greenenergycorp.com) under one or
* more contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright ownership.
* Green Energy Corp licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This project was forked on 01/01/2013 by Automatak, LLC and modifications
* may have been made to this file. Automatak, LLC licenses these modifications
* to you under the terms of the License.
*/
#include <catch.hpp>
#include <openpal/container/ManagedPtr.h>
using namespace openpal;
#include <vector>
#define SUITE(name) "ManagedPointerTestSuite - " name
struct Flags
{
Flags(int x_, int y_) : x(x_), y(y_)
{}
int x;
int y;
};
TEST_CASE(SUITE("ManagedPointersCanCreatedViaPoinerToStack"))
{
Flags stack = { 4, 3 };
auto pFlags = ManagedPtr<Flags>::WrapperOnly(&stack);
REQUIRE(pFlags->x == 4);
REQUIRE(pFlags->y == 3);
pFlags->x = 10;
pFlags->y = 20;
REQUIRE(pFlags->x == 10);
REQUIRE(pFlags->y == 20);
}
TEST_CASE(SUITE("ContainerTypesLikeVectorCanHoldAMixtureOfManagedAndUnmanaged"))
{
std::vector<ManagedPtr<Flags>> container;
Flags stack = { 4, 3 };
container.push_back(ManagedPtr<Flags>::WrapperOnly(&stack));
container.push_back(ManagedPtr<Flags>::WrapperOnly(&stack));
container.push_back(ManagedPtr<Flags>::Deleted(new Flags{ 10, 20 }));
container.push_back(ManagedPtr<Flags>::Deleted(new Flags{ 30, 40 }));
}
TEST_CASE(SUITE("ManagedPointersCanBeDereferenced"))
{
auto pFlags = ManagedPtr<Flags>::Deleted(new Flags{ 4, 3 });
REQUIRE(pFlags->x == 4);
REQUIRE(pFlags->y == 3);
pFlags->x = 10;
pFlags->y = 20;
REQUIRE(pFlags->x == 10);
REQUIRE(pFlags->y == 20);
}
TEST_CASE(SUITE("ManagedPointersCanBeMovementConstructed"))
{
auto pInt = ManagedPtr<int>::Deleted(new int);
ManagedPtr<int> copy(std::move(pInt));
REQUIRE_FALSE(pInt.IsDefined());
REQUIRE(copy.IsDefined());
}
TEST_CASE(SUITE("ManagedPointersCanBeMovementAssigned"))
{
auto pInt = ManagedPtr<int>::Deleted(new int);
auto pInt2 = std::move(pInt);
REQUIRE_FALSE(pInt.IsDefined());
REQUIRE(pInt2.IsDefined());
}
| 26.137255
| 80
| 0.723556
|
SensusDA
|
584f96c0ba024b5ad58956d1a91f0191a6e1b2c8
| 3,004
|
hpp
|
C++
|
include/continuable/detail/traversal/container-category.hpp
|
sTabishAzam/continuable
|
809f82673ad3458fe12b11fa6dee46d3cbcaf749
|
[
"MIT"
] | 745
|
2017-02-27T22:17:27.000Z
|
2022-03-21T20:15:14.000Z
|
include/continuable/detail/traversal/container-category.hpp
|
sTabishAzam/continuable
|
809f82673ad3458fe12b11fa6dee46d3cbcaf749
|
[
"MIT"
] | 45
|
2018-02-14T22:32:13.000Z
|
2022-02-09T14:56:09.000Z
|
include/continuable/detail/traversal/container-category.hpp
|
sTabishAzam/continuable
|
809f82673ad3458fe12b11fa6dee46d3cbcaf749
|
[
"MIT"
] | 47
|
2017-03-07T17:24:13.000Z
|
2022-02-03T07:06:21.000Z
|
/*
/~` _ _ _|_. _ _ |_ | _
\_,(_)| | | || ||_|(_||_)|(/_
https://github.com/Naios/continuable
v4.1.0
Copyright(c) 2015 - 2020 Denis Blank <denis.blank at outlook dot com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files(the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**/
#ifndef CONTINUABLE_DETAIL_CONTAINER_CATEGORY_HPP_INCLUDED
#define CONTINUABLE_DETAIL_CONTAINER_CATEGORY_HPP_INCLUDED
#include <tuple>
#include <type_traits>
#include <continuable/detail/utility/traits.hpp>
namespace cti {
namespace detail {
namespace traversal {
/// Deduces to a true type if the given parameter T
/// has a begin() and end() method.
// TODO Find out whether we should use std::begin and std::end instead, which
// could cause issues with plain arrays.
template <typename T, typename = void>
struct is_range : std::false_type {};
template <typename T>
struct is_range<T, traits::void_t<decltype(std::declval<T>().begin() ==
std::declval<T>().end())>>
: std::true_type {};
/// Deduces to a true type if the given parameter T
/// is accessible through std::tuple_size.
template <typename T, typename = void>
struct is_tuple_like : std::false_type {};
template <typename T>
struct is_tuple_like<T, traits::void_t<decltype(std::tuple_size<T>::value)>>
: std::true_type {};
/// A tag for dispatching based on the tuple like
/// or container properties of a type.
///
/// This type deduces to a true_type if it has any category.
template <bool IsContainer, bool IsTupleLike>
struct container_category_tag
: std::integral_constant<bool, IsContainer || IsTupleLike> {};
/// Deduces to the container_category_tag of the given type T.
template <typename T>
using container_category_of_t =
container_category_tag<is_range<T>::value, is_tuple_like<T>::value>;
} // namespace traversal
} // namespace detail
} // namespace cti
#endif // CONTINUABLE_DETAIL_CONTAINER_CATEGORY_HPP_INCLUDED
| 39.012987
| 79
| 0.713049
|
sTabishAzam
|
585aec9599f2b44a9fc6e914ba7a38d72528d475
| 10,982
|
cpp
|
C++
|
examples/src/jsonpointer_examples.cpp
|
bergmansj/jsoncons
|
11db194bd3f0e3e89f29b3447e28d131db242501
|
[
"BSL-1.0"
] | null | null | null |
examples/src/jsonpointer_examples.cpp
|
bergmansj/jsoncons
|
11db194bd3f0e3e89f29b3447e28d131db242501
|
[
"BSL-1.0"
] | null | null | null |
examples/src/jsonpointer_examples.cpp
|
bergmansj/jsoncons
|
11db194bd3f0e3e89f29b3447e28d131db242501
|
[
"BSL-1.0"
] | null | null | null |
// Copyright 2017 Daniel Parker
// Distributed under Boost license
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
namespace jp = jsoncons::jsonpointer;
void jsonpointer_select_RFC6901()
{
// Example from RFC 6901
auto j = jsoncons::json::parse(R"(
{
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
}
)");
try
{
const jsoncons::json& result1 = jp::get(j, "");
std::cout << "(1) " << result1 << std::endl;
const jsoncons::json& result2 = jp::get(j, "/foo");
std::cout << "(2) " << result2 << std::endl;
const jsoncons::json& result3 = jp::get(j, "/foo/0");
std::cout << "(3) " << result3 << std::endl;
const jsoncons::json& result4 = jp::get(j, "/");
std::cout << "(4) " << result4 << std::endl;
const jsoncons::json& result5 = jp::get(j, "/a~1b");
std::cout << "(5) " << result5 << std::endl;
const jsoncons::json& result6 = jp::get(j, "/c%d");
std::cout << "(6) " << result6 << std::endl;
const jsoncons::json& result7 = jp::get(j, "/e^f");
std::cout << "(7) " << result7 << std::endl;
const jsoncons::json& result8 = jp::get(j, "/g|h");
std::cout << "(8) " << result8 << std::endl;
const jsoncons::json& result9 = jp::get(j, "/i\\j");
std::cout << "(9) " << result9 << std::endl;
const jsoncons::json& result10 = jp::get(j, "/k\"l");
std::cout << "(10) " << result10 << std::endl;
const jsoncons::json& result11 = jp::get(j, "/ ");
std::cout << "(11) " << result11 << std::endl;
const jsoncons::json& result12 = jp::get(j, "/m~0n");
std::cout << "(12) " << result12 << std::endl;
}
catch (const jp::jsonpointer_error& e)
{
std::cerr << e.what() << std::endl;
}
}
void jsonpointer_contains()
{
// Example from RFC 6901
auto j = jsoncons::json::parse(R"(
{
"foo": ["bar", "baz"],
"": 0,
"a/b": 1,
"c%d": 2,
"e^f": 3,
"g|h": 4,
"i\\j": 5,
"k\"l": 6,
" ": 7,
"m~n": 8
}
)");
std::cout << "(1) " << jp::contains(j, "/foo/0") << std::endl;
std::cout << "(2) " << jp::contains(j, "e^g") << std::endl;
}
void jsonpointer_select_author()
{
auto j = jsoncons::json::parse(R"(
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
]
)");
// Using exceptions to report errors
try
{
jsoncons::json result = jp::get(j, "/1/author");
std::cout << "(1) " << result << std::endl;
}
catch (const jp::jsonpointer_error& e)
{
std::cout << e.what() << std::endl;
}
// Using error codes to report errors
std::error_code ec;
const jsoncons::json& result = jp::get(j, "/0/title", ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << "(2) " << result << std::endl;
}
}
void jsonpointer_add_member_to_object()
{
auto target = jsoncons::json::parse(R"(
{ "foo": "bar"}
)");
std::error_code ec;
jp::insert(target, "/baz", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_add_element_to_array()
{
auto target = jsoncons::json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
std::error_code ec;
jp::insert(target, "/foo/1", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_add_element_to_end_array()
{
auto target = jsoncons::json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
std::error_code ec;
jp::insert(target, "/foo/-", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_insert_name_exists()
{
auto target = jsoncons::json::parse(R"(
{ "foo": "bar", "baz" : "abc"}
)");
std::error_code ec;
jp::insert(target, "/baz", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_add_element_outside_range()
{
auto target = jsoncons::json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
std::error_code ec;
jp::insert_or_assign(target, "/foo/3", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_insert_or_assign_name_exists()
{
auto target = jsoncons::json::parse(R"(
{ "foo": "bar", "baz" : "abc"}
)");
std::error_code ec;
jp::insert_or_assign(target, "/baz", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_remove_object_member()
{
auto target = jsoncons::json::parse(R"(
{ "foo": "bar", "baz" : "qux"}
)");
std::error_code ec;
jp::remove(target, "/baz", ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_remove_array_element()
{
auto target = jsoncons::json::parse(R"(
{ "foo": [ "bar", "qux", "baz" ] }
)");
std::error_code ec;
jp::remove(target, "/foo/1", ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_replace_object_value()
{
auto target = jsoncons::json::parse(R"(
{
"baz": "qux",
"foo": "bar"
}
)");
std::error_code ec;
jp::replace(target, "/baz", jsoncons::json("boo"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
void jsonpointer_replace_array_value()
{
auto target = jsoncons::json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
std::error_code ec;
jp::replace(target, "/foo/1", jsoncons::json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << pretty_print(target) << std::endl;
}
}
void jsonpointer_error_example()
{
auto j = jsoncons::json::parse(R"(
[
{ "category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{ "category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
}
]
)");
try
{
jsoncons::json result = jp::get(j, "/1/isbn");
std::cout << "succeeded?" << std::endl;
std::cout << result << std::endl;
}
catch (const jp::jsonpointer_error& e)
{
std::cout << "Caught jsonpointer_error with category " << e.code().category().name()
<< ", code " << e.code().value()
<< " and message \"" << e.what() << "\"" << std::endl;
}
}
void jsonpointer_get_examples()
{
{
jsoncons::json j = jsoncons::json::array{"baz","foo"};
jsoncons::json& item = jp::get(j,"/0");
std::cout << "(1) " << item << std::endl;
//std::vector<uint8_t> u;
//cbor::encode_cbor(j,u);
//for (auto c : u)
//{
// std::cout << "0x" << std::hex << (int)c << ",";
//}
//std::cout << std::endl;
}
{
const jsoncons::json j = jsoncons::json::array{"baz","foo"};
const jsoncons::json& item = jp::get(j,"/1");
std::cout << "(2) " << item << std::endl;
}
{
jsoncons::json j = jsoncons::json::array{"baz","foo"};
std::error_code ec;
jsoncons::json& item = jp::get(j,"/1",ec);
std::cout << "(4) " << item << std::endl;
}
{
const jsoncons::json j = jsoncons::json::array{"baz","foo"};
std::error_code ec;
const jsoncons::json& item = jp::get(j,"/0",ec);
std::cout << "(5) " << item << std::endl;
}
}
void jsonpointer_address_example()
{
auto j = jsoncons::json::parse(R"(
{
"a/b": ["bar", "baz"],
"m~n": ["foo", "qux"]
}
)");
jp::address addr;
addr /= "m~n";
addr /= "1";
std::cout << "(1) " << addr << "\n\n";
std::cout << "(2)\n";
for (const auto& item : addr)
{
std::cout << item << "\n";
}
std::cout << "\n";
jsoncons::json item = jp::get(j, addr);
std::cout << "(3) " << item << "\n";
}
void jsonpointer_address_iterator_example()
{
jp::address addr("/store/book/1/author");
std::cout << "(1) " << addr << "\n\n";
std::cout << "(2)\n";
for (const auto& token : addr)
{
std::cout << token << "\n";
}
std::cout << "\n";
}
void jsonpointer_address_append_tokens()
{
jp::address addr;
addr /= "a/b";
addr /= "";
addr /= "m~n";
std::cout << "(1) " << addr << "\n\n";
std::cout << "(2)\n";
for (const auto& token : addr)
{
std::cout << token << "\n";
}
std::cout << "\n";
}
void jsonpointer_address_concatentae()
{
jp::address addr("/a~1b");
addr += jp::address("//m~0n");
std::cout << "(1) " << addr << "\n\n";
std::cout << "(2)\n";
for (const auto& token : addr)
{
std::cout << token << "\n";
}
std::cout << "\n";
}
void jsonpointer_examples()
{
std::cout << "\njsonpointer examples\n\n";
jsonpointer_select_author();
jsonpointer_address_example();
jsonpointer_select_RFC6901();
jsonpointer_add_member_to_object();
jsonpointer_add_element_to_array();
jsonpointer_add_element_to_end_array();
jsonpointer_add_element_outside_range();
jsonpointer_remove_object_member();
jsonpointer_remove_array_element();
jsonpointer_replace_object_value();
jsonpointer_replace_array_value();
jsonpointer_contains();
jsonpointer_error_example();
jsonpointer_insert_name_exists();
jsonpointer_insert_or_assign_name_exists();
jsonpointer_get_examples();
jsonpointer_address_iterator_example();
jsonpointer_address_append_tokens();
jsonpointer_address_concatentae();
}
| 23.12
| 93
| 0.490985
|
bergmansj
|
585b9624374e86b71ee3eecae40bcac3b41045de
| 798
|
hpp
|
C++
|
src/system/mainloop.hpp
|
ranjak/opengl-tutorial
|
fff192b9966c9e14d77b4becb9c205ea21a02069
|
[
"MIT"
] | 2
|
2018-08-24T00:09:03.000Z
|
2019-08-25T23:03:11.000Z
|
src/system/mainloop.hpp
|
ranjak/opengl-tutorial
|
fff192b9966c9e14d77b4becb9c205ea21a02069
|
[
"MIT"
] | null | null | null |
src/system/mainloop.hpp
|
ranjak/opengl-tutorial
|
fff192b9966c9e14d77b4becb9c205ea21a02069
|
[
"MIT"
] | 3
|
2016-12-02T17:22:14.000Z
|
2018-05-08T11:34:56.000Z
|
#ifndef MAINLOOP_HPP
#define MAINLOOP_HPP
#include "window.hpp"
#include "system.hpp"
#include "tutorial.hpp"
#include <string>
#include <memory>
class MainLoop
{
public:
static const ogl::time TIMESTEP;
static void requestExit();
MainLoop();
MainLoop(const MainLoop &) = delete;
MainLoop& operator=(const MainLoop &) = delete;
bool init(int width=640, int height=480, const std::string& title="OpenGL Window");
void run();
void setExit();
private:
void updateStats(ogl::time frameTime);
void logStats();
private:
static MainLoop *instance;
std::unique_ptr<Window> mMainWindow;
std::unique_ptr<Tutorial> mTutorial;
bool mExitRequested;
bool mDoLogStats;
ogl::time mMaxFrameTime;
ogl::time mAccuFrameTimes;
int mNumFrames;
};
#endif // MAINLOOP_HPP
| 16.978723
| 85
| 0.716792
|
ranjak
|
5862afb7b1e1ceb3205573978b688bf3ba0fdcf3
| 110,605
|
cpp
|
C++
|
mysql_install/inc/mysql-connector-c++-1.1.4/driver/mysql_util.cpp
|
vkardon/dbstream
|
1e5eb9354a1fb05466a178d2275aecab4b7f8bdd
|
[
"MIT"
] | null | null | null |
mysql_install/inc/mysql-connector-c++-1.1.4/driver/mysql_util.cpp
|
vkardon/dbstream
|
1e5eb9354a1fb05466a178d2275aecab4b7f8bdd
|
[
"MIT"
] | null | null | null |
mysql_install/inc/mysql-connector-c++-1.1.4/driver/mysql_util.cpp
|
vkardon/dbstream
|
1e5eb9354a1fb05466a178d2275aecab4b7f8bdd
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <string.h>
#include <stdlib.h>
#include <memory>
#include <sstream>
#include <cppconn/datatype.h>
#include <cppconn/exception.h>
#include "mysql_util.h"
#include "mysql_debug.h"
#include "nativeapi/native_connection_wrapper.h"
#include "nativeapi/native_statement_wrapper.h"
namespace sql {
namespace mysql {
namespace util {
/* just for cases when we need to return const empty string reference */
const sql::SQLString EMPTYSTR("");
const sql::SQLString LOCALHOST("localhost");
/* {{{ throwSQLException -I- */
void throwSQLException(::sql::mysql::NativeAPI::NativeConnectionWrapper & proxy)
{
throw sql::SQLException(proxy.error(), proxy.sqlstate(), proxy.errNo());
}
/* }}} */
/* {{{ throwSQLException -I- */
void throwSQLException(::sql::mysql::NativeAPI::NativeStatementWrapper & proxy)
{
throw sql::SQLException(proxy.error(), proxy.sqlstate(), proxy.errNo());
}
/* }}} */
#define cppconn_mbcharlen_big5 NULL
#define check_mb_big5 NULL
#define cppconn_mbcharlen_ujis NULL
#define check_mb_ujis NULL
#define cppconn_mbcharlen_sjis NULL
#define check_mb_sjis NULL
#define cppconn_mbcharlen_euckr NULL
#define check_mb_euckr NULL
#define cppconn_mbcharlen_gb2312 NULL
#define check_mb_gb2312 NULL
#define cppconn_mbcharlen_gbk NULL
#define check_mb_gbk NULL
#define cppconn_mbcharlen_utf8 NULL
#define check_mb_utf8_valid NULL
#define cppconn_mbcharlen_ucs2 NULL
#define check_mb_ucs2 NULL
#define cppconn_mbcharlen_cp932 NULL
#define check_mb_cp932 NULL
#define cppconn_mbcharlen_eucjpms NULL
#define check_mb_eucjpms NULL
#define cppconn_mbcharlen_utf8 NULL
#define check_mb_utf8_valid NULL
#define cppconn_mbcharlen_utf8mb4 cppconn_mbcharlen_utf8
#define check_mb_utf8mb4_valid check_mb_utf8_valid
#define cppconn_mbcharlen_utf16 NULL
#define check_mb_utf16_valid NULL
#define cppconn_mbcharlen_utf32 NULL
#define check_mb_utf32_valid NULL
/* {{{ our_charsets60 */
const OUR_CHARSET our_charsets60[] =
{
{ 1, "big5","big5_chinese_ci", 1, 2, "", cppconn_mbcharlen_big5, check_mb_big5},
{ 3, "dec8", "dec8_swedisch_ci", 1, 1, "", NULL, NULL},
{ 4, "cp850", "cp850_general_ci", 1, 1, "", NULL, NULL},
{ 6, "hp8", "hp8_english_ci", 1, 1, "", NULL, NULL},
{ 7, "koi8r", "koi8r_general_ci", 1, 1, "", NULL, NULL},
{ 8, "latin1", "latin1_swedish_ci", 1, 1, "", NULL, NULL},
{ 9, "latin2", "latin2_general_ci", 1, 1, "", NULL, NULL},
{ 10, "swe7", "swe7_swedish_ci", 1, 1, "", NULL, NULL},
{ 11, "ascii", "ascii_general_ci", 1, 1, "", NULL, NULL},
{ 12, "ujis", "ujis_japanese_ci", 1, 3, "", cppconn_mbcharlen_ujis, check_mb_ujis},
{ 13, "sjis", "sjis_japanese_ci", 1, 2, "", cppconn_mbcharlen_sjis, check_mb_sjis},
{ 16, "hebrew", "hebrew_general_ci", 1, 1, "", NULL, NULL},
{ 18, "tis620", "tis620_thai_ci", 1, 1, "", NULL, NULL},
{ 19, "euckr", "euckr_korean_ci", 1, 2, "", cppconn_mbcharlen_euckr, check_mb_euckr},
{ 22, "koi8u", "koi8u_general_ci", 1, 1, "", NULL, NULL},
{ 24, "gb2312", "gb2312_chinese_ci", 1, 2, "", cppconn_mbcharlen_gb2312, check_mb_gb2312},
{ 25, "greek", "greek_general_ci", 1, 1, "", NULL, NULL},
{ 26, "cp1250", "cp1250_general_ci", 1, 1, "", NULL, NULL},
{ 28, "gbk", "gbk_chinese_ci", 1, 2, "", cppconn_mbcharlen_gbk, check_mb_gbk},
{ 30, "latin5", "latin5_turkish_ci", 1, 1, "", NULL, NULL},
{ 32, "armscii8", "armscii8_general_ci", 1, 1, "", NULL, NULL},
{ 33, "utf8", "utf8_general_ci", 1, 3, "UTF-8 Unicode", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 35, "ucs2", "ucs2_general_ci", 2, 2, "UCS-2 Unicode", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 36, "cp866", "cp866_general_ci", 1, 1, "", NULL, NULL},
{ 37, "keybcs2", "keybcs2_general_ci", 1, 1, "", NULL, NULL},
{ 38, "macce", "macce_general_ci", 1, 1, "", NULL, NULL},
{ 39, "macroman", "macroman_general_ci", 1, 1, "", NULL, NULL},
{ 40, "cp852", "cp852_general_ci", 1, 1, "", NULL, NULL},
{ 41, "latin7", "latin7_general_ci", 1, 1, "", NULL, NULL},
{ 51, "cp1251", "cp1251_general_ci", 1, 1, "", NULL, NULL},
{ 57, "cp1256", "cp1256_general_ci", 1, 1, "", NULL, NULL},
{ 59, "cp1257", "cp1257_general_ci", 1, 1, "", NULL, NULL},
{ 63, "binary", "binary", 1, 1, "", NULL, NULL},
{ 92, "geostd8", "geostd8_general_ci", 1, 1, "", NULL, NULL},
{ 95, "cp932", "cp932_japanese_ci", 1, 2, "", cppconn_mbcharlen_cp932, check_mb_cp932},
{ 97, "eucjpms", "eucjpms_japanese_ci", 1, 3, "", cppconn_mbcharlen_eucjpms, check_mb_eucjpms},
{ 2, "latin2", "latin2_czech_cs", 1, 1, "", NULL, NULL},
{ 5, "latin1", "latin1_german_ci", 1, 1, "", NULL, NULL},
{ 14, "cp1251", "cp1251_bulgarian_ci", 1, 1, "", NULL, NULL},
{ 15, "latin1", "latin1_danish_ci", 1, 1, "", NULL, NULL},
{ 17, "filename", "filename", 1, 5, "", NULL, NULL},
{ 20, "latin7", "latin7_estonian_cs", 1, 1, "", NULL, NULL},
{ 21, "latin2", "latin2_hungarian_ci", 1, 1, "", NULL, NULL},
{ 23, "cp1251", "cp1251_ukrainian_ci", 1, 1, "", NULL, NULL},
{ 27, "latin2", "latin2_croatian_ci", 1, 1, "", NULL, NULL},
{ 29, "cp1257", "cp1257_lithunian_ci", 1, 1, "", NULL, NULL},
{ 31, "latin1", "latin1_german2_ci", 1, 1, "", NULL, NULL},
{ 34, "cp1250", "cp1250_czech_cs", 1, 1, "", NULL, NULL},
{ 42, "latin7", "latin7_general_cs", 1, 1, "", NULL, NULL},
{ 43, "macce", "macce_bin", 1, 1, "", NULL, NULL},
{ 44, "cp1250", "cp1250_croatian_ci", 1, 1, "", NULL, NULL},
{ 47, "latin1", "latin1_bin", 1, 1, "", NULL, NULL},
{ 48, "latin1", "latin1_general_ci", 1, 1, "", NULL, NULL},
{ 49, "latin1", "latin1_general_cs", 1, 1, "", NULL, NULL},
{ 50, "cp1251", "cp1251_bin", 1, 1, "", NULL, NULL},
{ 52, "cp1251", "cp1251_general_cs", 1, 1, "", NULL, NULL},
{ 53, "macroman", "macroman_bin", 1, 1, "", NULL, NULL},
{ 58, "cp1257", "cp1257_bin", 1, 1, "", NULL, NULL},
{ 60, "armascii8", "armascii8_bin", 1, 1, "", NULL, NULL},
{ 65, "ascii", "ascii_bin", 1, 1, "", NULL, NULL},
{ 66, "cp1250", "cp1250_bin", 1, 1, "", NULL, NULL},
{ 67, "cp1256", "cp1256_bin", 1, 1, "", NULL, NULL},
{ 68, "cp866", "cp866_bin", 1, 1, "", NULL, NULL},
{ 69, "dec8", "dec8_bin", 1, 1, "", NULL, NULL},
{ 70, "greek", "greek_bin", 1, 1, "", NULL, NULL},
{ 71, "hebrew", "hebrew_bin", 1, 1, "", NULL, NULL},
{ 72, "hp8", "hp8_bin", 1, 1, "", NULL, NULL},
{ 73, "keybcs2", "keybcs2_bin", 1, 1, "", NULL, NULL},
{ 74, "koi8r", "koi8r_bin", 1, 1, "", NULL, NULL},
{ 75, "koi8u", "koi8u_bin", 1, 1, "", NULL, NULL},
{ 77, "latin2", "latin2_bin", 1, 1, "", NULL, NULL},
{ 78, "latin5", "latin5_bin", 1, 1, "", NULL, NULL},
{ 79, "latin7", "latin7_bin", 1, 1, "", NULL, NULL},
{ 80, "cp850", "cp850_bin", 1, 1, "", NULL, NULL},
{ 81, "cp852", "cp852_bin", 1, 1, "", NULL, NULL},
{ 82, "swe7", "swe7_bin", 1, 1, "", NULL, NULL},
{ 93, "geostd8", "geostd8_bin", 1, 1, "", NULL, NULL},
{ 83, "utf8", "utf8_bin", 1, 3, "UTF-8 Unicode", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 84, "big5", "big5_bin", 1, 2, "", cppconn_mbcharlen_big5, check_mb_big5},
{ 85, "euckr", "euckr_bin", 1, 2, "", cppconn_mbcharlen_euckr, check_mb_euckr},
{ 86, "gb2312", "gb2312_bin", 1, 2, "", cppconn_mbcharlen_gb2312, check_mb_gb2312},
{ 87, "gbk", "gbk_bin", 1, 2, "", cppconn_mbcharlen_gbk, check_mb_gbk},
{ 88, "sjis", "sjis_bin", 1, 2, "", cppconn_mbcharlen_sjis, check_mb_sjis},
{ 89, "tis620", "tis620_bin", 1, 1, "", NULL, NULL},
{ 90, "ucs2", "ucs2_bin", 2, 2, "UCS-2 Unicode", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 91, "ujis", "ujis_bin", 1, 3, "", cppconn_mbcharlen_ujis, check_mb_ujis},
{ 94, "latin1", "latin1_spanish_ci", 1, 1, "", NULL, NULL},
{ 96, "cp932", "cp932_bin", 1, 2, "", cppconn_mbcharlen_cp932, check_mb_cp932},
{ 99, "cp1250", "cp1250_polish_ci", 1, 1, "", NULL, NULL},
{ 98, "eucjpms", "eucjpms_bin", 1, 3, "", cppconn_mbcharlen_eucjpms, check_mb_eucjpms},
{ 128, "ucs2", "ucs2_unicode_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 129, "ucs2", "ucs2_icelandic_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 130, "ucs2", "ucs2_latvian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 131, "ucs2", "ucs2_romanian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 132, "ucs2", "ucs2_slovenian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 133, "ucs2", "ucs2_polish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 134, "ucs2", "ucs2_estonian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 135, "ucs2", "ucs2_spanish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 136, "ucs2", "ucs2_swedish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 137, "ucs2", "ucs2_turkish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 138, "ucs2", "ucs2_czech_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 139, "ucs2", "ucs2_danish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 140, "ucs2", "ucs2_lithunian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 141, "ucs2", "ucs2_slovak_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 142, "ucs2", "ucs2_spanish2_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 143, "ucs2", "ucs2_roman_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 144, "ucs2", "ucs2_persian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 145, "ucs2", "ucs2_esperanto_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 146, "ucs2", "ucs2_hungarian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 147, "ucs2", "ucs2_sinhala_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 148, "ucs2", "ucs2_german2_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 149, "ucs2", "ucs2_croatian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 150, "ucs2", "ucs2_unicode_520_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2},
{ 192, "utf8", "utf8_unicode_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 193, "utf8", "utf8_icelandic_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 194, "utf8", "utf8_latvian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 195, "utf8", "utf8_romanian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 196, "utf8", "utf8_slovenian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 197, "utf8", "utf8_polish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 198, "utf8", "utf8_estonian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 199, "utf8", "utf8_spanish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 200, "utf8", "utf8_swedish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 201, "utf8", "utf8_turkish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 202, "utf8", "utf8_czech_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 203, "utf8", "utf8_danish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid },
{ 204, "utf8", "utf8_lithunian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid },
{ 205, "utf8", "utf8_slovak_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 206, "utf8", "utf8_spanish2_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 207, "utf8", "utf8_roman_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 208, "utf8", "utf8_persian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 209, "utf8", "utf8_esperanto_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 210, "utf8", "utf8_hungarian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 211, "utf8", "utf8_sinhala_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 212, "utf8", "utf8_german2_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 213, "utf8", "utf8_croatian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 214, "utf8", "utf8_unicode_520_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 215, "utf8", "utf8_vietnamese_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 223, "utf8", "utf8_general_mysql500_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 45, "utf8mb4", "utf8mb4_general_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 46, "utf8mb4", "utf8mb4_bin", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 224, "utf8mb4", "utf8mb4_unicode_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 225, "utf8mb4", "utf8mb4_icelandic_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 226, "utf8mb4", "utf8mb4_latvian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 227, "utf8mb4", "utf8mb4_romanian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 228, "utf8mb4", "utf8mb4_slovenian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 229, "utf8mb4", "utf8mb4_polish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 230, "utf8mb4", "utf8mb4_estonian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 231, "utf8mb4", "utf8mb4_spanish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 232, "utf8mb4", "utf8mb4_swedish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 233, "utf8mb4", "utf8mb4_turkish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 234, "utf8mb4", "utf8mb4_czech_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 235, "utf8mb4", "utf8mb4_danish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 236, "utf8mb4", "utf8mb4_lithuanian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 237, "utf8mb4", "utf8mb4_slovak_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 238, "utf8mb4", "utf8mb4_spanish2_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 239, "utf8mb4", "utf8mb4_roman_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 240, "utf8mb4", "utf8mb4_persian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 241, "utf8mb4", "utf8mb4_esperanto_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 242, "utf8mb4", "utf8mb4_hungarian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 243, "utf8mb4", "utf8mb4_sinhala_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 244, "utf8mb4", "utf8mb4_german2_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 245, "utf8mb4", "utf8mb4_croatian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 246, "utf8mb4", "utf8mb4_unicode_520_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
{ 247, "utf8mb4", "utf8mb4_vietnamese_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid},
/*Should not really happen, but adding them */
{ 254, "utf8", "utf8_general_cs", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid},
{ 101, "utf16", "utf16_unicode_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 102, "utf16", "utf16_icelandic_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 103, "utf16", "utf16_latvian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 104, "utf16", "utf16_romanian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 105, "utf16", "utf16_slovenian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 106, "utf16", "utf16_polish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 107, "utf16", "utf16_estonian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 108, "utf16", "utf16_spanish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 109, "utf16", "utf16_swedish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 110, "utf16", "utf16_turkish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 111, "utf16", "utf16_czech_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 112, "utf16", "utf16_danish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 113, "utf16", "utf16_lithuanian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 114, "utf16", "utf16_slovak_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 115, "utf16", "utf16_spanish2_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 116, "utf16", "utf16_roman_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 117, "utf16", "utf16_persian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 118, "utf16", "utf16_esperanto_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 119, "utf16", "utf16_hungarian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 120, "utf16", "utf16_sinhala_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 121, "utf16", "utf16_german2_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 122, "utf16", "utf16_croatian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 123, "utf16", "utf16_unicode_520_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 124, "utf16", "utf16_vietnamese_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid},
{ 160, "utf32", "utf32_unicode_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 161, "utf32", "utf32_icelandic_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 162, "utf32", "utf32_latvian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 163, "utf32", "utf32_romanian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 164, "utf32", "utf32_slovenian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 165, "utf32", "utf32_polish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 166, "utf32", "utf32_estonian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 167, "utf32", "utf32_spanish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 168, "utf32", "utf32_swedish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 169, "utf32", "utf32_turkish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 170, "utf32", "utf32_czech_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 171, "utf32", "utf32_danish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 172, "utf32", "utf32_lithuanian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 173, "utf32", "utf32_slovak_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 174, "utf32", "utf32_spanish2_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 175, "utf32", "utf32_roman_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 176, "utf32", "utf32_persian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 177, "utf32", "utf32_esperanto_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 178, "utf32", "utf32_hungarian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 179, "utf32", "utf32_sinhala_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 180, "utf32", "utf32_german2_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 181, "utf32", "utf32_croatian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 182, "utf32", "utf32_unicode_520_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 183, "utf32", "utf32_vietnamese_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid},
{ 0, NULL, NULL, 0, 0, NULL, NULL, NULL}
};
/* }}} */
/* {{{ find_charset */
const OUR_CHARSET * find_charset(unsigned int charsetnr)
{
const OUR_CHARSET * c = our_charsets60;
do {
if (c->nr == charsetnr) {
return c;
}
++c;
} while (c[0].nr != 0);
return NULL;
}
/* }}} */
#define MAGIC_BINARY_CHARSET_NR 63
/* {{{ mysql_to_datatype() -I- */
int
mysql_type_to_datatype(const MYSQL_FIELD * const field)
{
switch (field->type) {
case MYSQL_TYPE_BIT:
return sql::DataType::BIT;
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_NEWDECIMAL:
return sql::DataType::DECIMAL;
case MYSQL_TYPE_TINY:
return sql::DataType::TINYINT;
case MYSQL_TYPE_SHORT:
return sql::DataType::SMALLINT;
case MYSQL_TYPE_INT24:
return sql::DataType::MEDIUMINT;
case MYSQL_TYPE_LONG:
return sql::DataType::INTEGER;
case MYSQL_TYPE_LONGLONG:
return sql::DataType::BIGINT;
case MYSQL_TYPE_FLOAT:
return sql::DataType::REAL;
case MYSQL_TYPE_DOUBLE:
return sql::DataType::DOUBLE;
case MYSQL_TYPE_NULL:
return sql::DataType::SQLNULL;
case MYSQL_TYPE_TIMESTAMP:
return sql::DataType::TIMESTAMP;
case MYSQL_TYPE_DATE:
return sql::DataType::DATE;
case MYSQL_TYPE_TIME:
return sql::DataType::TIME;
case MYSQL_TYPE_YEAR:
return sql::DataType::YEAR;
case MYSQL_TYPE_DATETIME:
return sql::DataType::TIMESTAMP;
case MYSQL_TYPE_TINY_BLOB:// should no appear over the wire
{
bool isBinary = (field->flags & BINARY_FLAG) &&
field->charsetnr == MAGIC_BINARY_CHARSET_NR;
const sql::mysql::util::OUR_CHARSET * const cs =
sql::mysql::util::find_charset(field->charsetnr);
if (!cs) {
std::ostringstream msg("Server sent unknown charsetnr (");
msg << field->charsetnr << ") . Please report";
throw SQLException(msg.str());
}
return isBinary ? sql::DataType::VARBINARY : sql::DataType::VARCHAR;
}
case MYSQL_TYPE_MEDIUM_BLOB:// should no appear over the wire
case MYSQL_TYPE_LONG_BLOB:// should no appear over the wire
case MYSQL_TYPE_BLOB:
{
bool isBinary = (field->flags & BINARY_FLAG) &&
field->charsetnr == MAGIC_BINARY_CHARSET_NR;
const sql::mysql::util::OUR_CHARSET * const cs =
sql::mysql::util::find_charset(field->charsetnr);
if (!cs) {
std::ostringstream msg("Server sent unknown charsetnr (");
msg << field->charsetnr << ") . Please report";
throw SQLException(msg.str());
}
return isBinary ? sql::DataType::LONGVARBINARY : sql::DataType::LONGVARCHAR;
}
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
if (field->flags & SET_FLAG) {
return sql::DataType::SET;
}
if (field->flags & ENUM_FLAG) {
return sql::DataType::ENUM;
}
if ((field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR) {
return sql::DataType::VARBINARY;
}
return sql::DataType::VARCHAR;
case MYSQL_TYPE_STRING:
if (field->flags & SET_FLAG) {
return sql::DataType::SET;
}
if (field->flags & ENUM_FLAG) {
return sql::DataType::ENUM;
}
if ((field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR) {
return sql::DataType::BINARY;
}
return sql::DataType::CHAR;
case MYSQL_TYPE_ENUM:
/* This hould never happen - MYSQL_TYPE_ENUM is not sent over the wire, just used in the server */
return sql::DataType::ENUM;
case MYSQL_TYPE_SET:
/* This hould never happen - MYSQL_TYPE_SET is not sent over the wire, just used in the server */
return sql::DataType::SET;
case MYSQL_TYPE_GEOMETRY:
return sql::DataType::GEOMETRY;
default:
return sql::DataType::UNKNOWN;
}
}
/* }}} */
/* {{{ mysql_to_datatype() -I- */
int
mysql_string_type_to_datatype(const sql::SQLString & name)
{
/*
I_S.COLUMNS is buggy, because it deflivers (float|double) unsigned
but not (tinyint|smallint|mediumint|int|bigint) unsigned
*/
if (!name.compare("bit")) {
return sql::DataType::BIT;
} else if (!name.compare("decimal") || !name.compare("decimal unsigned")) {
return sql::DataType::DECIMAL;
} else if (!name.compare("tinyint") || !name.compare("tinyint unsigned")) {
return sql::DataType::TINYINT;
} else if (!name.compare("smallint") || !name.compare("smallint unsigned")) {
return sql::DataType::SMALLINT;
} else if (!name.compare("mediumint") || !name.compare("mediumint unsigned")) {
return sql::DataType::MEDIUMINT;
} else if (!name.compare("int") || !name.compare("int unsigned")) {
return sql::DataType::INTEGER;
} else if (!name.compare("bigint") || !name.compare("bigint unsigned")) {
return sql::DataType::BIGINT;
} else if (!name.compare("float") || !name.compare("float unsigned")) {
return sql::DataType::REAL;
} else if (!name.compare("double") || !name.compare("double unsigned")) {
return sql::DataType::DOUBLE;
} else if (!name.compare("timestamp")) {
return sql::DataType::TIMESTAMP;
} else if (!name.compare("date")) {
return sql::DataType::DATE;
} else if (!name.compare("time")) {
return sql::DataType::TIME;
} else if (!name.compare("year")) {
return sql::DataType::YEAR;
} else if (!name.compare("datetime")) {
return sql::DataType::TIMESTAMP;
} else if (!name.compare("tinytext")) {
return sql::DataType::VARCHAR;
} else if (!name.compare("mediumtext") || !name.compare("text") || !name.compare("longtext")) {
return sql::DataType::LONGVARCHAR;
} else if (!name.compare("tinyblob")) {
return sql::DataType::VARBINARY;
} else if (!name.compare("mediumblob") || !name.compare("blob") || !name.compare("longblob")) {
return sql::DataType::LONGVARBINARY;
} else if (!name.compare("char")) {
return sql::DataType::CHAR;
} else if (!name.compare("binary")) {
return sql::DataType::BINARY;
} else if (!name.compare("varchar")) {
return sql::DataType::VARCHAR;
} else if (!name.compare("varbinary")) {
return sql::DataType::VARBINARY;
} else if (!name.compare("enum")) {
return sql::DataType::ENUM;
} else if (!name.compare("set")) {
return sql::DataType::SET;
} else if (!name.compare("geometry")) {
return sql::DataType::GEOMETRY;
} else {
return sql::DataType::UNKNOWN;
}
}
/* }}} */
/* {{{ mysql_to_datatype() -I- */
const char *
mysql_type_to_string(const MYSQL_FIELD * const field, boost::shared_ptr< sql::mysql::MySQL_DebugLogger > & l)
{
CPP_ENTER_WL(l, "mysql_type_to_string");
bool isUnsigned = (field->flags & UNSIGNED_FLAG) != 0;
bool isZerofill = (field->flags & ZEROFILL_FLAG) != 0;
switch (field->type) {
case MYSQL_TYPE_BIT:
return "BIT";
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_NEWDECIMAL:
return isUnsigned ? (isZerofill? "DECIMAL UNSIGNED ZEROFILL" : "DECIMAL UNSIGNED"): "DECIMAL";
case MYSQL_TYPE_TINY:
return isUnsigned ? (isZerofill? "TINYINT UNSIGNED ZEROFILL" : "TINYINT UNSIGNED"): "TINYINT";
case MYSQL_TYPE_SHORT:
return isUnsigned ? (isZerofill? "SMALLINT UNSIGNED ZEROFILL" : "SMALLINT UNSIGNED"): "SMALLINT";
case MYSQL_TYPE_LONG:
return isUnsigned ? (isZerofill? "INT UNSIGNED ZEROFILL" : "INT UNSIGNED"): "INT";
case MYSQL_TYPE_FLOAT:
return isUnsigned ? (isZerofill? "FLOAT UNSIGNED ZEROFILL" : "FLOAT UNSIGNED"): "FLOAT";
case MYSQL_TYPE_DOUBLE:
return isUnsigned ? (isZerofill? "DOUBLE UNSIGNED ZEROFILL" : "DOUBLE UNSIGNED"): "DOUBLE";
case MYSQL_TYPE_NULL:
return "NULL";
case MYSQL_TYPE_TIMESTAMP:
return "TIMESTAMP";
case MYSQL_TYPE_LONGLONG:
return isUnsigned ? (isZerofill? "BIGINT UNSIGNED ZEROFILL" : "BIGINT UNSIGNED") : "BIGINT";
case MYSQL_TYPE_INT24:
return isUnsigned ? (isZerofill? "MEDIUMINT UNSIGNED ZEROFILL" : "MEDIUMINT UNSIGNED") : "MEDIUMINT";
case MYSQL_TYPE_DATE:
return "DATE";
case MYSQL_TYPE_TIME:
return "TIME";
case MYSQL_TYPE_DATETIME:
return "DATETIME";
case MYSQL_TYPE_TINY_BLOB:// should no appear over the wire
{
bool isBinary = field->charsetnr == MAGIC_BINARY_CHARSET_NR;
unsigned int char_maxlen = 1;
if (!isBinary) {
const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr);
if (!cset) {
std::ostringstream msg("Server sent unknown charsetnr (");
msg << field->charsetnr << ") . Please report";
throw SQLException(msg.str());
}
char_maxlen = cset->char_maxlen;
}
CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length);
return isBinary? "TINYBLOB":"TINYTEXT";
}
case MYSQL_TYPE_MEDIUM_BLOB:// should no appear over the wire
{
bool isBinary = field->charsetnr == MAGIC_BINARY_CHARSET_NR;
unsigned int char_maxlen = 1;
if (!isBinary) {
const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr);
if (!cset) {
std::ostringstream msg("Server sent unknown charsetnr (");
msg << field->charsetnr << ") . Please report";
throw SQLException(msg.str());
}
char_maxlen = cset->char_maxlen;
}
CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length);
return isBinary? "MEDIUMBLOB":"MEDIUMTEXT";
}
case MYSQL_TYPE_LONG_BLOB:// should no appear over the wire
{
bool isBinary = field->charsetnr == MAGIC_BINARY_CHARSET_NR;
unsigned int char_maxlen = 1;
if (!isBinary) {
const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr);
if (!cset) {
std::ostringstream msg("Server sent unknown charsetnr (");
msg << field->charsetnr << ") . Please report";
throw SQLException(msg.str());
}
char_maxlen = cset->char_maxlen;
}
CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length);
return isBinary? "LONGBLOB":"LONGTEXT";
}
case MYSQL_TYPE_BLOB:
{
bool isBinary= field->charsetnr == MAGIC_BINARY_CHARSET_NR;
unsigned int char_maxlen = 1;
if (!isBinary) {
const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr);
if (!cset) {
std::ostringstream msg("Server sent unknown charsetnr (");
msg << field->charsetnr << ") . Please report";
throw SQLException(msg.str());
}
char_maxlen = cset->char_maxlen;
}
CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length);
return isBinary? "BLOB":"TEXT";
}
case MYSQL_TYPE_VARCHAR:
case MYSQL_TYPE_VAR_STRING:
if (field->flags & ENUM_FLAG) {
return "ENUM";
}
if (field->flags & SET_FLAG) {
return "SET";
}
if (field->charsetnr == MAGIC_BINARY_CHARSET_NR) {
return "VARBINARY";
}
return "VARCHAR";
case MYSQL_TYPE_STRING:
if (field->flags & ENUM_FLAG) {
return "ENUM";
}
if (field->flags & SET_FLAG) {
return "SET";
}
if ((field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR) {
return "BINARY";
}
return "CHAR";
case MYSQL_TYPE_ENUM:
/* This should never happen */
return "ENUM";
case MYSQL_TYPE_YEAR:
return "YEAR";
case MYSQL_TYPE_SET:
/* This should never happen */
return "SET";
case MYSQL_TYPE_GEOMETRY:
return "GEOMETRY";
default:
return "UNKNOWN";
}
}
/* }}} */
/* The following code is from libmysql and is under the following license */
/*
Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.
The MySQL Connector/C++ is licensed under the terms of the GPLv2
<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most
MySQL Connectors. There are special exceptions to the terms and
conditions of the GPLv2 as it is applied to this software, see the
FLOSS License Exception
<http://www.mysql.com/about/legal/licensing/foss-exception.html>.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* UTF8 according RFC 2279 */
/* Written by Alexander Barkov <bar@udm.net> */
typedef struct unicase_info_st
{
uint16_t toupper;
uint16_t tolower;
uint16_t sort;
} MY_UNICASE_INFO;
static MY_UNICASE_INFO plane00[]={
{0x0000,0x0000,0x0000}, {0x0001,0x0001,0x0001},
{0x0002,0x0002,0x0002}, {0x0003,0x0003,0x0003},
{0x0004,0x0004,0x0004}, {0x0005,0x0005,0x0005},
{0x0006,0x0006,0x0006}, {0x0007,0x0007,0x0007},
{0x0008,0x0008,0x0008}, {0x0009,0x0009,0x0009},
{0x000A,0x000A,0x000A}, {0x000B,0x000B,0x000B},
{0x000C,0x000C,0x000C}, {0x000D,0x000D,0x000D},
{0x000E,0x000E,0x000E}, {0x000F,0x000F,0x000F},
{0x0010,0x0010,0x0010}, {0x0011,0x0011,0x0011},
{0x0012,0x0012,0x0012}, {0x0013,0x0013,0x0013},
{0x0014,0x0014,0x0014}, {0x0015,0x0015,0x0015},
{0x0016,0x0016,0x0016}, {0x0017,0x0017,0x0017},
{0x0018,0x0018,0x0018}, {0x0019,0x0019,0x0019},
{0x001A,0x001A,0x001A}, {0x001B,0x001B,0x001B},
{0x001C,0x001C,0x001C}, {0x001D,0x001D,0x001D},
{0x001E,0x001E,0x001E}, {0x001F,0x001F,0x001F},
{0x0020,0x0020,0x0020}, {0x0021,0x0021,0x0021},
{0x0022,0x0022,0x0022}, {0x0023,0x0023,0x0023},
{0x0024,0x0024,0x0024}, {0x0025,0x0025,0x0025},
{0x0026,0x0026,0x0026}, {0x0027,0x0027,0x0027},
{0x0028,0x0028,0x0028}, {0x0029,0x0029,0x0029},
{0x002A,0x002A,0x002A}, {0x002B,0x002B,0x002B},
{0x002C,0x002C,0x002C}, {0x002D,0x002D,0x002D},
{0x002E,0x002E,0x002E}, {0x002F,0x002F,0x002F},
{0x0030,0x0030,0x0030}, {0x0031,0x0031,0x0031},
{0x0032,0x0032,0x0032}, {0x0033,0x0033,0x0033},
{0x0034,0x0034,0x0034}, {0x0035,0x0035,0x0035},
{0x0036,0x0036,0x0036}, {0x0037,0x0037,0x0037},
{0x0038,0x0038,0x0038}, {0x0039,0x0039,0x0039},
{0x003A,0x003A,0x003A}, {0x003B,0x003B,0x003B},
{0x003C,0x003C,0x003C}, {0x003D,0x003D,0x003D},
{0x003E,0x003E,0x003E}, {0x003F,0x003F,0x003F},
{0x0040,0x0040,0x0040}, {0x0041,0x0061,0x0041},
{0x0042,0x0062,0x0042}, {0x0043,0x0063,0x0043},
{0x0044,0x0064,0x0044}, {0x0045,0x0065,0x0045},
{0x0046,0x0066,0x0046}, {0x0047,0x0067,0x0047},
{0x0048,0x0068,0x0048}, {0x0049,0x0069,0x0049},
{0x004A,0x006A,0x004A}, {0x004B,0x006B,0x004B},
{0x004C,0x006C,0x004C}, {0x004D,0x006D,0x004D},
{0x004E,0x006E,0x004E}, {0x004F,0x006F,0x004F},
{0x0050,0x0070,0x0050}, {0x0051,0x0071,0x0051},
{0x0052,0x0072,0x0052}, {0x0053,0x0073,0x0053},
{0x0054,0x0074,0x0054}, {0x0055,0x0075,0x0055},
{0x0056,0x0076,0x0056}, {0x0057,0x0077,0x0057},
{0x0058,0x0078,0x0058}, {0x0059,0x0079,0x0059},
{0x005A,0x007A,0x005A}, {0x005B,0x005B,0x005B},
{0x005C,0x005C,0x005C}, {0x005D,0x005D,0x005D},
{0x005E,0x005E,0x005E}, {0x005F,0x005F,0x005F},
{0x0060,0x0060,0x0060}, {0x0041,0x0061,0x0041},
{0x0042,0x0062,0x0042}, {0x0043,0x0063,0x0043},
{0x0044,0x0064,0x0044}, {0x0045,0x0065,0x0045},
{0x0046,0x0066,0x0046}, {0x0047,0x0067,0x0047},
{0x0048,0x0068,0x0048}, {0x0049,0x0069,0x0049},
{0x004A,0x006A,0x004A}, {0x004B,0x006B,0x004B},
{0x004C,0x006C,0x004C}, {0x004D,0x006D,0x004D},
{0x004E,0x006E,0x004E}, {0x004F,0x006F,0x004F},
{0x0050,0x0070,0x0050}, {0x0051,0x0071,0x0051},
{0x0052,0x0072,0x0052}, {0x0053,0x0073,0x0053},
{0x0054,0x0074,0x0054}, {0x0055,0x0075,0x0055},
{0x0056,0x0076,0x0056}, {0x0057,0x0077,0x0057},
{0x0058,0x0078,0x0058}, {0x0059,0x0079,0x0059},
{0x005A,0x007A,0x005A}, {0x007B,0x007B,0x007B},
{0x007C,0x007C,0x007C}, {0x007D,0x007D,0x007D},
{0x007E,0x007E,0x007E}, {0x007F,0x007F,0x007F},
{0x0080,0x0080,0x0080}, {0x0081,0x0081,0x0081},
{0x0082,0x0082,0x0082}, {0x0083,0x0083,0x0083},
{0x0084,0x0084,0x0084}, {0x0085,0x0085,0x0085},
{0x0086,0x0086,0x0086}, {0x0087,0x0087,0x0087},
{0x0088,0x0088,0x0088}, {0x0089,0x0089,0x0089},
{0x008A,0x008A,0x008A}, {0x008B,0x008B,0x008B},
{0x008C,0x008C,0x008C}, {0x008D,0x008D,0x008D},
{0x008E,0x008E,0x008E}, {0x008F,0x008F,0x008F},
{0x0090,0x0090,0x0090}, {0x0091,0x0091,0x0091},
{0x0092,0x0092,0x0092}, {0x0093,0x0093,0x0093},
{0x0094,0x0094,0x0094}, {0x0095,0x0095,0x0095},
{0x0096,0x0096,0x0096}, {0x0097,0x0097,0x0097},
{0x0098,0x0098,0x0098}, {0x0099,0x0099,0x0099},
{0x009A,0x009A,0x009A}, {0x009B,0x009B,0x009B},
{0x009C,0x009C,0x009C}, {0x009D,0x009D,0x009D},
{0x009E,0x009E,0x009E}, {0x009F,0x009F,0x009F},
{0x00A0,0x00A0,0x00A0}, {0x00A1,0x00A1,0x00A1},
{0x00A2,0x00A2,0x00A2}, {0x00A3,0x00A3,0x00A3},
{0x00A4,0x00A4,0x00A4}, {0x00A5,0x00A5,0x00A5},
{0x00A6,0x00A6,0x00A6}, {0x00A7,0x00A7,0x00A7},
{0x00A8,0x00A8,0x00A8}, {0x00A9,0x00A9,0x00A9},
{0x00AA,0x00AA,0x00AA}, {0x00AB,0x00AB,0x00AB},
{0x00AC,0x00AC,0x00AC}, {0x00AD,0x00AD,0x00AD},
{0x00AE,0x00AE,0x00AE}, {0x00AF,0x00AF,0x00AF},
{0x00B0,0x00B0,0x00B0}, {0x00B1,0x00B1,0x00B1},
{0x00B2,0x00B2,0x00B2}, {0x00B3,0x00B3,0x00B3},
{0x00B4,0x00B4,0x00B4}, {0x039C,0x00B5,0x039C},
{0x00B6,0x00B6,0x00B6}, {0x00B7,0x00B7,0x00B7},
{0x00B8,0x00B8,0x00B8}, {0x00B9,0x00B9,0x00B9},
{0x00BA,0x00BA,0x00BA}, {0x00BB,0x00BB,0x00BB},
{0x00BC,0x00BC,0x00BC}, {0x00BD,0x00BD,0x00BD},
{0x00BE,0x00BE,0x00BE}, {0x00BF,0x00BF,0x00BF},
{0x00C0,0x00E0,0x0041}, {0x00C1,0x00E1,0x0041},
{0x00C2,0x00E2,0x0041}, {0x00C3,0x00E3,0x0041},
{0x00C4,0x00E4,0x0041}, {0x00C5,0x00E5,0x0041},
{0x00C6,0x00E6,0x00C6}, {0x00C7,0x00E7,0x0043},
{0x00C8,0x00E8,0x0045}, {0x00C9,0x00E9,0x0045},
{0x00CA,0x00EA,0x0045}, {0x00CB,0x00EB,0x0045},
{0x00CC,0x00EC,0x0049}, {0x00CD,0x00ED,0x0049},
{0x00CE,0x00EE,0x0049}, {0x00CF,0x00EF,0x0049},
{0x00D0,0x00F0,0x00D0}, {0x00D1,0x00F1,0x004E},
{0x00D2,0x00F2,0x004F}, {0x00D3,0x00F3,0x004F},
{0x00D4,0x00F4,0x004F}, {0x00D5,0x00F5,0x004F},
{0x00D6,0x00F6,0x004F}, {0x00D7,0x00D7,0x00D7},
{0x00D8,0x00F8,0x00D8}, {0x00D9,0x00F9,0x0055},
{0x00DA,0x00FA,0x0055}, {0x00DB,0x00FB,0x0055},
{0x00DC,0x00FC,0x0055}, {0x00DD,0x00FD,0x0059},
{0x00DE,0x00FE,0x00DE}, {0x00DF,0x00DF,0x00DF},
{0x00C0,0x00E0,0x0041}, {0x00C1,0x00E1,0x0041},
{0x00C2,0x00E2,0x0041}, {0x00C3,0x00E3,0x0041},
{0x00C4,0x00E4,0x0041}, {0x00C5,0x00E5,0x0041},
{0x00C6,0x00E6,0x00C6}, {0x00C7,0x00E7,0x0043},
{0x00C8,0x00E8,0x0045}, {0x00C9,0x00E9,0x0045},
{0x00CA,0x00EA,0x0045}, {0x00CB,0x00EB,0x0045},
{0x00CC,0x00EC,0x0049}, {0x00CD,0x00ED,0x0049},
{0x00CE,0x00EE,0x0049}, {0x00CF,0x00EF,0x0049},
{0x00D0,0x00F0,0x00D0}, {0x00D1,0x00F1,0x004E},
{0x00D2,0x00F2,0x004F}, {0x00D3,0x00F3,0x004F},
{0x00D4,0x00F4,0x004F}, {0x00D5,0x00F5,0x004F},
{0x00D6,0x00F6,0x004F}, {0x00F7,0x00F7,0x00F7},
{0x00D8,0x00F8,0x00D8}, {0x00D9,0x00F9,0x0055},
{0x00DA,0x00FA,0x0055}, {0x00DB,0x00FB,0x0055},
{0x00DC,0x00FC,0x0055}, {0x00DD,0x00FD,0x0059},
{0x00DE,0x00FE,0x00DE}, {0x0178,0x00FF,0x0059}
};
static MY_UNICASE_INFO plane01[]={
{0x0100,0x0101,0x0041}, {0x0100,0x0101,0x0041},
{0x0102,0x0103,0x0041}, {0x0102,0x0103,0x0041},
{0x0104,0x0105,0x0041}, {0x0104,0x0105,0x0041},
{0x0106,0x0107,0x0043}, {0x0106,0x0107,0x0043},
{0x0108,0x0109,0x0043}, {0x0108,0x0109,0x0043},
{0x010A,0x010B,0x0043}, {0x010A,0x010B,0x0043},
{0x010C,0x010D,0x0043}, {0x010C,0x010D,0x0043},
{0x010E,0x010F,0x0044}, {0x010E,0x010F,0x0044},
{0x0110,0x0111,0x0110}, {0x0110,0x0111,0x0110},
{0x0112,0x0113,0x0045}, {0x0112,0x0113,0x0045},
{0x0114,0x0115,0x0045}, {0x0114,0x0115,0x0045},
{0x0116,0x0117,0x0045}, {0x0116,0x0117,0x0045},
{0x0118,0x0119,0x0045}, {0x0118,0x0119,0x0045},
{0x011A,0x011B,0x0045}, {0x011A,0x011B,0x0045},
{0x011C,0x011D,0x0047}, {0x011C,0x011D,0x0047},
{0x011E,0x011F,0x0047}, {0x011E,0x011F,0x0047},
{0x0120,0x0121,0x0047}, {0x0120,0x0121,0x0047},
{0x0122,0x0123,0x0047}, {0x0122,0x0123,0x0047},
{0x0124,0x0125,0x0048}, {0x0124,0x0125,0x0048},
{0x0126,0x0127,0x0126}, {0x0126,0x0127,0x0126},
{0x0128,0x0129,0x0049}, {0x0128,0x0129,0x0049},
{0x012A,0x012B,0x0049}, {0x012A,0x012B,0x0049},
{0x012C,0x012D,0x0049}, {0x012C,0x012D,0x0049},
{0x012E,0x012F,0x0049}, {0x012E,0x012F,0x0049},
{0x0130,0x0069,0x0049}, {0x0049,0x0131,0x0049},
{0x0132,0x0133,0x0132}, {0x0132,0x0133,0x0132},
{0x0134,0x0135,0x004A}, {0x0134,0x0135,0x004A},
{0x0136,0x0137,0x004B}, {0x0136,0x0137,0x004B},
{0x0138,0x0138,0x0138}, {0x0139,0x013A,0x004C},
{0x0139,0x013A,0x004C}, {0x013B,0x013C,0x004C},
{0x013B,0x013C,0x004C}, {0x013D,0x013E,0x004C},
{0x013D,0x013E,0x004C}, {0x013F,0x0140,0x013F},
{0x013F,0x0140,0x013F}, {0x0141,0x0142,0x0141},
{0x0141,0x0142,0x0141}, {0x0143,0x0144,0x004E},
{0x0143,0x0144,0x004E}, {0x0145,0x0146,0x004E},
{0x0145,0x0146,0x004E}, {0x0147,0x0148,0x004E},
{0x0147,0x0148,0x004E}, {0x0149,0x0149,0x0149},
{0x014A,0x014B,0x014A}, {0x014A,0x014B,0x014A},
{0x014C,0x014D,0x004F}, {0x014C,0x014D,0x004F},
{0x014E,0x014F,0x004F}, {0x014E,0x014F,0x004F},
{0x0150,0x0151,0x004F}, {0x0150,0x0151,0x004F},
{0x0152,0x0153,0x0152}, {0x0152,0x0153,0x0152},
{0x0154,0x0155,0x0052}, {0x0154,0x0155,0x0052},
{0x0156,0x0157,0x0052}, {0x0156,0x0157,0x0052},
{0x0158,0x0159,0x0052}, {0x0158,0x0159,0x0052},
{0x015A,0x015B,0x0053}, {0x015A,0x015B,0x0053},
{0x015C,0x015D,0x0053}, {0x015C,0x015D,0x0053},
{0x015E,0x015F,0x0053}, {0x015E,0x015F,0x0053},
{0x0160,0x0161,0x0053}, {0x0160,0x0161,0x0053},
{0x0162,0x0163,0x0054}, {0x0162,0x0163,0x0054},
{0x0164,0x0165,0x0054}, {0x0164,0x0165,0x0054},
{0x0166,0x0167,0x0166}, {0x0166,0x0167,0x0166},
{0x0168,0x0169,0x0055}, {0x0168,0x0169,0x0055},
{0x016A,0x016B,0x0055}, {0x016A,0x016B,0x0055},
{0x016C,0x016D,0x0055}, {0x016C,0x016D,0x0055},
{0x016E,0x016F,0x0055}, {0x016E,0x016F,0x0055},
{0x0170,0x0171,0x0055}, {0x0170,0x0171,0x0055},
{0x0172,0x0173,0x0055}, {0x0172,0x0173,0x0055},
{0x0174,0x0175,0x0057}, {0x0174,0x0175,0x0057},
{0x0176,0x0177,0x0059}, {0x0176,0x0177,0x0059},
{0x0178,0x00FF,0x0059}, {0x0179,0x017A,0x005A},
{0x0179,0x017A,0x005A}, {0x017B,0x017C,0x005A},
{0x017B,0x017C,0x005A}, {0x017D,0x017E,0x005A},
{0x017D,0x017E,0x005A}, {0x0053,0x017F,0x0053},
{0x0180,0x0180,0x0180}, {0x0181,0x0253,0x0181},
{0x0182,0x0183,0x0182}, {0x0182,0x0183,0x0182},
{0x0184,0x0185,0x0184}, {0x0184,0x0185,0x0184},
{0x0186,0x0254,0x0186}, {0x0187,0x0188,0x0187},
{0x0187,0x0188,0x0187}, {0x0189,0x0256,0x0189},
{0x018A,0x0257,0x018A}, {0x018B,0x018C,0x018B},
{0x018B,0x018C,0x018B}, {0x018D,0x018D,0x018D},
{0x018E,0x01DD,0x018E}, {0x018F,0x0259,0x018F},
{0x0190,0x025B,0x0190}, {0x0191,0x0192,0x0191},
{0x0191,0x0192,0x0191}, {0x0193,0x0260,0x0193},
{0x0194,0x0263,0x0194}, {0x01F6,0x0195,0x01F6},
{0x0196,0x0269,0x0196}, {0x0197,0x0268,0x0197},
{0x0198,0x0199,0x0198}, {0x0198,0x0199,0x0198},
{0x019A,0x019A,0x019A}, {0x019B,0x019B,0x019B},
{0x019C,0x026F,0x019C}, {0x019D,0x0272,0x019D},
{0x019E,0x019E,0x019E}, {0x019F,0x0275,0x019F},
{0x01A0,0x01A1,0x004F}, {0x01A0,0x01A1,0x004F},
{0x01A2,0x01A3,0x01A2}, {0x01A2,0x01A3,0x01A2},
{0x01A4,0x01A5,0x01A4}, {0x01A4,0x01A5,0x01A4},
{0x01A6,0x0280,0x01A6}, {0x01A7,0x01A8,0x01A7},
{0x01A7,0x01A8,0x01A7}, {0x01A9,0x0283,0x01A9},
{0x01AA,0x01AA,0x01AA}, {0x01AB,0x01AB,0x01AB},
{0x01AC,0x01AD,0x01AC}, {0x01AC,0x01AD,0x01AC},
{0x01AE,0x0288,0x01AE}, {0x01AF,0x01B0,0x0055},
{0x01AF,0x01B0,0x0055}, {0x01B1,0x028A,0x01B1},
{0x01B2,0x028B,0x01B2}, {0x01B3,0x01B4,0x01B3},
{0x01B3,0x01B4,0x01B3}, {0x01B5,0x01B6,0x01B5},
{0x01B5,0x01B6,0x01B5}, {0x01B7,0x0292,0x01B7},
{0x01B8,0x01B9,0x01B8}, {0x01B8,0x01B9,0x01B8},
{0x01BA,0x01BA,0x01BA}, {0x01BB,0x01BB,0x01BB},
{0x01BC,0x01BD,0x01BC}, {0x01BC,0x01BD,0x01BC},
{0x01BE,0x01BE,0x01BE}, {0x01F7,0x01BF,0x01F7},
{0x01C0,0x01C0,0x01C0}, {0x01C1,0x01C1,0x01C1},
{0x01C2,0x01C2,0x01C2}, {0x01C3,0x01C3,0x01C3},
{0x01C4,0x01C6,0x01C4}, {0x01C4,0x01C6,0x01C4},
{0x01C4,0x01C6,0x01C4}, {0x01C7,0x01C9,0x01C7},
{0x01C7,0x01C9,0x01C7}, {0x01C7,0x01C9,0x01C7},
{0x01CA,0x01CC,0x01CA}, {0x01CA,0x01CC,0x01CA},
{0x01CA,0x01CC,0x01CA}, {0x01CD,0x01CE,0x0041},
{0x01CD,0x01CE,0x0041}, {0x01CF,0x01D0,0x0049},
{0x01CF,0x01D0,0x0049}, {0x01D1,0x01D2,0x004F},
{0x01D1,0x01D2,0x004F}, {0x01D3,0x01D4,0x0055},
{0x01D3,0x01D4,0x0055}, {0x01D5,0x01D6,0x0055},
{0x01D5,0x01D6,0x0055}, {0x01D7,0x01D8,0x0055},
{0x01D7,0x01D8,0x0055}, {0x01D9,0x01DA,0x0055},
{0x01D9,0x01DA,0x0055}, {0x01DB,0x01DC,0x0055},
{0x01DB,0x01DC,0x0055}, {0x018E,0x01DD,0x018E},
{0x01DE,0x01DF,0x0041}, {0x01DE,0x01DF,0x0041},
{0x01E0,0x01E1,0x0041}, {0x01E0,0x01E1,0x0041},
{0x01E2,0x01E3,0x00C6}, {0x01E2,0x01E3,0x00C6},
{0x01E4,0x01E5,0x01E4}, {0x01E4,0x01E5,0x01E4},
{0x01E6,0x01E7,0x0047}, {0x01E6,0x01E7,0x0047},
{0x01E8,0x01E9,0x004B}, {0x01E8,0x01E9,0x004B},
{0x01EA,0x01EB,0x004F}, {0x01EA,0x01EB,0x004F},
{0x01EC,0x01ED,0x004F}, {0x01EC,0x01ED,0x004F},
{0x01EE,0x01EF,0x01B7}, {0x01EE,0x01EF,0x01B7},
{0x01F0,0x01F0,0x004A}, {0x01F1,0x01F3,0x01F1},
{0x01F1,0x01F3,0x01F1}, {0x01F1,0x01F3,0x01F1},
{0x01F4,0x01F5,0x0047}, {0x01F4,0x01F5,0x0047},
{0x01F6,0x0195,0x01F6}, {0x01F7,0x01BF,0x01F7},
{0x01F8,0x01F9,0x004E}, {0x01F8,0x01F9,0x004E},
{0x01FA,0x01FB,0x0041}, {0x01FA,0x01FB,0x0041},
{0x01FC,0x01FD,0x00C6}, {0x01FC,0x01FD,0x00C6},
{0x01FE,0x01FF,0x00D8}, {0x01FE,0x01FF,0x00D8}
};
static MY_UNICASE_INFO plane02[]={
{0x0200,0x0201,0x0041}, {0x0200,0x0201,0x0041},
{0x0202,0x0203,0x0041}, {0x0202,0x0203,0x0041},
{0x0204,0x0205,0x0045}, {0x0204,0x0205,0x0045},
{0x0206,0x0207,0x0045}, {0x0206,0x0207,0x0045},
{0x0208,0x0209,0x0049}, {0x0208,0x0209,0x0049},
{0x020A,0x020B,0x0049}, {0x020A,0x020B,0x0049},
{0x020C,0x020D,0x004F}, {0x020C,0x020D,0x004F},
{0x020E,0x020F,0x004F}, {0x020E,0x020F,0x004F},
{0x0210,0x0211,0x0052}, {0x0210,0x0211,0x0052},
{0x0212,0x0213,0x0052}, {0x0212,0x0213,0x0052},
{0x0214,0x0215,0x0055}, {0x0214,0x0215,0x0055},
{0x0216,0x0217,0x0055}, {0x0216,0x0217,0x0055},
{0x0218,0x0219,0x0053}, {0x0218,0x0219,0x0053},
{0x021A,0x021B,0x0054}, {0x021A,0x021B,0x0054},
{0x021C,0x021D,0x021C}, {0x021C,0x021D,0x021C},
{0x021E,0x021F,0x0048}, {0x021E,0x021F,0x0048},
{0x0220,0x0220,0x0220}, {0x0221,0x0221,0x0221},
{0x0222,0x0223,0x0222}, {0x0222,0x0223,0x0222},
{0x0224,0x0225,0x0224}, {0x0224,0x0225,0x0224},
{0x0226,0x0227,0x0041}, {0x0226,0x0227,0x0041},
{0x0228,0x0229,0x0045}, {0x0228,0x0229,0x0045},
{0x022A,0x022B,0x004F}, {0x022A,0x022B,0x004F},
{0x022C,0x022D,0x004F}, {0x022C,0x022D,0x004F},
{0x022E,0x022F,0x004F}, {0x022E,0x022F,0x004F},
{0x0230,0x0231,0x004F}, {0x0230,0x0231,0x004F},
{0x0232,0x0233,0x0059}, {0x0232,0x0233,0x0059},
{0x0234,0x0234,0x0234}, {0x0235,0x0235,0x0235},
{0x0236,0x0236,0x0236}, {0x0237,0x0237,0x0237},
{0x0238,0x0238,0x0238}, {0x0239,0x0239,0x0239},
{0x023A,0x023A,0x023A}, {0x023B,0x023B,0x023B},
{0x023C,0x023C,0x023C}, {0x023D,0x023D,0x023D},
{0x023E,0x023E,0x023E}, {0x023F,0x023F,0x023F},
{0x0240,0x0240,0x0240}, {0x0241,0x0241,0x0241},
{0x0242,0x0242,0x0242}, {0x0243,0x0243,0x0243},
{0x0244,0x0244,0x0244}, {0x0245,0x0245,0x0245},
{0x0246,0x0246,0x0246}, {0x0247,0x0247,0x0247},
{0x0248,0x0248,0x0248}, {0x0249,0x0249,0x0249},
{0x024A,0x024A,0x024A}, {0x024B,0x024B,0x024B},
{0x024C,0x024C,0x024C}, {0x024D,0x024D,0x024D},
{0x024E,0x024E,0x024E}, {0x024F,0x024F,0x024F},
{0x0250,0x0250,0x0250}, {0x0251,0x0251,0x0251},
{0x0252,0x0252,0x0252}, {0x0181,0x0253,0x0181},
{0x0186,0x0254,0x0186}, {0x0255,0x0255,0x0255},
{0x0189,0x0256,0x0189}, {0x018A,0x0257,0x018A},
{0x0258,0x0258,0x0258}, {0x018F,0x0259,0x018F},
{0x025A,0x025A,0x025A}, {0x0190,0x025B,0x0190},
{0x025C,0x025C,0x025C}, {0x025D,0x025D,0x025D},
{0x025E,0x025E,0x025E}, {0x025F,0x025F,0x025F},
{0x0193,0x0260,0x0193}, {0x0261,0x0261,0x0261},
{0x0262,0x0262,0x0262}, {0x0194,0x0263,0x0194},
{0x0264,0x0264,0x0264}, {0x0265,0x0265,0x0265},
{0x0266,0x0266,0x0266}, {0x0267,0x0267,0x0267},
{0x0197,0x0268,0x0197}, {0x0196,0x0269,0x0196},
{0x026A,0x026A,0x026A}, {0x026B,0x026B,0x026B},
{0x026C,0x026C,0x026C}, {0x026D,0x026D,0x026D},
{0x026E,0x026E,0x026E}, {0x019C,0x026F,0x019C},
{0x0270,0x0270,0x0270}, {0x0271,0x0271,0x0271},
{0x019D,0x0272,0x019D}, {0x0273,0x0273,0x0273},
{0x0274,0x0274,0x0274}, {0x019F,0x0275,0x019F},
{0x0276,0x0276,0x0276}, {0x0277,0x0277,0x0277},
{0x0278,0x0278,0x0278}, {0x0279,0x0279,0x0279},
{0x027A,0x027A,0x027A}, {0x027B,0x027B,0x027B},
{0x027C,0x027C,0x027C}, {0x027D,0x027D,0x027D},
{0x027E,0x027E,0x027E}, {0x027F,0x027F,0x027F},
{0x01A6,0x0280,0x01A6}, {0x0281,0x0281,0x0281},
{0x0282,0x0282,0x0282}, {0x01A9,0x0283,0x01A9},
{0x0284,0x0284,0x0284}, {0x0285,0x0285,0x0285},
{0x0286,0x0286,0x0286}, {0x0287,0x0287,0x0287},
{0x01AE,0x0288,0x01AE}, {0x0289,0x0289,0x0289},
{0x01B1,0x028A,0x01B1}, {0x01B2,0x028B,0x01B2},
{0x028C,0x028C,0x028C}, {0x028D,0x028D,0x028D},
{0x028E,0x028E,0x028E}, {0x028F,0x028F,0x028F},
{0x0290,0x0290,0x0290}, {0x0291,0x0291,0x0291},
{0x01B7,0x0292,0x01B7}, {0x0293,0x0293,0x0293},
{0x0294,0x0294,0x0294}, {0x0295,0x0295,0x0295},
{0x0296,0x0296,0x0296}, {0x0297,0x0297,0x0297},
{0x0298,0x0298,0x0298}, {0x0299,0x0299,0x0299},
{0x029A,0x029A,0x029A}, {0x029B,0x029B,0x029B},
{0x029C,0x029C,0x029C}, {0x029D,0x029D,0x029D},
{0x029E,0x029E,0x029E}, {0x029F,0x029F,0x029F},
{0x02A0,0x02A0,0x02A0}, {0x02A1,0x02A1,0x02A1},
{0x02A2,0x02A2,0x02A2}, {0x02A3,0x02A3,0x02A3},
{0x02A4,0x02A4,0x02A4}, {0x02A5,0x02A5,0x02A5},
{0x02A6,0x02A6,0x02A6}, {0x02A7,0x02A7,0x02A7},
{0x02A8,0x02A8,0x02A8}, {0x02A9,0x02A9,0x02A9},
{0x02AA,0x02AA,0x02AA}, {0x02AB,0x02AB,0x02AB},
{0x02AC,0x02AC,0x02AC}, {0x02AD,0x02AD,0x02AD},
{0x02AE,0x02AE,0x02AE}, {0x02AF,0x02AF,0x02AF},
{0x02B0,0x02B0,0x02B0}, {0x02B1,0x02B1,0x02B1},
{0x02B2,0x02B2,0x02B2}, {0x02B3,0x02B3,0x02B3},
{0x02B4,0x02B4,0x02B4}, {0x02B5,0x02B5,0x02B5},
{0x02B6,0x02B6,0x02B6}, {0x02B7,0x02B7,0x02B7},
{0x02B8,0x02B8,0x02B8}, {0x02B9,0x02B9,0x02B9},
{0x02BA,0x02BA,0x02BA}, {0x02BB,0x02BB,0x02BB},
{0x02BC,0x02BC,0x02BC}, {0x02BD,0x02BD,0x02BD},
{0x02BE,0x02BE,0x02BE}, {0x02BF,0x02BF,0x02BF},
{0x02C0,0x02C0,0x02C0}, {0x02C1,0x02C1,0x02C1},
{0x02C2,0x02C2,0x02C2}, {0x02C3,0x02C3,0x02C3},
{0x02C4,0x02C4,0x02C4}, {0x02C5,0x02C5,0x02C5},
{0x02C6,0x02C6,0x02C6}, {0x02C7,0x02C7,0x02C7},
{0x02C8,0x02C8,0x02C8}, {0x02C9,0x02C9,0x02C9},
{0x02CA,0x02CA,0x02CA}, {0x02CB,0x02CB,0x02CB},
{0x02CC,0x02CC,0x02CC}, {0x02CD,0x02CD,0x02CD},
{0x02CE,0x02CE,0x02CE}, {0x02CF,0x02CF,0x02CF},
{0x02D0,0x02D0,0x02D0}, {0x02D1,0x02D1,0x02D1},
{0x02D2,0x02D2,0x02D2}, {0x02D3,0x02D3,0x02D3},
{0x02D4,0x02D4,0x02D4}, {0x02D5,0x02D5,0x02D5},
{0x02D6,0x02D6,0x02D6}, {0x02D7,0x02D7,0x02D7},
{0x02D8,0x02D8,0x02D8}, {0x02D9,0x02D9,0x02D9},
{0x02DA,0x02DA,0x02DA}, {0x02DB,0x02DB,0x02DB},
{0x02DC,0x02DC,0x02DC}, {0x02DD,0x02DD,0x02DD},
{0x02DE,0x02DE,0x02DE}, {0x02DF,0x02DF,0x02DF},
{0x02E0,0x02E0,0x02E0}, {0x02E1,0x02E1,0x02E1},
{0x02E2,0x02E2,0x02E2}, {0x02E3,0x02E3,0x02E3},
{0x02E4,0x02E4,0x02E4}, {0x02E5,0x02E5,0x02E5},
{0x02E6,0x02E6,0x02E6}, {0x02E7,0x02E7,0x02E7},
{0x02E8,0x02E8,0x02E8}, {0x02E9,0x02E9,0x02E9},
{0x02EA,0x02EA,0x02EA}, {0x02EB,0x02EB,0x02EB},
{0x02EC,0x02EC,0x02EC}, {0x02ED,0x02ED,0x02ED},
{0x02EE,0x02EE,0x02EE}, {0x02EF,0x02EF,0x02EF},
{0x02F0,0x02F0,0x02F0}, {0x02F1,0x02F1,0x02F1},
{0x02F2,0x02F2,0x02F2}, {0x02F3,0x02F3,0x02F3},
{0x02F4,0x02F4,0x02F4}, {0x02F5,0x02F5,0x02F5},
{0x02F6,0x02F6,0x02F6}, {0x02F7,0x02F7,0x02F7},
{0x02F8,0x02F8,0x02F8}, {0x02F9,0x02F9,0x02F9},
{0x02FA,0x02FA,0x02FA}, {0x02FB,0x02FB,0x02FB},
{0x02FC,0x02FC,0x02FC}, {0x02FD,0x02FD,0x02FD},
{0x02FE,0x02FE,0x02FE}, {0x02FF,0x02FF,0x02FF}
};
static MY_UNICASE_INFO plane03[]={
{0x0300,0x0300,0x0300}, {0x0301,0x0301,0x0301},
{0x0302,0x0302,0x0302}, {0x0303,0x0303,0x0303},
{0x0304,0x0304,0x0304}, {0x0305,0x0305,0x0305},
{0x0306,0x0306,0x0306}, {0x0307,0x0307,0x0307},
{0x0308,0x0308,0x0308}, {0x0309,0x0309,0x0309},
{0x030A,0x030A,0x030A}, {0x030B,0x030B,0x030B},
{0x030C,0x030C,0x030C}, {0x030D,0x030D,0x030D},
{0x030E,0x030E,0x030E}, {0x030F,0x030F,0x030F},
{0x0310,0x0310,0x0310}, {0x0311,0x0311,0x0311},
{0x0312,0x0312,0x0312}, {0x0313,0x0313,0x0313},
{0x0314,0x0314,0x0314}, {0x0315,0x0315,0x0315},
{0x0316,0x0316,0x0316}, {0x0317,0x0317,0x0317},
{0x0318,0x0318,0x0318}, {0x0319,0x0319,0x0319},
{0x031A,0x031A,0x031A}, {0x031B,0x031B,0x031B},
{0x031C,0x031C,0x031C}, {0x031D,0x031D,0x031D},
{0x031E,0x031E,0x031E}, {0x031F,0x031F,0x031F},
{0x0320,0x0320,0x0320}, {0x0321,0x0321,0x0321},
{0x0322,0x0322,0x0322}, {0x0323,0x0323,0x0323},
{0x0324,0x0324,0x0324}, {0x0325,0x0325,0x0325},
{0x0326,0x0326,0x0326}, {0x0327,0x0327,0x0327},
{0x0328,0x0328,0x0328}, {0x0329,0x0329,0x0329},
{0x032A,0x032A,0x032A}, {0x032B,0x032B,0x032B},
{0x032C,0x032C,0x032C}, {0x032D,0x032D,0x032D},
{0x032E,0x032E,0x032E}, {0x032F,0x032F,0x032F},
{0x0330,0x0330,0x0330}, {0x0331,0x0331,0x0331},
{0x0332,0x0332,0x0332}, {0x0333,0x0333,0x0333},
{0x0334,0x0334,0x0334}, {0x0335,0x0335,0x0335},
{0x0336,0x0336,0x0336}, {0x0337,0x0337,0x0337},
{0x0338,0x0338,0x0338}, {0x0339,0x0339,0x0339},
{0x033A,0x033A,0x033A}, {0x033B,0x033B,0x033B},
{0x033C,0x033C,0x033C}, {0x033D,0x033D,0x033D},
{0x033E,0x033E,0x033E}, {0x033F,0x033F,0x033F},
{0x0340,0x0340,0x0340}, {0x0341,0x0341,0x0341},
{0x0342,0x0342,0x0342}, {0x0343,0x0343,0x0343},
{0x0344,0x0344,0x0344}, {0x0399,0x0345,0x0399},
{0x0346,0x0346,0x0346}, {0x0347,0x0347,0x0347},
{0x0348,0x0348,0x0348}, {0x0349,0x0349,0x0349},
{0x034A,0x034A,0x034A}, {0x034B,0x034B,0x034B},
{0x034C,0x034C,0x034C}, {0x034D,0x034D,0x034D},
{0x034E,0x034E,0x034E}, {0x034F,0x034F,0x034F},
{0x0350,0x0350,0x0350}, {0x0351,0x0351,0x0351},
{0x0352,0x0352,0x0352}, {0x0353,0x0353,0x0353},
{0x0354,0x0354,0x0354}, {0x0355,0x0355,0x0355},
{0x0356,0x0356,0x0356}, {0x0357,0x0357,0x0357},
{0x0358,0x0358,0x0358}, {0x0359,0x0359,0x0359},
{0x035A,0x035A,0x035A}, {0x035B,0x035B,0x035B},
{0x035C,0x035C,0x035C}, {0x035D,0x035D,0x035D},
{0x035E,0x035E,0x035E}, {0x035F,0x035F,0x035F},
{0x0360,0x0360,0x0360}, {0x0361,0x0361,0x0361},
{0x0362,0x0362,0x0362}, {0x0363,0x0363,0x0363},
{0x0364,0x0364,0x0364}, {0x0365,0x0365,0x0365},
{0x0366,0x0366,0x0366}, {0x0367,0x0367,0x0367},
{0x0368,0x0368,0x0368}, {0x0369,0x0369,0x0369},
{0x036A,0x036A,0x036A}, {0x036B,0x036B,0x036B},
{0x036C,0x036C,0x036C}, {0x036D,0x036D,0x036D},
{0x036E,0x036E,0x036E}, {0x036F,0x036F,0x036F},
{0x0370,0x0370,0x0370}, {0x0371,0x0371,0x0371},
{0x0372,0x0372,0x0372}, {0x0373,0x0373,0x0373},
{0x0374,0x0374,0x0374}, {0x0375,0x0375,0x0375},
{0x0376,0x0376,0x0376}, {0x0377,0x0377,0x0377},
{0x0378,0x0378,0x0378}, {0x0379,0x0379,0x0379},
{0x037A,0x037A,0x037A}, {0x037B,0x037B,0x037B},
{0x037C,0x037C,0x037C}, {0x037D,0x037D,0x037D},
{0x037E,0x037E,0x037E}, {0x037F,0x037F,0x037F},
{0x0380,0x0380,0x0380}, {0x0381,0x0381,0x0381},
{0x0382,0x0382,0x0382}, {0x0383,0x0383,0x0383},
{0x0384,0x0384,0x0384}, {0x0385,0x0385,0x0385},
{0x0386,0x03AC,0x0391}, {0x0387,0x0387,0x0387},
{0x0388,0x03AD,0x0395}, {0x0389,0x03AE,0x0397},
{0x038A,0x03AF,0x0399}, {0x038B,0x038B,0x038B},
{0x038C,0x03CC,0x039F}, {0x038D,0x038D,0x038D},
{0x038E,0x03CD,0x03A5}, {0x038F,0x03CE,0x03A9},
{0x0390,0x0390,0x0399}, {0x0391,0x03B1,0x0391},
{0x0392,0x03B2,0x0392}, {0x0393,0x03B3,0x0393},
{0x0394,0x03B4,0x0394}, {0x0395,0x03B5,0x0395},
{0x0396,0x03B6,0x0396}, {0x0397,0x03B7,0x0397},
{0x0398,0x03B8,0x0398}, {0x0399,0x03B9,0x0399},
{0x039A,0x03BA,0x039A}, {0x039B,0x03BB,0x039B},
{0x039C,0x03BC,0x039C}, {0x039D,0x03BD,0x039D},
{0x039E,0x03BE,0x039E}, {0x039F,0x03BF,0x039F},
{0x03A0,0x03C0,0x03A0}, {0x03A1,0x03C1,0x03A1},
{0x03A2,0x03A2,0x03A2}, {0x03A3,0x03C3,0x03A3},
{0x03A4,0x03C4,0x03A4}, {0x03A5,0x03C5,0x03A5},
{0x03A6,0x03C6,0x03A6}, {0x03A7,0x03C7,0x03A7},
{0x03A8,0x03C8,0x03A8}, {0x03A9,0x03C9,0x03A9},
{0x03AA,0x03CA,0x0399}, {0x03AB,0x03CB,0x03A5},
{0x0386,0x03AC,0x0391}, {0x0388,0x03AD,0x0395},
{0x0389,0x03AE,0x0397}, {0x038A,0x03AF,0x0399},
{0x03B0,0x03B0,0x03A5}, {0x0391,0x03B1,0x0391},
{0x0392,0x03B2,0x0392}, {0x0393,0x03B3,0x0393},
{0x0394,0x03B4,0x0394}, {0x0395,0x03B5,0x0395},
{0x0396,0x03B6,0x0396}, {0x0397,0x03B7,0x0397},
{0x0398,0x03B8,0x0398}, {0x0399,0x03B9,0x0399},
{0x039A,0x03BA,0x039A}, {0x039B,0x03BB,0x039B},
{0x039C,0x03BC,0x039C}, {0x039D,0x03BD,0x039D},
{0x039E,0x03BE,0x039E}, {0x039F,0x03BF,0x039F},
{0x03A0,0x03C0,0x03A0}, {0x03A1,0x03C1,0x03A1},
{0x03A3,0x03C2,0x03A3}, {0x03A3,0x03C3,0x03A3},
{0x03A4,0x03C4,0x03A4}, {0x03A5,0x03C5,0x03A5},
{0x03A6,0x03C6,0x03A6}, {0x03A7,0x03C7,0x03A7},
{0x03A8,0x03C8,0x03A8}, {0x03A9,0x03C9,0x03A9},
{0x03AA,0x03CA,0x0399}, {0x03AB,0x03CB,0x03A5},
{0x038C,0x03CC,0x039F}, {0x038E,0x03CD,0x03A5},
{0x038F,0x03CE,0x03A9}, {0x03CF,0x03CF,0x03CF},
{0x0392,0x03D0,0x0392}, {0x0398,0x03D1,0x0398},
{0x03D2,0x03D2,0x03D2}, {0x03D3,0x03D3,0x03D2},
{0x03D4,0x03D4,0x03D2}, {0x03A6,0x03D5,0x03A6},
{0x03A0,0x03D6,0x03A0}, {0x03D7,0x03D7,0x03D7},
{0x03D8,0x03D8,0x03D8}, {0x03D9,0x03D9,0x03D9},
{0x03DA,0x03DB,0x03DA}, {0x03DA,0x03DB,0x03DA},
{0x03DC,0x03DD,0x03DC}, {0x03DC,0x03DD,0x03DC},
{0x03DE,0x03DF,0x03DE}, {0x03DE,0x03DF,0x03DE},
{0x03E0,0x03E1,0x03E0}, {0x03E0,0x03E1,0x03E0},
{0x03E2,0x03E3,0x03E2}, {0x03E2,0x03E3,0x03E2},
{0x03E4,0x03E5,0x03E4}, {0x03E4,0x03E5,0x03E4},
{0x03E6,0x03E7,0x03E6}, {0x03E6,0x03E7,0x03E6},
{0x03E8,0x03E9,0x03E8}, {0x03E8,0x03E9,0x03E8},
{0x03EA,0x03EB,0x03EA}, {0x03EA,0x03EB,0x03EA},
{0x03EC,0x03ED,0x03EC}, {0x03EC,0x03ED,0x03EC},
{0x03EE,0x03EF,0x03EE}, {0x03EE,0x03EF,0x03EE},
{0x039A,0x03F0,0x039A}, {0x03A1,0x03F1,0x03A1},
{0x03A3,0x03F2,0x03A3}, {0x03F3,0x03F3,0x03F3},
{0x03F4,0x03F4,0x03F4}, {0x03F5,0x03F5,0x03F5},
{0x03F6,0x03F6,0x03F6}, {0x03F7,0x03F7,0x03F7},
{0x03F8,0x03F8,0x03F8}, {0x03F9,0x03F9,0x03F9},
{0x03FA,0x03FA,0x03FA}, {0x03FB,0x03FB,0x03FB},
{0x03FC,0x03FC,0x03FC}, {0x03FD,0x03FD,0x03FD},
{0x03FE,0x03FE,0x03FE}, {0x03FF,0x03FF,0x03FF}
};
static MY_UNICASE_INFO plane04[]={
{0x0400,0x0450,0x0415}, {0x0401,0x0451,0x0415},
{0x0402,0x0452,0x0402}, {0x0403,0x0453,0x0413},
{0x0404,0x0454,0x0404}, {0x0405,0x0455,0x0405},
{0x0406,0x0456,0x0406}, {0x0407,0x0457,0x0406},
{0x0408,0x0458,0x0408}, {0x0409,0x0459,0x0409},
{0x040A,0x045A,0x040A}, {0x040B,0x045B,0x040B},
{0x040C,0x045C,0x041A}, {0x040D,0x045D,0x0418},
{0x040E,0x045E,0x0423}, {0x040F,0x045F,0x040F},
{0x0410,0x0430,0x0410}, {0x0411,0x0431,0x0411},
{0x0412,0x0432,0x0412}, {0x0413,0x0433,0x0413},
{0x0414,0x0434,0x0414}, {0x0415,0x0435,0x0415},
{0x0416,0x0436,0x0416}, {0x0417,0x0437,0x0417},
{0x0418,0x0438,0x0418}, {0x0419,0x0439,0x0419},
{0x041A,0x043A,0x041A}, {0x041B,0x043B,0x041B},
{0x041C,0x043C,0x041C}, {0x041D,0x043D,0x041D},
{0x041E,0x043E,0x041E}, {0x041F,0x043F,0x041F},
{0x0420,0x0440,0x0420}, {0x0421,0x0441,0x0421},
{0x0422,0x0442,0x0422}, {0x0423,0x0443,0x0423},
{0x0424,0x0444,0x0424}, {0x0425,0x0445,0x0425},
{0x0426,0x0446,0x0426}, {0x0427,0x0447,0x0427},
{0x0428,0x0448,0x0428}, {0x0429,0x0449,0x0429},
{0x042A,0x044A,0x042A}, {0x042B,0x044B,0x042B},
{0x042C,0x044C,0x042C}, {0x042D,0x044D,0x042D},
{0x042E,0x044E,0x042E}, {0x042F,0x044F,0x042F},
{0x0410,0x0430,0x0410}, {0x0411,0x0431,0x0411},
{0x0412,0x0432,0x0412}, {0x0413,0x0433,0x0413},
{0x0414,0x0434,0x0414}, {0x0415,0x0435,0x0415},
{0x0416,0x0436,0x0416}, {0x0417,0x0437,0x0417},
{0x0418,0x0438,0x0418}, {0x0419,0x0439,0x0419},
{0x041A,0x043A,0x041A}, {0x041B,0x043B,0x041B},
{0x041C,0x043C,0x041C}, {0x041D,0x043D,0x041D},
{0x041E,0x043E,0x041E}, {0x041F,0x043F,0x041F},
{0x0420,0x0440,0x0420}, {0x0421,0x0441,0x0421},
{0x0422,0x0442,0x0422}, {0x0423,0x0443,0x0423},
{0x0424,0x0444,0x0424}, {0x0425,0x0445,0x0425},
{0x0426,0x0446,0x0426}, {0x0427,0x0447,0x0427},
{0x0428,0x0448,0x0428}, {0x0429,0x0449,0x0429},
{0x042A,0x044A,0x042A}, {0x042B,0x044B,0x042B},
{0x042C,0x044C,0x042C}, {0x042D,0x044D,0x042D},
{0x042E,0x044E,0x042E}, {0x042F,0x044F,0x042F},
{0x0400,0x0450,0x0415}, {0x0401,0x0451,0x0415},
{0x0402,0x0452,0x0402}, {0x0403,0x0453,0x0413},
{0x0404,0x0454,0x0404}, {0x0405,0x0455,0x0405},
{0x0406,0x0456,0x0406}, {0x0407,0x0457,0x0406},
{0x0408,0x0458,0x0408}, {0x0409,0x0459,0x0409},
{0x040A,0x045A,0x040A}, {0x040B,0x045B,0x040B},
{0x040C,0x045C,0x041A}, {0x040D,0x045D,0x0418},
{0x040E,0x045E,0x0423}, {0x040F,0x045F,0x040F},
{0x0460,0x0461,0x0460}, {0x0460,0x0461,0x0460},
{0x0462,0x0463,0x0462}, {0x0462,0x0463,0x0462},
{0x0464,0x0465,0x0464}, {0x0464,0x0465,0x0464},
{0x0466,0x0467,0x0466}, {0x0466,0x0467,0x0466},
{0x0468,0x0469,0x0468}, {0x0468,0x0469,0x0468},
{0x046A,0x046B,0x046A}, {0x046A,0x046B,0x046A},
{0x046C,0x046D,0x046C}, {0x046C,0x046D,0x046C},
{0x046E,0x046F,0x046E}, {0x046E,0x046F,0x046E},
{0x0470,0x0471,0x0470}, {0x0470,0x0471,0x0470},
{0x0472,0x0473,0x0472}, {0x0472,0x0473,0x0472},
{0x0474,0x0475,0x0474}, {0x0474,0x0475,0x0474},
{0x0476,0x0477,0x0474}, {0x0476,0x0477,0x0474},
{0x0478,0x0479,0x0478}, {0x0478,0x0479,0x0478},
{0x047A,0x047B,0x047A}, {0x047A,0x047B,0x047A},
{0x047C,0x047D,0x047C}, {0x047C,0x047D,0x047C},
{0x047E,0x047F,0x047E}, {0x047E,0x047F,0x047E},
{0x0480,0x0481,0x0480}, {0x0480,0x0481,0x0480},
{0x0482,0x0482,0x0482}, {0x0483,0x0483,0x0483},
{0x0484,0x0484,0x0484}, {0x0485,0x0485,0x0485},
{0x0486,0x0486,0x0486}, {0x0487,0x0487,0x0487},
{0x0488,0x0488,0x0488}, {0x0489,0x0489,0x0489},
{0x048A,0x048A,0x048A}, {0x048B,0x048B,0x048B},
{0x048C,0x048D,0x048C}, {0x048C,0x048D,0x048C},
{0x048E,0x048F,0x048E}, {0x048E,0x048F,0x048E},
{0x0490,0x0491,0x0490}, {0x0490,0x0491,0x0490},
{0x0492,0x0493,0x0492}, {0x0492,0x0493,0x0492},
{0x0494,0x0495,0x0494}, {0x0494,0x0495,0x0494},
{0x0496,0x0497,0x0496}, {0x0496,0x0497,0x0496},
{0x0498,0x0499,0x0498}, {0x0498,0x0499,0x0498},
{0x049A,0x049B,0x049A}, {0x049A,0x049B,0x049A},
{0x049C,0x049D,0x049C}, {0x049C,0x049D,0x049C},
{0x049E,0x049F,0x049E}, {0x049E,0x049F,0x049E},
{0x04A0,0x04A1,0x04A0}, {0x04A0,0x04A1,0x04A0},
{0x04A2,0x04A3,0x04A2}, {0x04A2,0x04A3,0x04A2},
{0x04A4,0x04A5,0x04A4}, {0x04A4,0x04A5,0x04A4},
{0x04A6,0x04A7,0x04A6}, {0x04A6,0x04A7,0x04A6},
{0x04A8,0x04A9,0x04A8}, {0x04A8,0x04A9,0x04A8},
{0x04AA,0x04AB,0x04AA}, {0x04AA,0x04AB,0x04AA},
{0x04AC,0x04AD,0x04AC}, {0x04AC,0x04AD,0x04AC},
{0x04AE,0x04AF,0x04AE}, {0x04AE,0x04AF,0x04AE},
{0x04B0,0x04B1,0x04B0}, {0x04B0,0x04B1,0x04B0},
{0x04B2,0x04B3,0x04B2}, {0x04B2,0x04B3,0x04B2},
{0x04B4,0x04B5,0x04B4}, {0x04B4,0x04B5,0x04B4},
{0x04B6,0x04B7,0x04B6}, {0x04B6,0x04B7,0x04B6},
{0x04B8,0x04B9,0x04B8}, {0x04B8,0x04B9,0x04B8},
{0x04BA,0x04BB,0x04BA}, {0x04BA,0x04BB,0x04BA},
{0x04BC,0x04BD,0x04BC}, {0x04BC,0x04BD,0x04BC},
{0x04BE,0x04BF,0x04BE}, {0x04BE,0x04BF,0x04BE},
{0x04C0,0x04C0,0x04C0}, {0x04C1,0x04C2,0x0416},
{0x04C1,0x04C2,0x0416}, {0x04C3,0x04C4,0x04C3},
{0x04C3,0x04C4,0x04C3}, {0x04C5,0x04C5,0x04C5},
{0x04C6,0x04C6,0x04C6}, {0x04C7,0x04C8,0x04C7},
{0x04C7,0x04C8,0x04C7}, {0x04C9,0x04C9,0x04C9},
{0x04CA,0x04CA,0x04CA}, {0x04CB,0x04CC,0x04CB},
{0x04CB,0x04CC,0x04CB}, {0x04CD,0x04CD,0x04CD},
{0x04CE,0x04CE,0x04CE}, {0x04CF,0x04CF,0x04CF},
{0x04D0,0x04D1,0x0410}, {0x04D0,0x04D1,0x0410},
{0x04D2,0x04D3,0x0410}, {0x04D2,0x04D3,0x0410},
{0x04D4,0x04D5,0x04D4}, {0x04D4,0x04D5,0x04D4},
{0x04D6,0x04D7,0x0415}, {0x04D6,0x04D7,0x0415},
{0x04D8,0x04D9,0x04D8}, {0x04D8,0x04D9,0x04D8},
{0x04DA,0x04DB,0x04D8}, {0x04DA,0x04DB,0x04D8},
{0x04DC,0x04DD,0x0416}, {0x04DC,0x04DD,0x0416},
{0x04DE,0x04DF,0x0417}, {0x04DE,0x04DF,0x0417},
{0x04E0,0x04E1,0x04E0}, {0x04E0,0x04E1,0x04E0},
{0x04E2,0x04E3,0x0418}, {0x04E2,0x04E3,0x0418},
{0x04E4,0x04E5,0x0418}, {0x04E4,0x04E5,0x0418},
{0x04E6,0x04E7,0x041E}, {0x04E6,0x04E7,0x041E},
{0x04E8,0x04E9,0x04E8}, {0x04E8,0x04E9,0x04E8},
{0x04EA,0x04EB,0x04E8}, {0x04EA,0x04EB,0x04E8},
{0x04EC,0x04ED,0x042D}, {0x04EC,0x04ED,0x042D},
{0x04EE,0x04EF,0x0423}, {0x04EE,0x04EF,0x0423},
{0x04F0,0x04F1,0x0423}, {0x04F0,0x04F1,0x0423},
{0x04F2,0x04F3,0x0423}, {0x04F2,0x04F3,0x0423},
{0x04F4,0x04F5,0x0427}, {0x04F4,0x04F5,0x0427},
{0x04F6,0x04F6,0x04F6}, {0x04F7,0x04F7,0x04F7},
{0x04F8,0x04F9,0x042B}, {0x04F8,0x04F9,0x042B},
{0x04FA,0x04FA,0x04FA}, {0x04FB,0x04FB,0x04FB},
{0x04FC,0x04FC,0x04FC}, {0x04FD,0x04FD,0x04FD},
{0x04FE,0x04FE,0x04FE}, {0x04FF,0x04FF,0x04FF}
};
static MY_UNICASE_INFO plane05[]={
{0x0500,0x0500,0x0500}, {0x0501,0x0501,0x0501},
{0x0502,0x0502,0x0502}, {0x0503,0x0503,0x0503},
{0x0504,0x0504,0x0504}, {0x0505,0x0505,0x0505},
{0x0506,0x0506,0x0506}, {0x0507,0x0507,0x0507},
{0x0508,0x0508,0x0508}, {0x0509,0x0509,0x0509},
{0x050A,0x050A,0x050A}, {0x050B,0x050B,0x050B},
{0x050C,0x050C,0x050C}, {0x050D,0x050D,0x050D},
{0x050E,0x050E,0x050E}, {0x050F,0x050F,0x050F},
{0x0510,0x0510,0x0510}, {0x0511,0x0511,0x0511},
{0x0512,0x0512,0x0512}, {0x0513,0x0513,0x0513},
{0x0514,0x0514,0x0514}, {0x0515,0x0515,0x0515},
{0x0516,0x0516,0x0516}, {0x0517,0x0517,0x0517},
{0x0518,0x0518,0x0518}, {0x0519,0x0519,0x0519},
{0x051A,0x051A,0x051A}, {0x051B,0x051B,0x051B},
{0x051C,0x051C,0x051C}, {0x051D,0x051D,0x051D},
{0x051E,0x051E,0x051E}, {0x051F,0x051F,0x051F},
{0x0520,0x0520,0x0520}, {0x0521,0x0521,0x0521},
{0x0522,0x0522,0x0522}, {0x0523,0x0523,0x0523},
{0x0524,0x0524,0x0524}, {0x0525,0x0525,0x0525},
{0x0526,0x0526,0x0526}, {0x0527,0x0527,0x0527},
{0x0528,0x0528,0x0528}, {0x0529,0x0529,0x0529},
{0x052A,0x052A,0x052A}, {0x052B,0x052B,0x052B},
{0x052C,0x052C,0x052C}, {0x052D,0x052D,0x052D},
{0x052E,0x052E,0x052E}, {0x052F,0x052F,0x052F},
{0x0530,0x0530,0x0530}, {0x0531,0x0561,0x0531},
{0x0532,0x0562,0x0532}, {0x0533,0x0563,0x0533},
{0x0534,0x0564,0x0534}, {0x0535,0x0565,0x0535},
{0x0536,0x0566,0x0536}, {0x0537,0x0567,0x0537},
{0x0538,0x0568,0x0538}, {0x0539,0x0569,0x0539},
{0x053A,0x056A,0x053A}, {0x053B,0x056B,0x053B},
{0x053C,0x056C,0x053C}, {0x053D,0x056D,0x053D},
{0x053E,0x056E,0x053E}, {0x053F,0x056F,0x053F},
{0x0540,0x0570,0x0540}, {0x0541,0x0571,0x0541},
{0x0542,0x0572,0x0542}, {0x0543,0x0573,0x0543},
{0x0544,0x0574,0x0544}, {0x0545,0x0575,0x0545},
{0x0546,0x0576,0x0546}, {0x0547,0x0577,0x0547},
{0x0548,0x0578,0x0548}, {0x0549,0x0579,0x0549},
{0x054A,0x057A,0x054A}, {0x054B,0x057B,0x054B},
{0x054C,0x057C,0x054C}, {0x054D,0x057D,0x054D},
{0x054E,0x057E,0x054E}, {0x054F,0x057F,0x054F},
{0x0550,0x0580,0x0550}, {0x0551,0x0581,0x0551},
{0x0552,0x0582,0x0552}, {0x0553,0x0583,0x0553},
{0x0554,0x0584,0x0554}, {0x0555,0x0585,0x0555},
{0x0556,0x0586,0x0556}, {0x0557,0x0557,0x0557},
{0x0558,0x0558,0x0558}, {0x0559,0x0559,0x0559},
{0x055A,0x055A,0x055A}, {0x055B,0x055B,0x055B},
{0x055C,0x055C,0x055C}, {0x055D,0x055D,0x055D},
{0x055E,0x055E,0x055E}, {0x055F,0x055F,0x055F},
{0x0560,0x0560,0x0560}, {0x0531,0x0561,0x0531},
{0x0532,0x0562,0x0532}, {0x0533,0x0563,0x0533},
{0x0534,0x0564,0x0534}, {0x0535,0x0565,0x0535},
{0x0536,0x0566,0x0536}, {0x0537,0x0567,0x0537},
{0x0538,0x0568,0x0538}, {0x0539,0x0569,0x0539},
{0x053A,0x056A,0x053A}, {0x053B,0x056B,0x053B},
{0x053C,0x056C,0x053C}, {0x053D,0x056D,0x053D},
{0x053E,0x056E,0x053E}, {0x053F,0x056F,0x053F},
{0x0540,0x0570,0x0540}, {0x0541,0x0571,0x0541},
{0x0542,0x0572,0x0542}, {0x0543,0x0573,0x0543},
{0x0544,0x0574,0x0544}, {0x0545,0x0575,0x0545},
{0x0546,0x0576,0x0546}, {0x0547,0x0577,0x0547},
{0x0548,0x0578,0x0548}, {0x0549,0x0579,0x0549},
{0x054A,0x057A,0x054A}, {0x054B,0x057B,0x054B},
{0x054C,0x057C,0x054C}, {0x054D,0x057D,0x054D},
{0x054E,0x057E,0x054E}, {0x054F,0x057F,0x054F},
{0x0550,0x0580,0x0550}, {0x0551,0x0581,0x0551},
{0x0552,0x0582,0x0552}, {0x0553,0x0583,0x0553},
{0x0554,0x0584,0x0554}, {0x0555,0x0585,0x0555},
{0x0556,0x0586,0x0556}, {0x0587,0x0587,0x0587},
{0x0588,0x0588,0x0588}, {0x0589,0x0589,0x0589},
{0x058A,0x058A,0x058A}, {0x058B,0x058B,0x058B},
{0x058C,0x058C,0x058C}, {0x058D,0x058D,0x058D},
{0x058E,0x058E,0x058E}, {0x058F,0x058F,0x058F},
{0x0590,0x0590,0x0590}, {0x0591,0x0591,0x0591},
{0x0592,0x0592,0x0592}, {0x0593,0x0593,0x0593},
{0x0594,0x0594,0x0594}, {0x0595,0x0595,0x0595},
{0x0596,0x0596,0x0596}, {0x0597,0x0597,0x0597},
{0x0598,0x0598,0x0598}, {0x0599,0x0599,0x0599},
{0x059A,0x059A,0x059A}, {0x059B,0x059B,0x059B},
{0x059C,0x059C,0x059C}, {0x059D,0x059D,0x059D},
{0x059E,0x059E,0x059E}, {0x059F,0x059F,0x059F},
{0x05A0,0x05A0,0x05A0}, {0x05A1,0x05A1,0x05A1},
{0x05A2,0x05A2,0x05A2}, {0x05A3,0x05A3,0x05A3},
{0x05A4,0x05A4,0x05A4}, {0x05A5,0x05A5,0x05A5},
{0x05A6,0x05A6,0x05A6}, {0x05A7,0x05A7,0x05A7},
{0x05A8,0x05A8,0x05A8}, {0x05A9,0x05A9,0x05A9},
{0x05AA,0x05AA,0x05AA}, {0x05AB,0x05AB,0x05AB},
{0x05AC,0x05AC,0x05AC}, {0x05AD,0x05AD,0x05AD},
{0x05AE,0x05AE,0x05AE}, {0x05AF,0x05AF,0x05AF},
{0x05B0,0x05B0,0x05B0}, {0x05B1,0x05B1,0x05B1},
{0x05B2,0x05B2,0x05B2}, {0x05B3,0x05B3,0x05B3},
{0x05B4,0x05B4,0x05B4}, {0x05B5,0x05B5,0x05B5},
{0x05B6,0x05B6,0x05B6}, {0x05B7,0x05B7,0x05B7},
{0x05B8,0x05B8,0x05B8}, {0x05B9,0x05B9,0x05B9},
{0x05BA,0x05BA,0x05BA}, {0x05BB,0x05BB,0x05BB},
{0x05BC,0x05BC,0x05BC}, {0x05BD,0x05BD,0x05BD},
{0x05BE,0x05BE,0x05BE}, {0x05BF,0x05BF,0x05BF},
{0x05C0,0x05C0,0x05C0}, {0x05C1,0x05C1,0x05C1},
{0x05C2,0x05C2,0x05C2}, {0x05C3,0x05C3,0x05C3},
{0x05C4,0x05C4,0x05C4}, {0x05C5,0x05C5,0x05C5},
{0x05C6,0x05C6,0x05C6}, {0x05C7,0x05C7,0x05C7},
{0x05C8,0x05C8,0x05C8}, {0x05C9,0x05C9,0x05C9},
{0x05CA,0x05CA,0x05CA}, {0x05CB,0x05CB,0x05CB},
{0x05CC,0x05CC,0x05CC}, {0x05CD,0x05CD,0x05CD},
{0x05CE,0x05CE,0x05CE}, {0x05CF,0x05CF,0x05CF},
{0x05D0,0x05D0,0x05D0}, {0x05D1,0x05D1,0x05D1},
{0x05D2,0x05D2,0x05D2}, {0x05D3,0x05D3,0x05D3},
{0x05D4,0x05D4,0x05D4}, {0x05D5,0x05D5,0x05D5},
{0x05D6,0x05D6,0x05D6}, {0x05D7,0x05D7,0x05D7},
{0x05D8,0x05D8,0x05D8}, {0x05D9,0x05D9,0x05D9},
{0x05DA,0x05DA,0x05DA}, {0x05DB,0x05DB,0x05DB},
{0x05DC,0x05DC,0x05DC}, {0x05DD,0x05DD,0x05DD},
{0x05DE,0x05DE,0x05DE}, {0x05DF,0x05DF,0x05DF},
{0x05E0,0x05E0,0x05E0}, {0x05E1,0x05E1,0x05E1},
{0x05E2,0x05E2,0x05E2}, {0x05E3,0x05E3,0x05E3},
{0x05E4,0x05E4,0x05E4}, {0x05E5,0x05E5,0x05E5},
{0x05E6,0x05E6,0x05E6}, {0x05E7,0x05E7,0x05E7},
{0x05E8,0x05E8,0x05E8}, {0x05E9,0x05E9,0x05E9},
{0x05EA,0x05EA,0x05EA}, {0x05EB,0x05EB,0x05EB},
{0x05EC,0x05EC,0x05EC}, {0x05ED,0x05ED,0x05ED},
{0x05EE,0x05EE,0x05EE}, {0x05EF,0x05EF,0x05EF},
{0x05F0,0x05F0,0x05F0}, {0x05F1,0x05F1,0x05F1},
{0x05F2,0x05F2,0x05F2}, {0x05F3,0x05F3,0x05F3},
{0x05F4,0x05F4,0x05F4}, {0x05F5,0x05F5,0x05F5},
{0x05F6,0x05F6,0x05F6}, {0x05F7,0x05F7,0x05F7},
{0x05F8,0x05F8,0x05F8}, {0x05F9,0x05F9,0x05F9},
{0x05FA,0x05FA,0x05FA}, {0x05FB,0x05FB,0x05FB},
{0x05FC,0x05FC,0x05FC}, {0x05FD,0x05FD,0x05FD},
{0x05FE,0x05FE,0x05FE}, {0x05FF,0x05FF,0x05FF}
};
static MY_UNICASE_INFO plane1E[]={
{0x1E00,0x1E01,0x0041}, {0x1E00,0x1E01,0x0041},
{0x1E02,0x1E03,0x0042}, {0x1E02,0x1E03,0x0042},
{0x1E04,0x1E05,0x0042}, {0x1E04,0x1E05,0x0042},
{0x1E06,0x1E07,0x0042}, {0x1E06,0x1E07,0x0042},
{0x1E08,0x1E09,0x0043}, {0x1E08,0x1E09,0x0043},
{0x1E0A,0x1E0B,0x0044}, {0x1E0A,0x1E0B,0x0044},
{0x1E0C,0x1E0D,0x0044}, {0x1E0C,0x1E0D,0x0044},
{0x1E0E,0x1E0F,0x0044}, {0x1E0E,0x1E0F,0x0044},
{0x1E10,0x1E11,0x0044}, {0x1E10,0x1E11,0x0044},
{0x1E12,0x1E13,0x0044}, {0x1E12,0x1E13,0x0044},
{0x1E14,0x1E15,0x0045}, {0x1E14,0x1E15,0x0045},
{0x1E16,0x1E17,0x0045}, {0x1E16,0x1E17,0x0045},
{0x1E18,0x1E19,0x0045}, {0x1E18,0x1E19,0x0045},
{0x1E1A,0x1E1B,0x0045}, {0x1E1A,0x1E1B,0x0045},
{0x1E1C,0x1E1D,0x0045}, {0x1E1C,0x1E1D,0x0045},
{0x1E1E,0x1E1F,0x0046}, {0x1E1E,0x1E1F,0x0046},
{0x1E20,0x1E21,0x0047}, {0x1E20,0x1E21,0x0047},
{0x1E22,0x1E23,0x0048}, {0x1E22,0x1E23,0x0048},
{0x1E24,0x1E25,0x0048}, {0x1E24,0x1E25,0x0048},
{0x1E26,0x1E27,0x0048}, {0x1E26,0x1E27,0x0048},
{0x1E28,0x1E29,0x0048}, {0x1E28,0x1E29,0x0048},
{0x1E2A,0x1E2B,0x0048}, {0x1E2A,0x1E2B,0x0048},
{0x1E2C,0x1E2D,0x0049}, {0x1E2C,0x1E2D,0x0049},
{0x1E2E,0x1E2F,0x0049}, {0x1E2E,0x1E2F,0x0049},
{0x1E30,0x1E31,0x004B}, {0x1E30,0x1E31,0x004B},
{0x1E32,0x1E33,0x004B}, {0x1E32,0x1E33,0x004B},
{0x1E34,0x1E35,0x004B}, {0x1E34,0x1E35,0x004B},
{0x1E36,0x1E37,0x004C}, {0x1E36,0x1E37,0x004C},
{0x1E38,0x1E39,0x004C}, {0x1E38,0x1E39,0x004C},
{0x1E3A,0x1E3B,0x004C}, {0x1E3A,0x1E3B,0x004C},
{0x1E3C,0x1E3D,0x004C}, {0x1E3C,0x1E3D,0x004C},
{0x1E3E,0x1E3F,0x004D}, {0x1E3E,0x1E3F,0x004D},
{0x1E40,0x1E41,0x004D}, {0x1E40,0x1E41,0x004D},
{0x1E42,0x1E43,0x004D}, {0x1E42,0x1E43,0x004D},
{0x1E44,0x1E45,0x004E}, {0x1E44,0x1E45,0x004E},
{0x1E46,0x1E47,0x004E}, {0x1E46,0x1E47,0x004E},
{0x1E48,0x1E49,0x004E}, {0x1E48,0x1E49,0x004E},
{0x1E4A,0x1E4B,0x004E}, {0x1E4A,0x1E4B,0x004E},
{0x1E4C,0x1E4D,0x004F}, {0x1E4C,0x1E4D,0x004F},
{0x1E4E,0x1E4F,0x004F}, {0x1E4E,0x1E4F,0x004F},
{0x1E50,0x1E51,0x004F}, {0x1E50,0x1E51,0x004F},
{0x1E52,0x1E53,0x004F}, {0x1E52,0x1E53,0x004F},
{0x1E54,0x1E55,0x0050}, {0x1E54,0x1E55,0x0050},
{0x1E56,0x1E57,0x0050}, {0x1E56,0x1E57,0x0050},
{0x1E58,0x1E59,0x0052}, {0x1E58,0x1E59,0x0052},
{0x1E5A,0x1E5B,0x0052}, {0x1E5A,0x1E5B,0x0052},
{0x1E5C,0x1E5D,0x0052}, {0x1E5C,0x1E5D,0x0052},
{0x1E5E,0x1E5F,0x0052}, {0x1E5E,0x1E5F,0x0052},
{0x1E60,0x1E61,0x0053}, {0x1E60,0x1E61,0x0053},
{0x1E62,0x1E63,0x0053}, {0x1E62,0x1E63,0x0053},
{0x1E64,0x1E65,0x0053}, {0x1E64,0x1E65,0x0053},
{0x1E66,0x1E67,0x0053}, {0x1E66,0x1E67,0x0053},
{0x1E68,0x1E69,0x0053}, {0x1E68,0x1E69,0x0053},
{0x1E6A,0x1E6B,0x0054}, {0x1E6A,0x1E6B,0x0054},
{0x1E6C,0x1E6D,0x0054}, {0x1E6C,0x1E6D,0x0054},
{0x1E6E,0x1E6F,0x0054}, {0x1E6E,0x1E6F,0x0054},
{0x1E70,0x1E71,0x0054}, {0x1E70,0x1E71,0x0054},
{0x1E72,0x1E73,0x0055}, {0x1E72,0x1E73,0x0055},
{0x1E74,0x1E75,0x0055}, {0x1E74,0x1E75,0x0055},
{0x1E76,0x1E77,0x0055}, {0x1E76,0x1E77,0x0055},
{0x1E78,0x1E79,0x0055}, {0x1E78,0x1E79,0x0055},
{0x1E7A,0x1E7B,0x0055}, {0x1E7A,0x1E7B,0x0055},
{0x1E7C,0x1E7D,0x0056}, {0x1E7C,0x1E7D,0x0056},
{0x1E7E,0x1E7F,0x0056}, {0x1E7E,0x1E7F,0x0056},
{0x1E80,0x1E81,0x0057}, {0x1E80,0x1E81,0x0057},
{0x1E82,0x1E83,0x0057}, {0x1E82,0x1E83,0x0057},
{0x1E84,0x1E85,0x0057}, {0x1E84,0x1E85,0x0057},
{0x1E86,0x1E87,0x0057}, {0x1E86,0x1E87,0x0057},
{0x1E88,0x1E89,0x0057}, {0x1E88,0x1E89,0x0057},
{0x1E8A,0x1E8B,0x0058}, {0x1E8A,0x1E8B,0x0058},
{0x1E8C,0x1E8D,0x0058}, {0x1E8C,0x1E8D,0x0058},
{0x1E8E,0x1E8F,0x0059}, {0x1E8E,0x1E8F,0x0059},
{0x1E90,0x1E91,0x005A}, {0x1E90,0x1E91,0x005A},
{0x1E92,0x1E93,0x005A}, {0x1E92,0x1E93,0x005A},
{0x1E94,0x1E95,0x005A}, {0x1E94,0x1E95,0x005A},
{0x1E96,0x1E96,0x0048}, {0x1E97,0x1E97,0x0054},
{0x1E98,0x1E98,0x0057}, {0x1E99,0x1E99,0x0059},
{0x1E9A,0x1E9A,0x1E9A}, {0x1E60,0x1E9B,0x0053},
{0x1E9C,0x1E9C,0x1E9C}, {0x1E9D,0x1E9D,0x1E9D},
{0x1E9E,0x1E9E,0x1E9E}, {0x1E9F,0x1E9F,0x1E9F},
{0x1EA0,0x1EA1,0x0041}, {0x1EA0,0x1EA1,0x0041},
{0x1EA2,0x1EA3,0x0041}, {0x1EA2,0x1EA3,0x0041},
{0x1EA4,0x1EA5,0x0041}, {0x1EA4,0x1EA5,0x0041},
{0x1EA6,0x1EA7,0x0041}, {0x1EA6,0x1EA7,0x0041},
{0x1EA8,0x1EA9,0x0041}, {0x1EA8,0x1EA9,0x0041},
{0x1EAA,0x1EAB,0x0041}, {0x1EAA,0x1EAB,0x0041},
{0x1EAC,0x1EAD,0x0041}, {0x1EAC,0x1EAD,0x0041},
{0x1EAE,0x1EAF,0x0041}, {0x1EAE,0x1EAF,0x0041},
{0x1EB0,0x1EB1,0x0041}, {0x1EB0,0x1EB1,0x0041},
{0x1EB2,0x1EB3,0x0041}, {0x1EB2,0x1EB3,0x0041},
{0x1EB4,0x1EB5,0x0041}, {0x1EB4,0x1EB5,0x0041},
{0x1EB6,0x1EB7,0x0041}, {0x1EB6,0x1EB7,0x0041},
{0x1EB8,0x1EB9,0x0045}, {0x1EB8,0x1EB9,0x0045},
{0x1EBA,0x1EBB,0x0045}, {0x1EBA,0x1EBB,0x0045},
{0x1EBC,0x1EBD,0x0045}, {0x1EBC,0x1EBD,0x0045},
{0x1EBE,0x1EBF,0x0045}, {0x1EBE,0x1EBF,0x0045},
{0x1EC0,0x1EC1,0x0045}, {0x1EC0,0x1EC1,0x0045},
{0x1EC2,0x1EC3,0x0045}, {0x1EC2,0x1EC3,0x0045},
{0x1EC4,0x1EC5,0x0045}, {0x1EC4,0x1EC5,0x0045},
{0x1EC6,0x1EC7,0x0045}, {0x1EC6,0x1EC7,0x0045},
{0x1EC8,0x1EC9,0x0049}, {0x1EC8,0x1EC9,0x0049},
{0x1ECA,0x1ECB,0x0049}, {0x1ECA,0x1ECB,0x0049},
{0x1ECC,0x1ECD,0x004F}, {0x1ECC,0x1ECD,0x004F},
{0x1ECE,0x1ECF,0x004F}, {0x1ECE,0x1ECF,0x004F},
{0x1ED0,0x1ED1,0x004F}, {0x1ED0,0x1ED1,0x004F},
{0x1ED2,0x1ED3,0x004F}, {0x1ED2,0x1ED3,0x004F},
{0x1ED4,0x1ED5,0x004F}, {0x1ED4,0x1ED5,0x004F},
{0x1ED6,0x1ED7,0x004F}, {0x1ED6,0x1ED7,0x004F},
{0x1ED8,0x1ED9,0x004F}, {0x1ED8,0x1ED9,0x004F},
{0x1EDA,0x1EDB,0x004F}, {0x1EDA,0x1EDB,0x004F},
{0x1EDC,0x1EDD,0x004F}, {0x1EDC,0x1EDD,0x004F},
{0x1EDE,0x1EDF,0x004F}, {0x1EDE,0x1EDF,0x004F},
{0x1EE0,0x1EE1,0x004F}, {0x1EE0,0x1EE1,0x004F},
{0x1EE2,0x1EE3,0x004F}, {0x1EE2,0x1EE3,0x004F},
{0x1EE4,0x1EE5,0x0055}, {0x1EE4,0x1EE5,0x0055},
{0x1EE6,0x1EE7,0x0055}, {0x1EE6,0x1EE7,0x0055},
{0x1EE8,0x1EE9,0x0055}, {0x1EE8,0x1EE9,0x0055},
{0x1EEA,0x1EEB,0x0055}, {0x1EEA,0x1EEB,0x0055},
{0x1EEC,0x1EED,0x0055}, {0x1EEC,0x1EED,0x0055},
{0x1EEE,0x1EEF,0x0055}, {0x1EEE,0x1EEF,0x0055},
{0x1EF0,0x1EF1,0x0055}, {0x1EF0,0x1EF1,0x0055},
{0x1EF2,0x1EF3,0x0059}, {0x1EF2,0x1EF3,0x0059},
{0x1EF4,0x1EF5,0x0059}, {0x1EF4,0x1EF5,0x0059},
{0x1EF6,0x1EF7,0x0059}, {0x1EF6,0x1EF7,0x0059},
{0x1EF8,0x1EF9,0x0059}, {0x1EF8,0x1EF9,0x0059},
{0x1EFA,0x1EFA,0x1EFA}, {0x1EFB,0x1EFB,0x1EFB},
{0x1EFC,0x1EFC,0x1EFC}, {0x1EFD,0x1EFD,0x1EFD},
{0x1EFE,0x1EFE,0x1EFE}, {0x1EFF,0x1EFF,0x1EFF}
};
static MY_UNICASE_INFO plane1F[]={
{0x1F08,0x1F00,0x0391}, {0x1F09,0x1F01,0x0391},
{0x1F0A,0x1F02,0x0391}, {0x1F0B,0x1F03,0x0391},
{0x1F0C,0x1F04,0x0391}, {0x1F0D,0x1F05,0x0391},
{0x1F0E,0x1F06,0x0391}, {0x1F0F,0x1F07,0x0391},
{0x1F08,0x1F00,0x0391}, {0x1F09,0x1F01,0x0391},
{0x1F0A,0x1F02,0x0391}, {0x1F0B,0x1F03,0x0391},
{0x1F0C,0x1F04,0x0391}, {0x1F0D,0x1F05,0x0391},
{0x1F0E,0x1F06,0x0391}, {0x1F0F,0x1F07,0x0391},
{0x1F18,0x1F10,0x0395}, {0x1F19,0x1F11,0x0395},
{0x1F1A,0x1F12,0x0395}, {0x1F1B,0x1F13,0x0395},
{0x1F1C,0x1F14,0x0395}, {0x1F1D,0x1F15,0x0395},
{0x1F16,0x1F16,0x1F16}, {0x1F17,0x1F17,0x1F17},
{0x1F18,0x1F10,0x0395}, {0x1F19,0x1F11,0x0395},
{0x1F1A,0x1F12,0x0395}, {0x1F1B,0x1F13,0x0395},
{0x1F1C,0x1F14,0x0395}, {0x1F1D,0x1F15,0x0395},
{0x1F1E,0x1F1E,0x1F1E}, {0x1F1F,0x1F1F,0x1F1F},
{0x1F28,0x1F20,0x0397}, {0x1F29,0x1F21,0x0397},
{0x1F2A,0x1F22,0x0397}, {0x1F2B,0x1F23,0x0397},
{0x1F2C,0x1F24,0x0397}, {0x1F2D,0x1F25,0x0397},
{0x1F2E,0x1F26,0x0397}, {0x1F2F,0x1F27,0x0397},
{0x1F28,0x1F20,0x0397}, {0x1F29,0x1F21,0x0397},
{0x1F2A,0x1F22,0x0397}, {0x1F2B,0x1F23,0x0397},
{0x1F2C,0x1F24,0x0397}, {0x1F2D,0x1F25,0x0397},
{0x1F2E,0x1F26,0x0397}, {0x1F2F,0x1F27,0x0397},
{0x1F38,0x1F30,0x0399}, {0x1F39,0x1F31,0x0399},
{0x1F3A,0x1F32,0x0399}, {0x1F3B,0x1F33,0x0399},
{0x1F3C,0x1F34,0x0399}, {0x1F3D,0x1F35,0x0399},
{0x1F3E,0x1F36,0x0399}, {0x1F3F,0x1F37,0x0399},
{0x1F38,0x1F30,0x0399}, {0x1F39,0x1F31,0x0399},
{0x1F3A,0x1F32,0x0399}, {0x1F3B,0x1F33,0x0399},
{0x1F3C,0x1F34,0x0399}, {0x1F3D,0x1F35,0x0399},
{0x1F3E,0x1F36,0x0399}, {0x1F3F,0x1F37,0x0399},
{0x1F48,0x1F40,0x039F}, {0x1F49,0x1F41,0x039F},
{0x1F4A,0x1F42,0x039F}, {0x1F4B,0x1F43,0x039F},
{0x1F4C,0x1F44,0x039F}, {0x1F4D,0x1F45,0x039F},
{0x1F46,0x1F46,0x1F46}, {0x1F47,0x1F47,0x1F47},
{0x1F48,0x1F40,0x039F}, {0x1F49,0x1F41,0x039F},
{0x1F4A,0x1F42,0x039F}, {0x1F4B,0x1F43,0x039F},
{0x1F4C,0x1F44,0x039F}, {0x1F4D,0x1F45,0x039F},
{0x1F4E,0x1F4E,0x1F4E}, {0x1F4F,0x1F4F,0x1F4F},
{0x1F50,0x1F50,0x03A5}, {0x1F59,0x1F51,0x03A5},
{0x1F52,0x1F52,0x03A5}, {0x1F5B,0x1F53,0x03A5},
{0x1F54,0x1F54,0x03A5}, {0x1F5D,0x1F55,0x03A5},
{0x1F56,0x1F56,0x03A5}, {0x1F5F,0x1F57,0x03A5},
{0x1F58,0x1F58,0x1F58}, {0x1F59,0x1F51,0x03A5},
{0x1F5A,0x1F5A,0x1F5A}, {0x1F5B,0x1F53,0x03A5},
{0x1F5C,0x1F5C,0x1F5C}, {0x1F5D,0x1F55,0x03A5},
{0x1F5E,0x1F5E,0x1F5E}, {0x1F5F,0x1F57,0x03A5},
{0x1F68,0x1F60,0x03A9}, {0x1F69,0x1F61,0x03A9},
{0x1F6A,0x1F62,0x03A9}, {0x1F6B,0x1F63,0x03A9},
{0x1F6C,0x1F64,0x03A9}, {0x1F6D,0x1F65,0x03A9},
{0x1F6E,0x1F66,0x03A9}, {0x1F6F,0x1F67,0x03A9},
{0x1F68,0x1F60,0x03A9}, {0x1F69,0x1F61,0x03A9},
{0x1F6A,0x1F62,0x03A9}, {0x1F6B,0x1F63,0x03A9},
{0x1F6C,0x1F64,0x03A9}, {0x1F6D,0x1F65,0x03A9},
{0x1F6E,0x1F66,0x03A9}, {0x1F6F,0x1F67,0x03A9},
{0x1FBA,0x1F70,0x0391}, {0x1FBB,0x1F71,0x1FBB},
{0x1FC8,0x1F72,0x0395}, {0x1FC9,0x1F73,0x1FC9},
{0x1FCA,0x1F74,0x0397}, {0x1FCB,0x1F75,0x1FCB},
{0x1FDA,0x1F76,0x0399}, {0x1FDB,0x1F77,0x1FDB},
{0x1FF8,0x1F78,0x039F}, {0x1FF9,0x1F79,0x1FF9},
{0x1FEA,0x1F7A,0x03A5}, {0x1FEB,0x1F7B,0x1FEB},
{0x1FFA,0x1F7C,0x03A9}, {0x1FFB,0x1F7D,0x1FFB},
{0x1F7E,0x1F7E,0x1F7E}, {0x1F7F,0x1F7F,0x1F7F},
{0x1F88,0x1F80,0x0391}, {0x1F89,0x1F81,0x0391},
{0x1F8A,0x1F82,0x0391}, {0x1F8B,0x1F83,0x0391},
{0x1F8C,0x1F84,0x0391}, {0x1F8D,0x1F85,0x0391},
{0x1F8E,0x1F86,0x0391}, {0x1F8F,0x1F87,0x0391},
{0x1F88,0x1F80,0x0391}, {0x1F89,0x1F81,0x0391},
{0x1F8A,0x1F82,0x0391}, {0x1F8B,0x1F83,0x0391},
{0x1F8C,0x1F84,0x0391}, {0x1F8D,0x1F85,0x0391},
{0x1F8E,0x1F86,0x0391}, {0x1F8F,0x1F87,0x0391},
{0x1F98,0x1F90,0x0397}, {0x1F99,0x1F91,0x0397},
{0x1F9A,0x1F92,0x0397}, {0x1F9B,0x1F93,0x0397},
{0x1F9C,0x1F94,0x0397}, {0x1F9D,0x1F95,0x0397},
{0x1F9E,0x1F96,0x0397}, {0x1F9F,0x1F97,0x0397},
{0x1F98,0x1F90,0x0397}, {0x1F99,0x1F91,0x0397},
{0x1F9A,0x1F92,0x0397}, {0x1F9B,0x1F93,0x0397},
{0x1F9C,0x1F94,0x0397}, {0x1F9D,0x1F95,0x0397},
{0x1F9E,0x1F96,0x0397}, {0x1F9F,0x1F97,0x0397},
{0x1FA8,0x1FA0,0x03A9}, {0x1FA9,0x1FA1,0x03A9},
{0x1FAA,0x1FA2,0x03A9}, {0x1FAB,0x1FA3,0x03A9},
{0x1FAC,0x1FA4,0x03A9}, {0x1FAD,0x1FA5,0x03A9},
{0x1FAE,0x1FA6,0x03A9}, {0x1FAF,0x1FA7,0x03A9},
{0x1FA8,0x1FA0,0x03A9}, {0x1FA9,0x1FA1,0x03A9},
{0x1FAA,0x1FA2,0x03A9}, {0x1FAB,0x1FA3,0x03A9},
{0x1FAC,0x1FA4,0x03A9}, {0x1FAD,0x1FA5,0x03A9},
{0x1FAE,0x1FA6,0x03A9}, {0x1FAF,0x1FA7,0x03A9},
{0x1FB8,0x1FB0,0x0391}, {0x1FB9,0x1FB1,0x0391},
{0x1FB2,0x1FB2,0x0391}, {0x1FBC,0x1FB3,0x0391},
{0x1FB4,0x1FB4,0x0391}, {0x1FB5,0x1FB5,0x1FB5},
{0x1FB6,0x1FB6,0x0391}, {0x1FB7,0x1FB7,0x0391},
{0x1FB8,0x1FB0,0x0391}, {0x1FB9,0x1FB1,0x0391},
{0x1FBA,0x1F70,0x0391}, {0x1FBB,0x1F71,0x1FBB},
{0x1FBC,0x1FB3,0x0391}, {0x1FBD,0x1FBD,0x1FBD},
{0x0399,0x1FBE,0x0399}, {0x1FBF,0x1FBF,0x1FBF},
{0x1FC0,0x1FC0,0x1FC0}, {0x1FC1,0x1FC1,0x1FC1},
{0x1FC2,0x1FC2,0x0397}, {0x1FCC,0x1FC3,0x0397},
{0x1FC4,0x1FC4,0x0397}, {0x1FC5,0x1FC5,0x1FC5},
{0x1FC6,0x1FC6,0x0397}, {0x1FC7,0x1FC7,0x0397},
{0x1FC8,0x1F72,0x0395}, {0x1FC9,0x1F73,0x1FC9},
{0x1FCA,0x1F74,0x0397}, {0x1FCB,0x1F75,0x1FCB},
{0x1FCC,0x1FC3,0x0397}, {0x1FCD,0x1FCD,0x1FCD},
{0x1FCE,0x1FCE,0x1FCE}, {0x1FCF,0x1FCF,0x1FCF},
{0x1FD8,0x1FD0,0x0399}, {0x1FD9,0x1FD1,0x0399},
{0x1FD2,0x1FD2,0x0399}, {0x1FD3,0x1FD3,0x1FD3},
{0x1FD4,0x1FD4,0x1FD4}, {0x1FD5,0x1FD5,0x1FD5},
{0x1FD6,0x1FD6,0x0399}, {0x1FD7,0x1FD7,0x0399},
{0x1FD8,0x1FD0,0x0399}, {0x1FD9,0x1FD1,0x0399},
{0x1FDA,0x1F76,0x0399}, {0x1FDB,0x1F77,0x1FDB},
{0x1FDC,0x1FDC,0x1FDC}, {0x1FDD,0x1FDD,0x1FDD},
{0x1FDE,0x1FDE,0x1FDE}, {0x1FDF,0x1FDF,0x1FDF},
{0x1FE8,0x1FE0,0x03A5}, {0x1FE9,0x1FE1,0x03A5},
{0x1FE2,0x1FE2,0x03A5}, {0x1FE3,0x1FE3,0x1FE3},
{0x1FE4,0x1FE4,0x03A1}, {0x1FEC,0x1FE5,0x03A1},
{0x1FE6,0x1FE6,0x03A5}, {0x1FE7,0x1FE7,0x03A5},
{0x1FE8,0x1FE0,0x03A5}, {0x1FE9,0x1FE1,0x03A5},
{0x1FEA,0x1F7A,0x03A5}, {0x1FEB,0x1F7B,0x1FEB},
{0x1FEC,0x1FE5,0x03A1}, {0x1FED,0x1FED,0x1FED},
{0x1FEE,0x1FEE,0x1FEE}, {0x1FEF,0x1FEF,0x1FEF},
{0x1FF0,0x1FF0,0x1FF0}, {0x1FF1,0x1FF1,0x1FF1},
{0x1FF2,0x1FF2,0x03A9}, {0x1FFC,0x1FF3,0x03A9},
{0x1FF4,0x1FF4,0x03A9}, {0x1FF5,0x1FF5,0x1FF5},
{0x1FF6,0x1FF6,0x03A9}, {0x1FF7,0x1FF7,0x03A9},
{0x1FF8,0x1F78,0x039F}, {0x1FF9,0x1F79,0x1FF9},
{0x1FFA,0x1F7C,0x03A9}, {0x1FFB,0x1F7D,0x1FFB},
{0x1FFC,0x1FF3,0x03A9}, {0x1FFD,0x1FFD,0x1FFD},
{0x1FFE,0x1FFE,0x1FFE}, {0x1FFF,0x1FFF,0x1FFF}
};
static MY_UNICASE_INFO plane21[]={
{0x2100,0x2100,0x2100}, {0x2101,0x2101,0x2101},
{0x2102,0x2102,0x2102}, {0x2103,0x2103,0x2103},
{0x2104,0x2104,0x2104}, {0x2105,0x2105,0x2105},
{0x2106,0x2106,0x2106}, {0x2107,0x2107,0x2107},
{0x2108,0x2108,0x2108}, {0x2109,0x2109,0x2109},
{0x210A,0x210A,0x210A}, {0x210B,0x210B,0x210B},
{0x210C,0x210C,0x210C}, {0x210D,0x210D,0x210D},
{0x210E,0x210E,0x210E}, {0x210F,0x210F,0x210F},
{0x2110,0x2110,0x2110}, {0x2111,0x2111,0x2111},
{0x2112,0x2112,0x2112}, {0x2113,0x2113,0x2113},
{0x2114,0x2114,0x2114}, {0x2115,0x2115,0x2115},
{0x2116,0x2116,0x2116}, {0x2117,0x2117,0x2117},
{0x2118,0x2118,0x2118}, {0x2119,0x2119,0x2119},
{0x211A,0x211A,0x211A}, {0x211B,0x211B,0x211B},
{0x211C,0x211C,0x211C}, {0x211D,0x211D,0x211D},
{0x211E,0x211E,0x211E}, {0x211F,0x211F,0x211F},
{0x2120,0x2120,0x2120}, {0x2121,0x2121,0x2121},
{0x2122,0x2122,0x2122}, {0x2123,0x2123,0x2123},
{0x2124,0x2124,0x2124}, {0x2125,0x2125,0x2125},
{0x2126,0x03C9,0x2126}, {0x2127,0x2127,0x2127},
{0x2128,0x2128,0x2128}, {0x2129,0x2129,0x2129},
{0x212A,0x006B,0x212A}, {0x212B,0x00E5,0x212B},
{0x212C,0x212C,0x212C}, {0x212D,0x212D,0x212D},
{0x212E,0x212E,0x212E}, {0x212F,0x212F,0x212F},
{0x2130,0x2130,0x2130}, {0x2131,0x2131,0x2131},
{0x2132,0x2132,0x2132}, {0x2133,0x2133,0x2133},
{0x2134,0x2134,0x2134}, {0x2135,0x2135,0x2135},
{0x2136,0x2136,0x2136}, {0x2137,0x2137,0x2137},
{0x2138,0x2138,0x2138}, {0x2139,0x2139,0x2139},
{0x213A,0x213A,0x213A}, {0x213B,0x213B,0x213B},
{0x213C,0x213C,0x213C}, {0x213D,0x213D,0x213D},
{0x213E,0x213E,0x213E}, {0x213F,0x213F,0x213F},
{0x2140,0x2140,0x2140}, {0x2141,0x2141,0x2141},
{0x2142,0x2142,0x2142}, {0x2143,0x2143,0x2143},
{0x2144,0x2144,0x2144}, {0x2145,0x2145,0x2145},
{0x2146,0x2146,0x2146}, {0x2147,0x2147,0x2147},
{0x2148,0x2148,0x2148}, {0x2149,0x2149,0x2149},
{0x214A,0x214A,0x214A}, {0x214B,0x214B,0x214B},
{0x214C,0x214C,0x214C}, {0x214D,0x214D,0x214D},
{0x214E,0x214E,0x214E}, {0x214F,0x214F,0x214F},
{0x2150,0x2150,0x2150}, {0x2151,0x2151,0x2151},
{0x2152,0x2152,0x2152}, {0x2153,0x2153,0x2153},
{0x2154,0x2154,0x2154}, {0x2155,0x2155,0x2155},
{0x2156,0x2156,0x2156}, {0x2157,0x2157,0x2157},
{0x2158,0x2158,0x2158}, {0x2159,0x2159,0x2159},
{0x215A,0x215A,0x215A}, {0x215B,0x215B,0x215B},
{0x215C,0x215C,0x215C}, {0x215D,0x215D,0x215D},
{0x215E,0x215E,0x215E}, {0x215F,0x215F,0x215F},
{0x2160,0x2170,0x2160}, {0x2161,0x2171,0x2161},
{0x2162,0x2172,0x2162}, {0x2163,0x2173,0x2163},
{0x2164,0x2174,0x2164}, {0x2165,0x2175,0x2165},
{0x2166,0x2176,0x2166}, {0x2167,0x2177,0x2167},
{0x2168,0x2178,0x2168}, {0x2169,0x2179,0x2169},
{0x216A,0x217A,0x216A}, {0x216B,0x217B,0x216B},
{0x216C,0x217C,0x216C}, {0x216D,0x217D,0x216D},
{0x216E,0x217E,0x216E}, {0x216F,0x217F,0x216F},
{0x2160,0x2170,0x2160}, {0x2161,0x2171,0x2161},
{0x2162,0x2172,0x2162}, {0x2163,0x2173,0x2163},
{0x2164,0x2174,0x2164}, {0x2165,0x2175,0x2165},
{0x2166,0x2176,0x2166}, {0x2167,0x2177,0x2167},
{0x2168,0x2178,0x2168}, {0x2169,0x2179,0x2169},
{0x216A,0x217A,0x216A}, {0x216B,0x217B,0x216B},
{0x216C,0x217C,0x216C}, {0x216D,0x217D,0x216D},
{0x216E,0x217E,0x216E}, {0x216F,0x217F,0x216F},
{0x2180,0x2180,0x2180}, {0x2181,0x2181,0x2181},
{0x2182,0x2182,0x2182}, {0x2183,0x2183,0x2183},
{0x2184,0x2184,0x2184}, {0x2185,0x2185,0x2185},
{0x2186,0x2186,0x2186}, {0x2187,0x2187,0x2187},
{0x2188,0x2188,0x2188}, {0x2189,0x2189,0x2189},
{0x218A,0x218A,0x218A}, {0x218B,0x218B,0x218B},
{0x218C,0x218C,0x218C}, {0x218D,0x218D,0x218D},
{0x218E,0x218E,0x218E}, {0x218F,0x218F,0x218F},
{0x2190,0x2190,0x2190}, {0x2191,0x2191,0x2191},
{0x2192,0x2192,0x2192}, {0x2193,0x2193,0x2193},
{0x2194,0x2194,0x2194}, {0x2195,0x2195,0x2195},
{0x2196,0x2196,0x2196}, {0x2197,0x2197,0x2197},
{0x2198,0x2198,0x2198}, {0x2199,0x2199,0x2199},
{0x219A,0x219A,0x219A}, {0x219B,0x219B,0x219B},
{0x219C,0x219C,0x219C}, {0x219D,0x219D,0x219D},
{0x219E,0x219E,0x219E}, {0x219F,0x219F,0x219F},
{0x21A0,0x21A0,0x21A0}, {0x21A1,0x21A1,0x21A1},
{0x21A2,0x21A2,0x21A2}, {0x21A3,0x21A3,0x21A3},
{0x21A4,0x21A4,0x21A4}, {0x21A5,0x21A5,0x21A5},
{0x21A6,0x21A6,0x21A6}, {0x21A7,0x21A7,0x21A7},
{0x21A8,0x21A8,0x21A8}, {0x21A9,0x21A9,0x21A9},
{0x21AA,0x21AA,0x21AA}, {0x21AB,0x21AB,0x21AB},
{0x21AC,0x21AC,0x21AC}, {0x21AD,0x21AD,0x21AD},
{0x21AE,0x21AE,0x21AE}, {0x21AF,0x21AF,0x21AF},
{0x21B0,0x21B0,0x21B0}, {0x21B1,0x21B1,0x21B1},
{0x21B2,0x21B2,0x21B2}, {0x21B3,0x21B3,0x21B3},
{0x21B4,0x21B4,0x21B4}, {0x21B5,0x21B5,0x21B5},
{0x21B6,0x21B6,0x21B6}, {0x21B7,0x21B7,0x21B7},
{0x21B8,0x21B8,0x21B8}, {0x21B9,0x21B9,0x21B9},
{0x21BA,0x21BA,0x21BA}, {0x21BB,0x21BB,0x21BB},
{0x21BC,0x21BC,0x21BC}, {0x21BD,0x21BD,0x21BD},
{0x21BE,0x21BE,0x21BE}, {0x21BF,0x21BF,0x21BF},
{0x21C0,0x21C0,0x21C0}, {0x21C1,0x21C1,0x21C1},
{0x21C2,0x21C2,0x21C2}, {0x21C3,0x21C3,0x21C3},
{0x21C4,0x21C4,0x21C4}, {0x21C5,0x21C5,0x21C5},
{0x21C6,0x21C6,0x21C6}, {0x21C7,0x21C7,0x21C7},
{0x21C8,0x21C8,0x21C8}, {0x21C9,0x21C9,0x21C9},
{0x21CA,0x21CA,0x21CA}, {0x21CB,0x21CB,0x21CB},
{0x21CC,0x21CC,0x21CC}, {0x21CD,0x21CD,0x21CD},
{0x21CE,0x21CE,0x21CE}, {0x21CF,0x21CF,0x21CF},
{0x21D0,0x21D0,0x21D0}, {0x21D1,0x21D1,0x21D1},
{0x21D2,0x21D2,0x21D2}, {0x21D3,0x21D3,0x21D3},
{0x21D4,0x21D4,0x21D4}, {0x21D5,0x21D5,0x21D5},
{0x21D6,0x21D6,0x21D6}, {0x21D7,0x21D7,0x21D7},
{0x21D8,0x21D8,0x21D8}, {0x21D9,0x21D9,0x21D9},
{0x21DA,0x21DA,0x21DA}, {0x21DB,0x21DB,0x21DB},
{0x21DC,0x21DC,0x21DC}, {0x21DD,0x21DD,0x21DD},
{0x21DE,0x21DE,0x21DE}, {0x21DF,0x21DF,0x21DF},
{0x21E0,0x21E0,0x21E0}, {0x21E1,0x21E1,0x21E1},
{0x21E2,0x21E2,0x21E2}, {0x21E3,0x21E3,0x21E3},
{0x21E4,0x21E4,0x21E4}, {0x21E5,0x21E5,0x21E5},
{0x21E6,0x21E6,0x21E6}, {0x21E7,0x21E7,0x21E7},
{0x21E8,0x21E8,0x21E8}, {0x21E9,0x21E9,0x21E9},
{0x21EA,0x21EA,0x21EA}, {0x21EB,0x21EB,0x21EB},
{0x21EC,0x21EC,0x21EC}, {0x21ED,0x21ED,0x21ED},
{0x21EE,0x21EE,0x21EE}, {0x21EF,0x21EF,0x21EF},
{0x21F0,0x21F0,0x21F0}, {0x21F1,0x21F1,0x21F1},
{0x21F2,0x21F2,0x21F2}, {0x21F3,0x21F3,0x21F3},
{0x21F4,0x21F4,0x21F4}, {0x21F5,0x21F5,0x21F5},
{0x21F6,0x21F6,0x21F6}, {0x21F7,0x21F7,0x21F7},
{0x21F8,0x21F8,0x21F8}, {0x21F9,0x21F9,0x21F9},
{0x21FA,0x21FA,0x21FA}, {0x21FB,0x21FB,0x21FB},
{0x21FC,0x21FC,0x21FC}, {0x21FD,0x21FD,0x21FD},
{0x21FE,0x21FE,0x21FE}, {0x21FF,0x21FF,0x21FF}
};
static MY_UNICASE_INFO plane24[]={
{0x2400,0x2400,0x2400}, {0x2401,0x2401,0x2401},
{0x2402,0x2402,0x2402}, {0x2403,0x2403,0x2403},
{0x2404,0x2404,0x2404}, {0x2405,0x2405,0x2405},
{0x2406,0x2406,0x2406}, {0x2407,0x2407,0x2407},
{0x2408,0x2408,0x2408}, {0x2409,0x2409,0x2409},
{0x240A,0x240A,0x240A}, {0x240B,0x240B,0x240B},
{0x240C,0x240C,0x240C}, {0x240D,0x240D,0x240D},
{0x240E,0x240E,0x240E}, {0x240F,0x240F,0x240F},
{0x2410,0x2410,0x2410}, {0x2411,0x2411,0x2411},
{0x2412,0x2412,0x2412}, {0x2413,0x2413,0x2413},
{0x2414,0x2414,0x2414}, {0x2415,0x2415,0x2415},
{0x2416,0x2416,0x2416}, {0x2417,0x2417,0x2417},
{0x2418,0x2418,0x2418}, {0x2419,0x2419,0x2419},
{0x241A,0x241A,0x241A}, {0x241B,0x241B,0x241B},
{0x241C,0x241C,0x241C}, {0x241D,0x241D,0x241D},
{0x241E,0x241E,0x241E}, {0x241F,0x241F,0x241F},
{0x2420,0x2420,0x2420}, {0x2421,0x2421,0x2421},
{0x2422,0x2422,0x2422}, {0x2423,0x2423,0x2423},
{0x2424,0x2424,0x2424}, {0x2425,0x2425,0x2425},
{0x2426,0x2426,0x2426}, {0x2427,0x2427,0x2427},
{0x2428,0x2428,0x2428}, {0x2429,0x2429,0x2429},
{0x242A,0x242A,0x242A}, {0x242B,0x242B,0x242B},
{0x242C,0x242C,0x242C}, {0x242D,0x242D,0x242D},
{0x242E,0x242E,0x242E}, {0x242F,0x242F,0x242F},
{0x2430,0x2430,0x2430}, {0x2431,0x2431,0x2431},
{0x2432,0x2432,0x2432}, {0x2433,0x2433,0x2433},
{0x2434,0x2434,0x2434}, {0x2435,0x2435,0x2435},
{0x2436,0x2436,0x2436}, {0x2437,0x2437,0x2437},
{0x2438,0x2438,0x2438}, {0x2439,0x2439,0x2439},
{0x243A,0x243A,0x243A}, {0x243B,0x243B,0x243B},
{0x243C,0x243C,0x243C}, {0x243D,0x243D,0x243D},
{0x243E,0x243E,0x243E}, {0x243F,0x243F,0x243F},
{0x2440,0x2440,0x2440}, {0x2441,0x2441,0x2441},
{0x2442,0x2442,0x2442}, {0x2443,0x2443,0x2443},
{0x2444,0x2444,0x2444}, {0x2445,0x2445,0x2445},
{0x2446,0x2446,0x2446}, {0x2447,0x2447,0x2447},
{0x2448,0x2448,0x2448}, {0x2449,0x2449,0x2449},
{0x244A,0x244A,0x244A}, {0x244B,0x244B,0x244B},
{0x244C,0x244C,0x244C}, {0x244D,0x244D,0x244D},
{0x244E,0x244E,0x244E}, {0x244F,0x244F,0x244F},
{0x2450,0x2450,0x2450}, {0x2451,0x2451,0x2451},
{0x2452,0x2452,0x2452}, {0x2453,0x2453,0x2453},
{0x2454,0x2454,0x2454}, {0x2455,0x2455,0x2455},
{0x2456,0x2456,0x2456}, {0x2457,0x2457,0x2457},
{0x2458,0x2458,0x2458}, {0x2459,0x2459,0x2459},
{0x245A,0x245A,0x245A}, {0x245B,0x245B,0x245B},
{0x245C,0x245C,0x245C}, {0x245D,0x245D,0x245D},
{0x245E,0x245E,0x245E}, {0x245F,0x245F,0x245F},
{0x2460,0x2460,0x2460}, {0x2461,0x2461,0x2461},
{0x2462,0x2462,0x2462}, {0x2463,0x2463,0x2463},
{0x2464,0x2464,0x2464}, {0x2465,0x2465,0x2465},
{0x2466,0x2466,0x2466}, {0x2467,0x2467,0x2467},
{0x2468,0x2468,0x2468}, {0x2469,0x2469,0x2469},
{0x246A,0x246A,0x246A}, {0x246B,0x246B,0x246B},
{0x246C,0x246C,0x246C}, {0x246D,0x246D,0x246D},
{0x246E,0x246E,0x246E}, {0x246F,0x246F,0x246F},
{0x2470,0x2470,0x2470}, {0x2471,0x2471,0x2471},
{0x2472,0x2472,0x2472}, {0x2473,0x2473,0x2473},
{0x2474,0x2474,0x2474}, {0x2475,0x2475,0x2475},
{0x2476,0x2476,0x2476}, {0x2477,0x2477,0x2477},
{0x2478,0x2478,0x2478}, {0x2479,0x2479,0x2479},
{0x247A,0x247A,0x247A}, {0x247B,0x247B,0x247B},
{0x247C,0x247C,0x247C}, {0x247D,0x247D,0x247D},
{0x247E,0x247E,0x247E}, {0x247F,0x247F,0x247F},
{0x2480,0x2480,0x2480}, {0x2481,0x2481,0x2481},
{0x2482,0x2482,0x2482}, {0x2483,0x2483,0x2483},
{0x2484,0x2484,0x2484}, {0x2485,0x2485,0x2485},
{0x2486,0x2486,0x2486}, {0x2487,0x2487,0x2487},
{0x2488,0x2488,0x2488}, {0x2489,0x2489,0x2489},
{0x248A,0x248A,0x248A}, {0x248B,0x248B,0x248B},
{0x248C,0x248C,0x248C}, {0x248D,0x248D,0x248D},
{0x248E,0x248E,0x248E}, {0x248F,0x248F,0x248F},
{0x2490,0x2490,0x2490}, {0x2491,0x2491,0x2491},
{0x2492,0x2492,0x2492}, {0x2493,0x2493,0x2493},
{0x2494,0x2494,0x2494}, {0x2495,0x2495,0x2495},
{0x2496,0x2496,0x2496}, {0x2497,0x2497,0x2497},
{0x2498,0x2498,0x2498}, {0x2499,0x2499,0x2499},
{0x249A,0x249A,0x249A}, {0x249B,0x249B,0x249B},
{0x249C,0x249C,0x249C}, {0x249D,0x249D,0x249D},
{0x249E,0x249E,0x249E}, {0x249F,0x249F,0x249F},
{0x24A0,0x24A0,0x24A0}, {0x24A1,0x24A1,0x24A1},
{0x24A2,0x24A2,0x24A2}, {0x24A3,0x24A3,0x24A3},
{0x24A4,0x24A4,0x24A4}, {0x24A5,0x24A5,0x24A5},
{0x24A6,0x24A6,0x24A6}, {0x24A7,0x24A7,0x24A7},
{0x24A8,0x24A8,0x24A8}, {0x24A9,0x24A9,0x24A9},
{0x24AA,0x24AA,0x24AA}, {0x24AB,0x24AB,0x24AB},
{0x24AC,0x24AC,0x24AC}, {0x24AD,0x24AD,0x24AD},
{0x24AE,0x24AE,0x24AE}, {0x24AF,0x24AF,0x24AF},
{0x24B0,0x24B0,0x24B0}, {0x24B1,0x24B1,0x24B1},
{0x24B2,0x24B2,0x24B2}, {0x24B3,0x24B3,0x24B3},
{0x24B4,0x24B4,0x24B4}, {0x24B5,0x24B5,0x24B5},
{0x24B6,0x24D0,0x24B6}, {0x24B7,0x24D1,0x24B7},
{0x24B8,0x24D2,0x24B8}, {0x24B9,0x24D3,0x24B9},
{0x24BA,0x24D4,0x24BA}, {0x24BB,0x24D5,0x24BB},
{0x24BC,0x24D6,0x24BC}, {0x24BD,0x24D7,0x24BD},
{0x24BE,0x24D8,0x24BE}, {0x24BF,0x24D9,0x24BF},
{0x24C0,0x24DA,0x24C0}, {0x24C1,0x24DB,0x24C1},
{0x24C2,0x24DC,0x24C2}, {0x24C3,0x24DD,0x24C3},
{0x24C4,0x24DE,0x24C4}, {0x24C5,0x24DF,0x24C5},
{0x24C6,0x24E0,0x24C6}, {0x24C7,0x24E1,0x24C7},
{0x24C8,0x24E2,0x24C8}, {0x24C9,0x24E3,0x24C9},
{0x24CA,0x24E4,0x24CA}, {0x24CB,0x24E5,0x24CB},
{0x24CC,0x24E6,0x24CC}, {0x24CD,0x24E7,0x24CD},
{0x24CE,0x24E8,0x24CE}, {0x24CF,0x24E9,0x24CF},
{0x24B6,0x24D0,0x24B6}, {0x24B7,0x24D1,0x24B7},
{0x24B8,0x24D2,0x24B8}, {0x24B9,0x24D3,0x24B9},
{0x24BA,0x24D4,0x24BA}, {0x24BB,0x24D5,0x24BB},
{0x24BC,0x24D6,0x24BC}, {0x24BD,0x24D7,0x24BD},
{0x24BE,0x24D8,0x24BE}, {0x24BF,0x24D9,0x24BF},
{0x24C0,0x24DA,0x24C0}, {0x24C1,0x24DB,0x24C1},
{0x24C2,0x24DC,0x24C2}, {0x24C3,0x24DD,0x24C3},
{0x24C4,0x24DE,0x24C4}, {0x24C5,0x24DF,0x24C5},
{0x24C6,0x24E0,0x24C6}, {0x24C7,0x24E1,0x24C7},
{0x24C8,0x24E2,0x24C8}, {0x24C9,0x24E3,0x24C9},
{0x24CA,0x24E4,0x24CA}, {0x24CB,0x24E5,0x24CB},
{0x24CC,0x24E6,0x24CC}, {0x24CD,0x24E7,0x24CD},
{0x24CE,0x24E8,0x24CE}, {0x24CF,0x24E9,0x24CF},
{0x24EA,0x24EA,0x24EA}, {0x24EB,0x24EB,0x24EB},
{0x24EC,0x24EC,0x24EC}, {0x24ED,0x24ED,0x24ED},
{0x24EE,0x24EE,0x24EE}, {0x24EF,0x24EF,0x24EF},
{0x24F0,0x24F0,0x24F0}, {0x24F1,0x24F1,0x24F1},
{0x24F2,0x24F2,0x24F2}, {0x24F3,0x24F3,0x24F3},
{0x24F4,0x24F4,0x24F4}, {0x24F5,0x24F5,0x24F5},
{0x24F6,0x24F6,0x24F6}, {0x24F7,0x24F7,0x24F7},
{0x24F8,0x24F8,0x24F8}, {0x24F9,0x24F9,0x24F9},
{0x24FA,0x24FA,0x24FA}, {0x24FB,0x24FB,0x24FB},
{0x24FC,0x24FC,0x24FC}, {0x24FD,0x24FD,0x24FD},
{0x24FE,0x24FE,0x24FE}, {0x24FF,0x24FF,0x24FF}
};
static MY_UNICASE_INFO planeFF[]={
{0xFF00,0xFF00,0xFF00}, {0xFF01,0xFF01,0xFF01},
{0xFF02,0xFF02,0xFF02}, {0xFF03,0xFF03,0xFF03},
{0xFF04,0xFF04,0xFF04}, {0xFF05,0xFF05,0xFF05},
{0xFF06,0xFF06,0xFF06}, {0xFF07,0xFF07,0xFF07},
{0xFF08,0xFF08,0xFF08}, {0xFF09,0xFF09,0xFF09},
{0xFF0A,0xFF0A,0xFF0A}, {0xFF0B,0xFF0B,0xFF0B},
{0xFF0C,0xFF0C,0xFF0C}, {0xFF0D,0xFF0D,0xFF0D},
{0xFF0E,0xFF0E,0xFF0E}, {0xFF0F,0xFF0F,0xFF0F},
{0xFF10,0xFF10,0xFF10}, {0xFF11,0xFF11,0xFF11},
{0xFF12,0xFF12,0xFF12}, {0xFF13,0xFF13,0xFF13},
{0xFF14,0xFF14,0xFF14}, {0xFF15,0xFF15,0xFF15},
{0xFF16,0xFF16,0xFF16}, {0xFF17,0xFF17,0xFF17},
{0xFF18,0xFF18,0xFF18}, {0xFF19,0xFF19,0xFF19},
{0xFF1A,0xFF1A,0xFF1A}, {0xFF1B,0xFF1B,0xFF1B},
{0xFF1C,0xFF1C,0xFF1C}, {0xFF1D,0xFF1D,0xFF1D},
{0xFF1E,0xFF1E,0xFF1E}, {0xFF1F,0xFF1F,0xFF1F},
{0xFF20,0xFF20,0xFF20}, {0xFF21,0xFF41,0xFF21},
{0xFF22,0xFF42,0xFF22}, {0xFF23,0xFF43,0xFF23},
{0xFF24,0xFF44,0xFF24}, {0xFF25,0xFF45,0xFF25},
{0xFF26,0xFF46,0xFF26}, {0xFF27,0xFF47,0xFF27},
{0xFF28,0xFF48,0xFF28}, {0xFF29,0xFF49,0xFF29},
{0xFF2A,0xFF4A,0xFF2A}, {0xFF2B,0xFF4B,0xFF2B},
{0xFF2C,0xFF4C,0xFF2C}, {0xFF2D,0xFF4D,0xFF2D},
{0xFF2E,0xFF4E,0xFF2E}, {0xFF2F,0xFF4F,0xFF2F},
{0xFF30,0xFF50,0xFF30}, {0xFF31,0xFF51,0xFF31},
{0xFF32,0xFF52,0xFF32}, {0xFF33,0xFF53,0xFF33},
{0xFF34,0xFF54,0xFF34}, {0xFF35,0xFF55,0xFF35},
{0xFF36,0xFF56,0xFF36}, {0xFF37,0xFF57,0xFF37},
{0xFF38,0xFF58,0xFF38}, {0xFF39,0xFF59,0xFF39},
{0xFF3A,0xFF5A,0xFF3A}, {0xFF3B,0xFF3B,0xFF3B},
{0xFF3C,0xFF3C,0xFF3C}, {0xFF3D,0xFF3D,0xFF3D},
{0xFF3E,0xFF3E,0xFF3E}, {0xFF3F,0xFF3F,0xFF3F},
{0xFF40,0xFF40,0xFF40}, {0xFF21,0xFF41,0xFF21},
{0xFF22,0xFF42,0xFF22}, {0xFF23,0xFF43,0xFF23},
{0xFF24,0xFF44,0xFF24}, {0xFF25,0xFF45,0xFF25},
{0xFF26,0xFF46,0xFF26}, {0xFF27,0xFF47,0xFF27},
{0xFF28,0xFF48,0xFF28}, {0xFF29,0xFF49,0xFF29},
{0xFF2A,0xFF4A,0xFF2A}, {0xFF2B,0xFF4B,0xFF2B},
{0xFF2C,0xFF4C,0xFF2C}, {0xFF2D,0xFF4D,0xFF2D},
{0xFF2E,0xFF4E,0xFF2E}, {0xFF2F,0xFF4F,0xFF2F},
{0xFF30,0xFF50,0xFF30}, {0xFF31,0xFF51,0xFF31},
{0xFF32,0xFF52,0xFF32}, {0xFF33,0xFF53,0xFF33},
{0xFF34,0xFF54,0xFF34}, {0xFF35,0xFF55,0xFF35},
{0xFF36,0xFF56,0xFF36}, {0xFF37,0xFF57,0xFF37},
{0xFF38,0xFF58,0xFF38}, {0xFF39,0xFF59,0xFF39},
{0xFF3A,0xFF5A,0xFF3A}, {0xFF5B,0xFF5B,0xFF5B},
{0xFF5C,0xFF5C,0xFF5C}, {0xFF5D,0xFF5D,0xFF5D},
{0xFF5E,0xFF5E,0xFF5E}, {0xFF5F,0xFF5F,0xFF5F},
{0xFF60,0xFF60,0xFF60}, {0xFF61,0xFF61,0xFF61},
{0xFF62,0xFF62,0xFF62}, {0xFF63,0xFF63,0xFF63},
{0xFF64,0xFF64,0xFF64}, {0xFF65,0xFF65,0xFF65},
{0xFF66,0xFF66,0xFF66}, {0xFF67,0xFF67,0xFF67},
{0xFF68,0xFF68,0xFF68}, {0xFF69,0xFF69,0xFF69},
{0xFF6A,0xFF6A,0xFF6A}, {0xFF6B,0xFF6B,0xFF6B},
{0xFF6C,0xFF6C,0xFF6C}, {0xFF6D,0xFF6D,0xFF6D},
{0xFF6E,0xFF6E,0xFF6E}, {0xFF6F,0xFF6F,0xFF6F},
{0xFF70,0xFF70,0xFF70}, {0xFF71,0xFF71,0xFF71},
{0xFF72,0xFF72,0xFF72}, {0xFF73,0xFF73,0xFF73},
{0xFF74,0xFF74,0xFF74}, {0xFF75,0xFF75,0xFF75},
{0xFF76,0xFF76,0xFF76}, {0xFF77,0xFF77,0xFF77},
{0xFF78,0xFF78,0xFF78}, {0xFF79,0xFF79,0xFF79},
{0xFF7A,0xFF7A,0xFF7A}, {0xFF7B,0xFF7B,0xFF7B},
{0xFF7C,0xFF7C,0xFF7C}, {0xFF7D,0xFF7D,0xFF7D},
{0xFF7E,0xFF7E,0xFF7E}, {0xFF7F,0xFF7F,0xFF7F},
{0xFF80,0xFF80,0xFF80}, {0xFF81,0xFF81,0xFF81},
{0xFF82,0xFF82,0xFF82}, {0xFF83,0xFF83,0xFF83},
{0xFF84,0xFF84,0xFF84}, {0xFF85,0xFF85,0xFF85},
{0xFF86,0xFF86,0xFF86}, {0xFF87,0xFF87,0xFF87},
{0xFF88,0xFF88,0xFF88}, {0xFF89,0xFF89,0xFF89},
{0xFF8A,0xFF8A,0xFF8A}, {0xFF8B,0xFF8B,0xFF8B},
{0xFF8C,0xFF8C,0xFF8C}, {0xFF8D,0xFF8D,0xFF8D},
{0xFF8E,0xFF8E,0xFF8E}, {0xFF8F,0xFF8F,0xFF8F},
{0xFF90,0xFF90,0xFF90}, {0xFF91,0xFF91,0xFF91},
{0xFF92,0xFF92,0xFF92}, {0xFF93,0xFF93,0xFF93},
{0xFF94,0xFF94,0xFF94}, {0xFF95,0xFF95,0xFF95},
{0xFF96,0xFF96,0xFF96}, {0xFF97,0xFF97,0xFF97},
{0xFF98,0xFF98,0xFF98}, {0xFF99,0xFF99,0xFF99},
{0xFF9A,0xFF9A,0xFF9A}, {0xFF9B,0xFF9B,0xFF9B},
{0xFF9C,0xFF9C,0xFF9C}, {0xFF9D,0xFF9D,0xFF9D},
{0xFF9E,0xFF9E,0xFF9E}, {0xFF9F,0xFF9F,0xFF9F},
{0xFFA0,0xFFA0,0xFFA0}, {0xFFA1,0xFFA1,0xFFA1},
{0xFFA2,0xFFA2,0xFFA2}, {0xFFA3,0xFFA3,0xFFA3},
{0xFFA4,0xFFA4,0xFFA4}, {0xFFA5,0xFFA5,0xFFA5},
{0xFFA6,0xFFA6,0xFFA6}, {0xFFA7,0xFFA7,0xFFA7},
{0xFFA8,0xFFA8,0xFFA8}, {0xFFA9,0xFFA9,0xFFA9},
{0xFFAA,0xFFAA,0xFFAA}, {0xFFAB,0xFFAB,0xFFAB},
{0xFFAC,0xFFAC,0xFFAC}, {0xFFAD,0xFFAD,0xFFAD},
{0xFFAE,0xFFAE,0xFFAE}, {0xFFAF,0xFFAF,0xFFAF},
{0xFFB0,0xFFB0,0xFFB0}, {0xFFB1,0xFFB1,0xFFB1},
{0xFFB2,0xFFB2,0xFFB2}, {0xFFB3,0xFFB3,0xFFB3},
{0xFFB4,0xFFB4,0xFFB4}, {0xFFB5,0xFFB5,0xFFB5},
{0xFFB6,0xFFB6,0xFFB6}, {0xFFB7,0xFFB7,0xFFB7},
{0xFFB8,0xFFB8,0xFFB8}, {0xFFB9,0xFFB9,0xFFB9},
{0xFFBA,0xFFBA,0xFFBA}, {0xFFBB,0xFFBB,0xFFBB},
{0xFFBC,0xFFBC,0xFFBC}, {0xFFBD,0xFFBD,0xFFBD},
{0xFFBE,0xFFBE,0xFFBE}, {0xFFBF,0xFFBF,0xFFBF},
{0xFFC0,0xFFC0,0xFFC0}, {0xFFC1,0xFFC1,0xFFC1},
{0xFFC2,0xFFC2,0xFFC2}, {0xFFC3,0xFFC3,0xFFC3},
{0xFFC4,0xFFC4,0xFFC4}, {0xFFC5,0xFFC5,0xFFC5},
{0xFFC6,0xFFC6,0xFFC6}, {0xFFC7,0xFFC7,0xFFC7},
{0xFFC8,0xFFC8,0xFFC8}, {0xFFC9,0xFFC9,0xFFC9},
{0xFFCA,0xFFCA,0xFFCA}, {0xFFCB,0xFFCB,0xFFCB},
{0xFFCC,0xFFCC,0xFFCC}, {0xFFCD,0xFFCD,0xFFCD},
{0xFFCE,0xFFCE,0xFFCE}, {0xFFCF,0xFFCF,0xFFCF},
{0xFFD0,0xFFD0,0xFFD0}, {0xFFD1,0xFFD1,0xFFD1},
{0xFFD2,0xFFD2,0xFFD2}, {0xFFD3,0xFFD3,0xFFD3},
{0xFFD4,0xFFD4,0xFFD4}, {0xFFD5,0xFFD5,0xFFD5},
{0xFFD6,0xFFD6,0xFFD6}, {0xFFD7,0xFFD7,0xFFD7},
{0xFFD8,0xFFD8,0xFFD8}, {0xFFD9,0xFFD9,0xFFD9},
{0xFFDA,0xFFDA,0xFFDA}, {0xFFDB,0xFFDB,0xFFDB},
{0xFFDC,0xFFDC,0xFFDC}, {0xFFDD,0xFFDD,0xFFDD},
{0xFFDE,0xFFDE,0xFFDE}, {0xFFDF,0xFFDF,0xFFDF},
{0xFFE0,0xFFE0,0xFFE0}, {0xFFE1,0xFFE1,0xFFE1},
{0xFFE2,0xFFE2,0xFFE2}, {0xFFE3,0xFFE3,0xFFE3},
{0xFFE4,0xFFE4,0xFFE4}, {0xFFE5,0xFFE5,0xFFE5},
{0xFFE6,0xFFE6,0xFFE6}, {0xFFE7,0xFFE7,0xFFE7},
{0xFFE8,0xFFE8,0xFFE8}, {0xFFE9,0xFFE9,0xFFE9},
{0xFFEA,0xFFEA,0xFFEA}, {0xFFEB,0xFFEB,0xFFEB},
{0xFFEC,0xFFEC,0xFFEC}, {0xFFED,0xFFED,0xFFED},
{0xFFEE,0xFFEE,0xFFEE}, {0xFFEF,0xFFEF,0xFFEF},
{0xFFF0,0xFFF0,0xFFF0}, {0xFFF1,0xFFF1,0xFFF1},
{0xFFF2,0xFFF2,0xFFF2}, {0xFFF3,0xFFF3,0xFFF3},
{0xFFF4,0xFFF4,0xFFF4}, {0xFFF5,0xFFF5,0xFFF5},
{0xFFF6,0xFFF6,0xFFF6}, {0xFFF7,0xFFF7,0xFFF7},
{0xFFF8,0xFFF8,0xFFF8}, {0xFFF9,0xFFF9,0xFFF9},
{0xFFFA,0xFFFA,0xFFFA}, {0xFFFB,0xFFFB,0xFFFB},
{0xFFFC,0xFFFC,0xFFFC}, {0xFFFD,0xFFFD,0xFFFD},
{0xFFFE,0xFFFE,0xFFFE}, {0xFFFF,0xFFFF,0xFFFF}
};
MY_UNICASE_INFO *my_unicase_default[256]={
plane00, plane01, plane02, plane03, plane04, plane05, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, plane1E, plane1F,
NULL, plane21, NULL, NULL, plane24, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, planeFF
};
#define MY_CS_ILSEQ 0 /* Wrong by sequence: wb_wc */
#define MY_CS_TOOSMALL -101 /* Need at least one byte: wc_mb and mb_wc */
#define MY_CS_TOOSMALL2 -102 /* Need at least two bytes: wc_mb and mb_wc */
#define MY_CS_TOOSMALL3 -103 /* Need at least three bytes: wc_mb and mb_wc */
#define MY_CS_TOOSMALL4 -104 /* Need at least 4 bytes: wc_mb and mb_wc */
#define MY_CS_TOOSMALL5 -105 /* Need at least 5 bytes: wc_mb and mb_wc */
#define MY_CS_TOOSMALL6 -106 /* Need at least 6 bytes: wc_mb and mb_wc */
static int my_utf8_uni(unsigned long * pwc, const unsigned char *s, const unsigned char *e)
{
unsigned char c;
if (s >= e)
return MY_CS_TOOSMALL;
c= s[0];
if (c < 0x80)
{
*pwc = c;
return 1;
}
else if (c < 0xc2)
return MY_CS_ILSEQ;
else if (c < 0xe0)
{
if (s+2 > e) /* We need 2 characters */
return MY_CS_TOOSMALL2;
if (!((s[1] ^ 0x80) < 0x40))
return MY_CS_ILSEQ;
*pwc = ((unsigned long) (c & 0x1f) << 6) | (unsigned long) (s[1] ^ 0x80);
return 2;
}
else if (c < 0xf0)
{
if (s+3 > e) /* We need 3 characters */
return MY_CS_TOOSMALL3;
if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 &&
(c >= 0xe1 || s[1] >= 0xa0)))
return MY_CS_ILSEQ;
*pwc = ((unsigned long) (c & 0x0f) << 12) |
((unsigned long) (s[1] ^ 0x80) << 6) |
(unsigned long) (s[2] ^ 0x80);
return 3;
}
#ifdef UNICODE_32BIT
else if (c < 0xf8 && sizeof(my_wc_t)*8 >= 32)
{
if (s+4 > e) /* We need 4 characters */
return MY_CS_TOOSMALL4;
if (!((s[1] ^ 0x80) < 0x40 &&
(s[2] ^ 0x80) < 0x40 &&
(s[3] ^ 0x80) < 0x40 &&
(c >= 0xf1 || s[1] >= 0x90)))
return MY_CS_ILSEQ;
*pwc = ((unsigned long) (c & 0x07) << 18) |
((unsigned long) (s[1] ^ 0x80) << 12) |
((unsigned long) (s[2] ^ 0x80) << 6) |
(unsigned long) (s[3] ^ 0x80);
return 4;
}
else if (c < 0xfc && sizeof(my_wc_t)*8 >= 32)
{
if (s+5 >e) /* We need 5 characters */
return MY_CS_TOOSMALL5;
if (!((s[1] ^ 0x80) < 0x40 &&
(s[2] ^ 0x80) < 0x40 &&
(s[3] ^ 0x80) < 0x40 &&
(s[4] ^ 0x80) < 0x40 &&
(c >= 0xf9 || s[1] >= 0x88)))
return MY_CS_ILSEQ;
*pwc = ((unsigned long) (c & 0x03) << 24) |
((unsigned long) (s[1] ^ 0x80) << 18) |
((unsigned long) (s[2] ^ 0x80) << 12) |
((unsigned long) (s[3] ^ 0x80) << 6) |
(unsigned long) (s[4] ^ 0x80);
return 5;
}
else if (c < 0xfe && sizeof(my_wc_t)*8 >= 32)
{
if ( s+6 >e ) /* We need 6 characters */
return MY_CS_TOOSMALL6;
if (!((s[1] ^ 0x80) < 0x40 &&
(s[2] ^ 0x80) < 0x40 &&
(s[3] ^ 0x80) < 0x40 &&
(s[4] ^ 0x80) < 0x40 &&
(s[5] ^ 0x80) < 0x40 &&
(c >= 0xfd || s[1] >= 0x84)))
return MY_CS_ILSEQ;
*pwc = ((unsigned long) (c & 0x01) << 30)
| ((unsigned long) (s[1] ^ 0x80) << 24)
| ((unsigned long) (s[2] ^ 0x80) << 18)
| ((unsigned long) (s[3] ^ 0x80) << 12)
| ((unsigned long) (s[4] ^ 0x80) << 6)
| (unsigned long) (s[5] ^ 0x80);
return 6;
}
#endif
return MY_CS_ILSEQ;
}
#define MY_CS_ILUNI 0 /* Cannot encode Unicode to charset: wc_mb */
#define MY_CS_TOOSMALLN(n) (-100-(n))
static int my_uni_utf8(unsigned long wc, unsigned char *r, unsigned char *e)
{
int count;
if (r >= e)
return MY_CS_TOOSMALL;
if (wc < 0x80)
count = 1;
else if (wc < 0x800)
count = 2;
else if (wc < 0x10000)
count = 3;
#ifdef UNICODE_32BIT
else if (wc < 0x200000)
count = 4;
else if (wc < 0x4000000)
count = 5;
else if (wc <= 0x7fffffff)
count = 6;
#endif
else return MY_CS_ILUNI;
/*
e is a character after the string r, not the last character of it.
Because of it (r+count > e), not (r+count-1 >e )
*/
if ( r+count > e )
return MY_CS_TOOSMALLN(count);
switch (count) {
/* Fall through all cases!!! */
#ifdef UNICODE_32BIT
case 6: r[5] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x4000000;
case 5: r[4] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x200000;
case 4: r[3] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x10000;
#endif
case 3: r[2] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x800;
case 2: r[1] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0xc0;
case 1: r[0] = (unsigned char) wc;
}
return count;
}
static int cppmysql_caseup_utf8(const char * src, size_t srclen, char *dst, size_t dstlen)
{
unsigned long wc;
int srcres, dstres;
const char *srcend = src + srclen;
char *dstend = dst + dstlen, *dst0 = dst;
MY_UNICASE_INFO **uni_plane= my_unicase_default;
while ((src < srcend) && (srcres= my_utf8_uni(&wc, (unsigned char *) src, (unsigned char*) srcend)) > 0) {
int plane = (wc>>8) & 0xFF;
wc = uni_plane[plane] ? uni_plane[plane][wc & 0xFF].toupper : wc;
if ((dstres = my_uni_utf8(wc, (unsigned char*) dst, (unsigned char*) dstend)) <= 0) {
break;
}
src += srcres;
dst += dstres;
}
return static_cast<int>((dst - dst0));
}
char * utf8_strup(const char * const src, size_t srclen)
{
size_t dstlen;
char * dst;
if (srclen == 0) {
srclen = strlen(src);
}
dst = new char[(dstlen = srclen * 4) + 1];
if (!dst) {
return NULL;
}
dst[cppmysql_caseup_utf8(src, srclen, dst, dstlen)] = '\0';
return dst;
}
/*
HPUX has some problems with long double : http://docs.hp.com/en/B3782-90716/ch02s02.html
strtold() has implementations that return struct long_double, 128bit one,
which contains four 32bit words.
Fix described :
--------
union {
long_double l_d;
long double ld;
} u;
// convert str to a long_double; store return val in union
//(Putting value into union enables converted value to be
// accessed as an ANSI C long double)
u.l_d = strtold( (const char *)str, (char **)NULL);
--------
reinterpret_cast doesn't work :(
*/
long double strtold(const char *nptr, char **endptr)
{
/*
* Experienced odd compilation errors on one of windows build hosts -
* cmake reported there is strold function. Since double and long double on windows
* are of the same size - we are using strtod on those platforms regardless
* to the HAVE_FUNCTION_STRTOLD value
*/
#ifdef _WIN32
return ::strtod(nptr, endptr);
#else
# ifndef HAVE_FUNCTION_STRTOLD
return ::strtod(nptr, endptr);
# else
# if defined(__hpux) && defined(_LONG_DOUBLE)
union {
long_double l_d;
long double ld;
} u;
u.l_d = ::strtold( nptr, endptr);
return u.ld;
# else
return ::strtold(nptr, endptr);
# endif
# endif
#endif
}
} /* namespace util */
} /* namespace mysql */
} /* namespace sql */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| 45.591509
| 109
| 0.71174
|
vkardon
|
5865579641bcaa78604060f2531c001750bf1e03
| 4,298
|
cpp
|
C++
|
src/frameworks/native/services/surfaceflinger/tests/unittests/SchedulerUtilsTest.cpp
|
dAck2cC2/m3e
|
475b89b59d5022a94e00b636438b25e27e4eaab2
|
[
"Apache-2.0"
] | null | null | null |
src/frameworks/native/services/surfaceflinger/tests/unittests/SchedulerUtilsTest.cpp
|
dAck2cC2/m3e
|
475b89b59d5022a94e00b636438b25e27e4eaab2
|
[
"Apache-2.0"
] | null | null | null |
src/frameworks/native/services/surfaceflinger/tests/unittests/SchedulerUtilsTest.cpp
|
dAck2cC2/m3e
|
475b89b59d5022a94e00b636438b25e27e4eaab2
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2018 The Android Open Source Project
*
* 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.
*/
#undef LOG_TAG
#define LOG_TAG "SchedulerUnittests"
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <array>
#include "Scheduler/SchedulerUtils.h"
namespace android {
namespace scheduler {
class SchedulerUtilsTest : public testing::Test {
public:
SchedulerUtilsTest() = default;
~SchedulerUtilsTest() override = default;
};
namespace {
TEST_F(SchedulerUtilsTest, calculate_mean) {
std::array<int64_t, 30> testArray{};
// Calling the function on empty array returns 0.
EXPECT_EQ(0, calculate_mean(testArray));
testArray[0] = 33;
EXPECT_EQ(1, calculate_mean(testArray));
testArray[1] = 33;
testArray[2] = 33;
EXPECT_EQ(3, calculate_mean(testArray));
testArray[3] = 42;
EXPECT_EQ(4, calculate_mean(testArray));
testArray[4] = 33;
EXPECT_EQ(5, calculate_mean(testArray));
testArray[5] = 42;
EXPECT_EQ(7, calculate_mean(testArray));
for (int i = 6; i < 30; i++) {
testArray[i] = 33;
}
EXPECT_EQ(33, calculate_mean(testArray));
}
TEST_F(SchedulerUtilsTest, calculate_median) {
std::vector<int64_t> testVector;
// Calling the function on empty vector returns 0.
EXPECT_EQ(0, calculate_median(&testVector));
testVector.push_back(33);
EXPECT_EQ(33, calculate_median(&testVector));
testVector.push_back(33);
testVector.push_back(33);
EXPECT_EQ(33, calculate_median(&testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_median(&testVector));
testVector.push_back(33);
EXPECT_EQ(33, calculate_median(&testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_median(&testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_median(&testVector));
testVector.push_back(42);
EXPECT_EQ(42, calculate_median(&testVector));
testVector.push_back(60);
EXPECT_EQ(42, calculate_median(&testVector));
testVector.push_back(60);
EXPECT_EQ(42, calculate_median(&testVector));
testVector.push_back(33);
EXPECT_EQ(42, calculate_median(&testVector));
testVector.push_back(33);
EXPECT_EQ(42, calculate_median(&testVector));
testVector.push_back(33);
EXPECT_EQ(33, calculate_median(&testVector));
}
TEST_F(SchedulerUtilsTest, calculate_mode) {
std::vector<int64_t> testVector;
// Calling the function on empty vector returns 0.
EXPECT_EQ(0, calculate_mode(testVector));
testVector.push_back(33);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(33);
testVector.push_back(33);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(33);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(42);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(60);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(60);
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(33);
// 5 occurences of 33.
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(42);
// 5 occurences of 33, 5 occurences of 42. We choose the first one.
EXPECT_EQ(33, calculate_mode(testVector));
testVector.push_back(42);
// 5 occurences of 33, 6 occurences of 42.
EXPECT_EQ(42, calculate_mode(testVector));
testVector.push_back(42);
// 5 occurences of 33, 7 occurences of 42.
EXPECT_EQ(42, calculate_mode(testVector));
}
} // namespace
} // namespace scheduler
} // namespace android
| 32.80916
| 75
| 0.713355
|
dAck2cC2
|
586619c126017122df89c63316c233ea8027efa4
| 26,060
|
hpp
|
C++
|
Motorola/MCore IDA IDP/5.0/IDA/Inc/area.hpp
|
erithion/old_junk
|
b2dcaa23320824f8b2c17571f27826869ccd0d4b
|
[
"MIT"
] | 1
|
2021-06-26T17:08:24.000Z
|
2021-06-26T17:08:24.000Z
|
Motorola/MCore IDA IDP/5.0/IDA/Inc/area.hpp
|
erithion/old_junk
|
b2dcaa23320824f8b2c17571f27826869ccd0d4b
|
[
"MIT"
] | null | null | null |
Motorola/MCore IDA IDP/5.0/IDA/Inc/area.hpp
|
erithion/old_junk
|
b2dcaa23320824f8b2c17571f27826869ccd0d4b
|
[
"MIT"
] | null | null | null |
/*
* Interactive disassembler (IDA).
* Copyright (c) 1990-97 by Ilfak Guilfanov.
* ALL RIGHTS RESERVED.
* E-mail: ig@estar.msk.su
* FIDO: 2:5020/209
*
*/
#ifndef _AREA_HPP
#define _AREA_HPP
//
// This file contains definition of "areacb_t".
// "areacb_t" is a base class used by many parts of IDA.
// "areacb_t" is a collection of address ranges in the program.
// "areacb_t" conceptually consists of separate area_t instances.
// An area is a non-empty contiguous range of addresses (specified by
// its start and end addresses, the end address is excluded from the
// range) with some characteristics. For example, the ensemble of program
// segments is represented by an "areacb_t" called "segs".
//
// Areas are stored in the Btree part of the IDA database.
// To learn more about Btrees (Balanced Trees):
// http://www.bluerwhite.org/btree/
//
#include <help.h>
#pragma pack(push, 1) // IDA uses 1 byte alignments!
//--------------------------------------------------------------------------
// Base class for an area. This class is used as a base class for
// a class with real information - see segment.hpp for example.
// The end address points beyond the area.
struct area_t
{
ea_t startEA;
ea_t endEA; // endEA excluded
area_t(void) {}
area_t(ea_t ea1, ea_t ea2) { startEA = ea1; endEA = ea2; }
int compare(const area_t &r) const { return startEA > r.startEA ? 1 : startEA < r.startEA ? -1 : 0; }
bool operator ==(const area_t &r) const { return compare(r) == 0; }
bool operator !=(const area_t &r) const { return compare(r) != 0; }
bool operator > (const area_t &r) const { return compare(r) > 0; }
bool operator < (const area_t &r) const { return compare(r) < 0; }
bool contains(ea_t ea) const { return startEA <= ea && endEA > ea; }
bool contains(const area_t &r) const { return r.startEA >= startEA && r.endEA <= endEA; }
bool empty(void) const { return startEA >= endEA; }
asize_t size(void) const { return endEA - startEA; }
void intersect(const area_t &r)
{
if ( startEA < r.startEA ) startEA = r.startEA;
if ( endEA > r.endEA ) endEA = r.endEA;
if ( endEA < startEA ) endEA = startEA;
}
};
// This class is used to store part of information about areacb_t.
class sarray; // sorted array - keeps information in Btree.
// Size of internal cache of areas.
#define AREA_CACHE_SIZE 128
// Convenience shortcut, used internally
#define ANODE netnode(areasCode)
#define ANODE2 netnode(cb->areasCode)
// Special tag used to mark long comments
#define AREA_LONG_COMMENT_TAG 0x01020304L // internal
//--------------------------------------------------------------------------
// Helper functions. Should not be called directly!
#define AREA_HELPER_DEFINITIONS(decl) \
decl void ida_export areacb_t_zero (areacb_t *);\
decl void ida_export areacb_t_terminate (areacb_t *);\
decl void ida_export areacb_t_save (areacb_t *);\
decl bool ida_export areacb_t_link (areacb_t *,const char *file, const char *name, int infosize);\
decl bool ida_export areacb_t_create (areacb_t *,const char *file,const char *name,uint infosize);\
decl void ida_export areacb_t_kill (areacb_t *);\
decl bool ida_export areacb_t_create_area (areacb_t *,area_t *info);\
decl bool ida_export areacb_t_update (areacb_t *,area_t *info);\
decl area_t *ida_export areacb_t_get_area (areacb_t *,ea_t ea);\
decl area_t *ida_export areacb_t_getn_area (areacb_t *,unsigned int n);\
decl int ida_export areacb_t_get_area_num (areacb_t *,ea_t ea);\
decl ea_t ida_export areacb_t_prepare_to_create(areacb_t *,ea_t start,ea_t end);\
decl int ida_export areacb_t_get_next_area (areacb_t *,ea_t ea);\
decl int ida_export areacb_t_get_prev_area (areacb_t *,ea_t ea);\
decl bool ida_export areacb_t_del_area (areacb_t *,ea_t ea, bool delcmt);\
decl bool ida_export areacb_t_may_start_at (areacb_t *,uint n,ea_t newstart);\
decl bool ida_export areacb_t_may_end_at (areacb_t *,uint n,ea_t newend);\
decl bool ida_export areacb_t_set_start (areacb_t *,uint n,ea_t newstart);\
decl bool ida_export areacb_t_set_end (areacb_t *,uint n,ea_t newend);\
decl bool ida_export areacb_t_resize_areas (areacb_t *,uint n,ea_t newstart);\
decl uint ida_export areacb_t_get_area_qty (areacb_t *);\
decl area_t *ida_export areacb_t_choose_area (areacb_t *,int flags, int width, char *(idaapi*getl)(areacb_t *obj,ulong n,char *buf), const char *title, int icon, int x0,int y0,int x1,int y1, const char * const *popup_menus, ea_t defea);\
decl area_t *ida_export areacb_t_choose_area2 (areacb_t *,int flags, int ncol, const int *widths, void (idaapi*getl)(areacb_t *obj,ulong n,char * const *arrptr), const char *title, int icon, int x0,int y0,int x1,int y1, const char * const *popup_menus, ea_t defea);\
decl bool ida_export areacb_t_set_area_cmt (areacb_t *,const area_t *a, const char *cmt, bool repeatable);\
decl char *ida_export areacb_t_get_area_cmt (areacb_t *,const area_t *a, bool repeatable);\
decl int ida_export areacb_t_move_areas (areacb_t *,ea_t from,ea_t to, asize_t size, int (idaapi*area_mover)(area_t *a, adiff_t delta, void *ud), void *ud);\
decl void ida_export areacb_t_make_hole (areacb_t *,ea_t ea1, ea_t ea2, bool create_tail_area);\
decl int ida_export areacb_t_for_all_areas (areacb_t *,ea_t ea1, ea_t ea2, area_visitor_t *av, void *ud);
class areacb_t;
typedef int idaapi area_visitor_t(area_t *a, void *ud);
AREA_HELPER_DEFINITIONS(idaman)
//--------------------------------------------------------------------------
// Definition of areas control block. Each type of areas has its own
// control block. Access to all areas of one type is made using this
// control block.
class areacb_t
{
AREA_HELPER_DEFINITIONS(friend)
// private definitions, I won't comment them thoroughly
uval_t areasCode; // code in the database
ushort infosize; // sizeof info for area
area_t *lastInfo; // pointer to the last area
long lastNum; // the last area number (-1: no last area)
sarray *sa; // sorted array on supvals
area_t *cache[AREA_CACHE_SIZE];
void allocate(const char *file, bool del_other); // allocate memory for lastInfo
area_t *search(ea_t EA, long *n); // search for area
area_t *readArea(ea_t EA); // read area info from base
// exit if any error (with a message)
int findCache(ea_t ea);
area_t *addCache(area_t *a); // returns allocated in cache Area
void delCache(ea_t ea);
void free_cache(void);
ea_t find_nth_start(int n);
void build_optimizer(void);
void move_area_comment(ea_t oldea, ea_t newea);
bool pack_and_write_area(area_t *a); // returns 1-ok, 0-failure
bool move_away(int cur,
ea_t ea1,
ea_t ea2,
bool create_tail_area);
public:
// Read callback: read area from the database.
// This function is called when a (possibly packed) area is read from the database.
// packed - stream of packed bytes
// ebd - ptr to the end of the stream
// a - place to put unpacked version of the area
// This callback may be NULL.
void (idaapi *read_cb)(const uchar *packed, const uchar *end, area_t *a);
// Write callback: write area to the database.
// This function is called when an area is about to be writed to the database.
// It may pack the the area to the stream of bytes.
// a - area to be written
// packbuf - buffer to hold packed version of the area
// packend - ptr to the end of packbuf
// Returns: number of bytes in the packed form
// This callback may be NULL.
size_t (idaapi *write_cb)(const area_t *a,uchar *packbuf, uchar *packend);
// Destroy callback: remove an area from the internal cache.
// This function is called when an area is freed from the cache.
// This callback may be NULL.
void (idaapi *delcache_cb)(area_t *a);
// The following three callbacks are used in open_areas_window() function.
// When the user presses Ctrl-E key the following callback is called
// to edit the selected area.
// This callback may be NULL.
int (idaapi *edit_cb)(area_t *a);
// Callback to handle "Del" keystroke in open_areas_window() function
// This callback may be NULL.
int (idaapi *kill_cb)(area_t *a);
// Callback to handle "Ins" keystroke in open_areas_window() function
// This callback may be NULL.
int (idaapi *new_cb)(void);
// Constructor. Initialized area control block. You need to link
// area control block to existing area information in Btree (link) or
// to create a new area information structure in Btree (create).
void zero(void) { areacb_t_zero(this); }
areacb_t(void) { zero(); }
// Destructor. Flushes all information to Btree, deallocates caches and
// unlinks area control block from Btree.
void terminate(void) { areacb_t_terminate(this); }
~areacb_t(void) { terminate(); }
// Flush area control block to Btree.
void save(void) { areacb_t_save(this); }
// Link area control block to Btree. Allocate cache, etc.
// Btree should contain information about the specified areas.
// After calling this function you may work with areas.
// file - name of input file being disassembled.
// Doesn't matter if useva==0.
// This parameter is used to build name of the file
// with the virtual array.
// name - name of area information in Btree.
// The name should start with "$ " (yes, including a space)
// You may use any name you like. For example, area control
// block keeping information about separation of program regions
// to different output files might be:
// "$ here is info about output file areas"
// infosize- size of a structure with actual area information
// (size of class based on class area_t)
// This function properly terminates work with the previous area control
// block in Btree if the current class was used to access information.
//
// returns:1-ok,0-failure (no such node in Btree)
bool link(const char *file, // Access to existing areas
const char *name,
int infosize)
{ return areacb_t_link(this, file, name, infosize); }
// Create area information node in Btree.
// This function usually is used when a new file is loaded into the database.
// See link() for explanations of input parameteres.
// This function properly terminates work with the previous area control
// block in Btree if the current class was used to access information.
//
// returns:1-ok
// 0-failure (Btree already contains node with the specified name)
bool create(const char *file,const char *name,uint infosize)
{ return areacb_t_create(this, file, name, infosize); }
// Delete area information in Btree.
// All information about the current type of areas is deleted.
// Deallocate cache.
void kill(void) { areacb_t_kill(this); }
// Create an area.
// The new area should not overlap with existing ones.
// info - structure containing information about a new area
// startEA and endEA specify address range.
// startEA should be lower than endEA
// returns 1-ok,0-failure, area overlaps with another area or bad address range.
bool create_area(area_t *info) // Create new area
{ return areacb_t_create_area(this, info); }
// Update information about area in Btree.
// This function can't change startEA and endEA fields.
// Its only purpose is to update additional characteristics of the area.
bool update(area_t *info) // Update info about area_t.
{ return areacb_t_update(this, info); }
// Get pointer to area structure by address
// ea - any address in the area
// returns NULL: no area occupies the specified address
// otherwise returns pointer to area structure.
area_t *get_area(ea_t ea) // Get area by EA
{ return areacb_t_get_area(this, ea); }
// Get pointer to area structure by its number
// n - number of area (0..get_area_qty()-1)
// returns NULL: the specified area doesn't exist.
// otherwise returns pointer to area structure.
area_t *getn_area(unsigned int n) // Get n-th area (0..n)
{ return areacb_t_getn_area(this, n); }
// Get number of area by address
// ea - any address in the area
// returns -1: no area occupies the specified address
// otherwise returns number of the specified area (0..get_area_qty()-1)
int get_area_num(ea_t ea) // Get area number. -1 - no such area
{ return areacb_t_get_area_num(this, ea); }
// Prepare to create a new area
// This function checks whether the new area overlap with an existing one
// and trims an existing area to make enough address range for the creation
// of the new area. If the trimming of the existing area doesn't make enough
// room for the new area, the existing area is simply deleted.
// start - start address of the new area
// end - end address of the new area
// returns: an adjusted end address for the new area. The end address may
// require some adjustment if another (next) area exists and occupies
// some addresses from (start..end) range. In this case we don't
// delete the existing area but adjust end address of the new area.
ea_t prepare_to_create(ea_t start,ea_t end)// Prepare to create an area (sEA,eEA)
// - trim previous area
// - return max allowed end of area
{ return areacb_t_prepare_to_create(this, start, end); }
// Get number of the next area.
// This function returns number of the next (higher in the addressing space)
// area.
// ea - any address in the program
// returns -1: no (more) areas
// otherwise returns number in the range (0..get_area_qty()-1)
int get_next_area(ea_t ea) // Return next area for EA
// -1 - no (more) areas
{ return areacb_t_get_next_area(this, ea); }
// Get number of the previous area.
// This function returns number of the previous (lower in the addressing space)
// area.
// ea - any address in the program
// returns -1: no (more) areas
// otherwise returns number in the range (0..get_area_qty()-1)
int get_prev_area(ea_t ea) // Returns prev area for EA
// Returns -1 if not found
{ return areacb_t_get_prev_area(this, ea); }
// Delete an area.
// ea - any address in the area
// delcmt - delete area comments
// you may choose not to delete comments if you want to
// create a new area with the same start address immediately.
// In this case the new area will inherit old area comments.
// returns 1-ok,0-failure (no such area)
bool del_area(ea_t ea, bool delcmt=true) // Delete area
{ return areacb_t_del_area(this, ea, delcmt); }
// Check if the specified area may start at the specified address.
// This function checks whether the specified area can be changed so
// that its start address would be 'newstart'.
// n - number of area to check
// newstart - new start address for the area
// returns: 1-yes, it can
// 0-no
// the specified area doesn't exist
// new start address is higher or equal to end address
// the area would overlap with another area
bool may_start_at(uint n,ea_t newstart) // can the area have 'newstart'
{ return areacb_t_may_start_at(this, n, newstart); }
// Check if the specified area may end at the specified address.
// This function checks whether the specified area can be changed so
// that its end address would be 'newend'.
// n - number of area to check
// newend - new end address for the area
// returns: 1-yes, it can
// 0-no
// the specified area doesn't exist
// new end address is lower or equal to start address
// the area would overlap with another area
bool may_end_at(uint n,ea_t newend) // can the area have 'newend'
{ return areacb_t_may_end_at(this, n, newend); }
// Change start address of the area
// n - number of area to change
// newstart - new start address for the area
// This function doesn't modify other areas.
// returns: 1-ok, area is changed
// 0-failure
// the specified area doesn't exist
// new start address is higher or equal to end address
// the area would overlap with another area
bool set_start(uint n, ea_t newstart)
{ return areacb_t_set_start(this, n, newstart); }
// Change end address of the area
// n - number of area to change
// newend - new end address for the area
// This function doesn't modify other areas.
// returns: 1-ok, area is changed
// 0-failure
// the specified area doesn't exist
// new end address is lower or equal to start address
// the area would overlap with another area
bool set_end(uint n, ea_t newend)
{ return areacb_t_set_end(this, n, newend); }
// Make a hole at the specified address by deleting or modifying
// existing areas
// ea1, ea2 - range to clear
// create_tail_area - in the case if there is a big area overlapping
// the specified range, should it be divided in two areas?
// if 'false', then it will be truncated and the tail
// will be left without any covering area
void make_hole(ea_t ea1, ea_t ea2, bool create_tail_area)
{ areacb_t_make_hole(this, ea1, ea2, create_tail_area); }
// Resize adjacent areas simultaneously
// n - number of area to change
// The adjacent (previous) area will be trimmed or expanded
// if it exists and two areas are contiguous.
// Otherwise this function behaves like set_start() function.
// returns: 1-ok,0-failure
bool resize_areas(uint n,ea_t newstart) // Resize adjacent areas
{ return areacb_t_resize_areas(this, n, newstart); }
// Get number of areas.
// returns: number of areas ( >= 0 )
uint get_area_qty(void) // Get number of areas
{ return areacb_t_get_area_qty(this); }
// Let the user choose an area. (1-column chooser)
// This function displays a window with a list of areas
// and allows the user to choose an area from the list.
// flags - see kernwin.hpp for choose() flags description and callbacks usage
// width - width of the window
// getl - callback function to get text representation of an area
// obj - pointer to area control block
// n - (number of area + 1). if n==0 then getl() should
// return text of a header line.
// buf - buffer for the text representation
// getl() should return pointer to text representation string
// (not nesessarily the same pointer as 'buf')
// title - title of the window.
// icon - number of icon to display
// defea - address which points to the default area. The cursor will be
// position to this area.
// (x0,y0,x1,y1) - window position on the screen
// -1 values specify default window position
// (txt:upper left corner of the screen)
// (gui:centered on the foreground window)
// popup_menus - default is insert, delete, edit, refresh
// returns: NULL - the user pressed Esc.
// otherwise - pointer to the selected area.
area_t *choose_area(int flags,
int width,
char *(idaapi*getl)(areacb_t *obj,ulong n,char *buf),
const char *title,
int icon,
int x0=-1,int y0=-1,int x1=-1,int y1=-1,
const char * const *popup_menus=NULL,
ea_t defea=BADADDR)
{
return areacb_t_choose_area(this, flags, width, getl, title, icon,
x0, y0, x1, y1, popup_menus, defea);
}
// Let the user choose an area. (n-column chooser)
// This function displays a window with a list of areas
// and allows the user to choose an area from the list.
// flags - see kernwin.hpp for choose() flags description and callbacks usage
// ncol - number of columns
// widths- widths of each column in characters (may be NULL)
// getl - callback function to get text representation of an area
// obj - pointer to area control block
// n - (number of area + 1). if n==0 then getl() should
// return text of a header line.
// arrptr - array of buffers for the text representation
// title - title of the window.
// icon - number of icon to display
// defea - address which points to the default area. The cursor will be
// position to this area.
// (x0,y0,x1,y1) - window position on the screen
// -1 values specify default window position
// (txt:upper left corner of the screen)
// (gui:centered on the foreground window)
// popup_menus - default is insert, delete, edit, refresh
// returns: NULL - the user cancelled the selection
// otherwise - pointer to the selected area.
area_t *choose_area2(int flags,
int ncol,
const int *widths,
void (idaapi*getl)(areacb_t *obj,ulong n,char * const *arrptr),
const char *title,
int icon,
int x0=-1,int y0=-1,int x1=-1,int y1=-1,
const char * const *popup_menus=NULL,
ea_t defea=BADADDR)
{
return areacb_t_choose_area2(this, flags, ncol, widths, getl, title, icon,
x0, y0, x1, y1, popup_menus, defea);
}
// Find previous gap in areas.
// This function finds a gap between areas. Only enabled addresses
// (see bytes.hpp for explanations on addressing) are used in the search.
// ea - any linear address
// returns: BADADDR - no previous gap is found
// otherwise returns maximal address in the previous gap
ea_t find_prev_gap(ea_t ea); // find prev/next gaps in the enabled addresses
// Find next gap in areas.
// This function finds a gap between areas. Only enabled addresses
// (see bytes.hpp for explanations on addressing) are used in the search.
// ea - any linear address
// returns: BADADDR - no next gap is found
// otherwise returns start address of the next gap
ea_t find_next_gap(ea_t ea); // if not found, returns BADADDR
// Set area comment.
// This function sets area comment.
// a - pointer to area structure (may be NULL)
// repratable - 0: set regular comment
// 1: set repeatable comment
bool set_area_cmt(const area_t *a, const char *cmt, bool repeatable)
{ return areacb_t_set_area_cmt(this, a, cmt, repeatable); }
// Delete area comment.
// Each area may have its comment (a function may have a comment, for example)
// This function deletes such a comment
// a - pointer to area structure (may be NULL)
// repratable - 0: delete regular comment
// 1: delete repeatable comment
void del_area_cmt(const area_t *a, bool repeatable)
{ set_area_cmt(a, "", repeatable); }
// Get area comment.
// This function gets area comment.
// a - pointer to area structure (may be NULL)
// repratable - 0: get regular comment
// 1: get repeatable comment
// The caller must qfree() the result.
char *get_area_cmt(const area_t *a, bool repeatable)
{ return areacb_t_get_area_cmt(this, a, repeatable); }
// Move area information to the specified addresses
// Returns: 0 if ok, otherwise the code returned by area_mover
int move_areas(ea_t from,
ea_t to,
asize_t size,
int (idaapi *area_mover)(area_t *a, adiff_t delta, void *ud)=NULL,
void *ud=NULL)
{ return areacb_t_move_areas(this, from, to, size, area_mover, ud); }
// Call a function for all areas in the specified range
// Stop the enumeration if the function returns non-zero
// Returns: 0 if all areas were visited, otherwise the code returned
// by the callback
int for_all_areas(ea_t ea1, ea_t ea2, area_visitor_t *av, void *ud)
{ return areacb_t_for_all_areas(this, ea1, ea2, av, ud); }
};
#pragma pack(pop)
#endif // _AREA_HPP
| 43.0033
| 271
| 0.622064
|
erithion
|
586bb863a9de73e152602383fa33a2ad3c592a0f
| 1,173
|
hpp
|
C++
|
Workspace/src/MediaManager.hpp
|
Llemmert/UntitledCatGame
|
4618cef62d329a90a7387a63cdf87b5b9762097b
|
[
"MIT"
] | null | null | null |
Workspace/src/MediaManager.hpp
|
Llemmert/UntitledCatGame
|
4618cef62d329a90a7387a63cdf87b5b9762097b
|
[
"MIT"
] | null | null | null |
Workspace/src/MediaManager.hpp
|
Llemmert/UntitledCatGame
|
4618cef62d329a90a7387a63cdf87b5b9762097b
|
[
"MIT"
] | null | null | null |
#pragma once
using namespace std;
class MediaManager
{
map<string, SDL_Texture *> images;
SDL_Renderer *ren;
map<string, Mix_Chunk *> samples;
public:
MediaManager(SDL_Renderer *newRen)
{
ren = newRen;
}
Mix_Chunk *readWav(string filename)
{
if (samples.find(filename) == samples.end())
{
Mix_Chunk *sample;
sample = Mix_LoadWAV(filename.c_str());
if (!sample)
throw Exception(/*"Mix_LoadWav: " +*/ Mix_GetError());
samples[filename] = sample;
}
return (samples[filename]);
}
SDL_Texture *read(string filename)
{
SDL_Texture *bitmapTex;
if (images.find(filename) == images.end())
{
cout << "Read " << filename << endl;
SDL_Surface *ob;
ob = SDL_LoadBMP(filename.c_str());
SDL_SetColorKey(ob, SDL_TRUE, SDL_MapRGB(ob->format, 164, 117, 160));
if (ob == NULL)
throw Exception("Could not load " + filename);
bitmapTex = SDL_CreateTextureFromSurface(ren, ob);
if (bitmapTex == NULL)
throw Exception("Could not create texture");
SDL_FreeSurface(ob);
images[filename] = bitmapTex;
}
return images[filename];
}
~MediaManager()
{
for (auto i : images)
SDL_DestroyTexture(i.second);
}
};
| 22.132075
| 72
| 0.666667
|
Llemmert
|
586c63f7330e0398aa7063848f5ce84fe7f033a4
| 6,000
|
cpp
|
C++
|
utilities/pandaSetSystemTime.cpp
|
eswierk/libpanda
|
6540181edcf7df3e4ec1ee530456fff741176257
|
[
"MIT"
] | 11
|
2020-12-02T00:12:25.000Z
|
2022-03-31T07:38:32.000Z
|
utilities/pandaSetSystemTime.cpp
|
eswierk/libpanda
|
6540181edcf7df3e4ec1ee530456fff741176257
|
[
"MIT"
] | 29
|
2021-07-15T23:03:38.000Z
|
2021-10-08T22:02:29.000Z
|
utilities/pandaSetSystemTime.cpp
|
eswierk/libpanda
|
6540181edcf7df3e4ec1ee530456fff741176257
|
[
"MIT"
] | 7
|
2021-07-15T21:09:23.000Z
|
2022-02-04T04:06:25.000Z
|
/*
Author: Matt Bunting
Copyright (c) 2020 Arizona Board of Regents
All rights reserved.
Permission is hereby granted, without written agreement and without
license or royalty fees, to use, copy, modify, and distribute this
software and its documentation for any purpose, provided that the
above copyright notice and the following two paragraphs appear in
all copies of this software.
IN NO EVENT SHALL THE ARIZONA BOARD OF REGENTS BE LIABLE TO ANY PARTY
FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
THE ARIZONA BOARD OF REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER
IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION
TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#include <iostream>
#include <signal.h>
#include <unistd.h> // usleep()
#include <cmath> // fabs()
#include <time.h>
#include <iomanip>
#include <ctime>
#include "panda.h"
// A ctrl-c handler for safe panda handler destruction
static volatile bool keepRunning = true;
void killPanda(int killSignal) {
std::cerr << std::endl << "Caught SIGINT: Terminating..." << std::endl;
keepRunning = false;
}
//// For debugging time
//std::string timevalToPrettyString(struct timeval& time) {
// char timeString[64];
// time_t time_tPrint = time.tv_sec;
// struct tm* tmPrint = localtime(&time_tPrint);
// int uSecondIndex = strftime(timeString, sizeof(timeString), "%d/%m/%Y %H:%M:%S", tmPrint);
// snprintf(timeString+uSecondIndex, sizeof(timeString)-uSecondIndex, ".%06d", (int)time.tv_usec);
// return timeString;
//}
//
//class SetSystemTimeObserver : public Panda::GpsListener {
//public:
// SetSystemTimeObserver(double minimumAcceptableOffsetInSeconds) {
// timeHasBeenSet = false;
// epsilon = minimumAcceptableOffsetInSeconds;
// }
// // Check this before using system time
// bool hasTimeBeenSet() {
// return timeHasBeenSet;
// }
//private:
// bool timeHasBeenSet;
// double epsilon;
//
// void newDataNotification( Panda::GpsData* gpsData ) {
// if (timeHasBeenSet || (gpsData->info.status != 'A')) {
// return;
// }
//
// // Current system time
// struct timeval sysTime;
// struct timezone sysZone;
// //gettimeofday(&sysTime, &sysZone);
// // per web, need NULL or behavior undefined for tz
// gettimeofday(&sysTime, NULL);
//
// // testing different time method
// std::time_t t = std::time(nullptr);
// std::cout << "UTC: " << std::put_time(std::gmtime(&t), "%c %Z") << '\n';
// std::cout << "local: " << std::put_time(std::localtime(&t), "%c %Z") << '\n';
// std::time_t gmt = mktime(std::gmtime(&t));
// std::time_t localt = mktime(std::localtime(&t));
// // offset in seconds: will use this rather than taking the
// // tz value from gettimeofday which may not be consistent or supported
// // across different distros or with different packages installed
// time_t offset = gmt-localt;
//
// // Current GPS local time based on GMT offset
// time_t gpsTime_t = mktime(&gpsData->time);
// struct timeval gpsTime;
//
// std::cout << " sysTime=" << sysTime.tv_sec << std::endl;
// std::cout << " sysZone=" << sysZone.tz_minuteswest << std::endl;
//
// // fixing CH-61 by removing undefined behavior of tz (timezone)
// // the offset value is calculated by the minute subtraction from gmt
// gpsTime.tv_sec = gpsTime_t - offset;
// //gpsTime.tv_sec = gpsTime_t - sysZone.tz_minuteswest*60;
// gpsTime.tv_usec = (gpsData->timeMilliseconds)*1000;
//
// // This seems convoluted, but I think it will avoid floating point error math
// int differenceInSeconds = gpsTime.tv_sec - sysTime.tv_sec;
// int differenceInMicroseconds = gpsTime.tv_usec - sysTime.tv_usec;
// double totalDifference = (double)differenceInSeconds + ((double)differenceInMicroseconds)/1000000.0;
//
// std::cout << std::endl << "SetSystemTimeObserver.newDataNotification()" << std::endl;
// std::cout << " - GPS Time:" << timevalToPrettyString(gpsTime) << std::endl;
// std::cout << " - Sys Time:" << timevalToPrettyString(sysTime) << std::endl;
// std::cout << " - Time offset of " << totalDifference << " seconds, epsilon:" << epsilon << std::endl;
//
// if (fabs(totalDifference) > epsilon) {
// if (settimeofday(&gpsTime, NULL)) {
// std::cerr << "ERROR: Unable to set system time from GPS!" << std::endl;
// } else {
// std::cout << " |-- System time set to GPS time!" << std::endl;
// }
// } else {
// std::cout << " |-- No need to change system time" << std::endl;
// }
//
// timeHasBeenSet = true;
// }
//};
int main(int argc, char **argv) {
std::cout << "Starting " << argv[0] << std::endl;
//Set up graceful exit
signal(SIGINT, killPanda);
double epsilon = 0.2; // If system time is off from GPS time by this amount, update time.
Panda::SetSystemTimeObserver mSetSystemTimeObserver(epsilon);
// Initialize Usb, this requires a conencted Panda
Panda::Handler pandaHandler;
pandaHandler.addGpsObserver(mSetSystemTimeObserver);
//pandaHandler.getGps().saveToFile("nmeaDump.txt");
pandaHandler.initialize(); // starts USB and GPS
std::cout << "Waiting to acquire satellites..." << std::endl;
std::cout << " - Each \'.\' represents 100 NMEA messages received:" << std::endl;
int lastNmeaMessageCount = 0;
while (keepRunning == true) {
if (pandaHandler.getGps().getData().successfulParseCount-lastNmeaMessageCount > 100) {
std::cerr << ".";
lastNmeaMessageCount = pandaHandler.getGps().getData().successfulParseCount;
}
usleep(10000);
if (mSetSystemTimeObserver.hasTimeBeenSet()) { // Only run until time has been checked/
keepRunning = false;
}
}
std::cout << std::endl;
pandaHandler.stop();
std::cout << "\rDone." << std::endl;
return 0;
}
| 36.363636
| 105
| 0.692833
|
eswierk
|
586f2306c7c0840df4cdd4b2f66351d3924bb447
| 2,410
|
cpp
|
C++
|
source/dataset.cpp
|
Santili/cppsqlx
|
32ba861d737cb16c2e337209c1c54e10fa575d3c
|
[
"MIT"
] | null | null | null |
source/dataset.cpp
|
Santili/cppsqlx
|
32ba861d737cb16c2e337209c1c54e10fa575d3c
|
[
"MIT"
] | null | null | null |
source/dataset.cpp
|
Santili/cppsqlx
|
32ba861d737cb16c2e337209c1c54e10fa575d3c
|
[
"MIT"
] | null | null | null |
/*
* Copyright (c) 2014-2016, Santili Y-HRAH KRONG
* 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.
*
* 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 <dataset.hpp>
#include <table.hpp>
#include <logger.hpp>
namespace cppsqlx
{
Dataset::Dataset(std::string name):name_(name),alias_(name)
{
LOG_DEBUG("Dataset::Dataset");
}
Dataset::~Dataset()
{
LOG_DEBUG("Dataset::~Dataset");
}
std::string Dataset::name()
{
return name_;
}
std::string Dataset::alias()
{
return alias_;
}
std::string Dataset::schema()
{
return schema_;
}
std::string Dataset::catalog()
{
return catalog_;
}
DBPROVIDER Dataset::provider()
{
return provider_;
}
void Dataset::setSchema(std::string schema)
{
schema_ = schema;
}
void Dataset::setProvider(DBPROVIDER provider)
{
provider_ = provider;
}
void Dataset::setCatalog(std::string catalog)
{
catalog_ = catalog;
}
Dataset& Dataset::as(std::string alias)
{
alias_ = alias;
return *this;
}
Column Dataset::at(int index)
{
return columns_.at(index);
}
int Dataset::rowSize()
{
return columns_.size();
}
std::string Dataset::joinidentifier()
{
return name_;
}
};/*namespace cppsqlx*/
| 21.517857
| 83
| 0.726971
|
Santili
|
586f36e592acdf9b84d55f1480090bab1221332c
| 2,186
|
cc
|
C++
|
leetcode/math_pow.cc
|
prashrock/C-
|
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
|
[
"MIT"
] | 1
|
2016-12-05T10:42:46.000Z
|
2016-12-05T10:42:46.000Z
|
leetcode/math_pow.cc
|
prashrock/CPP
|
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
|
[
"MIT"
] | null | null | null |
leetcode/math_pow.cc
|
prashrock/CPP
|
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
|
[
"MIT"
] | null | null | null |
//g++-5 -Wall --std=c++11 -g -o math_pow math_pow.cc
/**
* @file Integer Pow(x,n)
* @brief Implement Pow(x,n)
*/
// https://leetcode.com/problems/powx-n/
#include <iostream> /* std::cout */
#include <algorithm> /* std::max */
#include <cmath> /* std::round */
using namespace std;
/** Implement int pow(x, n) */
/* If n is -ve and x is an integer, we can avoid floating pt *
* ops by using a long to store the ans till the end */
double myPow(double x, int n) {
double ans = 1;
/* Handle special cases first (x^0 and overflow of -n to n) */
if(n == 0) return ans;
if(n == std::numeric_limits<int>::min()) {
if(x == 1 || x == -1) return ans;
else return 0;
}
/* If n is negative, make it +ve and instead change x to 1/x */
if(n < 0) { x = 1/x; n = -n; }
for(; n > 0; n >>= 1) {
if(n & 1) ans *= x;
x *= x;
}
return ans;
}
struct test_vector {
double x;
int n;
double exp;
};
const struct test_vector test[11] = {
{ 8.88023, 7, 4354812.89022},
{ 8.84372, -5, 0.00002},
{34.00515, 3, 39321.86291},
{34.00515, -3, 0.00003},
{ 0.00001, 2147483647, 0.00000},
{ 1.00000, 2147483647, 1.00000},
{ 2.00000, -2147483648, 0.00000},
{ 1.00000, -2147483648, 1.00000},
{-1.00000, -2147483648, 1.00000},
{ 1.00005, -2147483648, 0.00000},
{12351235, -2147483648, 0.00000},
};
int main()
{
for(auto tst : test) {
auto ans = pow(tst.x, tst.n);
ans = ((double)std::round(ans * 10000.0)) / 10000.0;
auto exp = ((double)std::round(tst.exp * 10000.0)) / 10000.0;
if(ans != exp) {
cout << "Error:pow failed. Exp "
<< exp << " Got " << ans << " for "
<< tst.x << "^" << tst.n << endl;
return -1;
}
}
cout << "Info: All manual testcases passed" << endl;
return 0;
}
| 30.788732
| 69
| 0.451967
|
prashrock
|
587037e5cf7e3e4aabaa681eea335d81562b1fd3
| 2,225
|
hpp
|
C++
|
src/zipf_distribution.hpp
|
manuhalo/PLACeS
|
1574a34a2a98468e72d072cc9d1f2b32fcee38f2
|
[
"Apache-2.0"
] | null | null | null |
src/zipf_distribution.hpp
|
manuhalo/PLACeS
|
1574a34a2a98468e72d072cc9d1f2b32fcee38f2
|
[
"Apache-2.0"
] | 1
|
2015-04-24T10:10:51.000Z
|
2015-06-18T08:32:16.000Z
|
src/zipf_distribution.hpp
|
manuhalo/PLACeS
|
1574a34a2a98468e72d072cc9d1f2b32fcee38f2
|
[
"Apache-2.0"
] | null | null | null |
/* boost-supplement random/discrete_distribution.hpp header file
*
* Copyright (C) 2008 Kenta Murata.
* Distributed under the Boost Software License, Version 1.0. (See
* accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* $Id: discrete_distribution.hpp 5906 2008-01-30 15:09:35Z mrkn $
*
*/
#ifndef BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP
#define BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP 1
#include <boost/random/discrete_distribution.hpp>
#include <cmath>
namespace boost { namespace random {
// Zipf-Mandelbrot distribution
//
// Let N, q, and s be num, shift, and exp, respectively. The
// probability distribution is P(k) = (k + q)^{-s} / H_{N,q,s} where k
// = 1, 2, ..., N, and H_{N,q,s} is generalized harmonic number, that
// is H_{N,q,s} = \sum_{i=1}^N (i+q)^{-s}.
//
// http://en.wikipedia.org/wiki/Zipf-Mandelbrot_law.
template<class IntType = long, class RealType = double>
class zipf_distribution
{
public:
typedef RealType input_type;
typedef IntType result_type;
#if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300)
BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer);
BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer);
#endif
private:
result_type num_;
input_type shift_;
input_type exp_;
typedef discrete_distribution<IntType, RealType> dist_type;
dist_type dist_;
dist_type make_dist(result_type num, input_type shift, input_type exp)
{
std::vector<input_type> buffer(num);
for (result_type k = 1; k <= num; ++k)
buffer[k-1] = std::pow(k + shift, -exp);
return dist_type(buffer.begin(), buffer.end());
}
public:
zipf_distribution(result_type num, input_type shift, input_type exp)
: num_(num), shift_(shift), exp_(exp),
dist_(make_dist(num, shift, exp))
{}
result_type num() const { return num_; }
input_type shift() const { return shift_; }
input_type exponent() const { return exp_; }
template<class Engine>
result_type operator()(Engine& eng) { return dist_(eng); }
RealType pmf(IntType i) { return dist_.probabilities().at(i); }
};
} }
#endif // BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP
| 28.525641
| 100
| 0.710112
|
manuhalo
|
58734ce83a7a5f6a577f18835866dc8f4ec79183
| 1,816
|
hpp
|
C++
|
Mongoose/Include/Mongoose_QPDelta.hpp
|
puckbee/suitesparse
|
306d7f11792aca524571f4ae142bcd8b7e38c362
|
[
"Apache-2.0"
] | 29
|
2019-11-27T00:43:07.000Z
|
2020-02-25T14:35:54.000Z
|
Mongoose/Include/Mongoose_QPDelta.hpp
|
puckbee/suitesparse
|
306d7f11792aca524571f4ae142bcd8b7e38c362
|
[
"Apache-2.0"
] | null | null | null |
Mongoose/Include/Mongoose_QPDelta.hpp
|
puckbee/suitesparse
|
306d7f11792aca524571f4ae142bcd8b7e38c362
|
[
"Apache-2.0"
] | 4
|
2019-11-27T05:19:03.000Z
|
2020-03-23T22:49:53.000Z
|
/* ========================================================================== */
/* === Include/Mongoose_QPDelta.hpp ========================================= */
/* ========================================================================== */
/* -----------------------------------------------------------------------------
* Mongoose Graph Partitioning Library Copyright (C) 2017-2018,
* Scott P. Kolodziej, Nuri S. Yeralan, Timothy A. Davis, William W. Hager
* Mongoose is licensed under Version 3 of the GNU General Public License.
* Mongoose is also available under other licenses; contact authors for details.
* -------------------------------------------------------------------------- */
#pragma once
#include "Mongoose_Internal.hpp"
namespace Mongoose
{
class QPDelta
{
private:
static const Int WXSIZE = 3;
static const Int WISIZE = 2;
public:
double *x; /* current estimate of solution */
// FreeSet:
Int nFreeSet; /* number of i such that 0 < x_i < 1 */
Int *FreeSet_status; /* ix_i = +1,-1, or 0 if x_i = 1,0, or 0 < x_i < 1 */
Int *FreeSet_list; /* list for free indices */
//---
double *gradient; /* gradient at current x */
double *D; /* max value along the column. */
double lo; // lo <= a'*x <= hi must always hold
double hi;
// workspace
Int *wi[WISIZE];
double *wx[WXSIZE];
Int its;
double err;
Int ib; // ib = 0 means lo < b < hi
// ib = +1 means b == hi
// ib = -1 means b == lo
double b; // b = a'*x
double lambda;
static QPDelta *Create(Int numVars);
~QPDelta();
#ifndef NDEBUG
double check_cost;
#endif
};
} // end namespace Mongoose
| 29.290323
| 80
| 0.449339
|
puckbee
|
5879ad76ce941dd75a2af157749a79d1183d9a36
| 3,189
|
cpp
|
C++
|
MMOCoreORB/src/server/zone/objects/tangible/terminal/components/UplinkTerminalMenuComponent.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 18
|
2017-02-09T15:36:05.000Z
|
2021-12-21T04:22:15.000Z
|
MMOCoreORB/src/server/zone/objects/tangible/terminal/components/UplinkTerminalMenuComponent.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 61
|
2016-12-30T21:51:10.000Z
|
2021-12-10T20:25:56.000Z
|
MMOCoreORB/src/server/zone/objects/tangible/terminal/components/UplinkTerminalMenuComponent.cpp
|
V-Fib/FlurryClone
|
40e0ca7245ec31b3815eb6459329fd9e70f88936
|
[
"Zlib",
"OpenSSL"
] | 71
|
2017-01-01T05:34:38.000Z
|
2022-03-29T01:04:00.000Z
|
/*
* UplinkTerminalMenuComponent.cpp
*
* Created on: Oct 31, 2012
* Author: root
*/
#include "UplinkTerminalMenuComponent.h"
#include "server/zone/Zone.h"
#include "server/zone/packets/object/ObjectMenuResponse.h"
#include "server/zone/objects/scene/SceneObject.h"
#include "server/zone/objects/creature/CreatureObject.h"
#include "server/zone/objects/building/BuildingObject.h"
#include "server/zone/managers/gcw/GCWManager.h"
#include "server/zone/objects/tangible/TangibleObject.h"
void UplinkTerminalMenuComponent::fillObjectMenuResponse(SceneObject* sceneObject, ObjectMenuResponse* menuResponse, CreatureObject* player) const {
ManagedReference<BuildingObject*> building = sceneObject->getParentRecursively(SceneObjectType::FACTIONBUILDING).castTo<BuildingObject*>();
if (building == nullptr || player->isDead() || player->isIncapacitated())
return;
Zone* zone = building->getZone();
if (zone == nullptr)
return;
GCWManager* gcwMan = zone->getGCWManager();
if (gcwMan == nullptr)
return;
if (!gcwMan->isBaseVulnerable(building))
return;
menuResponse->addRadialMenuItem(20, 3, "@hq:mnu_jam");
}
int UplinkTerminalMenuComponent::handleObjectMenuSelect(SceneObject* sceneObject, CreatureObject* player, byte selectedID) const {
if (sceneObject == nullptr || !sceneObject->isTangibleObject() || player == nullptr || player->isDead() || player->isIncapacitated() || selectedID != 20)
return 0;
ManagedReference<BuildingObject*> building = sceneObject->getParentRecursively(SceneObjectType::FACTIONBUILDING).castTo<BuildingObject*>();
ManagedReference<TangibleObject*> uplinkTerminal = cast<TangibleObject*>(sceneObject);
if (building == nullptr)
return 1;
Zone* zone = sceneObject->getZone();
if (zone == nullptr)
return 1;
ManagedReference<GCWManager*> gcwMan = zone->getGCWManager();
if (gcwMan == nullptr)
return 1;
if (!gcwMan->isBaseVulnerable(building))
return 1;
// Most of the string rows for these errors did not exist in 14.1, pulled string text from a different patch
if (!gcwMan->areOpposingFactions(player->getFaction(), building->getFaction())) {
player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_tamper"); // You are not an enemy of this structure. Why would you want to tamper?
return 1;
} else if (gcwMan->isUplinkJammed(building)) {
player->sendSystemMessage("It's no use! The uplink has been jammed.");
return 1;
} else if (player->isInCombat()) {
player->sendSystemMessage("You cannot jam this uplink while you are in combat!");
return 1;
} else if (uplinkTerminal->getParentID() != player->getParentID()) {
player->sendSystemMessage("You cannot jam the uplink if you are not even in the same room!");
return 1;
} else if (uplinkTerminal->getDistanceTo(player) > 15) {
player->sendSystemMessage("You are too far away from the uplink to continue jamming!");
return 1;
} else if (!player->hasSkill("combat_bountyhunter_investigation_02")) {
player->sendSystemMessage("Only a bounty hunter with intermediate surveillance skill could expect to jam this uplink!");
return 1;
}
gcwMan->sendJamUplinkMenu(player, building, uplinkTerminal);
return 0;
}
| 35.433333
| 154
| 0.748511
|
V-Fib
|
587f3a3518e699cd57af64cd502cb880151e1ec4
| 2,884
|
hpp
|
C++
|
Source/Ilum/Graphics/GraphicsContext.hpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | 11
|
2022-01-09T05:32:56.000Z
|
2022-03-28T06:35:16.000Z
|
Source/Ilum/Graphics/GraphicsContext.hpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | null | null | null |
Source/Ilum/Graphics/GraphicsContext.hpp
|
Chaf-Libraries/Ilum
|
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
|
[
"MIT"
] | 1
|
2021-11-20T15:39:03.000Z
|
2021-11-20T15:39:03.000Z
|
#pragma once
#include "Engine/Subsystem.hpp"
#include "Eventing/Event.hpp"
#include "Graphics/Synchronization/QueueSystem.hpp"
#include "Graphics/Command/CommandPool.hpp"
#include "Timing/Stopwatch.hpp"
#include "Utils/PCH.hpp"
namespace Ilum
{
class Instance;
class PhysicalDevice;
class Surface;
class LogicalDevice;
class Swapchain;
class CommandBuffer;
class DescriptorCache;
class ShaderCache;
class ImGuiContext;
class Profiler;
class RenderFrame;
class GraphicsContext : public TSubsystem<GraphicsContext>
{
public:
GraphicsContext(Context *context);
~GraphicsContext() = default;
const Instance &getInstance() const;
const PhysicalDevice &getPhysicalDevice() const;
const Surface &getSurface() const;
const LogicalDevice &getLogicalDevice() const;
const Swapchain &getSwapchain() const;
DescriptorCache &getDescriptorCache();
ShaderCache &getShaderCache();
QueueSystem &getQueueSystem();
Profiler &getProfiler();
const VkPipelineCache &getPipelineCache() const;
CommandPool &getCommandPool(QueueUsage usage = QueueUsage::Graphics, CommandPool::ResetMode reset_mode = CommandPool::ResetMode::ResetPool);
uint32_t getFrameIndex() const;
const VkSemaphore &getPresentCompleteSemaphore() const;
const VkSemaphore &getRenderCompleteSemaphore() const;
void submitCommandBuffer(VkCommandBuffer cmd_buffer);
RenderFrame &getFrame();
uint64_t getFrameCount() const;
bool isVsync() const;
void setVsync(bool vsync);
public:
virtual bool onInitialize() override;
virtual void onPreTick() override;
virtual void onTick(float delta_time) override;
virtual void onPostTick() override;
virtual void onShutdown() override;
public:
void createSwapchain(bool vsync = false);
private:
void newFrame();
void submitFrame();
private:
scope<Instance> m_instance = nullptr;
scope<PhysicalDevice> m_physical_device = nullptr;
scope<Surface> m_surface = nullptr;
scope<LogicalDevice> m_logical_device = nullptr;
scope<Swapchain> m_swapchain = nullptr;
scope<DescriptorCache> m_descriptor_cache = nullptr;
scope<ShaderCache> m_shader_cache = nullptr;
scope<Profiler> m_profiler = nullptr;
// Command pool per thread
std::vector<scope<RenderFrame>> m_render_frames;
std::vector<VkCommandBuffer> m_submit_cmd_buffers;
// Present resource
CommandBuffer * cmd_buffer = nullptr;
std::vector<VkSemaphore> m_present_complete;
std::vector<VkSemaphore> m_render_complete;
uint32_t m_current_frame = 0;
bool m_vsync = false;
VkPipelineCache m_pipeline_cache = VK_NULL_HANDLE;
uint64_t m_frame_count = 0;
std::mutex m_command_pool_mutex;
std::mutex m_command_buffer_mutex;
scope<QueueSystem> m_queue_system = nullptr;
public:
Event<> Swapchain_Rebuild_Event;
};
} // namespace Ilum
| 22.708661
| 141
| 0.748266
|
Chaf-Libraries
|
5880350e3a96b3b7863451123c21a0ae18a48323
| 1,277
|
cpp
|
C++
|
01_Programming_Basics/05_Programming_Basics_Exams/04_CPP_Programming Basics_Online_Exam_3_and_4_November 2018/03_wedding_investment.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
01_Programming_Basics/05_Programming_Basics_Exams/04_CPP_Programming Basics_Online_Exam_3_and_4_November 2018/03_wedding_investment.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
01_Programming_Basics/05_Programming_Basics_Exams/04_CPP_Programming Basics_Online_Exam_3_and_4_November 2018/03_wedding_investment.cpp
|
Knightwalker/Knowledgebase
|
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
//#include <math.h>
//#include <stdlib.h>
#include <iomanip>
using namespace std;
int main() {
string contractLen = "";
string contractType = "";
string desert = "";
int months = 0;
getline(cin, contractLen);
getline(cin, contractType);
getline(cin, desert);
cin >> months;
cin.ignore();
double tax = 0.0;
if (contractLen == "one") {
if (contractType == "Small") {
tax = 9.98;
} else if (contractType == "Middle") {
tax = 18.99;
} else if (contractType == "Large") {
tax = 25.98;
} else if (contractType == "ExtraLarge") {
tax = 35.99;
}
} else if (contractLen == "two") {
if (contractType == "Small") {
tax = 8.58;
} else if (contractType == "Middle") {
tax = 17.09;
} else if (contractType == "Large") {
tax = 23.59;
} else if (contractType == "ExtraLarge") {
tax = 31.79;
}
}
if (desert == "yes") {
if (tax > 0 && tax <= 10) {
tax += 5.50;
} else if (tax > 10 && tax <= 30) {
tax += 4.35;
} else if (tax > 30) {
tax += 3.85;
}
}
if (contractLen == "two") {
tax -= tax * 0.0375;
}
cout << fixed << setprecision(2) << tax * months << " lv." << endl;
return 0;
}
| 20.596774
| 69
| 0.511355
|
Knightwalker
|
58834bd94e9823c5ce752f747a7a9a76a913d22c
| 2,918
|
cpp
|
C++
|
Source/MammutQOR/Model/MProperty.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 9
|
2016-05-27T01:00:39.000Z
|
2021-04-01T08:54:46.000Z
|
Source/MammutQOR/Model/MProperty.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 1
|
2016-03-03T22:54:08.000Z
|
2016-03-03T22:54:08.000Z
|
Source/MammutQOR/Model/MProperty.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 4
|
2016-05-27T01:00:43.000Z
|
2018-08-19T08:47:49.000Z
|
//MProperty.cpp
// Copyright Querysoft Limited 2015
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#include "MammutQOR.h"
#include "MammutQOR/Model/MProperty.h"
#include "MammutQOR/Model/MPropertySet.h"
//------------------------------------------------------------------------------
namespace nsMammut
{
//------------------------------------------------------------------------------
CPropertyBase::CPropertyBase( CModel* pContainer, const nsCodeQOR::CString& strName ) : CModelItem( pContainer ), m_Name( strName )
{
CPropertySet* pPropertySet = dynamic_cast< CPropertySet* >( pContainer );
if( pPropertySet )
{
pPropertySet->insert( Ref() );
}
}
//------------------------------------------------------------------------------
CPropertyBase::~CPropertyBase()
{
}
//------------------------------------------------------------------------------
CPropertyBase::CPropertyBase( const CPropertyBase& src ) : CModelItem( src ), m_Name( src.m_Name )
{
}
//------------------------------------------------------------------------------
CPropertyBase& CPropertyBase::operator = ( const CPropertyBase& src )
{
CModelItem::operator=( src );
if( &src != this )
{
m_Name = src.m_Name;
}
return *this;
}
//------------------------------------------------------------------------------
const nsCodeQOR::CString& CPropertyBase::Name( void ) const
{
return m_Name;
}
//------------------------------------------------------------------------------
CPropertyBase::refType CPropertyBase::Clone( void )
{
return refType( new CPropertyBase( *this ), true );
}
}//nsMammut
| 36.024691
| 132
| 0.593215
|
mfaithfull
|
58855a1d969826f5a467b796deb3b50623140186
| 15,638
|
cpp
|
C++
|
src/proxy_server/proxy_server.cpp
|
PetrPPetrov/gkm-world
|
7c24d1646e04b439733a7eb603c9a00526b39f4c
|
[
"BSD-2-Clause"
] | 2
|
2021-06-04T09:27:52.000Z
|
2021-06-08T05:23:21.000Z
|
src/proxy_server/proxy_server.cpp
|
PetrPPetrov/gkm-world
|
7c24d1646e04b439733a7eb603c9a00526b39f4c
|
[
"BSD-2-Clause"
] | null | null | null |
src/proxy_server/proxy_server.cpp
|
PetrPPetrov/gkm-world
|
7c24d1646e04b439733a7eb603c9a00526b39f4c
|
[
"BSD-2-Clause"
] | null | null | null |
// Copyright 2018-2020 Petr Petrovich Petrov. All rights reserved.
// License: https://github.com/PetrPPetrov/gkm-world/blob/master/LICENSE
#include <iostream>
#include <fstream>
#include <memory>
#include <boost/uuid/uuid_io.hpp>
#include <boost/uuid/random_generator.hpp>
#include "gkm_world/protocol.h"
#include "gkm_world/logger.h"
#include "gkm_world/configuration_reader.h"
#include "proxy_server.h"
ProxyServer::ProxyServer(const std::string& cfg_file_name_) :
cfg_file_name(cfg_file_name_), signals(io_service, SIGINT, SIGTERM) {
setApplicationType(Packet::EApplicationType::ProxyServer);
std::ifstream config_file(cfg_file_name);
ConfigurationReader config_reader;
config_reader.addParameter("proxy_server_port_number", port_number);
config_reader.addParameter("balancer_server_ip", balancer_server_ip);
config_reader.addParameter("balancer_server_port_number", balancer_server_port_number);
config_reader.addParameter("log_min_severity", minimum_level);
config_reader.addParameter("log_to_screen", log_to_screen);
config_reader.addParameter("log_to_file", log_to_file);
config_reader.addParameter("registered_users_file_name", registered_users_file_name);
config_reader.read(config_file);
balancer_server_end_point = boost::asio::ip::udp::endpoint(IpAddress::from_string(balancer_server_ip), balancer_server_port_number);
proxy_server_end_point = boost::asio::ip::udp::endpoint(IpAddress(), port_number);
socket = boost::asio::ip::udp::socket(io_service, proxy_server_end_point);
}
ProxyServer::~ProxyServer() {
saveRegisteredUsers(registered_users_file_name);
}
bool ProxyServer::start() {
Logger::setLoggingToScreen(log_to_screen);
Logger::setLoggingToFile(log_to_file, "proxy_server_" + std::to_string(port_number) + ".log");
Logger::setMinimumLevel(minimum_level);
Logger::registerThisThread();
LOG_INFO << "Proxy Server is starting...";
try {
dumpParameters();
startImpl();
} catch (boost::system::system_error& error) {
LOG_FATAL << "boost::system::system_error: " << error.what();
return false;
} catch (const std::exception& exception) {
LOG_FATAL << "std::exception: " << exception.what();
return false;
} catch (...) {
LOG_FATAL << "Unknown error";
return false;
}
return true;
}
void ProxyServer::dumpParameters() {
LOG_INFO << "configuration_file_name " << cfg_file_name;
LOG_INFO << "balancer_server_ip " << balancer_server_ip;
LOG_INFO << "balancer_server_port_number " << balancer_server_port_number;
LOG_INFO << "proxy_server_ip " << proxy_server_end_point.address();
LOG_INFO << "proxy_server_port_number " << proxy_server_end_point.port();
LOG_INFO << "log_min_severity " << getText(minimum_level);
LOG_INFO << "log_to_screen " << log_to_screen;
LOG_INFO << "log_to_file " << log_to_file;
LOG_INFO << "registered_users_file_name " << registered_users_file_name;
}
void ProxyServer::startImpl() {
using namespace boost::placeholders;
loadRegisteredUsers(registered_users_file_name);
doReceive();
signals.async_wait(boost::bind(&ProxyServer::onQuit, this, _1, _2));
setReceiveHandler(Packet::EType::Login, boost::bind(&ProxyServer::onLogin, this, _1));
setReceiveHandler(Packet::EType::Logout, boost::bind(&ProxyServer::onLogout, this, _1));
setReceiveHandler(Packet::EType::LogoutInternalAnswer, boost::bind(&ProxyServer::onLogoutInternalAnswer, this, _1));
setReceiveHandler(Packet::EType::InitializePosition, boost::bind(&ProxyServer::onInitializePosition, this, _1));
setReceiveHandler(Packet::EType::InitializePositionInternalAnswer, boost::bind(&ProxyServer::onInitializePositionInternalAnswer, this, _1));
setReceiveHandler(Packet::EType::UnitAction, boost::bind(&ProxyServer::onUnitAction, this, _1));
setReceiveHandler(Packet::EType::UnitActionInternalAnswer, boost::bind(&ProxyServer::onUnitActionInternalAnswer, this, _1));
setReceiveHandler(Packet::EType::RegisterProxyAnswer, boost::bind(&ProxyServer::onRegisterProxyAnswer, this, _1));
auto register_proxy = createPacket<Packet::RegisterProxy>();
guaranteedSendTo(register_proxy, balancer_server_end_point, boost::bind(&Transport::logError, this, _1, _2));
io_service.run();
}
void ProxyServer::onQuit(const boost::system::error_code& error, int sig_number) {
if (!error) {
saveRegisteredUsers(registered_users_file_name);
} else {
LOG_ERROR << "users were not saved in the file";
}
onQuitSignal(error, sig_number);
}
bool ProxyServer::onLogin(size_t received_bytes) {
LOG_DEBUG << "onLogin";
const auto packet = getReceiveBufferAs<Packet::Login>();
std::string login = packet->login.str();
std::string password = packet->password.str();
std::string full_name = packet->full_name.str();
LOG_DEBUG << "end_point: " << remote_end_point;
LOG_DEBUG << "password: " << login;
LOG_DEBUG << "login: " << password;
LOG_DEBUG << "full_name: " << full_name;
auto fit_login_it = login_to_user_info.find(login);
UserInfo::Ptr cur_user;
if (fit_login_it != login_to_user_info.end()) {
LOG_DEBUG << "existing user";
cur_user = fit_login_it->second;
if (password != cur_user->password) {
LOG_DEBUG << "authorization failure";
auto answer = createPacket<Packet::LoginAnswer>(packet->packet_number);
answer->success = false;
standardSend(answer);
return true;
} else {
LOG_DEBUG << "authorization OK";
}
} else {
LOG_DEBUG << "new user";
UserInfo::Ptr new_user = std::make_shared<UserInfo>();
new_user->login = login;
new_user->password = password;
new_user->full_name = full_name;
login_to_user_info.emplace(login, new_user);
cur_user = new_user;
}
if (!cur_user->online) {
LOG_DEBUG << "user is logging";
IndexType new_token;
UserOnlineInfo* allocated_user_online_info = token_to_unit_info.allocate(new_token);
online_user_count++;
LOG_DEBUG << "generated new token " << new_token;
cur_user->unit_token = new_token;
cur_user->online = true;
UserOnlineInfo* user_online_info = new(allocated_user_online_info) UserOnlineInfo(cur_user.get());
user_online_info->user_end_point = remote_end_point;
} else {
#ifdef _DEBUG
LOG_DEBUG << "user is already online";
#endif
}
auto answer = createPacket<Packet::LoginAnswer>(packet->packet_number);
answer->success = true;
answer->unit_token = cur_user->unit_token;
standardSend(answer);
return true;
}
bool ProxyServer::onLogout(size_t received_bytes) {
LOG_DEBUG << "onLogout";
const auto packet = getReceiveBufferAs<Packet::Logout>();
LOG_DEBUG << "end point: " << remote_end_point;
IndexType unit_token = packet->unit_token;
UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token);
if (!user_online_info) {
LOG_ERROR << "user does not exist";
return true;
}
if (user_online_info->user_end_point != remote_end_point) {
LOG_ERROR << "user sent incorrect token " << unit_token << " ip: " << user_online_info->user_end_point << " and it should be ip: " << remote_end_point;
return true;
}
auto request = createPacket<Packet::LogoutInternal>();
request->unit_token = user_online_info->user_info->unit_token;
request->client_packet_number = packet->packet_number;
standardSendTo(request, user_online_info->node_server_end_point);
return true;
}
bool ProxyServer::onLogoutInternalAnswer(size_t received_bytes) {
LOG_DEBUG << "onLogoutInternalAnswer";
if (!validateInternalServer(remote_end_point)) {
LOG_WARNING << "internal server token validation error";
return true;
}
const auto packet = getReceiveBufferAs<Packet::LogoutInternalAnswer>();
IndexType unit_token = packet->unit_token;
UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token);
if (!user_online_info) {
LOG_ERROR << "user does not exist";
return true;
}
user_online_info->user_info->online = false;
user_online_info->user_info->unit_token = 0;
user_online_info->in_game = false;
user_online_info->user_info = nullptr;
boost::asio::ip::udp::endpoint user_end_point = user_online_info->user_end_point;
token_to_unit_info.deallocate(unit_token);
online_user_count--;
auto answer = createPacket<Packet::LogoutAnswer>(packet->client_packet_number);
answer->success = true;
standardSendTo(answer, user_end_point);
return true;
}
bool ProxyServer::onInitializePosition(size_t received_bytes) {
LOG_DEBUG << "onInitializePosition";
const auto packet = getReceiveBufferAs<Packet::InitializePosition>();
IndexType unit_token = packet->unit_location.unit_token;
UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token);
if (!user_online_info) {
LOG_ERROR << "user does not exist";
return true;
}
if (user_online_info->user_end_point != remote_end_point) {
LOG_ERROR << "unit sent incorrect token " << unit_token << " ip: " << user_online_info->user_end_point << " and it should be ip: " << remote_end_point;
return true;
}
if (!user_online_info->in_game) {
auto request = createPacket<Packet::InitializePositionInternal>();
request->client_packet_number = packet->packet_number;
request->proxy_packet_number = request->packet_number;
request->unit_location = packet->unit_location;
request->proxy_server_address = socket.local_endpoint().address().TO_V().to_bytes();
request->proxy_server_port_number = port_number;
standardSendTo(request, balancer_server_end_point);
return true;
}
auto answer = createPacket<Packet::InitializePositionAnswer>(packet->packet_number);
answer->success = true;
answer->corrected_location = packet->unit_location;
standardSend(answer);
return true;
}
bool ProxyServer::onInitializePositionInternalAnswer(size_t received_bytes) {
LOG_DEBUG << "onInitializePositionInternalAnswer";
if (!validateInternalServer(remote_end_point)) {
LOG_WARNING << "internal server token validation error";
return true;
}
const auto packet = getReceiveBufferAs<Packet::InitializePositionInternalAnswer>();
IndexType unit_token = packet->corrected_location.unit_token;
UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token);
if (!user_online_info) {
LOG_ERROR << "user does not exist";
return true;
}
if (!user_online_info->user_info->online) {
LOG_ERROR << "user is not online or is already in game";
return true;
}
if (user_online_info->in_game) {
LOG_ERROR << "user is already in game";
return true;
}
user_online_info->in_game = true;
user_online_info->node_server_end_point = boost::asio::ip::udp::endpoint(IpAddress(packet->node_server_address), packet->node_server_port_number);
if (user_online_info->node_server_end_point.address().is_loopback()) {
user_online_info->node_server_end_point = boost::asio::ip::udp::endpoint(remote_end_point.address().TO_V(), packet->node_server_port_number);
}
auto answer = createPacket<Packet::InitializePositionAnswer>(packet->client_packet_number);
answer->success = packet->success;
answer->corrected_location = packet->corrected_location;
standardSendTo(answer, user_online_info->user_end_point);
return true;
}
bool ProxyServer::onUnitAction(size_t received_bytes) {
LOG_DEBUG << "onUnitAction";
const auto packet = getReceiveBufferAs<Packet::UnitAction>();
IndexType unit_token = packet->unit_token;
UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token);
if (!user_online_info) {
LOG_ERROR << "user does not exist";
return true;
}
if (user_online_info->user_end_point != remote_end_point) {
LOG_ERROR << "user sent incorrect token " << unit_token << " ip: " << user_online_info->user_end_point << " and it should be ip: " << remote_end_point;
return true;
}
if (!user_online_info->in_game) {
LOG_ERROR << "user is not in game";
return true;
}
auto request = createPacket<Packet::UnitActionInternal>();
request->unit_token = user_online_info->user_info->unit_token;
request->keyboard_state = packet->keyboard_state;
request->client_packet_number = packet->packet_number;
standardSendTo(request, user_online_info->node_server_end_point);
return true;
}
bool ProxyServer::onUnitActionInternalAnswer(size_t received_bytes) {
LOG_DEBUG << "onUserActionInternalAnswer";
if (!validateInternalServer(remote_end_point)) {
LOG_WARNING << "fake internal server detected";
return true;
}
const auto packet = getReceiveBufferAs<Packet::UnitActionInternalAnswer>();
IndexType unit_token = packet->unit_location.unit_token;
UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token);
if (!user_online_info) {
LOG_ERROR << "user does not exist";
return true;
}
if (!user_online_info->in_game) {
LOG_ERROR << "user is not in game";
return true;
}
auto answer = createPacket<Packet::UnitActionAnswer>(packet->client_packet_number);
answer->unit_location = packet->unit_location;
answer->other_unit_count = packet->other_unit_count;
if (answer->other_unit_count >= Packet::MAX_UNIT_COUNT_IN_PACKET) {
answer->other_unit_count = Packet::MAX_UNIT_COUNT_IN_PACKET;
}
for (std::uint16_t i = 0; i < answer->other_unit_count; ++i) {
answer->other_unit[i] = packet->other_unit[i];
}
standardSendTo(answer, user_online_info->user_end_point);
return true;
}
bool ProxyServer::onRegisterProxyAnswer(size_t received_bytes) {
LOG_DEBUG << "onRegisterProxyAnswer";
if (!validateInternalServer(remote_end_point)) {
LOG_WARNING << "fake internal server detected";
return true;
}
const auto packet = getReceiveBufferAs<Packet::RegisterProxyAnswer>();
proxy_token = packet->proxy_token;
setApplicationToken(proxy_token);
LOG_DEBUG << "proxy_token " << proxy_token;
return true;
}
bool ProxyServer::validateInternalServer(const boost::asio::ip::udp::endpoint& end_point) const {
// TODO:
return true;
}
void ProxyServer::loadRegisteredUsers(const std::string& file_name) {
LOG_DEBUG << "loading users from " << file_name << "...";
std::ifstream registered_users(file_name);
while (!registered_users.bad() && !registered_users.eof()) {
UserInfo::Ptr new_user = std::make_shared<UserInfo>();
registered_users >> *new_user;
if (new_user->login.empty() || new_user->password.empty() || new_user->full_name.empty()) {
break;
}
login_to_user_info.insert_or_assign(new_user->login, new_user);
}
LOG_DEBUG << "users are loaded!";
}
void ProxyServer::saveRegisteredUsers(const std::string& file_name) const {
LOG_DEBUG << "saving users to " << file_name << "...";
std::ofstream registered_users(file_name);
for (auto cur_user : login_to_user_info) {
registered_users << *cur_user.second.get();
}
LOG_DEBUG << "users are saved!";
}
| 36.283063
| 159
| 0.700793
|
PetrPPetrov
|
5886178920a02fd588e4b2042d0693d1347b319c
| 2,160
|
hpp
|
C++
|
include/GameEngine/Graphics/Shader.hpp
|
iRohith/GameEngine
|
61d8ea417e5a9d03075d9cfcdc86f0a1a40f676f
|
[
"Apache-2.0"
] | null | null | null |
include/GameEngine/Graphics/Shader.hpp
|
iRohith/GameEngine
|
61d8ea417e5a9d03075d9cfcdc86f0a1a40f676f
|
[
"Apache-2.0"
] | null | null | null |
include/GameEngine/Graphics/Shader.hpp
|
iRohith/GameEngine
|
61d8ea417e5a9d03075d9cfcdc86f0a1a40f676f
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "../Core/Core.hpp"
#include "../Util/Array.hpp"
#include <string_view>
// TODO: ShaderLibrary (just copy from Hazel :| )
namespace GameEngine {
template<typename T> using Ref = std::shared_ptr<T>;
class ShaderUnit;
class GEAPI Shader {
public:
static Ref<Shader> Create(const char* name, const char* vertFilePath, const char* fragFilePath, bool addToLibrary = true);
static Ref<Shader> CreateFromUnits(const char* name, const ArrayConstView<Ref<ShaderUnit>>& shaderUnitsArray, bool addToLibrary = true, bool releaseShaderAfterUse = true);
static Ref<Shader> Get(const char* name);
inline const int GetID() const { return id; }
inline const char* GetName() const { return name; }
virtual void Use() const = 0;
virtual void Unuse() const = 0;
virtual ~Shader() = default;
virtual void SetInt(const char* name, int value) = 0;
virtual void SetIntArray(const char* name, const Array<int>&) = 0;
virtual void SetFloat(const char* name, float value) = 0;
virtual void SetFloat2(const char* name, const M::VecF<2>& value) = 0;
virtual void SetFloat3(const char* name, const M::VecF<3>& value) = 0;
virtual void SetFloat4(const char* name, const M::VecF<4>& value) = 0;
virtual void SetMat4(const char* name, const M::MatrixF<4,4>& value) = 0;
protected:
Shader() = default;
int id;
const char* name;
};
class GEAPI ShaderUnit {
public:
enum ShaderType { NONE, VERTEX, FRAGMENT/* TODO: , GEOMETRY, COMPUTE, TESSELLATION*/ };
static Ref<ShaderUnit> Create(const char* path, ShaderType t = ShaderType::NONE);
static Ref<ShaderUnit> CreateFromCode(const std::string_view& str, ShaderType t = ShaderType::NONE);
virtual void Attach(const Shader&) const = 0;
virtual void Release() = 0;
virtual ShaderType GetShaderType() const = 0;
inline const int& GetID() const { return id; }
virtual ~ShaderUnit() = default;
protected:
ShaderUnit() = default;
int id;
};
using ShaderType = ShaderUnit::ShaderType;
}
| 37.894737
| 179
| 0.651852
|
iRohith
|
588a1b7f7b93a3adbf6d81cc599f3e6653c7a145
| 16,847
|
cpp
|
C++
|
Source/Game.cpp
|
AdriaSeSa/Minigame
|
ca2a0f2d47bba25341962b5229eb304159e91749
|
[
"MIT"
] | 2
|
2021-03-16T00:49:11.000Z
|
2021-04-03T20:39:39.000Z
|
Source/Game.cpp
|
AdriaSeSa/Minigame
|
ca2a0f2d47bba25341962b5229eb304159e91749
|
[
"MIT"
] | null | null | null |
Source/Game.cpp
|
AdriaSeSa/Minigame
|
ca2a0f2d47bba25341962b5229eb304159e91749
|
[
"MIT"
] | null | null | null |
#include "Game.h"
//Game::Game() {}
//Game::~Game() {}
Menu menu;
bool Game::Init(Display Disp) {
srand((unsigned)time(NULL));
canvas = Disp;
bool result = canvas.createDisplay(SCREEN_WIDTH, SCREEN_HEIGHT);
menu.initSurfaces(canvas.getRenderer());
player = new Player(400, 300, 32, 32, 2, canvas.getRenderer());
// Init enemyBornPoint
for (int i = 0, k = 0; i < 2; i++)
{
int offsetY = OFFSET_SCREEN_HEIGHT;
int offsetX = OFFSET_SCREEN_WIDTH;
for (int j = 0; j < 3; j++, k += 2)
{
if (i == 0)
{
enemyPoints[k].x = (j * 32) + 224 + offsetX;
enemyPoints[k].y = (i * 32) + offsetY;
cout << "x: " << enemyPoints[k].x << "\ty: " << enemyPoints[k].y << endl;
enemyPoints[k + 1].x = (i * 32) + offsetX;
enemyPoints[k + 1].y = (j * 32) + offsetY + 228;
cout << "x: " << enemyPoints[k+1].x << "\ty: " << enemyPoints[k+1].y << endl;
}
else
{
enemyPoints[k].x = (j * 32) + 224 + offsetX;
enemyPoints[k].y = (i * 32) + offsetY + 480;
enemyPoints[k + 1].x = (i * 32) + offsetX + 480;
enemyPoints[k + 1].y = (j * 32) + offsetY + 228;
}
}
}
// Posicion de arboles, 1 significa que existe un arbol
int treePos[17][17]
{
{1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1},
{1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1},
{1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1},
};
// Init arboles
for (int i = 0, k = 0; i < 17; i++)
{
for (int j = 0; j < 17; j++)
{
if (treePos[i][j] == 1)
{
ent[k] = new Box(j * 32 + OFFSET_SCREEN_WIDTH, i * 32 + OFFSET_SCREEN_HEIGHT, 32, 32, 0, canvas.getRenderer());
k++;
//cout << i*32 << endl;
}
}
}
//ent[12] = new Box(512, 0, 32, 32, 0, canvas.getRenderer());
//cout << ent[12]->getH() << endl;
// Test zombie
/*
ent[96] = new Enemy(0, 200, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds());
ent[97] = new Enemy(0, 232, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds());
ent[98] = new Enemy(700, 250, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds());
ent[99] = new Enemy(700, 290, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds());
*/
CreateEnemy();
currentScreen = MENU;
//dp.draw(canvas.draw());
//Initialize keys array
for (int i = 0; i < MAX_KEYBOARD_KEYS; ++i)
keys[i] = KEY_IDLE;
// Initialize Sprites
IMG_Init;
// Init map sprite
BackTex = SDL_CreateTextureFromSurface(canvas.getRenderer(), IMG_Load("Assets/myAssets/Sprites/Map.png"));
// Init Time
TestTime = SDL_GetPerformanceCounter();
// Init Music
Mix_Init(MIX_INIT_MP3);
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1) {
printf("Mix_OpenAudio: %s\n", Mix_GetError());
}
music = Mix_LoadMUS("Assets/myAssets/Sounds/BGM.mp3");
fx_shoot = Mix_LoadWAV("Assets/myAssets/Sounds/shoot.mp3");
fx_lose = Mix_LoadWAV("Assets/myAssets/Sounds/lose.mp3");
fx_win = Mix_LoadWAV("Assets/myAssets/Sounds/win.wav");
string temp;
for (int i = 0; i < 5; i++) {
temp = "Assets/myAssets/Sounds/zombiegrunt"+ to_string(i) +".mp3";
fx_death[i] = Mix_LoadWAV(temp.c_str());
}
// -1 para que la musica suene para siempre
Mix_PlayMusic(music, -1);
Mix_Volume(-1, 25);
Mix_VolumeMusic(20);
return result;
}
bool Game::Tick() {
//cerr << "Ticks -> " << SDL_GetTicks() << " \n";
// Tiempo que ha pasado durante ejecuto
double currentTime = SDL_GetPerformanceCounter();
//cout << (currentTime -TestTime) / SDL_GetPerformanceFrequency() << endl;
switch (currentScreen)
{
case Game::MENU:
if (keys[SDL_SCANCODE_RETURN] == KEY_DOWN) currentScreen = GAMEPLAY;
break;
case Game::GAMEPLAY:
//if (keys[SDL_SCANCODE_L] == KEY_DOWN) { Mix_PlayChannel(-1, fx_lose, 0); currentScreen = GAME_OVER; } //Esto cambiará cuando se pueda perder
//--------------Debug------------
if (keys[SDL_SCANCODE_F10] == KEY_DOWN) {
debug = !debug;
}
//----------Entities-------------
endTime = SDL_GetPerformanceCounter();
timeOffset = SDL_GetPerformanceFrequency();
// Cada 1.5s ejecuta una vez para recalcular la posicion del jugador
if (((endTime - enemySpawunTime) / timeOffset) >= spawnTime)
{
cout << "Spawn Time ->"<< spawnTime <<endl;
enemySpawunTime = SDL_GetPerformanceCounter();
CreateEnemy();
if (tenScores == 4 && spawnTime >= spawnTimeLimit) {
//spawnTime *= (1 - (((float)score / 100)));
spawnTime -= 0.10;
tenScores = 0;
}
tenScores++;
}
//----------Shoot----------------
for (int i = 0; i < 20; i++)
{
// Modificar posicion de bala
if (shot[i].alive == false) continue;
if (shot[i].direction == LEFT) //shoot left
{
shot[i].rec.x -= shot[i].speed;
}
else if (shot[i].direction == RIGHT) { //shoot right
shot[i].rec.x += shot[i].speed;
}
else if (shot[i].direction == UP) { //shoot up
shot[i].rec.y += shot[i].speed;
}
else if (shot[i].direction == DOWN) { //shoot down
shot[i].rec.y -= shot[i].speed;
}
}
//----------Player---------------
//bool bx, by, ex, ey;
player->setBX(true);
player->setBY(true);
player->setYmove(0);
player->setXmove(0);
// Limitar rango de movimiento
if (keys[SDL_SCANCODE_UP] == KEY_REPEAT && player->getY() > OFFSET_SCREEN_HEIGHT) { player->setYmove(-1); };
if (keys[SDL_SCANCODE_DOWN] == KEY_REPEAT && player->getY() < SCREEN_HEIGHT - OFFSET_SCREEN_HEIGHT - 32) { player->setYmove(1); }
if (keys[SDL_SCANCODE_LEFT] == KEY_REPEAT && player->getX() > OFFSET_SCREEN_WIDTH) { player->setXmove(-1); }
if (keys[SDL_SCANCODE_RIGHT] == KEY_REPEAT && player->getX() < SCREEN_WIDTH - OFFSET_SCREEN_WIDTH - 32) { player->setXmove(1); }
for (int i = 0; i < MAX_ENTITIES; i++) {
if (ent[i] == NULL) break;
if (player->checkCollisions(ent[i]->getX(), ent[i]->getY(), false)) {
player->setBX(false);
}
if (player->checkCollisions(ent[i]->getX(), ent[i]->getY(), true)) {
player->setBY(false);
}
if (player->checkCollisions(ent[i]->getX(), ent[i]->getY(), false) &&
player->checkCollisions(ent[i]->getX(), ent[i]->getY(), true)) {//Player death
//cout << fx_lose;
Mix_PlayChannel(-1, fx_lose, 0);
currentScreen = GAME_OVER;
spawnTime = 1.3f;
for (int j = 0; j < MAX_ENTITIES; j++) {//Entities
if (ent[j] != NULL && ent[j]->getID() == 1) {
ent[j]->setAlive(false);
}
}
for (int j = 0; j < 20; j++) {//Bullet
shot[j].alive = false;
shot[j].rec.x = 840;
shot[j].rec.y = 600;
}
}
for (int j = 0; j < 20; j++) {
if (SDL_HasIntersection(&shot[j].rec, ent[i]->getCollsionBounds())) {
shot[j].alive = false;
shot[j].rec.x = 554;
shot[j].rec.y = 554;
ent[i]->setAlive(false);
if (ent[i]->getID() == 1) {
score++;
//cout << fx_death[rand() % 5];
Mix_PlayChannel(-1, fx_death[rand() % 5], 0);
}
}
}
//Entities collision
ent[i]->setBX(true);
ent[i]->setBY(true);
for (int j = 0; j < MAX_ENTITIES; j++) {
if (ent[j] == NULL) break;
if (ent[j] == ent[i]) { continue; }
//if (ent[i]->getID() == 2) {
if (ent[i]->checkCollisions(ent[j]->getX(), ent[j]->getY(), false)) {
ent[i]->setBX(false);
}
if (ent[i]->checkCollisions(ent[j]->getX(), ent[j]->getY(), true)) {
ent[i]->setBY(false);
}
//}
}
}
if(player->getBX()) player->moveX();
if(player->getBY()) player->moveY();
//Player Update
player->tick();
//Entities update
for (int i = 0; i < MAX_ENTITIES; i++) {
if (ent[i] == NULL) break;
ent[i]->tick();
}
break;
case Game::GAME_OVER:
Mix_PauseMusic();
if (keys[SDL_SCANCODE_R] == KEY_DOWN) {
Mix_PlayMusic(music, -1); currentScreen = GAMEPLAY;
player->setX(SCREEN_WIDTH / 2); player->setY(SCREEN_HEIGHT / 2);
score = 0;
}
else if (keys[SDL_SCANCODE_E] == KEY_DOWN) {
Mix_PlayMusic(music, -1);
currentScreen = MENU;
score = 0;
}
break;
}
if (!Input()) return true;
return false;
}
void Game::Draw() {
SDL_RenderClear(canvas.getRenderer());
switch (currentScreen) {
case MENU:
SDL_SetRenderDrawColor(canvas.getRenderer(), 0, 0, 0, 0);
SDL_RenderClear(canvas.getRenderer());
menu.menuHUD(canvas.getRenderer());
//MENU TEXT ////////////////////////////////////////////////////////////////////////////////////////
menu.showText(canvas.getRenderer(), 230, 272, "Start Game with <Enter>", canvas.getFonts(50), canvas.getColors(0));
menu.showText(canvas.getRenderer(), 250, 340, "Exit Game with <Esc>", canvas.getFonts(50), canvas.getColors(0));
menu.showText(canvas.getRenderer(), 215, 400, "Zhida", canvas.getFonts(50), canvas.getColors(1));
menu.showText(canvas.getRenderer(), 215, 440, "Chen", canvas.getFonts(50), canvas.getColors(1));
menu.showText(canvas.getRenderer(), 310, 400, "Robert", canvas.getFonts(50), canvas.getColors(0));
menu.showText(canvas.getRenderer(), 310, 440, "Recorda", canvas.getFonts(50), canvas.getColors(0));
menu.showText(canvas.getRenderer(), 430, 400, "Pol", canvas.getFonts(50), canvas.getColors(1));
menu.showText(canvas.getRenderer(), 430, 440, "Rius", canvas.getFonts(50), canvas.getColors(1));
menu.showText(canvas.getRenderer(), 500, 400, "Adria", canvas.getFonts(50), canvas.getColors(0));
menu.showText(canvas.getRenderer(), 500, 440, "Sellares", canvas.getFonts(50), canvas.getColors(0));
menu.showText(canvas.getRenderer(), 585, 580, "v1.0 87b3badc6c411651e56bfd19c770d53e", canvas.getFonts(20), canvas.getColors(2));
//-------------------------------------------------------------------------------------------------------------------//
break;
case GAMEPLAY:
//Rectangle Draw Test
SDL_SetRenderDrawColor(canvas.getRenderer(), 0, 0, 0, 0);
SDL_RenderClear(canvas.getRenderer());
SDL_Rect mapRect;
mapRect.x = 148;
mapRect.y = 28;
mapRect.w = 544;
mapRect.h = 544;
//MAP
SDL_RenderCopy(canvas.getRenderer(), BackTex, NULL, &mapRect);
//--------Entities-------
player->draw(canvas.getRenderer());
for (int i = 0; i < MAX_ENTITIES; i++) {
if (ent[i] == NULL) break;
ent[i]->draw(canvas.getRenderer());
}
//ent[68]->draw(canvas.getRenderer());
//cout <<"x: "<< ent[68]->getCollsionBounds()->x << "\t y: "<<ent[68]->getCollsionBounds()->y << endl;
//-------------
for (int i = 0; i < 20; i++)
//-------------SHOT----------
for (int i = 0; i < 20; i++)
{
if (shot[i].alive && shot[i].rec.x > OFFSET_SCREEN_WIDTH && shot[i].alive
&& shot[i].rec.x < SCREEN_WIDTH - OFFSET_SCREEN_WIDTH
&& shot[i].rec.y < SCREEN_HEIGHT - OFFSET_SCREEN_HEIGHT
&& shot[i].rec.y > OFFSET_SCREEN_HEIGHT) {
SDL_RenderCopy(canvas.getRenderer(), shot[i].tex, NULL, &shot[i].rec);
}
}
//----------HUD--------------
menu.gameplayHUD(canvas.getRenderer());
scoreS = to_string(score); //Converts Score to String
menu.showText(canvas.getRenderer(), 75, 40, scoreS.c_str(), canvas.getFonts(35), canvas.getColors(2));
// ---------DEBUG-------------
if (debug == true) {
if (keys[SDL_SCANCODE_UP] == KEY_REPEAT) {
menu.showText(canvas.getRenderer(), 0, -4, "UP!", canvas.getFonts(20), canvas.getColors(1));
}
if (keys[SDL_SCANCODE_DOWN] == KEY_REPEAT) {
menu.showText(canvas.getRenderer(), 0, -4, "DOWN!", canvas.getFonts(20), canvas.getColors(1));
}
if (keys[SDL_SCANCODE_LEFT] == KEY_REPEAT) {
menu.showText(canvas.getRenderer(), 0, -4, "LEFT!", canvas.getFonts(20), canvas.getColors(1));
}
if (keys[SDL_SCANCODE_RIGHT] == KEY_REPEAT) {
menu.showText(canvas.getRenderer(), 0, -4, "RIGHT!", canvas.getFonts(20), canvas.getColors(1));
}
menu.showText(canvas.getRenderer(), 785, -4, "60 FPS", canvas.getFonts(20), canvas.getColors(1)); //DEBUG FPS
// Posicion de spawn zombie
SDL_SetRenderDrawColor(canvas.getRenderer(), 255, 255, 255, -255);
SDL_Rect r;
r.w = 32;
r.h = 32;
for (int i = 0; i < 12; i++)
{
r.x = enemyPoints[i].x;
r.y = enemyPoints[i].y;
SDL_RenderDrawRect(canvas.getRenderer(), &r);
}
}
//-----------------------------
break;
case GAME_OVER:
SDL_SetRenderDrawColor(canvas.getRenderer(), 0, 0, 0, 255);
SDL_RenderClear(canvas.getRenderer());
scoreS = to_string(score); //Converts Score to String
menu.showText(canvas.getRenderer(), 320, 100, scoreS.c_str(), canvas.getFonts(80), canvas.getColors(1));
menu.gameOverHUD(canvas.getRenderer(), canvas.getColors(2), canvas.getColors(1), canvas.getFonts(80), canvas.getFonts(50));
break;
}
SDL_RenderPresent(canvas.getRenderer());
SDL_Delay(10);
}
bool Game::Input()
{
SDL_Event event;
for (int i = 0; i < MAX_MOUSE_BUTTONS; ++i)
{
if (mouse_buttons[i] == KEY_DOWN) mouse_buttons[i] = KEY_REPEAT;
if (mouse_buttons[i] == KEY_UP) mouse_buttons[i] = KEY_IDLE;
}
while (SDL_PollEvent(&event) != 0)
{
switch (event.type)
{
case SDL_QUIT: window_events[WE_QUIT] = true; break;
case SDL_WINDOWEVENT:
{
switch (event.window.event) {
//case SDL_WINDOWEVENT_LEAVE:
case SDL_WINDOWEVENT_HIDDEN:
case SDL_WINDOWEVENT_MINIMIZED:
case SDL_WINDOWEVENT_FOCUS_LOST: window_events[WE_HIDE] = true; break;
//case SDL_WINDOWEVENT_ENTER:
case SDL_WINDOWEVENT_SHOWN:
case SDL_WINDOWEVENT_FOCUS_GAINED:
case SDL_WINDOWEVENT_MAXIMIZED:
case SDL_WINDOWEVENT_RESTORED: window_events[WE_SHOW] = true; break;
case SDL_WINDOWEVENT_CLOSE: window_events[WE_QUIT] = true; break;
default: break;
}
} break;
//Comprobar estado del boton
case SDL_MOUSEBUTTONDOWN: mouse_buttons[event.button.button - 1] = KEY_DOWN; break;
case SDL_MOUSEBUTTONUP: mouse_buttons[event.button.button - 1] = KEY_UP; break;
case SDL_MOUSEMOTION:
{
mouse_x = event.motion.x;
mouse_y = event.motion.y;
} break;
default: break;
}
}
const Uint8* Keys = SDL_GetKeyboardState(NULL);
// Consider previous keys states for KEY_DOWN and KEY_UP
for (int i = 0; i < MAX_KEYBOARD_KEYS; ++i)
{
// Valor 1 = tecla esta pulsada , valor 0 no lo esta.
if (Keys[i] == 1)
{
if (keys[i] == KEY_IDLE) keys[i] = KEY_DOWN;
else keys[i] = KEY_REPEAT;
}
else
{
if (keys[i] == KEY_REPEAT || keys[i] == KEY_DOWN) keys[i] = KEY_UP;
else keys[i] = KEY_IDLE;
}
}
// Init Shoot
if (keys[SDL_SCANCODE_SPACE] == KEY_DOWN && currentScreen == GAMEPLAY)
{
int x, y, w, h;
// Inicializar textura de shot
if (shot[shotCount].tex == NULL)
{
shot[shotCount].tex = SDL_CreateTextureFromSurface(canvas.getRenderer(), IMG_Load("Assets/myAssets/Sprites/shoot.png"));
shot[shotCount].rec.w = 8;
shot[shotCount].rec.h = 8;
cout << shotCount << endl;
}
// Inicializar restos de valor
//shot[shotCount].rec.x = player->getX() + player->getW();
//shot[shotCount].rec.y = player->getY() + (player->getH()/2);
if (player->getXmove() == -1 || player->getLastMove() == LEFT) { //shoot left
shot[shotCount].rec.x = player->getX();
shot[shotCount].rec.y = player->getY() + (player->getH() / 2);
shot[shotCount].direction = LEFT;
}
else if (player->getXmove() == 1 || player->getLastMove() == RIGHT) { //shoot right
shot[shotCount].rec.x = player->getX() + player->getW();
shot[shotCount].rec.y = player->getY() + (player->getH() / 2);
shot[shotCount].direction = RIGHT;
}
else if (player->getYmove() == 1 || player->getLastMove() == UP) { //shoot up
shot[shotCount].rec.x = player->getX() + (player->getW() / 2);
shot[shotCount].rec.y = player->getY() + player->getH();
shot[shotCount].direction = UP;
}
else if (player->getYmove() == -1 || player->getLastMove() == DOWN) { //shoot down
shot[shotCount].rec.x = player->getX() + (player->getW() / 2);
shot[shotCount].rec.y = player->getY();
shot[shotCount].direction = DOWN;
}
shot[shotCount].alive = true;
// Repetir el bucle
if (++shotCount >= 20)
{
shotCount = 0;
}
Mix_PlayChannel(-1, fx_shoot, 0);
}
// Salir del juego
if (keys[SDL_SCANCODE_ESCAPE] == KEY_DOWN) { menu.freeMemory(); return false; }
// Check QUIT window event to finish the game
if (window_events[WE_QUIT] == true) { menu.freeMemory(); return false; }
return true;
}
void Game::CreateEnemy()
{
int temp = rand() % 12;
ent[zombieCount++] = new Enemy(enemyPoints[temp].x, enemyPoints[temp].y, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds());
if (zombieCount == MAX_ENTITIES)
{
zombieCount = 96;
}
}
| 29.976868
| 144
| 0.606161
|
AdriaSeSa
|
588fed9981cff1a9b92be3f195b532e55571a118
| 1,964
|
hpp
|
C++
|
SDK/PUBG_CharacterCapture_Gamepad_parameters.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 7
|
2019-03-06T11:04:52.000Z
|
2019-07-10T20:00:51.000Z
|
SDK/PUBG_CharacterCapture_Gamepad_parameters.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | null | null | null |
SDK/PUBG_CharacterCapture_Gamepad_parameters.hpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 10
|
2019-03-06T11:53:46.000Z
|
2021-02-18T14:01:11.000Z
|
#pragma once
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_CharacterCapture_Gamepad_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.PrepassCharacterCapture
struct UCharacterCapture_Gamepad_C_PrepassCharacterCapture_Params
{
class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.FinalizeCharacterCapture
struct UCharacterCapture_Gamepad_C_FinalizeCharacterCapture_Params
{
};
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.SaveCharacterStudio
struct UCharacterCapture_Gamepad_C_SaveCharacterStudio_Params
{
class AActor** Actor; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.InitCharacterCapture
struct UCharacterCapture_Gamepad_C_InitCharacterCapture_Params
{
};
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.Construct
struct UCharacterCapture_Gamepad_C_Construct_Params
{
};
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.Destruct
struct UCharacterCapture_Gamepad_C_Destruct_Params
{
};
// Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.ExecuteUbergraph_CharacterCapture_Gamepad
struct UCharacterCapture_Gamepad_C_ExecuteUbergraph_CharacterCapture_Gamepad_Params
{
int* EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 32.733333
| 152
| 0.674134
|
realrespecter
|
5892bc7540710686cf938dafd30aa91ccb05abe4
| 7,783
|
inl
|
C++
|
include/hfsm2/detail/control.inl
|
hfsm/HFSM2
|
61ecd4d36508dcc348049ee72d51f6cfca095311
|
[
"MIT"
] | 2
|
2021-01-26T02:50:53.000Z
|
2021-07-14T02:07:52.000Z
|
include/hfsm2/detail/control.inl
|
hfsm/HFSM2
|
61ecd4d36508dcc348049ee72d51f6cfca095311
|
[
"MIT"
] | 1
|
2021-01-26T02:51:46.000Z
|
2021-01-26T06:06:31.000Z
|
include/hfsm2/detail/control.inl
|
hfsm/HFSM2
|
61ecd4d36508dcc348049ee72d51f6cfca095311
|
[
"MIT"
] | null | null | null |
namespace hfsm2 {
namespace detail {
////////////////////////////////////////////////////////////////////////////////
template <typename TA>
ControlT<TA>::Origin::Origin(ControlT& control_,
const StateID id)
: control{control_}
, prevId(control._originId)
{
control.setOrigin(id);
}
//------------------------------------------------------------------------------
template <typename TA>
ControlT<TA>::Origin::~Origin() {
control.resetOrigin(prevId);
}
////////////////////////////////////////////////////////////////////////////////
template <typename TA>
ControlT<TA>::Region::Region(ControlT& control_,
const RegionID id,
const StateID index,
const LongIndex size)
: control{control_}
, prevId(control._regionId)
, prevIndex(control._regionIndex)
, prevSize(control._regionSize)
{
control.setRegion(id, index, size);
}
//------------------------------------------------------------------------------
template <typename TA>
ControlT<TA>::Region::~Region() {
control.resetRegion(prevId, prevIndex, prevSize);
control._status.clear();
}
////////////////////////////////////////////////////////////////////////////////
template <typename TA>
void
ControlT<TA>::setOrigin(const StateID id) {
// TODO: see if this still can be used
//HFSM_ASSERT(_regionId != INVALID_STATE_ID && _regionSize != INVALID_LONG_INDEX);
//HFSM_ASSERT(_regionId < StateList::SIZE && _regionId + _regionSize <= StateList::SIZE);
HFSM_ASSERT(id != INVALID_STATE_ID);
_originId = id;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA>
void
ControlT<TA>::resetOrigin(const StateID id) {
// TODO: see if this still can be used
//HFSM_ASSERT(_regionId != INVALID_STATE_ID && _regionSize != INVALID_LONG_INDEX);
//HFSM_ASSERT(_regionId < StateList::SIZE && _regionId + _regionSize <= StateList::SIZE);
HFSM_ASSERT(_originId != INVALID_STATE_ID);
_originId = id;
}
//------------------------------------------------------------------------------
template <typename TA>
void
ControlT<TA>::setRegion(const RegionID id,
const StateID index,
const LongIndex size)
{
HFSM_ASSERT(index != INVALID_STATE_ID && size != INVALID_LONG_INDEX);
if (_regionId == INVALID_REGION_ID) {
HFSM_ASSERT(_regionIndex == INVALID_STATE_ID);
HFSM_ASSERT(_regionSize == INVALID_LONG_INDEX);
HFSM_ASSERT(index < StateList::SIZE && index + size <= StateList::SIZE);
} else {
HFSM_ASSERT(_regionIndex != INVALID_STATE_ID);
HFSM_ASSERT(_regionSize != INVALID_LONG_INDEX);
HFSM_ASSERT(_regionIndex <= index && index + size <= _regionIndex + _regionSize);
}
HFSM_ASSERT(_originId == INVALID_STATE_ID);
_regionId = id;
_regionIndex = index;
_regionSize = size;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA>
void
ControlT<TA>::resetRegion(const RegionID id,
const StateID index,
const LongIndex size)
{
HFSM_ASSERT(_regionId != INVALID_REGION_ID);
HFSM_ASSERT(_regionIndex != INVALID_STATE_ID);
HFSM_ASSERT(_regionSize != INVALID_LONG_INDEX);
if (index == INVALID_STATE_ID)
HFSM_ASSERT(size == INVALID_LONG_INDEX);
else
HFSM_ASSERT(size != INVALID_LONG_INDEX);
_regionId = id;
_regionIndex = index;
_regionSize = size;
}
////////////////////////////////////////////////////////////////////////////////
template <typename TA>
FullControlT<TA>::Lock::Lock(FullControlT& control_)
: control(!control_._locked ? &control_ : nullptr)
{
if (control)
control->_locked = true;
}
//------------------------------------------------------------------------------
template <typename TA>
FullControlT<TA>::Lock::~Lock() {
if (control)
control->_locked = false;
}
////////////////////////////////////////////////////////////////////////////////
template <typename TA>
template <typename TState>
Status
FullControlT<TA>::updatePlan(TState& headState,
const Status subStatus)
{
using State = TState;
static constexpr StateID STATE_ID = State::STATE_ID;
HFSM_ASSERT(subStatus);
if (subStatus.failure) {
headState.wrapPlanFailed(*this);
return buildPlanStatus<State>(subStatus.outerTransition);
} else if (subStatus.success) {
if (Plan p = plan(_regionId)) {
for (auto it = p.begin(); it; ++it) {
if (isActive(it->origin) &&
_planData.tasksSuccesses[it->origin])
{
Origin origin{*this, STATE_ID};
changeTo(it->destination);
it.remove();
} else
break;
}
return {false, false, subStatus.outerTransition};
} else {
headState.wrapPlanSucceeded(*this);
return buildPlanStatus<State>(subStatus.outerTransition);
}
} else
return {false, false, subStatus.outerTransition};
}
//------------------------------------------------------------------------------
template <typename TA>
template <typename TState>
Status
FullControlT<TA>::buildPlanStatus(const bool outerTransition) {
using State = TState;
static constexpr StateID STATE_ID = State::STATE_ID;
if (_status.failure) {
_planData.tasksFailures[STATE_ID] = true;
HFSM_LOG_PLAN_STATUS(_regionId, StatusEvent::FAILED);
return {false, true, outerTransition};
} else if (_status.success) {
_planData.tasksSuccesses[STATE_ID] = true;
HFSM_LOG_PLAN_STATUS(_regionId, StatusEvent::SUCCEEDED);
return {true, false, outerTransition};
} else
return {false, false, outerTransition};
}
//------------------------------------------------------------------------------
template <typename TA>
void
FullControlT<TA>::changeTo(const StateID stateId) {
if (!_locked) {
const Request request{Request::Type::RESTART, stateId};
_requests << request;
if (_regionIndex + _regionSize <= stateId || stateId < _regionIndex)
_status.outerTransition = true;
#if defined HFSM_ENABLE_LOG_INTERFACE || defined HFSM_VERBOSE_DEBUG_LOG
if (_logger)
_logger->recordTransition(_originId, Transition::RESTART, stateId);
#endif
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA>
void
FullControlT<TA>::resume(const StateID stateId) {
if (!_locked) {
const Request request{Request::Type::RESUME, stateId};
_requests << request;
if (_regionIndex + _regionSize <= stateId || stateId < _regionIndex)
_status.outerTransition = true;
#if defined HFSM_ENABLE_LOG_INTERFACE || defined HFSM_VERBOSE_DEBUG_LOG
if (_logger)
_logger->recordTransition(_originId, Transition::RESUME, stateId);
#endif
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA>
void
FullControlT<TA>::schedule(const StateID stateId) {
const Request transition{Request::Type::SCHEDULE, stateId};
_requests << transition;
#if defined HFSM_ENABLE_LOG_INTERFACE || defined HFSM_VERBOSE_DEBUG_LOG
if (_logger)
_logger->recordTransition(_originId, Transition::SCHEDULE, stateId);
#endif
}
//------------------------------------------------------------------------------
template <typename TA>
void
FullControlT<TA>::succeed() {
_status.success = true;
_planData.tasksSuccesses[_originId] = true;
HFSM_LOG_TASK_STATUS(_regionId, _originId, StatusEvent::SUCCEEDED);
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
template <typename TA>
void
FullControlT<TA>::fail() {
_status.failure = true;
_planData.tasksFailures [_originId] = true;
HFSM_LOG_TASK_STATUS(_regionId, _originId, StatusEvent::FAILED);
}
////////////////////////////////////////////////////////////////////////////////
template <typename TA>
void
GuardControlT<TA>::cancelPendingChanges() {
_cancelled = true;
HFSM_LOG_CANCELLED_PENDING(_originId);
}
////////////////////////////////////////////////////////////////////////////////
}
}
| 26.293919
| 90
| 0.583837
|
hfsm
|
589aaa6574fc575fbb734930ed87d51ef4205acd
| 703
|
hpp
|
C++
|
luanics/logging/Sink.hpp
|
luanics/cpp-illustrated
|
6049de2119a53d656a63b65d9441e680355ef196
|
[
"MIT"
] | null | null | null |
luanics/logging/Sink.hpp
|
luanics/cpp-illustrated
|
6049de2119a53d656a63b65d9441e680355ef196
|
[
"MIT"
] | null | null | null |
luanics/logging/Sink.hpp
|
luanics/cpp-illustrated
|
6049de2119a53d656a63b65d9441e680355ef196
|
[
"MIT"
] | null | null | null |
#pragma once
#include <memory>
namespace luanics {
namespace logging {
class Record;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///
/// @class Sink
///
/// @brief Back-end of logging framework.
///
/// Consumes logging::Record handed off from Source.
///
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
class Sink {
public:
virtual void consume(std::unique_ptr<Record> record) = 0;
virtual ~Sink() {}
}; // class Sink
} // namespace logging
} // namespace luanics
| 23.433333
| 79
| 0.364154
|
luanics
|
589cad045e88539f85139d7bfc000dbfec36cfa7
| 2,049
|
cpp
|
C++
|
tests/engine/FilterGroup/tst_FilterGroupTest.cpp
|
tomvodi/QTail
|
2e7acf31664969e6890edede6b60e02b20f33eb2
|
[
"MIT"
] | 1
|
2017-04-29T12:17:59.000Z
|
2017-04-29T12:17:59.000Z
|
tests/engine/FilterGroup/tst_FilterGroupTest.cpp
|
tomvodi/QTail
|
2e7acf31664969e6890edede6b60e02b20f33eb2
|
[
"MIT"
] | 25
|
2016-06-11T17:35:42.000Z
|
2017-07-19T04:19:08.000Z
|
tests/engine/FilterGroup/tst_FilterGroupTest.cpp
|
tomvodi/QTail
|
2e7acf31664969e6890edede6b60e02b20f33eb2
|
[
"MIT"
] | null | null | null |
/**
* @author Thomas Baumann <teebaum@ymail.com>
*
* @section LICENSE
* See LICENSE for more informations.
*
*/
#include <QString>
#include <QtTest>
#include <QCoreApplication>
#include <include/FilterGroup.h>
class FilterGroupTest : public QObject
{
Q_OBJECT
public:
FilterGroupTest();
private Q_SLOTS:
void initTestCase();
void cleanupTestCase();
void testStringConstructor();
void testSetGetName();
void testSetGetFilterRules();
void testAppendFilterRule();
void testToAndFromJson();
};
FilterGroupTest::FilterGroupTest()
{
}
void FilterGroupTest::initTestCase()
{
}
void FilterGroupTest::cleanupTestCase()
{
}
void FilterGroupTest::testStringConstructor()
{
QString testGroupName("Testgroup");
FilterGroup group(testGroupName);
QVERIFY2(group.name() == testGroupName, "Failed setting groupname through constructor");
}
void FilterGroupTest::testSetGetName()
{
QString testGroupName("Testgroup");
FilterGroup group;
group.setName(testGroupName);
QVERIFY2(group.name() == testGroupName, "Failed setting/getting groupname");
}
void FilterGroupTest::testSetGetFilterRules()
{
FilterRule rule1("Rule 1");
FilterRule rule2("Rule 2");
QList<FilterRule> ruleList;
ruleList << rule1 << rule2;
FilterGroup group;
group.setFilterRules(ruleList);
QVERIFY2(group.filterRules() == ruleList, "Failed set/get rules");
}
void FilterGroupTest::testAppendFilterRule()
{
FilterRule rule("Rule 1");
FilterGroup group;
group.addFilterRule(rule);
QVERIFY2(group.filterRules().contains(rule), "Failed add rule");
}
void FilterGroupTest::testToAndFromJson()
{
FilterRule rule("Rule 1");
FilterGroup group;
group.setName("Test group");
group.addFilterRule(rule);
QJsonObject groupJson = group.toJson();
QVERIFY2(! groupJson.isEmpty(), "Empty json returned");
FilterGroup group2;
group2.fromJson(groupJson);
QVERIFY2(group == group2, "Failed convert to and from json");
}
QTEST_MAIN(FilterGroupTest)
#include "tst_FilterGroupTest.moc"
| 20.287129
| 91
| 0.724744
|
tomvodi
|
589d5cdc662c53a95fb4d11936b5347906dc7248
| 412
|
cpp
|
C++
|
HDU/20/hdu2072.cpp
|
bilibiliShen/CodeBank
|
49a69b2b2c3603bf105140a9d924946ed3193457
|
[
"MIT"
] | 1
|
2017-08-19T16:02:15.000Z
|
2017-08-19T16:02:15.000Z
|
HDU/20/hdu2072.cpp
|
bilibiliShen/CodeBank
|
49a69b2b2c3603bf105140a9d924946ed3193457
|
[
"MIT"
] | null | null | null |
HDU/20/hdu2072.cpp
|
bilibiliShen/CodeBank
|
49a69b2b2c3603bf105140a9d924946ed3193457
|
[
"MIT"
] | 1
|
2018-01-05T23:37:23.000Z
|
2018-01-05T23:37:23.000Z
|
//利用STL #include<set> 和 #include<sstream> 问题就简单多了
#include <iostream>
#include <sstream>
#include<string>
#include<set>
using namespace std;
int main()
{
set <string> ans;
stringstream temp;
string s;
while( getline(cin,s) && s!="#")
{
stringstream temp(s);
ans.clear();
while(temp>>s) ans.insert(s);
cout<<ans.size()<<endl;
}
return 0;
}
| 19.619048
| 51
| 0.563107
|
bilibiliShen
|
58a02e53d9c457ea10ac2c87de94d6fa4b75b174
| 905
|
cc
|
C++
|
mycode/cpp/thread/oo_threadpool/main.cc
|
stdbilly/CS_Note
|
a8a87e135a525d53c283a4c70fb942c9ca59a758
|
[
"MIT"
] | 2
|
2020-12-09T09:55:51.000Z
|
2021-01-08T11:38:22.000Z
|
mycode/cpp/thread/oo_threadpool/main.cc
|
stdbilly/CS_Note
|
a8a87e135a525d53c283a4c70fb942c9ca59a758
|
[
"MIT"
] | null | null | null |
mycode/cpp/thread/oo_threadpool/main.cc
|
stdbilly/CS_Note
|
a8a87e135a525d53c283a4c70fb942c9ca59a758
|
[
"MIT"
] | null | null | null |
#include "Threadpool.h"
#include "Task.h"
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <memory>
using std::unique_ptr;
using std::cout;
using std::endl;
using namespace wd;
class MyTask : public Task {
public:
void process() override {
::srand(::clock());
//::srand(::time(nullptr));
int num = rand() % 100;
cout << "sub thread " << pthread_self() << " num = " << num << endl;
//sleep(1);
}
};
int main() {
Threadpool threadpool(4, 10);
threadpool.start();
unique_ptr<Task> task(new MyTask());
//Task* task = new MyTask();
int cnt = 20;
while(cnt--) {
threadpool.addTask(task.get());
cout << "main thread :cnt = " << cnt << endl;
}
threadpool.stop();
//这里要显式的stop,虽然析构函数也会调用stop(),但是析构函数是在mian()之后执行的,
//此时task对象已经被销毁了,子线程无法正常执行,core dump
return 0;
}
| 22.073171
| 76
| 0.583425
|
stdbilly
|
58a08ac37d6c4e75a17b064bbddea071e696b1d3
| 3,334
|
cpp
|
C++
|
core/test/matrix/identity.cpp
|
flipflapflop/ginkgo
|
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
|
[
"BSD-3-Clause"
] | null | null | null |
core/test/matrix/identity.cpp
|
flipflapflop/ginkgo
|
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
|
[
"BSD-3-Clause"
] | null | null | null |
core/test/matrix/identity.cpp
|
flipflapflop/ginkgo
|
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
|
[
"BSD-3-Clause"
] | null | null | null |
/*******************************<GINKGO LICENSE>******************************
Copyright (c) 2017-2019, the Ginkgo authors
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.
******************************<GINKGO LICENSE>*******************************/
#include <ginkgo/core/matrix/identity.hpp>
#include <gtest/gtest.h>
#include <core/test/utils/assertions.hpp>
#include <ginkgo/core/matrix/dense.hpp>
namespace {
class Identity : public ::testing::Test {
protected:
using Id = gko::matrix::Identity<>;
using Vec = gko::matrix::Dense<>;
Identity() : exec(gko::ReferenceExecutor::create()) {}
std::shared_ptr<const gko::Executor> exec;
};
TEST_F(Identity, CanBeEmpty)
{
auto empty = Id::create(exec);
ASSERT_EQ(empty->get_size(), gko::dim<2>(0, 0));
}
TEST_F(Identity, CanBeConstructedWithSize)
{
auto identity = Id::create(exec, 5);
ASSERT_EQ(identity->get_size(), gko::dim<2>(5, 5));
}
TEST_F(Identity, AppliesToVector)
{
auto identity = Id::create(exec, 3);
auto x = Vec::create(exec, gko::dim<2>{3, 1});
auto b = gko::initialize<Vec>({2.0, 1.0, 5.0}, exec);
identity->apply(b.get(), x.get());
GKO_ASSERT_MTX_NEAR(x, l({2.0, 1.0, 5.0}), 0.0);
}
TEST_F(Identity, AppliesToMultipleVectors)
{
auto identity = Id::create(exec, 3);
auto x = Vec::create(exec, gko::dim<2>{3, 2}, 3);
auto b =
gko::initialize<Vec>(3, {{2.0, 3.0}, {1.0, 2.0}, {5.0, -1.0}}, exec);
identity->apply(b.get(), x.get());
GKO_ASSERT_MTX_NEAR(x, l({{2.0, 3.0}, {1.0, 2.0}, {5.0, -1.0}}), 0.0);
}
TEST(IdentityFactory, CanGenerateIdentityMatrix)
{
auto exec = gko::ReferenceExecutor::create();
auto id_factory = gko::matrix::IdentityFactory<>::create(exec);
auto mtx = gko::matrix::Dense<>::create(exec, gko::dim<2>{5, 5});
auto id = id_factory->generate(std::move(mtx));
ASSERT_EQ(id->get_size(), gko::dim<2>(5, 5));
}
} // namespace
| 30.587156
| 78
| 0.685363
|
flipflapflop
|
58a9f25c0802a949b51582de3a1b3777c8af4c0e
| 466
|
cpp
|
C++
|
Functions/perimeter.cpp
|
pepm99/School-C-
|
2d4b23d16a3b2fd0e589686db7d02cf6a647e447
|
[
"MIT"
] | null | null | null |
Functions/perimeter.cpp
|
pepm99/School-C-
|
2d4b23d16a3b2fd0e589686db7d02cf6a647e447
|
[
"MIT"
] | null | null | null |
Functions/perimeter.cpp
|
pepm99/School-C-
|
2d4b23d16a3b2fd0e589686db7d02cf6a647e447
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
double perimeter (double a, double b)
{
double p = 2*a+2*b;
return p;
}
double lice(double a, double b)
{
double s = a*b;
return s;
}
int main()
{
double a,b,a1,b1;
cout<<"a=";
cin>>a;
cout<<"b=";
cin>>b;
cout<<"a1=";
cin>>a1;
cout<<"a1=";
cin>>a1;
cout<<"P="<<perimeter(a,b)-perimeter(a1,b1);
cout<<'\n';
cout<<"S="<<lice(a,b)-lice(a1,b1);
return 0;
}
| 14.5625
| 45
| 0.51073
|
pepm99
|
58aa9e5187ab209f628b83120cb10779917599b5
| 1,472
|
cpp
|
C++
|
Parciales/examen_2/P7_PlanetsKingdoms.cpp
|
luismoroco/ProgrCompetitiva
|
011cdb18749a16d17fd635a7c36a8a21b2b643d9
|
[
"BSD-3-Clause"
] | null | null | null |
Parciales/examen_2/P7_PlanetsKingdoms.cpp
|
luismoroco/ProgrCompetitiva
|
011cdb18749a16d17fd635a7c36a8a21b2b643d9
|
[
"BSD-3-Clause"
] | null | null | null |
Parciales/examen_2/P7_PlanetsKingdoms.cpp
|
luismoroco/ProgrCompetitiva
|
011cdb18749a16d17fd635a7c36a8a21b2b643d9
|
[
"BSD-3-Clause"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
// https://cses.fi/problemset/task/1683
typedef int long long ll;
typedef vector<ll> vl;
typedef vector<vector<ll>> vll;
typedef map<ll, bool> mpb;
typedef vector<bool> vb;
void
DFS(vll &adj, mpb &visited, vl &a, ll x)
{
visited[x] = true;
for (ll i : adj[x]){
if (!visited[i]) DFS(adj, visited, a, i);
}
a.push_back(x);
}
void
Fx(vl &b, vll &reinos, ll x, ll y)
{
b[x] = y;
for (ll i : reinos[x]){
if (b[i] == -1) Fx(b, reinos, i, y);
}
}
void
solve(ll n, mpb &visited, vl &a, vl &b, vl &c, vll &adj, vll &reinos)
{
for (ll i = 0; i < n; ++i){
if (!visited[i]) DFS(adj, visited, a, i);
}
reverse(begin(a), end(a));
for (ll i : a){
if (b[i] == -1){
Fx(b, reinos, i, i);
c.push_back(i);
}
}
}
int
main(int argc, char const *argv[])
{
ll n, m, x, y;
cin >> n >> m;
vll adj, reinos;
vl a, b = vl(n, -1), c;
mpb visited;
adj.resize(n), reinos.resize(n);
while (m--){
cin >> x >> y;
--x, --y;
adj[x].push_back(y);
reinos[y].push_back(x);
}
solve(n, visited, a, b, c, adj, reinos);
int ID[200000]{};
int sol = 0;
for (size_t i = 0; i < n; ++i){
if (!ID[b[i]]) ID[b[i]] = ++sol;
}
cout << sol << '\n';
for (size_t i = 0; i < n; ++i){
cout << ID[b[i]] << " \n"[i == n - 1];
}
return 0;
}
| 18.871795
| 69
| 0.463995
|
luismoroco
|
58ad638394e98a88fb6bb66d9e7b9d0ce81bb78a
| 6,994
|
cpp
|
C++
|
breeze/cryptography/brz/sha512.cpp
|
gennaroprota/breeze
|
f1dfd7154222ae358f5ece936c2897a3ae110003
|
[
"BSD-3-Clause"
] | 1
|
2021-04-03T22:35:52.000Z
|
2021-04-03T22:35:52.000Z
|
breeze/cryptography/brz/sha512.cpp
|
gennaroprota/breeze
|
f1dfd7154222ae358f5ece936c2897a3ae110003
|
[
"BSD-3-Clause"
] | null | null | null |
breeze/cryptography/brz/sha512.cpp
|
gennaroprota/breeze
|
f1dfd7154222ae358f5ece936c2897a3ae110003
|
[
"BSD-3-Clause"
] | 1
|
2021-10-01T04:26:48.000Z
|
2021-10-01T04:26:48.000Z
|
// ===========================================================================
// Copyright 2006-2007 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
#include "breeze/cryptography/sha512.hpp"
#include "breeze/cryptography/private/sha_common.tpp"
#include "breeze/iteration/begin_end.hpp"
#include <algorithm>
#include <functional>
namespace breeze_ns {
namespace {
typedef sha512_engine::word_type
word_type ;
using sha_common_private::ror ;
word_type const k[] =
{
// These words represent the first sixty-four bits of the
// fractional parts of the cube roots of the first eighty prime
// numbers.
// -----------------------------------------------------------------------
0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL
} ;
word_type
big_sigma0( word_type x )
{
return ror< 28 >( x ) ^ ror< 34 >( x ) ^ ror< 39 >( x ) ;
}
word_type
big_sigma1( word_type x )
{
return ror< 14 >( x ) ^ ror< 18 >( x ) ^ ror< 41 >( x ) ;
}
word_type
sigma0( word_type x )
{
return ror< 1 >( x ) ^ ror< 8 >( x ) ^ ( x >> 7 ) ;
}
word_type
sigma1( word_type x )
{
return ror< 19 >( x ) ^ ror< 61 >( x ) ^ ( x >> 6 ) ;
}
}
void
sha512_engine::init_state( state_type & state )
{
// These words are obtained by taking the first sixty-four bits
// of the fractional parts of the square roots of the first
// eight prime numbers.
// -----------------------------------------------------------------------
state[ 0 ] = 0x6a09e667f3bcc908ULL ;
state[ 1 ] = 0xbb67ae8584caa73bULL ;
state[ 2 ] = 0x3c6ef372fe94f82bULL ;
state[ 3 ] = 0xa54ff53a5f1d36f1ULL ;
state[ 4 ] = 0x510e527fade682d1ULL ;
state[ 5 ] = 0x9b05688c2b3e6c1fULL ;
state[ 6 ] = 0x1f83d9abfb41bd6bULL ;
state[ 7 ] = 0x5be0cd19137e2179ULL ;
}
void
sha512_engine::process_block( block_type const & block, state_type & state )
{
using sha_common_private::ch ;
using sha_common_private::maj ;
// Create an 80-word "schedule" from the message block.
// -----------------------------------------------------------------------
int const count = 80 ;
word_type sched[ count ] ;
std::copy( breeze::cbegin( block ), breeze::cend( block ),
breeze::begin( sched ) ) ;
for ( int i = 16 ; i < count ; ++ i ) {
sched[ i ] = sigma1( sched[ i - 2 ] ) + sched[ i - 7 ]
+ sigma0( sched[ i - 15 ] ) + sched[ i - 16 ] ;
}
word_type working[ 8 ] ;
std::copy( breeze::cbegin( state ), breeze::cend( state ),
breeze::begin( working ) ) ;
// 0 1 2 3 4 5 6 7
// a b c d e f g h
// -----------------------------------------------------------------------
{
word_type t[ 2 ] ;
for ( int i = 0 ; i < count ; ++ i ) {
t[ 0 ] = working[ 7 ] + big_sigma1( working[ 4 ] )
+ ch( working[ 4 ], working[ 5 ], working[ 6 ] )
+ k[ i ] + sched[ i ] ;
t[ 1 ] = big_sigma0( working[ 0 ] )
+ maj( working[ 0 ], working[ 1 ], working[ 2 ] ) ;
working[ 7 ] = working[ 6 ] ;
working[ 6 ] = working[ 5 ] ;
working[ 5 ] = working[ 4 ] ;
working[ 4 ] = working[ 3 ] + t[ 0 ] ;
working[ 3 ] = working[ 2 ] ;
working[ 2 ] = working[ 1 ] ;
working[ 1 ] = working[ 0 ] ;
working[ 0 ] = t[ 0 ] + t[ 1 ] ;
}
}
std::transform( breeze::cbegin( state ), breeze::cend( state ),
breeze::cbegin( working ), breeze::begin( state ),
std::plus< word_type >() ) ;
}
void
sha512_224_engine::init_state( state_type & state )
{
state[ 0 ] = 0x8c3d37c819544da2ULL ;
state[ 1 ] = 0x73e1996689dcd4d6ULL ;
state[ 2 ] = 0x1dfab7ae32ff9c82ULL ;
state[ 3 ] = 0x679dd514582f9fcfULL ;
state[ 4 ] = 0x0f6d2b697bd44da8ULL ;
state[ 5 ] = 0x77e36f7304c48942ULL ;
state[ 6 ] = 0x3f9d85a86a1d36c8ULL ;
state[ 7 ] = 0x1112e6ad91d692a1ULL ;
}
void
sha512_224_engine::process_block( block_type const & block, state_type & state )
{
sha512_engine::process_block( block, state ) ;
}
void
sha512_256_engine::init_state( state_type & state )
{
state[ 0 ] = 0x22312194fc2bf72cULL ;
state[ 1 ] = 0x9f555fa3c84c64c2ULL ;
state[ 2 ] = 0x2393b86b6f53b151ULL ;
state[ 3 ] = 0x963877195940eabdULL ;
state[ 4 ] = 0x96283ee2a88effe3ULL ;
state[ 5 ] = 0xbe5e1e2553863992ULL ;
state[ 6 ] = 0x2b0199fc2c85b8aaULL ;
state[ 7 ] = 0x0eb72ddc81c52ca2ULL ;
}
void
sha512_256_engine::process_block( block_type const & block, state_type & state )
{
sha512_engine::process_block( block, state ) ;
}
}
| 34.623762
| 80
| 0.615671
|
gennaroprota
|
58ad8e01cff2451b726585464523a59170982242
| 1,769
|
hpp
|
C++
|
Trunk/Backstage/WebServer/src/mutex.hpp
|
tinoryj/StreamingMediaSystem_Demo
|
9252cd01cb615a1c55f7613466be1c30a9038b21
|
[
"MIT"
] | 1
|
2018-06-18T14:53:36.000Z
|
2018-06-18T14:53:36.000Z
|
Trunk/Backstage/WebServer/src/mutex.hpp
|
tinoryj/StreamingMediaSystem_Demo
|
9252cd01cb615a1c55f7613466be1c30a9038b21
|
[
"MIT"
] | 1
|
2018-01-13T16:13:42.000Z
|
2018-03-23T07:12:29.000Z
|
src/mutex.hpp
|
tinoryj/SimpleHTTPServer_epoll_threadPoll
|
1409acddf9427234a4e322c7134528b40ff9f0a9
|
[
"MIT"
] | null | null | null |
#ifndef _MUTEX_HPP_
#define _MUTEX_HPP_
//参照muduo库的mutex写出的一个简易的Mutex类
#include <bits/stdc++.h>
#include <assert.h>
#include <pthread.h>
class MutexLock{
public:
MutexLock(): holder_(0){
pthread_mutex_init(&mutex_, NULL); // 初始化
}
~MutexLock(){
assert(holder_ == 0);
pthread_mutex_destroy(&mutex_); // 销毁锁
}
const bool isLockedByThisThread(){ // 测试锁是否被当前线程持有
return holder_ == pthread_self();
}
const void assertLocked() {
assert(isLockedByThisThread());
}
void lock(){
pthread_mutex_lock(&mutex_);
assignHolder(); // 指定拥有者
}
void unlock(){
unassignHolder(); // 丢弃拥有者
pthread_mutex_unlock(&mutex_);
}
pthread_mutex_t* getPthreadMutex(){
return &mutex_;
}
private:
friend class Condition;
class UnassignGuard{
public:
UnassignGuard(MutexLock& owner) : owner_(owner){
owner_.unassignHolder();
}
~UnassignGuard(){
owner_.assignHolder();
}
private:
MutexLock& owner_;
};
void unassignHolder(){
holder_ = 0;
}
void assignHolder(){
holder_ = pthread_self();
}
pthread_mutex_t mutex_;
pthread_t holder_;
};
class MutexLockGuard{
public:
MutexLockGuard(MutexLock& mutex) : mutex_(mutex){
mutex_.lock();
}
~MutexLockGuard(){
mutex_.unlock();
}
private:
MutexLock& mutex_;
};
class Condition{
private:
MutexLock& mutex_;
pthread_cond_t pcond_;
public:
Condition(MutexLock& mutex) : mutex_(mutex){
pthread_cond_init(&pcond_, NULL);
}
~Condition(){
pthread_cond_destroy(&pcond_); // 销毁条件变量
}
void wait(){
MutexLock::UnassignGuard ug(mutex_);
pthread_cond_wait(&pcond_, mutex_.getPthreadMutex()); // 等待Mutex
}
void notify(){
pthread_cond_signal(&pcond_); // 唤醒一个线程
}
void notifyAll(){
pthread_cond_broadcast(&pcond_); // 唤醒多个线程
}
};
#endif
| 13.503817
| 66
| 0.686829
|
tinoryj
|
58b4d7e5a0a91e8babfcc14df33b8639e3b1a651
| 11,988
|
hpp
|
C++
|
LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/RandomGenerators.hpp
|
wis1906/letsgo-ar-space-generation
|
02d888a44bb9eb112f308356ab42720529349338
|
[
"MIT"
] | null | null | null |
LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/RandomGenerators.hpp
|
wis1906/letsgo-ar-space-generation
|
02d888a44bb9eb112f308356ab42720529349338
|
[
"MIT"
] | null | null | null |
LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/RandomGenerators.hpp
|
wis1906/letsgo-ar-space-generation
|
02d888a44bb9eb112f308356ab42720529349338
|
[
"MIT"
] | null | null | null |
// ========================================================================================
// ApproxMVBB
// Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz
// (døt) ch>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================================
#ifndef ApproxMVBB_RandomGenerator_hpp
#define ApproxMVBB_RandomGenerator_hpp
#include "ApproxMVBB/Common/StaticAssert.hpp"
#include "ApproxMVBB/Config/Config.hpp"
#include ApproxMVBB_TypeDefs_INCLUDE_FILE
#include <cstdint>
#include <ctime>
#include <limits>
#include <random>
#include <type_traits>
namespace ApproxMVBB
{
namespace RandomGenerators
{
/** This is a fixed-increment version of Java 8's SplittableRandom generator
See http://dx.doi.org/10.1145/2714064.2660195 and
http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html
It is a very fast generator passing BigCrush, and it can be useful if
for some reason you absolutely want 64 bits of state; otherwise, we
rather suggest to use a xorshift128+ (for moderately parallel
computations) or xorshift1024* (for massively parallel computations)
generator. */
class APPROXMVBB_EXPORT SplitMix64
{
private:
uint64_t x; //< The state can be seeded with any value.
public:
SplitMix64(const SplitMix64& gen) = default;
SplitMix64(SplitMix64&& gen) = default;
SplitMix64(uint64_t seed);
void seed(uint64_t seed);
uint64_t operator()();
// for standard random
using result_type = uint64_t;
static constexpr result_type min()
{
return std::numeric_limits<result_type>::min();
}
static constexpr result_type max()
{
return std::numeric_limits<result_type>::max();
}
};
/** This is the fastest generator passing BigCrush without
systematic failures, but due to the relatively short period it is
acceptable only for applications with a mild amount of parallelism;
otherwise, use a xorshift1024* generator.
The state must be seeded so that it is not everywhere zero. If you have
a 64-bit seed, we suggest to seed a splitmix64 generator and use its
output to fill s.
*/
class APPROXMVBB_EXPORT XorShift128Plus
{
private:
uint64_t s[2];
public:
XorShift128Plus(const XorShift128Plus& gen) = default;
XorShift128Plus(XorShift128Plus&& gen) = default;
XorShift128Plus(uint64_t seed);
/** Take time() to seed this generator */
XorShift128Plus();
void seed(uint64_t seed);
/** Generate random number */
uint64_t operator()();
/** This is the jump function for the generator. It is equivalent
to 2^64 calls to next(); it can be used to generate 2^64
non-overlapping subsequences for parallel computations. */
void jump();
// for standard random
using result_type = uint64_t;
static constexpr result_type min()
{
return std::numeric_limits<result_type>::min();
}
static constexpr result_type max()
{
return std::numeric_limits<result_type>::max();
}
};
/* This is a fast, top-quality generator. If 1024 bits of state are too
much, try a xorshift128+ generator.
The state must be seeded so that it is not everywhere zero. If you have
a 64-bit seed, we suggest to seed a splitmix64 generator and use its
output to fill s. */
class APPROXMVBB_EXPORT XorShift1024Star
{
private:
uint64_t s[16];
int p = 0;
public:
XorShift1024Star(const XorShift1024Star& gen) = default;
XorShift1024Star(XorShift1024Star&& gen) = default;
XorShift1024Star(uint64_t seed);
/** Take time() to seed this generator */
XorShift1024Star();
void seed(uint64_t seed);
/** Generate random number */
uint64_t operator()();
/** This is the jump function for the generator. It is equivalent
to 2^512 calls to next(); it can be used to generate 2^512
non-overlapping subsequences for parallel computations. */
void jump();
// for standard random
using result_type = uint64_t;
static constexpr result_type min()
{
return std::numeric_limits<result_type>::min();
}
static constexpr result_type max()
{
return std::numeric_limits<result_type>::max();
}
};
/** A fast portable, non-truly uniform integer distribution */
template<typename T>
class AlmostUniformUIntDistribution
{
public:
ApproxMVBB_STATIC_ASSERT(std::is_unsigned<T>::value);
AlmostUniformUIntDistribution(T min, T max)
: m_min(min), m_max(max)
{
m_nRange = m_max - m_min;
}
template<typename G>
T operator()(G& g)
{
return ((static_cast<double>(g() - G::min())) / (static_cast<double>(G::max() - G::min()))) * m_nRange + m_min;
}
private:
T m_min, m_max, m_nRange;
};
/** A fast portable, non-truly uniform real distribution */
template<typename T>
class AlmostUniformRealDistribution
{
public:
ApproxMVBB_STATIC_ASSERT(std::is_floating_point<T>::value);
AlmostUniformRealDistribution(T min, T max)
: m_min(min), m_max(max)
{
m_nRange = m_max - m_min;
}
template<typename G>
T operator()(G& g)
{
return ((static_cast<T>(g() - G::min())) / (static_cast<T>(G::max() - G::min()))) * m_nRange + m_min;
}
private:
T m_min, m_max, m_nRange;
};
/** Default random generator definitions */
static const uint64_t defaultSeed = 314159;
using DefaultRandomGen = XorShift128Plus;
/** Define the Uniform distributions for the library and for the tests */
#ifdef ApproxMVBB_BUILD_TESTS
template<typename T>
using DefaultUniformUIntDistribution = AlmostUniformUIntDistribution<T>;
template<typename T>
using DefaultUniformRealDistribution = AlmostUniformRealDistribution<T>;
#else
template<typename T>
using DefaultUniformUIntDistribution = std::uniform_int_distribution<T>;
template<typename T>
using DefaultUniformRealDistribution = std::uniform_real_distribution<T>;
#endif
} // namespace RandomGenerators
} // namespace ApproxMVBB
namespace ApproxMVBB
{
namespace RandomGenerators
{
inline SplitMix64::SplitMix64(uint64_t sd)
: x(sd)
{
}
inline void SplitMix64::seed(uint64_t sd)
{
x = sd;
}
inline uint64_t SplitMix64::operator()()
{
uint64_t z = (x += uint64_t(0x9E3779B97F4A7C15));
z = (z ^ (z >> 30)) * uint64_t(0xBF58476D1CE4E5B9);
z = (z ^ (z >> 27)) * uint64_t(0x94D049BB133111EB);
return z ^ (z >> 31);
}
inline XorShift128Plus::XorShift128Plus(uint64_t sd)
{
seed(sd);
}
/** Take time() to seed this generator */
inline XorShift128Plus::XorShift128Plus()
{
seed(static_cast<uint64_t>(time(nullptr)));
}
inline void XorShift128Plus::seed(uint64_t sd)
{
s[0] = SplitMix64{sd}();
s[1] = s[0];
}
/** Generate random number */
inline uint64_t XorShift128Plus::operator()()
{
uint64_t s1 = s[0];
const uint64_t s0 = s[1];
s[0] = s0;
s1 ^= s1 << 23; // a
s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); // b, c
return s[1] + s0;
}
inline void XorShift128Plus::jump()
{
static const uint64_t JUMP[] = {0x8a5cd789635d2dff, 0x121fd2155c472f96};
uint64_t s0 = 0;
uint64_t s1 = 0;
for(unsigned int i = 0; i < sizeof(JUMP) / sizeof(*JUMP); i++)
for(int b = 0; b < 64; b++)
{
if(JUMP[i] & uint64_t(1) << b)
{
s0 ^= s[0];
s1 ^= s[1];
}
this->operator()();
}
s[0] = s0;
s[1] = s1;
}
inline XorShift1024Star::XorShift1024Star(uint64_t sd)
{
seed(sd);
}
/** Take time() to seed this generator */
inline XorShift1024Star::XorShift1024Star()
{
seed(static_cast<uint64_t>(time(nullptr)));
}
inline void XorShift1024Star::seed(uint64_t sd)
{
uint64_t ss = SplitMix64{sd}();
for(auto& v : s)
{
v = ss;
}
}
/** Generate random number */
inline uint64_t XorShift1024Star::operator()()
{
const uint64_t s0 = s[p];
uint64_t s1 = s[p = (p + 1) & 15];
s1 ^= s1 << 31; // a
s[p] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30); // b,c
return s[p] * uint64_t(1181783497276652981);
}
/** This is the jump function for the generator. It is equivalent
to 2^512 calls to next(); it can be used to generate 2^512
non-overlapping subsequences for parallel computations. */
inline void XorShift1024Star::jump()
{
static const uint64_t JUMP[] = {0x84242f96eca9c41d,
0xa3c65b8776f96855,
0x5b34a39f070b5837,
0x4489affce4f31a1e,
0x2ffeeb0a48316f40,
0xdc2d9891fe68c022,
0x3659132bb12fea70,
0xaac17d8efa43cab8,
0xc4cb815590989b13,
0x5ee975283d71c93b,
0x691548c86c1bd540,
0x7910c41d10a1e6a5,
0x0b5fc64563b3e2a8,
0x047f7684e9fc949d,
0xb99181f2d8f685ca,
0x284600e3f30e38c3};
uint64_t t[16] = {0};
for(unsigned int i = 0; i < sizeof(JUMP) / sizeof(*JUMP); i++)
for(int b = 0; b < 64; b++)
{
if(JUMP[i] & uint64_t(1) << b)
for(int j = 0; j < 16; j++)
t[j] ^= s[(j + p) & 15];
this->operator()();
}
for(int j = 0; j < 16; j++)
s[(j + p) & 15] = t[j];
}
} // namespace RandomGenerators
} // namespace ApproxMVBB
#endif
| 34.34957
| 127
| 0.505172
|
wis1906
|
58b4ecd312d9528373d8831c3492fba4facfd7cd
| 5,538
|
cpp
|
C++
|
valeur_ajouter/QRCode_Generator/QRCode/test_main.cpp
|
SuperBatata/Sportify-QT-C---project
|
8c0a9630cc6577721cb0f9fe0afd1eb082b4d4ba
|
[
"MIT"
] | null | null | null |
valeur_ajouter/QRCode_Generator/QRCode/test_main.cpp
|
SuperBatata/Sportify-QT-C---project
|
8c0a9630cc6577721cb0f9fe0afd1eb082b4d4ba
|
[
"MIT"
] | null | null | null |
valeur_ajouter/QRCode_Generator/QRCode/test_main.cpp
|
SuperBatata/Sportify-QT-C---project
|
8c0a9630cc6577721cb0f9fe0afd1eb082b4d4ba
|
[
"MIT"
] | null | null | null |
/*
* QR Code Generator
* Copyright (C) 2014 Stefano BARILETTI <hackaroth@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <string.h>
#include <iostream>
#include <fstream>
#include <streambuf>
#include <stdlib.h>
#include "QRController.h"
using namespace std;
typedef struct _params
{
bool Verbose;
int Version;
int Width;
int Height;
string Data;
string of;
eCorrectionLevel ECL;
_params(void)
{
Verbose = false;
Version = 0;
Width = 300;
Height = 300;
Data = "QR CODE";
of = "./out.bmp";
ECL = eclLow;
}
}params;
string load_from_file(char* file_name)
{
string data = "";
ifstream f(file_name);
f.seekg(0, std::ios::end);
data.reserve((unsigned int)f.tellg());
f.seekg(0, std::ios::beg);
data.assign((std::istreambuf_iterator<char>(f)),
std::istreambuf_iterator<char>());
f.close();
return data;
}
void parse_parameters(int argc, char* argv[], params &p)
{
for (int i = 1; i < argc; i++)
{
if (strcmp (argv[i],"-w") == 0)
{
i++;
if (atoi(argv[i]) > 0)
p.Width = atoi(argv[i]);
}
else if (strcmp (argv[i],"-h") == 0)
{
i++;
if (atoi(argv[i]) > 0)
p.Height = atoi(argv[i]);
}
else if (strcmp (argv[i],"-ecl") == 0)
{
i++;
if (strcmp (argv[i],"L") == 0)
p.ECL = eclLow;
else if (strcmp (argv[i],"M") == 0)
p.ECL = eclMedium;
else if (strcmp (argv[i],"Q") == 0)
p.ECL = eclQuality;
else if (strcmp (argv[i],"H") == 0)
p.ECL = eclHigh;
}
else if (strcmp (argv[i],"-v") == 0)
{
i++;
if (atoi(argv[i]) >= 0 && atoi(argv[i]) <= 40)
p.Version = atoi(argv[i]);
}
else if (strcmp (argv[i],"-if") == 0)
{
i++;
string data = load_from_file(argv[i]);
if (data.length() > 0)
p.Data = data;
}
else if (strcmp (argv[i],"-d") == 0)
p.Data = argv[++i];
else if (strcmp (argv[i],"-of") == 0)
p.of = argv[++i];
else if (strcmp (argv[i],"--V") == 0)
p.Verbose = true;
}
}
void show_license(void)
{
printf("QR CODE Version 1.0\n"
"Copyright (C) 2014 Stefano BARILETTI <hackaroth@gmail.com>\n\n"
"This program is free software: you can redistribute it and/or modify it\n"
"under the terms of the GNU General Public License as published by the\n"
"Free Software Foundation, either version 3 of the License, or\n"
"(at your option) any later version.\n\n"
"This program is distributed in the hope that it will be useful, but\n"
"WITHOUT ANY WARRANTY; without even the implied warranty of\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
"See the GNU General Public License for more details.\n\n");
}
void show_help(void)
{
printf("USAGE:\n"
"QRCODE -v, -w, -h, -ecl, -if, -d, -of, --V, --help\n\n"
"-v\tQR Code Version: From 0 to 40\n\tSet 0 for auto version selection.\n\n"
"-w\tImage width\n\tSet the width of the output image\n\n"
"-h\tImage height\n\tSet the height of the output image\n\n"
"-ecl\tError correction level: L, M, Q, H\n\tSet the error correction level of the qr code.\n\tDefault value is L\n\n"
"-if\tInput File\n\tCreate a Qr Code reading data from a file\n\n"
"-d\tData\n\tSpecifies the data that must be encoded.\n\tIf the -if option is specified, this option take precedence \n\n"
"-of\tOutput File\n\tSpecifies the output file name and path\n\n"
"--V\tVerbose\n\tShow the Qr Code settings\n\n"
"--help\tHelp\n\tShow this help\n\n");
}
int test_main(int argc, char* argv[])
{
show_license();
params p;
if (argc > 1 && strcmp (argv[1],"--help") == 0)
{
show_help();
}
else
{
parse_parameters(argc, argv, p);
if (p.Verbose)
{
cout << "*** SETTINGS ***" << endl;
cout << "Ver:\t" << p.Version << endl;
cout << "Width:\t" << p.Width << endl;
cout << "Height:\t" << p.Height << endl;
cout << "ECL:\t" << p.ECL << endl;
cout << "Output:\t" << p.of << endl;
cout << endl;
cout << p.Data << endl;
}
QRController* controller = new QRController(p.Data, p.ECL, p.Width, p.Height, p.Version);
controller->SaveToFile(p.of);
delete controller;
}
return 0;
}
| 28.994764
| 133
| 0.5381
|
SuperBatata
|
58b66778648a001230b3bbc5e2bad52dfae5f1d7
| 540
|
hpp
|
C++
|
Kreator/implementation/Platform/OpenGL/OpenGLRendererContext.hpp
|
ashish1009/Kreator
|
68ff5073faef22ade314772a5127dd1cc98060b7
|
[
"Apache-2.0"
] | null | null | null |
Kreator/implementation/Platform/OpenGL/OpenGLRendererContext.hpp
|
ashish1009/Kreator
|
68ff5073faef22ade314772a5127dd1cc98060b7
|
[
"Apache-2.0"
] | null | null | null |
Kreator/implementation/Platform/OpenGL/OpenGLRendererContext.hpp
|
ashish1009/Kreator
|
68ff5073faef22ade314772a5127dd1cc98060b7
|
[
"Apache-2.0"
] | null | null | null |
//
// OpenGLRendererContext.hpp
// Kreator
//
// Created by iKan on 09/04/22.
//
#pragma once
#include <Renderer/Graphics/Context.hpp>
namespace Kreator {
/// Implementation of Renderer Graphics context for Open GL API
class OpenGLRendererContext : public RendererContext {
public:
OpenGLRendererContext(GLFWwindow* window);
virtual ~OpenGLRendererContext();
void Init() override;
void SwapBuffers() override;
private:
GLFWwindow* m_Window;
};
}
| 19.285714
| 67
| 0.637037
|
ashish1009
|
58b7850f102ffd92d424a925293aa874646a22b7
| 30,804
|
cpp
|
C++
|
src/history/test/HistoryTests.cpp
|
viichain/vii-core
|
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
src/history/test/HistoryTests.cpp
|
viichain/vii-core
|
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
src/history/test/HistoryTests.cpp
|
viichain/vii-core
|
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
|
[
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"ECL-2.0",
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null |
#include "bucket/BucketManager.h"
#include "catchup/test/CatchupWorkTests.h"
#include "history/FileTransferInfo.h"
#include "history/HistoryArchiveManager.h"
#include "history/HistoryManager.h"
#include "history/test/HistoryTestsUtils.h"
#include "historywork/GetHistoryArchiveStateWork.h"
#include "historywork/GunzipFileWork.h"
#include "historywork/GzipFileWork.h"
#include "historywork/PutHistoryArchiveStateWork.h"
#include "ledger/LedgerManager.h"
#include "main/ExternalQueue.h"
#include "main/PersistentState.h"
#include "process/ProcessManager.h"
#include "test/TestAccount.h"
#include "test/TestUtils.h"
#include "test/TxTests.h"
#include "test/test.h"
#include "util/Fs.h"
#include "util/Logging.h"
#include "work/WorkScheduler.h"
#include "historywork/DownloadBucketsWork.h"
#include <lib/catch.hpp>
#include <lib/util/format.h>
using namespace viichain;
using namespace historytestutils;
TEST_CASE("next checkpoint ledger", "[history]")
{
CatchupSimulation catchupSimulation{};
HistoryManager& hm = catchupSimulation.getApp().getHistoryManager();
REQUIRE(hm.nextCheckpointLedger(0) == 64);
REQUIRE(hm.nextCheckpointLedger(1) == 64);
REQUIRE(hm.nextCheckpointLedger(32) == 64);
REQUIRE(hm.nextCheckpointLedger(62) == 64);
REQUIRE(hm.nextCheckpointLedger(63) == 64);
REQUIRE(hm.nextCheckpointLedger(64) == 64);
REQUIRE(hm.nextCheckpointLedger(65) == 128);
REQUIRE(hm.nextCheckpointLedger(66) == 128);
REQUIRE(hm.nextCheckpointLedger(126) == 128);
REQUIRE(hm.nextCheckpointLedger(127) == 128);
REQUIRE(hm.nextCheckpointLedger(128) == 128);
REQUIRE(hm.nextCheckpointLedger(129) == 192);
REQUIRE(hm.nextCheckpointLedger(130) == 192);
}
TEST_CASE("HistoryManager compress", "[history]")
{
CatchupSimulation catchupSimulation{};
std::string s = "hello there";
HistoryManager& hm = catchupSimulation.getApp().getHistoryManager();
std::string fname = hm.localFilename("compressme");
{
std::ofstream out(fname, std::ofstream::binary);
out.write(s.data(), s.size());
}
std::string compressed = fname + ".gz";
auto& wm = catchupSimulation.getApp().getWorkScheduler();
auto g = wm.executeWork<GzipFileWork>(fname);
REQUIRE(g->getState() == BasicWork::State::WORK_SUCCESS);
REQUIRE(!fs::exists(fname));
REQUIRE(fs::exists(compressed));
auto u = wm.executeWork<GunzipFileWork>(compressed);
REQUIRE(u->getState() == BasicWork::State::WORK_SUCCESS);
REQUIRE(fs::exists(fname));
REQUIRE(!fs::exists(compressed));
}
TEST_CASE("HistoryArchiveState get_put", "[history]")
{
CatchupSimulation catchupSimulation{};
HistoryArchiveState has;
has.currentLedger = 0x1234;
auto archive =
catchupSimulation.getApp().getHistoryArchiveManager().getHistoryArchive(
"test");
REQUIRE(archive);
has.resolveAllFutures();
auto& wm = catchupSimulation.getApp().getWorkScheduler();
auto put = wm.executeWork<PutHistoryArchiveStateWork>(has, archive);
REQUIRE(put->getState() == BasicWork::State::WORK_SUCCESS);
HistoryArchiveState has2;
auto get = wm.executeWork<GetHistoryArchiveStateWork>(has2, 0, archive);
REQUIRE(get->getState() == BasicWork::State::WORK_SUCCESS);
REQUIRE(has2.currentLedger == 0x1234);
}
TEST_CASE("History bucket verification",
"[history][bucketverification][batching]")
{
Config cfg(getTestConfig());
VirtualClock clock;
auto cg = std::make_shared<TmpDirHistoryConfigurator>();
cg->configure(cfg, true);
Application::pointer app = createTestApplication(clock, cfg);
REQUIRE(app->getHistoryArchiveManager().initializeHistoryArchive("test"));
auto bucketGenerator = TestBucketGenerator{
*app, app->getHistoryArchiveManager().getHistoryArchive("test")};
std::vector<std::string> hashes;
auto& wm = app->getWorkScheduler();
std::map<std::string, std::shared_ptr<Bucket>> mBuckets;
auto tmpDir =
std::make_unique<TmpDir>(app->getTmpDirManager().tmpDir("bucket-test"));
SECTION("successful download and verify")
{
hashes.push_back(bucketGenerator.generateBucket(
TestBucketState::CONTENTS_AND_HASH_OK));
hashes.push_back(bucketGenerator.generateBucket(
TestBucketState::CONTENTS_AND_HASH_OK));
auto verify =
wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir);
REQUIRE(verify->getState() == BasicWork::State::WORK_SUCCESS);
}
SECTION("download fails file not found")
{
hashes.push_back(
bucketGenerator.generateBucket(TestBucketState::FILE_NOT_UPLOADED));
auto verify =
wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir);
REQUIRE(verify->getState() == BasicWork::State::WORK_FAILURE);
}
SECTION("download succeeds but unzip fails")
{
hashes.push_back(bucketGenerator.generateBucket(
TestBucketState::CORRUPTED_ZIPPED_FILE));
auto verify =
wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir);
REQUIRE(verify->getState() == BasicWork::State::WORK_FAILURE);
}
SECTION("verify fails hash mismatch")
{
hashes.push_back(
bucketGenerator.generateBucket(TestBucketState::HASH_MISMATCH));
auto verify =
wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir);
REQUIRE(verify->getState() == BasicWork::State::WORK_FAILURE);
}
SECTION("no hashes to verify")
{
auto verify = wm.executeWork<DownloadBucketsWork>(
mBuckets, std::vector<std::string>(), *tmpDir);
REQUIRE(verify->getState() == BasicWork::State::WORK_SUCCESS);
}
}
TEST_CASE("Ledger chain verification", "[ledgerheaderverification]")
{
Config cfg(getTestConfig(0));
VirtualClock clock;
auto cg = std::make_shared<TmpDirHistoryConfigurator>();
cg->configure(cfg, true);
Application::pointer app = createTestApplication(clock, cfg);
REQUIRE(app->getHistoryArchiveManager().initializeHistoryArchive("test"));
auto tmpDir = app->getTmpDirManager().tmpDir("tmp-chain-test");
auto& wm = app->getWorkScheduler();
LedgerHeaderHistoryEntry firstVerified{};
LedgerHeaderHistoryEntry verifiedAhead{};
uint32_t initLedger = 127;
LedgerRange ledgerRange{
initLedger,
initLedger + app->getHistoryManager().getCheckpointFrequency() * 10};
CheckpointRange checkpointRange{ledgerRange, app->getHistoryManager()};
auto ledgerChainGenerator = TestLedgerChainGenerator{
*app, app->getHistoryArchiveManager().getHistoryArchive("test"),
checkpointRange, tmpDir};
auto checkExpectedBehavior = [&](Work::State expectedState,
LedgerHeaderHistoryEntry lcl,
LedgerHeaderHistoryEntry last) {
auto lclPair = LedgerNumHashPair(lcl.header.ledgerSeq,
make_optional<Hash>(lcl.hash));
auto ledgerRangeEnd = LedgerNumHashPair(last.header.ledgerSeq,
make_optional<Hash>(last.hash));
auto w = wm.executeWork<VerifyLedgerChainWork>(tmpDir, ledgerRange,
lclPair, ledgerRangeEnd);
REQUIRE(expectedState == w->getState());
};
LedgerHeaderHistoryEntry lcl, last;
LOG(DEBUG) << "fully valid";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_OK);
checkExpectedBehavior(BasicWork::State::WORK_SUCCESS, lcl, last);
}
LOG(DEBUG) << "invalid link due to bad hash";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_ERR_BAD_HASH);
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "invalid ledger version";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_ERR_BAD_LEDGER_VERSION);
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "overshot";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_ERR_OVERSHOT);
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "undershot";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_ERR_UNDERSHOT);
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "missing entries";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_ERR_MISSING_ENTRIES);
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "chain does not agree with LCL";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_OK);
lcl.hash = HashUtils::random();
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "chain does not agree with LCL on checkpoint boundary";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_OK);
lcl.header.ledgerSeq +=
app->getHistoryManager().getCheckpointFrequency() - 1;
lcl.hash = HashUtils::random();
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "chain does not agree with LCL outside of range";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_OK);
lcl.header.ledgerSeq -= 1;
lcl.hash = HashUtils::random();
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "chain does not agree with trusted hash";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_OK);
last.hash = HashUtils::random();
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
LOG(DEBUG) << "missing file";
{
std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles(
HistoryManager::VERIFY_STATUS_OK);
FileTransferInfo ft(tmpDir, HISTORY_FILE_TYPE_LEDGER,
last.header.ledgerSeq);
std::remove(ft.localPath_nogz().c_str());
checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last);
}
}
TEST_CASE("History publish", "[history]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1);
catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger);
}
static std::string
resumeModeName(uint32_t count)
{
switch (count)
{
case 0:
return "CATCHUP_MINIMAL";
case std::numeric_limits<uint32_t>::max():
return "CATCHUP_COMPLETE";
default:
return "CATCHUP_RECENT";
}
}
static std::string
dbModeName(Config::TestDbMode mode)
{
switch (mode)
{
case Config::TESTDB_IN_MEMORY_SQLITE:
return "TESTDB_IN_MEMORY_SQLITE";
case Config::TESTDB_ON_DISK_SQLITE:
return "TESTDB_ON_DISK_SQLITE";
#ifdef USE_POSTGRES
case Config::TESTDB_POSTGRESQL:
return "TESTDB_POSTGRESQL";
#endif
default:
abort();
}
}
TEST_CASE("History catchup", "[history][catchup]")
{
CatchupSimulation catchupSimulation{VirtualClock::REAL_TIME};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
auto app = catchupSimulation.createCatchupApplication(
std::numeric_limits<uint32_t>::max(), Config::TESTDB_ON_DISK_SQLITE,
"app");
auto offlineNonCheckpointDestinationLedger =
checkpointLedger -
app->getHistoryManager().getCheckpointFrequency() / 2;
SECTION("when not enough publishes has been performed")
{
catchupSimulation.ensureLedgerAvailable(checkpointLedger);
SECTION("online")
{
REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger));
}
SECTION("offline")
{
REQUIRE(!catchupSimulation.catchupOffline(app, checkpointLedger));
}
SECTION("offline, in the middle of checkpoint")
{
REQUIRE(!catchupSimulation.catchupOffline(
app, offlineNonCheckpointDestinationLedger));
}
}
SECTION("when enough publishes has been performed, but no trigger ledger "
"was externalized")
{
catchupSimulation.ensureLedgerAvailable(checkpointLedger + 1);
catchupSimulation.ensurePublishesComplete();
SECTION("online")
{
REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger));
}
SECTION("offline")
{
REQUIRE(catchupSimulation.catchupOffline(app, checkpointLedger));
}
SECTION("offline, in the middle of checkpoint")
{
REQUIRE(catchupSimulation.catchupOffline(
app, offlineNonCheckpointDestinationLedger));
}
}
SECTION("when enough publishes has been performed, but no closing ledger "
"was externalized")
{
catchupSimulation.ensureLedgerAvailable(checkpointLedger + 2);
catchupSimulation.ensurePublishesComplete();
REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger));
}
SECTION("when enough publishes has been performed, 3 ledgers are buffered "
"and no closing ledger was externalized")
{
catchupSimulation.ensureLedgerAvailable(checkpointLedger + 5);
catchupSimulation.ensurePublishesComplete();
REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger, 3));
}
SECTION("when enough publishes has been performed, 3 ledgers are buffered "
"and closing ledger was externalized")
{
catchupSimulation.ensureLedgerAvailable(checkpointLedger + 6);
catchupSimulation.ensurePublishesComplete();
REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 3));
}
}
TEST_CASE("History catchup with different modes", "[history][catchup]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
std::vector<Application::pointer> apps;
std::vector<uint32_t> counts = {0, std::numeric_limits<uint32_t>::max(),
60};
std::vector<Config::TestDbMode> dbModes = {Config::TESTDB_IN_MEMORY_SQLITE,
Config::TESTDB_ON_DISK_SQLITE};
#ifdef USE_POSTGRES
if (!force_sqlite)
dbModes.push_back(Config::TESTDB_POSTGRESQL);
#endif
for (auto dbMode : dbModes)
{
for (auto count : counts)
{
auto a = catchupSimulation.createCatchupApplication(
count, dbMode,
std::string("full, ") + resumeModeName(count) + ", " +
dbModeName(dbMode));
REQUIRE(catchupSimulation.catchupOnline(a, checkpointLedger, 5));
apps.push_back(a);
}
}
}
TEST_CASE("History prefix catchup", "[history][catchup][prefixcatchup]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
auto a = catchupSimulation.createCatchupApplication(
std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE,
std::string("Catchup to prefix of published history"));
REQUIRE(catchupSimulation.catchupOnline(a, 10, 5));
uint32_t freq = a->getHistoryManager().getCheckpointFrequency();
REQUIRE(a->getLedgerManager().getLastClosedLedgerNum() == freq + 7);
auto b = catchupSimulation.createCatchupApplication(
std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE,
std::string("Catchup to second prefix of published history"));
REQUIRE(catchupSimulation.catchupOnline(b, freq + 10, 5));
REQUIRE(b->getLedgerManager().getLastClosedLedgerNum() == 2 * freq + 7);
}
TEST_CASE("Catchup non-initentry buckets to initentry-supporting works",
"[history][historyinitentry]")
{
uint32_t newProto =
Bucket::FIRST_PROTOCOL_SUPPORTING_INITENTRY_AND_METAENTRY;
uint32_t oldProto = newProto - 1;
auto configurator =
std::make_shared<RealGenesisTmpDirHistoryConfigurator>();
CatchupSimulation catchupSimulation{VirtualClock::VIRTUAL_TIME,
configurator};
catchupSimulation.generateRandomLedger(oldProto);
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger);
std::vector<Application::pointer> apps;
std::vector<uint32_t> counts = {0, std::numeric_limits<uint32_t>::max(),
60};
for (auto count : counts)
{
auto a = catchupSimulation.createCatchupApplication(
count, Config::TESTDB_IN_MEMORY_SQLITE,
std::string("full, ") + resumeModeName(count) + ", " +
dbModeName(Config::TESTDB_IN_MEMORY_SQLITE));
REQUIRE(catchupSimulation.catchupOnline(a, checkpointLedger - 2));
auto mc = a->getBucketManager().readMergeCounters();
REQUIRE(mc.mPostInitEntryProtocolMerges == 0);
REQUIRE(mc.mNewInitEntries == 0);
REQUIRE(mc.mOldInitEntries == 0);
for (auto i = 0; i < 3; ++i)
{
auto root = TestAccount{*a, txtest::getRoot(a->getNetworkID())};
auto stranger = TestAccount{
*a, txtest::getAccount(fmt::format("stranger{}", i))};
auto& lm = a->getLedgerManager();
TxSetFramePtr txSet = std::make_shared<TxSetFrame>(
lm.getLastClosedLedgerHeader().hash);
uint32_t ledgerSeq = lm.getLastClosedLedgerNum() + 1;
uint64_t minBalance = lm.getLastMinBalance(5);
uint64_t big = minBalance + ledgerSeq;
uint64_t closeTime = 60 * 5 * ledgerSeq;
txSet->add(root.tx({txtest::createAccount(stranger, big)}));
txSet->getContentsHash();
auto upgrades = xdr::xvector<UpgradeType, 6>{};
if (i == 0)
{
auto ledgerUpgrade = LedgerUpgrade{LEDGER_UPGRADE_VERSION};
ledgerUpgrade.newLedgerVersion() = newProto;
auto v = xdr::xdr_to_opaque(ledgerUpgrade);
upgrades.push_back(UpgradeType{v.begin(), v.end()});
}
CLOG(DEBUG, "History")
<< "Closing synthetic ledger " << ledgerSeq << " with "
<< txSet->size(lm.getLastClosedLedgerHeader().header)
<< " txs (txhash:" << hexAbbrev(txSet->getContentsHash())
<< ")";
VIIValue sv(txSet->getContentsHash(), closeTime, upgrades,
VII_VALUE_BASIC);
lm.closeLedger(LedgerCloseData(ledgerSeq, txSet, sv));
}
mc = a->getBucketManager().readMergeCounters();
REQUIRE(mc.mPostInitEntryProtocolMerges != 0);
REQUIRE(mc.mNewInitEntries != 0);
REQUIRE(mc.mOldInitEntries != 0);
apps.push_back(a);
}
}
TEST_CASE("Publish catchup alternation with stall",
"[history][catchup][catchupalternation]")
{
CatchupSimulation catchupSimulation{};
auto& lm = catchupSimulation.getApp().getLedgerManager();
auto checkpoint = 3;
auto checkpointLedger =
catchupSimulation.getLastCheckpointLedger(checkpoint);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
auto completeApp = catchupSimulation.createCatchupApplication(
std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE,
std::string("completeApp"));
auto minimalApp = catchupSimulation.createCatchupApplication(
0, Config::TESTDB_IN_MEMORY_SQLITE, std::string("minimalApp"));
REQUIRE(catchupSimulation.catchupOnline(completeApp, checkpointLedger, 5));
REQUIRE(catchupSimulation.catchupOnline(minimalApp, checkpointLedger, 5));
for (int i = 1; i < 4; ++i)
{
checkpoint += i;
checkpointLedger =
catchupSimulation.getLastCheckpointLedger(checkpoint);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
REQUIRE(
catchupSimulation.catchupOnline(completeApp, checkpointLedger, 5));
REQUIRE(
catchupSimulation.catchupOnline(minimalApp, checkpointLedger, 5));
}
catchupSimulation.generateRandomLedger();
catchupSimulation.generateRandomLedger();
catchupSimulation.generateRandomLedger();
auto targetLedger = lm.getLastClosedLedgerNum();
REQUIRE(!catchupSimulation.catchupOnline(completeApp, targetLedger, 5));
REQUIRE(!catchupSimulation.catchupOnline(minimalApp, targetLedger, 5));
catchupSimulation.ensureOnlineCatchupPossible(targetLedger, 5);
REQUIRE(catchupSimulation.catchupOnline(completeApp, targetLedger, 5));
REQUIRE(catchupSimulation.catchupOnline(minimalApp, targetLedger, 5));
}
TEST_CASE("Repair missing buckets via history",
"[history][historybucketrepair]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1);
catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger);
HistoryArchiveState has(checkpointLedger + 1,
catchupSimulation.getBucketListAtLastPublish());
has.resolveAllFutures();
auto state = has.toString();
auto cfg = getTestConfig(1);
cfg.BUCKET_DIR_PATH += "2";
VirtualClock clock;
auto app = createTestApplication(
clock,
catchupSimulation.getHistoryConfigurator().configure(cfg, false));
app->getPersistentState().setState(PersistentState::kHistoryArchiveState,
state);
app->start();
catchupSimulation.crankUntil(
app, [&]() { return app->getWorkScheduler().allChildrenDone(); },
std::chrono::seconds(30));
auto hash1 = catchupSimulation.getBucketListAtLastPublish().getHash();
auto hash2 = app->getBucketManager().getBucketList().getHash();
REQUIRE(hash1 == hash2);
}
TEST_CASE("Repair missing buckets fails", "[history][historybucketrepair]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1);
catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger);
HistoryArchiveState has(checkpointLedger + 1,
catchupSimulation.getBucketListAtLastPublish());
has.resolveAllFutures();
auto state = has.toString();
auto dir = catchupSimulation.getHistoryConfigurator().getArchiveDirName();
REQUIRE(!dir.empty());
fs::deltree(dir + "/bucket");
auto cfg = getTestConfig(1);
VirtualClock clock;
cfg.BUCKET_DIR_PATH += "2";
auto app = createTestApplication(
clock,
catchupSimulation.getHistoryConfigurator().configure(cfg, false));
app->getPersistentState().setState(PersistentState::kHistoryArchiveState,
state);
REQUIRE_THROWS_AS(app->start(), std::runtime_error);
}
TEST_CASE("Publish catchup via s3", "[!hide][s3]")
{
CatchupSimulation catchupSimulation{
VirtualClock::VIRTUAL_TIME, std::make_shared<S3HistoryConfigurator>()};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger);
auto app = catchupSimulation.createCatchupApplication(
std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE,
"s3");
REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5));
}
TEST_CASE("persist publish queue", "[history]")
{
Config cfg(getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE));
cfg.MAX_CONCURRENT_SUBPROCESSES = 0;
cfg.ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING = true;
TmpDirHistoryConfigurator tcfg;
cfg = tcfg.configure(cfg, true);
{
VirtualClock clock;
Application::pointer app0 = createTestApplication(clock, cfg);
app0->start();
auto& hm0 = app0->getHistoryManager();
while (hm0.getPublishQueueCount() < 5)
{
clock.crank(true);
}
REQUIRE(hm0.getPublishSuccessCount() == 0);
REQUIRE(hm0.getMinLedgerQueuedToPublish() == 7);
while (clock.cancelAllEvents() ||
app0->getProcessManager().getNumRunningProcesses() > 0)
{
clock.crank(true);
}
LOG(INFO) << app0->isStopping();
ExternalQueue ps(*app0);
ps.deleteOldEntries(50000);
}
cfg.MAX_CONCURRENT_SUBPROCESSES = 32;
{
VirtualClock clock;
Application::pointer app1 = Application::create(clock, cfg, 0);
app1->getHistoryArchiveManager().initializeHistoryArchive("test");
for (size_t i = 0; i < 100; ++i)
clock.crank(false);
app1->start();
auto& hm1 = app1->getHistoryManager();
while (hm1.getPublishSuccessCount() < 5)
{
clock.crank(true);
ExternalQueue ps(*app1);
ps.deleteOldEntries(50000);
}
auto minLedger = hm1.getMinLedgerQueuedToPublish();
LOG(INFO) << "minLedger " << minLedger;
bool okQueue = minLedger == 0 || minLedger >= 35;
REQUIRE(okQueue);
clock.cancelAllEvents();
while (clock.cancelAllEvents() ||
app1->getProcessManager().getNumRunningProcesses() > 0)
{
clock.crank(true);
}
LOG(INFO) << app1->isStopping();
}
}
TEST_CASE("catchup with a gap", "[history][catchup][catchupstall]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
auto app = catchupSimulation.createCatchupApplication(
std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE,
"app2");
REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5));
checkpointLedger = catchupSimulation.getLastCheckpointLedger(2);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
auto init = app->getLedgerManager().getLastClosedLedgerNum() + 2;
REQUIRE(init == 73);
LOG(INFO) << "Starting catchup (with gap) from " << init;
REQUIRE(!catchupSimulation.catchupOnline(app, init, 5, init + 10));
REQUIRE(app->getLedgerManager().getLastClosedLedgerNum() == 82);
checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
CHECK(catchupSimulation.catchupOnline(app, checkpointLedger, 5));
}
TEST_CASE("Catchup recent", "[history][catchup][catchuprecent][!hide]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
auto dbMode = Config::TESTDB_IN_MEMORY_SQLITE;
std::vector<Application::pointer> apps;
std::vector<uint32_t> recents = {0, 1, 2, 31, 32, 33, 62, 63,
64, 65, 66, 126, 127, 128, 129, 130,
190, 191, 192, 193, 194, 1000};
for (auto r : recents)
{
auto name = std::string("catchup-recent-") + std::to_string(r);
auto app = catchupSimulation.createCatchupApplication(r, dbMode, name);
REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5));
apps.push_back(app);
}
checkpointLedger = catchupSimulation.getLastCheckpointLedger(5);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
for (auto const& app : apps)
{
REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5));
}
checkpointLedger = catchupSimulation.getLastCheckpointLedger(30);
catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5);
for (auto const& app : apps)
{
REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5));
}
}
TEST_CASE("Catchup manual", "[history][catchup][catchupmanual]")
{
CatchupSimulation catchupSimulation{};
auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(6);
catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger);
auto dbMode = Config::TESTDB_IN_MEMORY_SQLITE;
for (auto i = 0; i < viichain::gCatchupRangeCases.size(); i += 10)
{
auto test = viichain::gCatchupRangeCases[i];
auto configuration = test.second;
auto name =
fmt::format("lcl = {}, to ledger = {}, count = {}", test.first,
configuration.toLedger(), configuration.count());
LOG(INFO) << "Catchup configuration: " << name;
auto app = catchupSimulation.createCatchupApplication(
configuration.count(), dbMode, name);
REQUIRE(
catchupSimulation.catchupOffline(app, configuration.toLedger()));
}
}
TEST_CASE("initialize existing history store fails", "[history]")
{
Config cfg(getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE));
TmpDirHistoryConfigurator tcfg;
cfg = tcfg.configure(cfg, true);
{
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
REQUIRE(
app->getHistoryArchiveManager().initializeHistoryArchive("test"));
}
{
VirtualClock clock;
Application::pointer app = createTestApplication(clock, cfg);
REQUIRE(
!app->getHistoryArchiveManager().initializeHistoryArchive("test"));
}
}
| 37.889299
| 86
| 0.657674
|
viichain
|
58b78abae22bb807c6b62e0f412e727385b3c970
| 1,932
|
cpp
|
C++
|
tests/track/pointer.cpp
|
lexxmark/ref_ptr
|
526e1c9a96a83de8d7290ca6fc72616681135079
|
[
"Apache-2.0"
] | 3
|
2017-04-04T16:45:22.000Z
|
2019-09-01T14:26:16.000Z
|
tests/track/pointer.cpp
|
lexxmark/ref_ptr
|
526e1c9a96a83de8d7290ca6fc72616681135079
|
[
"Apache-2.0"
] | null | null | null |
tests/track/pointer.cpp
|
lexxmark/ref_ptr
|
526e1c9a96a83de8d7290ca6fc72616681135079
|
[
"Apache-2.0"
] | 2
|
2019-11-19T21:58:22.000Z
|
2021-09-08T00:32:18.000Z
|
#include <UnitTest++/UnitTest++.h>
#define RSL_NULL_PTR_POLICY_DEFAULT(T) rsl::track::may_be_null<T>
#define RSL_ON_DANGLE_POLICY_DEFAULT(T) rsl::track::null_on_dangle<T>
#include <track/pointer.h>
SUITE(track_ptr_tests)
{
using namespace rsl::track;
TEST(basic_test)
{
trackable object;
{
auto p = make_ptr(&object);
CHECK(p);
CHECK_EQUAL(4*sizeof(void*), sizeof(p));
}
}
TEST(null_track_ptr_test)
{
{
pointer<char> p;
CHECK(!p);
}
{
pointer<int> ptr = nullptr;
CHECK(!ptr);
}
}
TEST(null_make_track_ptr_test)
{
{
auto ptr = make_ptr<int>(nullptr);
CHECK(!ptr);
}
{
trackable object;
auto ptr = make_ptr<int>(nullptr, object);
CHECK(!ptr);
}
{
trackable* object = nullptr;
auto ptr = make_ptr(object);
CHECK(!ptr);
}
}
TEST(check_track_ptr_after_delete_test)
{
auto object = std::make_unique<trackable>();
auto ptr = make_ptr(object.get());
CHECK(ptr);
object.reset();
CHECK(!ptr);
}
TEST(three_track_ptrs_test)
{
trackable object;
{
auto ptr1 = make_ptr(&object);
CHECK(ptr1);
{
auto ptr2 = make_ptr(&object);
CHECK(ptr2);
{
auto ptr3 = make_ptr(&object);
CHECK(ptr3);
}
CHECK(ptr2);
}
CHECK(ptr1);
}
}
TEST(copy_objects_test)
{
trackable object1;
auto ptr1 = make_ptr(&object1);
{
pointer<trackable> ptr2;
{
auto object2 = object1;
ptr2 = make_ptr(&object2, object2);
CHECK(ptr1);
CHECK(ptr2);
}
CHECK(ptr1);
CHECK(!ptr2);
}
CHECK(ptr1);
}
TEST(sub_object_test)
{
struct Object : public trackable
{
int i = 0;
};
Object object;
auto ptr1 = make_ptr(&object);
auto ptr2 = make_ptr(&object.i, object);
CHECK_EQUAL(0, ptr1->i);
CHECK_EQUAL(0, *ptr2);
ptr1->i = 1;
CHECK_EQUAL(1, object.i);
CHECK_EQUAL(1, *ptr2);
*ptr2 = 2;
CHECK_EQUAL(2, object.i);
CHECK_EQUAL(2, ptr1->i);
}
}
| 14.41791
| 69
| 0.613872
|
lexxmark
|
58bd16a0451473f7dfc3da70c4f56941b51add8d
| 1,748
|
hpp
|
C++
|
src/driver_authenticator.hpp
|
simwijs/naoqi_driver
|
89b00459dc517f8564b1d7092eb36a3fc68a7096
|
[
"Apache-2.0"
] | null | null | null |
src/driver_authenticator.hpp
|
simwijs/naoqi_driver
|
89b00459dc517f8564b1d7092eb36a3fc68a7096
|
[
"Apache-2.0"
] | null | null | null |
src/driver_authenticator.hpp
|
simwijs/naoqi_driver
|
89b00459dc517f8564b1d7092eb36a3fc68a7096
|
[
"Apache-2.0"
] | null | null | null |
/*
* Copyright 2015 Aldebaran
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#ifndef DRIVER_AUTHENTICATOR_HPP
#define DRIVER_AUTHENTICATOR_HPP
#include <qi/messaging/authprovider.hpp>
namespace naoqi {
class DriverAuthenticator : public qi::ClientAuthenticator {
public:
static const std::string user_key;
static const std::string pass_key;
DriverAuthenticator(
const std::string& user,
const std::string& pass) : _u(user), _p(pass) {}
qi::CapabilityMap initialAuthData() {
qi::CapabilityMap result;
result[DriverAuthenticator::user_key] = qi::AnyValue::from(_u);
result[DriverAuthenticator::pass_key] = qi::AnyValue::from(_p);
return result;
}
qi::CapabilityMap _processAuth(const qi::CapabilityMap&) {
return qi::CapabilityMap();
}
private:
std::string _u;
std::string _p;
};
const std::string DriverAuthenticator::user_key = "user";
const std::string DriverAuthenticator::pass_key = "token";
class DriverAuthenticatorFactory : public qi::ClientAuthenticatorFactory {
public:
std::string user;
std::string pass;
qi::ClientAuthenticatorPtr newAuthenticator() {
return boost::make_shared<DriverAuthenticator>(user, pass);
}
};
}
#endif // DRIVER_AUTHENTICATOR
| 27.3125
| 75
| 0.735126
|
simwijs
|
58bfd1e86ade32425829d201cf5f15563df29400
| 995
|
cpp
|
C++
|
TextDungeon/TextDungeon/Audio.cpp
|
Consalv0/TextDungeon
|
cabceee081745cc52801efc8b9c10268412578c8
|
[
"MIT"
] | null | null | null |
TextDungeon/TextDungeon/Audio.cpp
|
Consalv0/TextDungeon
|
cabceee081745cc52801efc8b9c10268412578c8
|
[
"MIT"
] | null | null | null |
TextDungeon/TextDungeon/Audio.cpp
|
Consalv0/TextDungeon
|
cabceee081745cc52801efc8b9c10268412578c8
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "Audio.h"
// Play the notes in a song.
void Audio::Play(array<Note>^ tune) {
System::Collections::IEnumerator^ myEnum = tune->GetEnumerator();
while (myEnum->MoveNext()) {
Note n = *safe_cast<Note ^>(myEnum->Current);
if (n.NoteTone == Tone::REST)
Thread::Sleep((int)n.NoteDuration);
else
Console::Beep((int)n.NoteTone, (int)n.NoteDuration);
}
}
void Audio::MainTheme() {
// Declare the first few notes of the song, "Mary Had A Little Lamb".
array<Note>^ Mary = { Note(Tone::C, Duration::QUARTER),Note(Tone::B, Duration::QUARTER),Note(Tone::GbelowC, Duration::QUARTER),Note(Tone::B, Duration::QUARTER),Note(Tone::C, Duration::QUARTER),Note(Tone::C, Duration::QUARTER),Note(Tone::C, Duration::HALF),Note(Tone::B, Duration::QUARTER),Note(Tone::B, Duration::QUARTER),Note(Tone::B, Duration::HALF),Note(Tone::C, Duration::QUARTER),Note(Tone::E, Duration::QUARTER),Note(Tone::E, Duration::HALF) };
// Play the song
Play(Mary);
}
| 45.227273
| 452
| 0.674372
|
Consalv0
|
58c2e888e4de6793a9dc0157cf9b5f4eb7b98680
| 1,933
|
hpp
|
C++
|
external/pss/include/rantala/tools/insertion_sort.hpp
|
kurpicz/dsss
|
ac50a22b1beec1d8613a6cd868798426352305c8
|
[
"BSD-2-Clause"
] | 3
|
2018-10-24T22:15:17.000Z
|
2019-09-21T22:56:05.000Z
|
external/pss/include/rantala/tools/insertion_sort.hpp
|
kurpicz/dsss
|
ac50a22b1beec1d8613a6cd868798426352305c8
|
[
"BSD-2-Clause"
] | null | null | null |
external/pss/include/rantala/tools/insertion_sort.hpp
|
kurpicz/dsss
|
ac50a22b1beec1d8613a6cd868798426352305c8
|
[
"BSD-2-Clause"
] | null | null | null |
/*
* Copyright 2007-2008 by Tommi Rantala <tt.rantala@gmail.com>
*
* 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.
*/
#pragma once
namespace rantala {
static inline int
cmp(const unsigned char* a, const unsigned char* b)
{
assert(a != 0);
assert(b != 0);
return strcmp(reinterpret_cast<const char*>(a),
reinterpret_cast<const char*>(b));
}
static inline void
insertion_sort(unsigned char** strings, int n, size_t depth)
{
for (unsigned char** i = strings + 1; --n > 0; ++i) {
unsigned char** j = i;
unsigned char* tmp = *i;
while (j > strings) {
unsigned char* s = *(j-1)+depth;
unsigned char* t = tmp+depth;
while (*s == *t and not is_end(*s)) {
++s;
++t;
}
if (*s <= *t) break;
*j = *(j-1);
--j;
}
*j = tmp;
}
}
static inline void
insertion_sort(unsigned char** strings, size_t n)
{ insertion_sort(strings, n, 0); }
} // namespace rantala
| 31.177419
| 79
| 0.694775
|
kurpicz
|
58c3fbf3ae0847cd1840a0026566255648e30af6
| 4,978
|
cpp
|
C++
|
src/design_editor/Settings.cpp
|
TheMrButcher/opengl_lessons
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | 1
|
2016-10-25T21:15:16.000Z
|
2016-10-25T21:15:16.000Z
|
src/design_editor/Settings.cpp
|
TheMrButcher/gamebase
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | 375
|
2016-06-04T11:27:40.000Z
|
2019-04-14T17:11:09.000Z
|
src/design_editor/Settings.cpp
|
TheMrButcher/gamebase
|
76ac96c45773a54a85d49c6994770b0c3496303f
|
[
"MIT"
] | null | null | null |
/**
* Copyright (c) 2018 Slavnejshev Filipp
* This file is licensed under the terms of the MIT license.
*/
#include "Settings.h"
#include "Presentation.h"
#include <gamebase/impl/app/Config.h>
#include <gamebase/text/StringUtils.h>
#include <json/reader.h>
#include <json/writer.h>
namespace gamebase { namespace editor { namespace settings {
bool isInterfaceExtended = false;
std::string workDir;
std::string imagesDir;
std::string soundsDir;
std::string musicDir;
std::string mainConf;
std::string designedObjConf;
bool isBackupEnabled;
bool isComplexBoxMode;
namespace {
bool complexLayerMode;
bool complexAnimationMode;
}
bool isComplexLayerMode()
{
return complexLayerMode;
}
void setComplexLayerMode(bool value)
{
complexLayerMode = value;
if (complexLayerMode) {
presentationForDesignView()->setPropertyBaseType(
"ImmobileLayer", "list", "");
presentationForDesignView()->setPropertyBaseType(
"GameView", "list", "");
} else {
presentationForDesignView()->setPropertyBaseType(
"ImmobileLayer", "list", "ObjectConstruct");
presentationForDesignView()->setPropertyBaseType(
"GameView", "list", "Layer");
}
}
bool isComplexAnimationMode()
{
return complexAnimationMode;
}
void setComplexAnimationMode(bool value)
{
complexAnimationMode = value;
if (complexAnimationMode) {
presentationForDesignView()->setPropertyBaseType(
"AnimatedObject", "animations", "");
presentationForDesignView()->setPropertyBaseType(
"CompositeAnimation", "animations", "");
presentationForDesignView()->setPropertyBaseType(
"ParallelAnimation", "animations", "");
presentationForDesignView()->setPropertyBaseType(
"RepeatingAnimation", "animation", "");
presentationForDesignView()->setPropertyBaseType(
"AnimatedCheckBoxSkin", "checkAnimation", "");
presentationForDesignView()->setPropertyBaseType(
"AnimatedCheckBoxSkin", "uncheckAnimation", "");
presentationForDesignView()->setPropertyBaseType(
"AnimatedObjectConstruct", "animations", "");
}
else {
presentationForDesignView()->setPropertyBaseType(
"AnimatedObject", "animations", "BasicAnimation");
presentationForDesignView()->setPropertyBaseType(
"CompositeAnimation", "animations", "BasicAnimation");
presentationForDesignView()->setPropertyBaseType(
"ParallelAnimation", "animations", "BasicAnimation");
presentationForDesignView()->setPropertyBaseType(
"RepeatingAnimation", "animation", "BasicAnimation");
presentationForDesignView()->setPropertyBaseType(
"AnimatedCheckBoxSkin", "checkAnimation", "BasicAnimation");
presentationForDesignView()->setPropertyBaseType(
"AnimatedCheckBoxSkin", "uncheckAnimation", "BasicAnimation");
presentationForDesignView()->setPropertyBaseType(
"AnimatedObjectConstruct", "animations", "BasicAnimation");
}
}
void init()
{
isInterfaceExtended = impl::getValueFromConfig("interface", "basic") == "extended";
workDir = impl::getValueFromConfig("workingPath", ".");
imagesDir = impl::getValueFromConfig("designedObjectImagesPath", impl::getValueFromConfig("imagesPath"));
soundsDir = impl::getValueFromConfig("soundsPath", addSlash(imagesDir) + "..\\sounds\\");
musicDir = impl::getValueFromConfig("musicPath", addSlash(imagesDir) + "..\\music\\");
isBackupEnabled = impl::getValueFromConfig("isBackupEnabled", "true") == "true";
isComplexBoxMode = impl::getValueFromConfig("isComplexBoxMode", "false") == "true";
setComplexLayerMode(impl::getValueFromConfig("isComplexLayerMode", "false") == "true");
setComplexAnimationMode(impl::getValueFromConfig("isComplexAnimationMode", "false") == "true");
mainConf = impl::configAsString();
formDesignedObjConfig();
}
void formMainConfig(int width, int height, impl::GraphicsMode::Enum mode)
{
Json::Value conf;
Json::Reader r;
r.parse(mainConf, conf);
conf["version"] = "VER3";
conf["workingPath"] = workDir;
conf["designedObjectImagesPath"] = imagesDir;
conf["soundsPath"] = soundsDir;
conf["musicPath"] = musicDir;
conf["width"] = width;
conf["height"] = height;
conf["mode"] = mode == impl::GraphicsMode::Window ? std::string("window") : std::string("fullscreen");
conf["isBackupEnabled"] = isBackupEnabled;
conf["isComplexBoxMode"] = isComplexBoxMode;
conf["isComplexLayerMode"] = isComplexLayerMode();
conf["isComplexAnimationMode"] = isComplexAnimationMode();
Json::StyledWriter w;
mainConf = w.write(conf);
}
void formDesignedObjConfig()
{
Json::Value conf;
Json::Reader r;
r.parse(mainConf, conf);
conf["imagesPath"] = imagesDir;
Json::FastWriter w;
designedObjConf = w.write(conf);
}
} } }
| 34.331034
| 109
| 0.684813
|
TheMrButcher
|
58cd1f4e7274498d12e2a00f4fb69ba75193e758
| 1,886
|
cpp
|
C++
|
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_Asap_Regular_18_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_Asap_Regular_18_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_Asap_Regular_18_4bpp.cpp
|
ramkumarkoppu/NUCLEO-F767ZI-ESW
|
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
|
[
"MIT"
] | null | null | null |
#include <touchgfx/Font.hpp>
#ifndef NO_USING_NAMESPACE_TOUCHGFX
using namespace touchgfx;
#endif
FONT_LOCATION_FLASH_PRAGMA
KEEP extern const touchgfx::GlyphNode glyphs_Asap_Regular_18_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE =
{
{ 0, 32, 0, 0, 0, 0, 4, 255, 0, 0},
{ 0, 65, 11, 13, 13, 0, 11, 255, 0, 0},
{ 72, 66, 10, 13, 13, 1, 11, 255, 0, 0},
{ 137, 70, 8, 13, 13, 1, 9, 255, 0, 0},
{ 189, 71, 10, 13, 13, 1, 12, 255, 0, 0},
{ 254, 76, 8, 13, 13, 1, 9, 255, 0, 0},
{ 306, 79, 12, 13, 13, 1, 13, 255, 0, 0},
{ 384, 83, 9, 13, 13, 0, 9, 255, 0, 0},
{ 443, 84, 10, 13, 13, 0, 10, 255, 0, 0},
{ 508, 88, 11, 13, 13, 0, 11, 255, 0, 0},
{ 580, 97, 9, 10, 10, 0, 10, 255, 0, 0},
{ 625, 98, 9, 14, 14, 1, 10, 255, 0, 0},
{ 688, 99, 9, 10, 10, 0, 9, 255, 0, 0},
{ 733, 100, 9, 14, 14, 0, 10, 255, 0, 0},
{ 796, 101, 9, 10, 10, 0, 10, 255, 0, 0},
{ 841, 103, 10, 14, 10, 0, 10, 255, 0, 0},
{ 911, 104, 8, 14, 14, 1, 10, 255, 0, 0},
{ 967, 105, 3, 14, 14, 1, 5, 255, 0, 0},
{ 988, 108, 5, 14, 14, 1, 5, 255, 0, 0},
{ 1023, 109, 13, 10, 10, 1, 15, 255, 0, 0},
{ 1088, 110, 8, 10, 10, 1, 10, 255, 0, 0},
{ 1128, 111, 10, 10, 10, 0, 10, 255, 0, 0},
{ 1178, 112, 9, 14, 10, 1, 10, 255, 0, 0},
{ 1241, 114, 6, 10, 10, 1, 7, 255, 0, 0},
{ 1271, 115, 7, 10, 10, 0, 7, 255, 0, 0},
{ 1306, 116, 6, 13, 13, 0, 6, 255, 0, 0},
{ 1345, 117, 8, 10, 10, 1, 10, 255, 0, 0},
{ 1385, 118, 9, 10, 10, 0, 9, 255, 0, 0},
{ 1430, 121, 9, 14, 10, 0, 9, 255, 0, 0}
};
| 44.904762
| 99
| 0.389183
|
ramkumarkoppu
|
58d884e94c43d12a08a34f33a92387ac0233dc97
| 899
|
cpp
|
C++
|
Ch09/date_941.cpp
|
rzotya0327/UDProg-Introduction
|
c64244ee541d4ad0c85645385ef4f0c2e1886621
|
[
"CC0-1.0"
] | null | null | null |
Ch09/date_941.cpp
|
rzotya0327/UDProg-Introduction
|
c64244ee541d4ad0c85645385ef4f0c2e1886621
|
[
"CC0-1.0"
] | null | null | null |
Ch09/date_941.cpp
|
rzotya0327/UDProg-Introduction
|
c64244ee541d4ad0c85645385ef4f0c2e1886621
|
[
"CC0-1.0"
] | null | null | null |
#include "std_lib_facilities.h"
struct Date
{
int y;
int m;
int d;
};
Date today;
Date tomorrow;
void init_day(Date& date, int y, int m, int d)
{
if (y > 0)
date.y = y;
else
error("Invalid year");
if (m <= 12 && m > 0)
date.m = m; //ekkor valid, felveheti az értéket
else
error("Invalid month");
if (d > 0 && d <=31)
date.d = d;
else
error("Invalid day");
}
void add_day(Date& dd, int n)
{
dd.d += n;
if (dd.d > 31);
}
ostream& operator<<(ostream& os, const Date& d)
{
return os << '(' << d.y
<< ',' << d.m
<< ',' << d.d << ')';
}
int main()
try {
Date today;
init_day(today, 1978, 6, 25);
Date tomorrow = today;
add_day(tomorrow, 1);
cout << "Today: " << today << endl;
cout << "Tomorrow: " << tomorrow << endl;
//Date bad_day;
//init_day(bad_day, 2004, 13, -5);
return 0;
} catch (exception& e) {
cout << e.what() << endl;
return 1;
}
| 14.5
| 54
| 0.549499
|
rzotya0327
|
58da56970c2661321a3644370d00a59248fcd730
| 1,092
|
cpp
|
C++
|
Engine/Source/Editor/SandboxApp.cpp
|
douysu/Sudou
|
23286e22a96814863ee55c6e2b5cc67be18acba9
|
[
"Apache-2.0"
] | 3
|
2022-01-07T01:09:06.000Z
|
2022-01-21T03:11:33.000Z
|
Engine/Source/Editor/SandboxApp.cpp
|
douysu/Sudou
|
23286e22a96814863ee55c6e2b5cc67be18acba9
|
[
"Apache-2.0"
] | null | null | null |
Engine/Source/Editor/SandboxApp.cpp
|
douysu/Sudou
|
23286e22a96814863ee55c6e2b5cc67be18acba9
|
[
"Apache-2.0"
] | null | null | null |
#include "Runtime/Core/Application.h"
#include "Runtime/Core/EntryPoint.h"
#include "Runtime/GUI/ImGuiLayer.h"
#include "Runtime/Core/Input.h"
#include "Runtime/Core/KeyCodes.h"
#include "Runtime/Core/MouseButtonCodes.h"
#include "imgui/imgui.h"
class ExampleLayer : public Sudou::Layer
{
public:
ExampleLayer() : Layer("Example") {}
void OnUpdate() override
{
if (Sudou::Input::IsKeyPressed(SD_KEY_TAB))
{
SD_TRACE("Tab key is pressed (poll)");
}
}
void OnEvent(Sudou::Event& event) override
{
if (event.GetEventType() == Sudou::EventType::KeyPressed)
{
Sudou::KeyPressedEvent& e = (Sudou::KeyPressedEvent&)event;
if (e.GetKeyCode() == SD_KEY_TAB)
SD_TRACE("Tab key is pressed (event)");
SD_TRACE("{0}", (char)e.GetKeyCode());
}
}
virtual void OnImGuiRender() override
{
ImGui::Begin("Test");
ImGui::Text("Hello Sudou!");
ImGui::End();
}
};
class Sandbox : public Sudou::Application
{
public:
Sandbox()
{
PushLayer(new ExampleLayer());
}
~Sandbox()
{
}
};
Sudou::Application* Sudou::CreateApplication()
{
return new Sandbox();
}
| 18.508475
| 62
| 0.675824
|
douysu
|
58dc8c5933254d81e8ba484a0dbff92210c644f3
| 784
|
cpp
|
C++
|
data/dailyCodingProblem774.cpp
|
vidit1999/daily_coding_problem
|
b90319cb4ddce11149f54010ba36c4bd6fa0a787
|
[
"MIT"
] | 2
|
2020-09-04T20:56:23.000Z
|
2021-06-11T07:42:26.000Z
|
data/dailyCodingProblem774.cpp
|
vidit1999/daily_coding_problem
|
b90319cb4ddce11149f54010ba36c4bd6fa0a787
|
[
"MIT"
] | null | null | null |
data/dailyCodingProblem774.cpp
|
vidit1999/daily_coding_problem
|
b90319cb4ddce11149f54010ba36c4bd6fa0a787
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
/*
Using a read7() method that returns 7 characters from a file,
implement readN(n) which reads n characters.
For example, given a file with the content “Hello world”,
three read7() returns “Hello w”, “orld” and then “”.
*/
int index;
string read7(string& s){
string ans = "";
int count = 7;
while(index < s.length() && count--){
ans.push_back(s[index++]);
}
return ans;
}
string readN(string s, int n){
string ans = "";
int count = 0;
while(count < n){
string r = read7(s);
if(r.empty())
break;
for(int i=0; i<r.length() && count<n; i++, count++){
ans.push_back(r[i]);
}
}
return ans;
}
// main function
int main(){
index = 0;
string s = "Hello world";
cout << readN(s, 17) << "\n";
return 0;
}
| 15.68
| 61
| 0.609694
|
vidit1999
|
58dce8362c760d85774b75d402d8c3dae2cf69fa
| 3,434
|
cpp
|
C++
|
main.cpp
|
aszecsei/kestrel_compiler
|
3b592c77042f534ee725d076701800d5ad19318c
|
[
"MIT"
] | null | null | null |
main.cpp
|
aszecsei/kestrel_compiler
|
3b592c77042f534ee725d076701800d5ad19318c
|
[
"MIT"
] | null | null | null |
main.cpp
|
aszecsei/kestrel_compiler
|
3b592c77042f534ee725d076701800d5ad19318c
|
[
"MIT"
] | null | null | null |
/* main.c -- main program for a Kestrel compiler */
/* Author: Douglas W. Jones
* Date 9/30/2016 -- code from lecture 17 with pro-forma comment changes
*/
#include "main.h"
#include "environment.h"
#include "lexical.h"
#include "block.h"
#include "program.h"
const char* main_infile;
const char* main_outfile;
int main( int argc, char * argv[] ) {
bool isinfile = false; /* has the input file been specified? */
bool isoutfile = false; /* has the output file been specified? */
int i; /* indexing the argument number in argv */
/* first, deal with the program name */
LogHandler::programName = DEFAULT_NAME;
if ((argc > 0) /* Unix/Linux shells guarantee this */
&& (argv[0] != NULL) /* Unix/Linux implies this */
&& (argv[0][0] != '\0')) { /* but nonstarndard exec could do this */
LogHandler::programName = argv[0];
}
/* assert: program name is now well defined */
/* set argument strings to indicate that they have not been set */
main_infile = NULL; /* this means read from stdin */
main_outfile = "a.s"; /* write to stdout */
/* then deal with the command line arguments */
i = 1; /* start with the argument after the program name */
while ((i < argc) && (argv[i] != NULL)) { /* for each arg */
const char * arg = argv[i]; /* this argument */
char ch = *arg; /* first char of this argument */
if ( ch == '\0' ) {
/* ignore empty argument strings */
} else if ( ch != DASH ) {
/* arg not starting with dash is the input file name */
if (isinfile) { /* too many input files given */
Log::Fatal(ER_EXTRAINFILE);
} else
main_infile = arg;
isinfile = true;
} else {
/* command line -option */
arg++; /* strip skip over the leading dash */
ch = *arg; /* first char of argument */
if (ch == '\0') { /* - by itself */
/* ... meaning read stdin */
if (isinfile) { /* input files already given */
Log::Fatal(ER_EXTRAINFILE);
}
isinfile = true;
} else if (ch == 'o') {
/* -o outfile or -o=outfile or -ooutfile */
if (isoutfile) { /* too many files */
Log::Fatal(ER_EXTRAOUTFILE);
}
arg++; /* strip off the letter o */
ch = *arg;
if (ch == '\0') { /* -o filename */
i = i + 1;
if ((i > argc) && (argv[i] != NULL)) {
Log::Fatal(ER_MISSINGFILE);
}
/* =BUG= what about -o - */
main_outfile = argv[i];
isoutfile = true;
} else { /* -ofilename or -o=filename */
if (ch == '=') {
arg++; /* strip off the = */
ch = *arg;
}
if (ch == '\0') {
Log::Error(ER_MISSINGFILE);
}
/* =BUG= what about -o- and -o=- */
main_outfile = arg;
isoutfile = true;
}
/* put code to parse other options here */
} else if (!strcmp( arg, "help" )) { /* -help */
LogHandler::ProgramHelp();
} else if (!strcmp( arg, "?" )) { /* -? means help */
LogHandler::ProgramHelp();
} else if (ch == 'v') {
LogHandler::verbosity = Log::DEBUG;
} else {
Log::Fatal(ER_BADARG);
}
}
i++; /* advance to the next argument */
}
/* now, we have the textual file names */
if ((!isoutfile)) { /* compute main_outfile */
lex_open( strdup(main_infile) );
Program * p = Program::compile(std::string(main_infile), std::string(main_outfile));
lex_close();
}
/* =BUG= must call initializers for major subsystems */
}
| 27.918699
| 96
| 0.562609
|
aszecsei
|
58dee9dad1c5a50edebdcbad1dfeb8178d6a2e38
| 2,993
|
cpp
|
C++
|
traces/trace_maker.cpp
|
umn-cris/MQSim
|
0c103c0a0fb0aee8d8f30e5bbbfb9224c1d6cb8d
|
[
"MIT"
] | null | null | null |
traces/trace_maker.cpp
|
umn-cris/MQSim
|
0c103c0a0fb0aee8d8f30e5bbbfb9224c1d6cb8d
|
[
"MIT"
] | null | null | null |
traces/trace_maker.cpp
|
umn-cris/MQSim
|
0c103c0a0fb0aee8d8f30e5bbbfb9224c1d6cb8d
|
[
"MIT"
] | null | null | null |
#include <string>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <time.h>
using namespace std;
const unsigned int sector_size_in_bytes = 512;
const unsigned int zone_size_MB = 256;
unsigned int smallest_zone_number = 2;
unsigned int biggest_zone_number = 14;
unsigned int total_size_of_accessed_file_in_GB = 1;
unsigned int total_no_of_request = 10000;
int main(int argc, char** argv) {
cout << "This generates a sequential write requets." << endl;
unsigned int request_size_in_KB = 8;
cout << "please enter the request size in KB : ";
scanf("%u", &request_size_in_KB);
cout << "please enter the smallest zone number : ";
scanf("%u", &smallest_zone_number);
cout << "please enter the whole file size to be accessed in GB : ";
scanf("%u", &total_size_of_accessed_file_in_GB);
string outputfile = "sequential_write_" + to_string(request_size_in_KB)+ "KB_from_zone" \
+ to_string(smallest_zone_number) + "_" + to_string(total_size_of_accessed_file_in_GB) + "GB";
cout << "output file name is " << outputfile << endl;
srand(time(NULL));
ofstream writeFile;
writeFile.open(outputfile);
string trace_line = "";
//cout << "request size is " << request_size_in_KB << " KB" << endl;
total_no_of_request = total_size_of_accessed_file_in_GB * 1024 * 1024 / request_size_in_KB;
cout << "total number of requests is " << total_no_of_request << endl;
unsigned long long int first_arrival_time = 4851300;
unsigned long long int first_start_LBA = smallest_zone_number * 512 * 1024; //256 * 1024 * 1024 / 512; == 256 MB / 512 B
// |---------512 byte-------||---------512 byte-------|
// LBA : 1 2
string arrival_time;
string start_LBA;
string device_number;
string request_size_in_sector;
string type_of_request;
unsigned long long int prev_arrival_time = first_arrival_time;
unsigned long long int prev_start_LBA = first_start_LBA;
for (int i = 0; i < total_no_of_request; i++) {
arrival_time = to_string(prev_arrival_time);
start_LBA = to_string(prev_start_LBA);
device_number = "1";
request_size_in_sector = to_string(request_size_in_KB * 2); // 2 == 1024 / sector_size_in_bytes
type_of_request = "0"; // 0 means that it's a write reqeust, read request is "1"
trace_line = arrival_time + " " + device_number + " " + start_LBA + " " + request_size_in_sector + " " + type_of_request + "\n";
writeFile.write(trace_line.c_str(), trace_line.size());
trace_line.clear();
//sscanf(arrival_time.c_str(), "%llu", &prev_arrival_time);
//sscanf(start_LBA.c_str(), "%llu", &prev_start_LBA);
prev_arrival_time = prev_arrival_time + ((rand() % 15) * 1000);
prev_start_LBA = prev_start_LBA + request_size_in_KB * 2; // 2 == 1024 / sector_size_in_bytes;
}
writeFile.close();
return 0;
}
| 38.87013
| 136
| 0.657534
|
umn-cris
|
58e0235318b844ba7b585f2fd9bc8dbb65a78e8f
| 13,528
|
cc
|
C++
|
code/render/physics/havok/havokscene.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 67
|
2015-03-30T19:56:16.000Z
|
2022-03-11T13:52:17.000Z
|
code/render/physics/havok/havokscene.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 5
|
2015-04-15T17:17:33.000Z
|
2016-02-11T00:40:17.000Z
|
code/render/physics/havok/havokscene.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 34
|
2015-03-30T15:08:00.000Z
|
2021-09-23T05:55:10.000Z
|
//------------------------------------------------------------------------------
// havokscene.cc
// (C) 2013-2014 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "physics/scene.h"
#include "physics/filterset.h"
#include "physics/physicsserver.h"
#include "physics/physicsbody.h"
#include "physics/visualdebuggerserver.h"
#include "physics/character.h"
#include "physics/model/templates.h"
#include "havokcharacterrigidbody.h"
#include "conversion.h"
#include "havokutil.h"
#include <Physics2012/Dynamics/World/hkpWorld.h>
#include <Physics2012/Collide/Dispatch/hkpAgentRegisterUtil.h>
#include <Physics2012/Dynamics/Entity/hkpRigidBody.h>
#include <Physics2012/Collide/Query/CastUtil/hkpWorldRayCastInput.h>
#include <Physics2012/Collide/Shape/hkpShapeBase.h>
#include <Physics2012/Collide/Query/Collector/RayCollector/hkpClosestRayHitCollector.h>
#include <Physics2012/Dynamics/Collide/Filter/Pair/hkpPairCollisionFilter.h>
#include <Physics2012/Collide/Query/Collector/RayCollector/hkpAllRayHitCollector.h>
#include <Physics2012/Collide/Shape/Convex/Sphere/hkpSphereShape.h>
#include <Physics2012/Collide/Shape/Convex/Box/hkpBoxShape.h>
#include <Physics2012/Collide/Agent/Query/hkpCdBodyPairCollector.h>
#include <Physics2012/Collide/Agent/Collidable/hkpCollidable.h>
#include <Physics2012/Collide/Query/Collector/BodyPairCollector/hkpAllCdBodyPairCollector.h>
#include <Physics2012/Collide/Agent/hkpProcessCollisionInput.h>
#include <Physics2012/Collide/Filter/Group/hkpGroupFilter.h>
#include <Physics2012/Collide/Filter/Group/hkpGroupFilterSetup.h>
using namespace Physics;
using namespace Math;
namespace Havok
{
__ImplementClass(Havok::HavokScene,'HKSC', Physics::BaseScene);
//------------------------------------------------------------------------------
/**
*/
HavokScene::HavokScene():
initialized(false),
lastFrame(-1)
{
this->world = 0;
}
//------------------------------------------------------------------------------
/**
*/
HavokScene::~HavokScene()
{
this->world = 0;
this->filter = 0;
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::RenderDebug()
{
IndexT i;
for (i = 0; i < this->objects.Size() ; i++)
{
this->objects[i]->RenderDebug();
}
}
//------------------------------------------------------------------------------
/**
*/
Util::Array<Ptr<Contact>>
HavokScene::RayCheck(const Math::vector& pos, const Math::vector& dir, const FilterSet& excludeSet, BaseScene::RayTestType rayType)
{
n_assert(this->IsInitialized());
hkVector4 position = Neb2HkFloat4(pos);
hkVector4 direction = Neb2HkFloat4(dir);
hkVector4 targetPoint;
targetPoint.setAdd(position, direction);
hkpWorldRayCastInput rayCastInput;
rayCastInput.m_enableShapeCollectionFilter = true;
rayCastInput.m_filterInfo = (int)Math::n_log2(Physics::Picking) /*FIXME*/;
rayCastInput.m_from = position;
rayCastInput.m_to = targetPoint;
hkArray<hkpWorldRayCastOutput> hits;
if (Test_Closest == rayType)
{
hkpClosestRayHitCollector collector;
this->world->castRay(rayCastInput, collector);
if(collector.hasHit())
{
hkpWorldRayCastOutput hit = collector.getHit();
hits.pushBack(hit);
}
}
else
{
hkpAllRayHitCollector collector;
this->world->castRay(rayCastInput, collector);
hits = collector.getHits();
}
Util::Array<Ptr<Contact>> contacts;
IndexT i;
for (i = 0; i < hits.getSize(); i++)
{
const hkpWorldRayCastOutput& hit = hits[i];
if (HK_NULL == hit.m_rootCollidable)
{
continue;
}
// get the nebula physicsobject from the entity
void* owner = hit.m_rootCollidable->getOwner();
hkpWorldObject* entity = (hkpWorldObject*)owner;
n_assert(0 != entity);
hkUlong userData = entity->getUserData();
HavokUtil::CheckWorldObjectUserData(userData);
Ptr<PhysicsObject> physObject = (PhysicsObject*)userData;
if (excludeSet.CheckObject(physObject))
{
continue;
}
Ptr<Contact> contact = Contact::Create();
contact->SetCollisionObject(physObject);
contact->SetMaterial(physObject->GetMaterialType());
contact->SetType(Contact::RayCheck);
contact->SetNormalVector(Hk2NebFloat4(hit.m_normal));
contact->SetPoint(pos + (dir * hit.m_hitFraction));
contacts.Append(contact);
if (Test_Closest == rayType)
{
break;
}
}
return contacts;
}
//------------------------------------------------------------------------------
/**
*/
Ptr<Contact>
HavokScene::GetClosestContactUnderMouse(const Math::line& worldMouseRay, const FilterSet& excludeSet)
{
Util::Array<Ptr<Contact>> contacts = this->RayCheck(worldMouseRay.b, worldMouseRay.m, excludeSet, Test_Closest);
if (contacts.IsEmpty())
{
return 0;
}
return contacts[0];
}
//------------------------------------------------------------------------------
/**
*/
Ptr<Contact>
HavokScene::GetClosestContactAlongRay(const Math::vector& pos, const Math::vector& dir, const FilterSet& excludeSet)
{
Util::Array<Ptr<Contact>> contacts = this->RayCheck(pos, dir, excludeSet, Test_Closest);
if (contacts.IsEmpty())
{
return 0;
}
return contacts[0];
}
//------------------------------------------------------------------------------
/**
*/
bool
HavokScene::ApplyImpulseAlongRay(const Math::vector& pos, const Math::vector& dir, const FilterSet& excludeSet, float impulse)
{
Util::Array<Ptr<Contact>> contacts = this->RayCheck(pos, dir, excludeSet, Test_All);
bool hitValidTarget = false;
IndexT i;
for (i = 0; i < contacts.Size(); i++)
{
const Ptr<Contact> contact = contacts[i];
const Ptr<PhysicsObject>& physObject = contact->GetCollisionObject();
hkRefPtr<hkpRigidBody> rigidBody = HK_NULL;
if (physObject->IsA(PhysicsBody::RTTI))
{
Ptr<HavokBody> havokBody = physObject.downcast<HavokBody>();
rigidBody = havokBody->GetRigidBody();
}
if (HK_NULL != rigidBody)
{
hitValidTarget = true;
vector impulseVector = float4::normalize(dir) * impulse;
rigidBody->applyPointImpulse(Neb2HkFloat4(impulseVector), Neb2HkFloat4(contact->GetPoint()));
}
}
return hitValidTarget;
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::OnActivate()
{
n_assert(!this->IsInitialized());
// set up default behaviour for world
hkpWorldCinfo worldInfo;
worldInfo.m_broadPhaseBorderBehaviour =
#if _DEBUG
//TODO: Revert when broadphase borders can be defined in the leveleditor
hkpWorldCinfo::BROADPHASE_BORDER_DO_NOTHING;
//hkpWorldCinfo::BROADPHASE_BORDER_ASSERT;
#else
hkpWorldCinfo::BROADPHASE_BORDER_DO_NOTHING;
#endif
worldInfo.m_fireCollisionCallbacks = true; //< this is needed for custom contact listeners
this->world = n_new(hkpWorld(worldInfo));
// set default gravity
this->SetGravity(Math::vector(0, -9.8f, 0));
// this is needed to detect collisions
hkpAgentRegisterUtil::registerAllAgents(this->world->getCollisionDispatcher());
this->SetupCollisionFilter();
this->initialized = true;
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::OnDeactivate()
{
n_assert(this->IsInitialized());
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::SetGravity(const Math::vector& v)
{
hkVector4 hkGravity = Neb2HkFloat4(v);
this->world->setGravity(hkGravity);
BaseScene::SetGravity(v);
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::Trigger()
{
// to have a consistent simulation
const float& simulationFrameTime = HavokPhysicsServer::Instance()->GetSimulationFrameTime();
if (-1 == this->lastFrame)
{
// first frame, simulate one step
this->lastFrame = PhysicsServer::Instance()->GetTime();
this->StepWorld(simulationFrameTime);
this->sinceLastTrigger = 0;
return;
}
// else default behaviour:
this->sinceLastTrigger += this->simulationSpeed * (PhysicsServer::Instance()->GetTime() - this->lastFrame);
this->lastFrame = PhysicsServer::Instance()->GetTime();
if (this->sinceLastTrigger > simulationFrameTime)
{
//for (; this->sinceLastTrigger > simulationFrameTime; this->sinceLastTrigger -= simulationFrameTime) //< may cause noticable minilags!
{
this->StepWorld(simulationFrameTime);
this->sinceLastTrigger -= simulationFrameTime;
this->time += simulationFrameTime;
}
}
// important note: it is tempting to just step the world using sinceLastTrigger but it will make the simulation inconsistent and
// will likely mess up the behaviour of the character - for example jump height might vary between different jumps
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::StepWorld(float time)
{
IndexT i;
for (i = 0; i < this->objects.Size(); i++)
{
this->objects[i]->OnStepBefore();
}
this->world->stepDeltaTime(time);
if (HavokVisualDebuggerServer::HasInstance())
{
// also perform a step for the visualdebugger
HavokVisualDebuggerServer::Instance()->OnStep();
}
HavokPhysicsServer::Instance()->HandleCollisions();
for (i = 0; i < this->objects.Size(); i++)
{
this->objects[i]->OnStepAfter();
}
}
//------------------------------------------------------------------------------
/**
*/
int
HavokScene::GetObjectsInSphere(const Math::vector& pos, float radius, const Physics::FilterSet& excludeSet, Util::Array<Ptr<PhysicsObject>>& result)
{
hkRefPtr<hkpShape> sphere = n_new(hkpSphereShape(radius));
return this->GetObjectsInShape(sphere, matrix44::translation(pos), excludeSet, result);
}
//------------------------------------------------------------------------------
/**
*/
int
HavokScene::GetObjectsInBox(const Math::vector& scale, const Math::matrix44& m, const Physics::FilterSet& excludeSet, Util::Array<Ptr<PhysicsObject>>& result)
{
hkRefPtr<hkpShape> box = n_new(hkpBoxShape(Neb2HkFloat4(scale)));
return this->GetObjectsInShape(box, m, excludeSet, result);
}
//------------------------------------------------------------------------------
/**
*/
int
HavokScene::GetObjectsInShape(hkRefPtr<hkpShape> shape, const Math::matrix44& m, const Physics::FilterSet& excludeSet, Util::Array<Ptr<PhysicsObject>>& result)
{
n_assert(result.IsEmpty());
hkpCollidable* collidable = n_new(hkpCollidable(shape, &NebMatrix442HkTransform(m)));
hkpAllCdBodyPairCollector collector;
const hkpProcessCollisionInput* input = this->world->getCollisionInput();
this->world->getPenetrations(collidable, *input, collector);
const hkArray<hkpRootCdBodyPair>& hits = collector.getHits();
IndexT i;
for (i = 0; i < hits.getSize(); i++)
{
void* owner = hits[i].m_rootCollidableB->getOwner();
hkpWorldObject* entity = (hkpWorldObject*)owner;
n_assert(0 != entity);
hkUlong userData = entity->getUserData();
HavokUtil::CheckWorldObjectUserData(userData);
Ptr<PhysicsObject> physObject = (PhysicsObject*)userData;
if (excludeSet.CheckObject(physObject)
|| InvalidIndex != result.FindIndex(physObject)) //< might be a shape of a compoundshape belonging to the same object
{
continue;
}
result.InsertSorted(physObject);
}
n_delete(collidable);
return result.Size();
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::SetupCollisionFilter()
{
n_assert(this->world);
/// set up a group filter as the default
hkRefPtr<hkpGroupFilter> groupFilter = n_new(hkpGroupFilter());
// initialize the group filter like hkpGroupFilterSetup::setupGroupFilter but with the default nebula collidecategories
groupFilter->enableCollisionsUsingBitfield(Physics::All, Physics::All);
groupFilter->enableCollisionsUsingBitfield(1<<Physics::None, 0xffffffff);
groupFilter->enableCollisionsUsingBitfield(0xffffffff, 1<<Physics::None);
//FIXME: Physics::CollideCategory is already shifted - its values should optimally be just 1, 2, 3... like in hkpGroupFilterSetup::setupGroupFilter.
//FIXME: (ctd) The below workaround have also been made for the physicsobjects' SetCollideCategory-methods
groupFilter->disableCollisionsBetween((int)n_log2(Physics::Kinematic), (int)n_log2(Physics::Kinematic));
groupFilter->disableCollisionsBetween((int)n_log2(Physics::Kinematic), (int)n_log2(Physics::Static));
this->world->setCollisionFilter(groupFilter);
this->filter = groupFilter;
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::DisableCollisionBetweenCategories(int categoryA, int categoryB)
{
n_assert(HK_NULL != this->filter);
hkpGroupFilter* groupFilter = dynamic_cast<hkpGroupFilter*>(this->filter.val());
groupFilter->disableCollisionsBetween(categoryA, categoryB);
}
//------------------------------------------------------------------------------
/**
*/
void
HavokScene::EnableCollisionBetweenCategories(int categoryA, int categoryB)
{
n_assert(HK_NULL != this->filter);
hkpGroupFilter* groupFilter = dynamic_cast<hkpGroupFilter*>(this->filter.val());
groupFilter->enableCollisionsBetween(categoryA, categoryB);
}
//------------------------------------------------------------------------------
/**
*/
bool
HavokScene::IsCollisionEnabledBetweenCategories(int categoryA, int categoryB)
{
n_assert(HK_NULL != this->filter);
hkpGroupFilter* groupFilter = dynamic_cast<hkpGroupFilter*>(this->filter.val());
return groupFilter->isCollisionEnabled(categoryA, categoryB);
}
}
| 28.540084
| 159
| 0.648137
|
gscept
|
58e353a0160167535f5ffddfb4f21c049eec11bc
| 9,729
|
cpp
|
C++
|
src/coreclr/src/vm/exinfo.cpp
|
davidsh/runtime
|
e5274e41fe13a8cfeeb4e87e39a1452cf8968f8c
|
[
"MIT"
] | 2
|
2020-05-27T10:46:24.000Z
|
2020-05-27T10:46:27.000Z
|
src/coreclr/src/vm/exinfo.cpp
|
witchakorn1999/runtime
|
cfd0172f89d237f79c47de51b64d5778c440bbc6
|
[
"MIT"
] | 2
|
2020-06-06T09:07:48.000Z
|
2020-06-06T09:13:07.000Z
|
src/coreclr/src/vm/exinfo.cpp
|
witchakorn1999/runtime
|
cfd0172f89d237f79c47de51b64d5778c440bbc6
|
[
"MIT"
] | 1
|
2020-08-04T14:01:38.000Z
|
2020-08-04T14:01:38.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
#include "common.h"
#include "exinfo.h"
#include "dbginterface.h"
#ifndef FEATURE_EH_FUNCLETS
#ifndef DACCESS_COMPILE
//
// Destroy the handle within an ExInfo. This respects the fact that we can have preallocated global handles living
// in ExInfo's.
//
void ExInfo::DestroyExceptionHandle(void)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
// Never, ever destroy a preallocated exception handle.
if ((m_hThrowable != NULL) && !CLRException::IsPreallocatedExceptionHandle(m_hThrowable))
{
DestroyHandle(m_hThrowable);
}
m_hThrowable = NULL;
}
//
// CopyAndClearSource copies the contents of the given ExInfo into the current ExInfo, then re-initializes the
// given ExInfo.
//
void ExInfo::CopyAndClearSource(ExInfo *from)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
if (GetThread() != NULL) MODE_COOPERATIVE; else MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
#ifdef TARGET_X86
LOG((LF_EH, LL_INFO100, "In ExInfo::CopyAndClearSource: m_dEsp=%08x, %08x <- [%08x], stackAddress = 0x%p <- 0x%p\n",
from->m_dEsp, &(this->m_dEsp), &from->m_dEsp, this->m_StackAddress, from->m_StackAddress));
#endif // TARGET_X86
// If we have a handle to an exception object in this ExInfo already, then go ahead and destroy it before we
// loose it.
DestroyExceptionHandle();
// The stack address is handled differently. Save the original value.
void* stackAddress = this->m_StackAddress;
// Blast the entire record. Note: we're copying the handle from the source ExInfo to this object. That's okay,
// since we're going to clear out the source ExInfo right below this.
memcpy(this, from, sizeof(ExInfo));
// Preserve the stack address. It should never change.
m_StackAddress = stackAddress;
// This ExInfo just took ownership of the handle to the exception object, so clear out that handle in the
// source ExInfo.
from->m_hThrowable = NULL;
// Finally, initialize the source ExInfo.
from->Init();
#ifndef TARGET_UNIX
// Clear the Watson Bucketing information as well since they
// have been transferred over by the "memcpy" above.
from->GetWatsonBucketTracker()->Init();
#endif // TARGET_UNIX
}
void ExInfo::Init()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
FORBID_FAULT;
}
CONTRACTL_END;
m_ExceptionFlags.Init();
m_StackTraceInfo.Init();
m_DebuggerExState.Init();
m_pSearchBoundary = NULL;
STRESS_LOG3(LF_EH, LL_INFO10000, "ExInfo::Init: setting ExInfo:0x%p m_pBottomMostHandler from 0x%p to 0x%p\n",
this, m_pBottomMostHandler, NULL);
m_pBottomMostHandler = NULL;
m_pPrevNestedInfo = NULL;
m_ExceptionCode = 0xcccccccc;
m_pExceptionRecord = NULL;
m_pContext = NULL;
m_pShadowSP = NULL;
m_StackAddress = this;
DestroyExceptionHandle();
m_hThrowable = NULL;
// By default, mark the tracker as not having delivered the first
// chance exception notification
m_fDeliveredFirstChanceNotification = FALSE;
m_pTopMostHandlerDuringSO = NULL;
#if defined(TARGET_X86) && defined(DEBUGGING_SUPPORTED)
m_InterceptionContext.Init();
m_ValidInterceptionContext = FALSE;
#endif //TARGET_X86 && DEBUGGING_SUPPORTED
}
ExInfo::ExInfo()
{
WRAPPER_NO_CONTRACT;
m_hThrowable = NULL;
Init();
#ifndef TARGET_UNIX
// Init the WatsonBucketTracker
m_WatsonBucketTracker.Init();
#endif // TARGET_UNIX
}
//*******************************************************************************
// When we hit an endcatch or an unwind and have nested handler info, either
// 1) we have contained a nested exception and will continue handling the original
// exception
// - or -
// 2) the nested exception was not contained, and was thrown beyond the original
// bounds where the first exception occurred.
//
// The way we can tell this is from the stack pointer. The topmost nested handler is
// installed at the point where the exception occurred. For a nested exception to be
// contained, it must be caught within the scope of any code that is called after
// the nested handler is installed. (remember: after is a lower stack address.)
//
// If it is caught by anything earlier on the stack, it was not contained, and we
// unwind the nested handlers until we get to one that is higher on the stack
// than the esp we will unwind to.
//
// If we still have a nested handler, then we have successfully handled a nested
// exception and should restore the exception settings that we saved so that
// processing of the original exception can continue.
// Otherwise the nested exception has gone beyond where the original exception was
// thrown and therefore replaces the original exception.
//
// We will always remove the current exception info from the chain.
//
void ExInfo::UnwindExInfo(VOID* limit)
{
CONTRACTL
{
NOTHROW; // This function does not throw.
GC_NOTRIGGER;
if (GetThread() != NULL) MODE_COOPERATIVE; else MODE_ANY;
}
CONTRACTL_END;
// We must be in cooperative mode to do the chaining below
#ifdef DEBUGGING_SUPPORTED
// The debugger thread will be using this, even though it has no
// Thread object associated with it.
_ASSERTE((GetThread() != NULL && GetThread()->PreemptiveGCDisabled()) ||
((g_pDebugInterface != NULL) && (g_pDebugInterface->GetRCThreadId() == GetCurrentThreadId())));
#endif // DEBUGGING_SUPPORTED
LOG((LF_EH, LL_INFO100, "UnwindExInfo: unwind limit is 0x%p, prevNested is 0x%p\n", limit, m_pPrevNestedInfo));
ExInfo *pPrevNestedInfo = m_pPrevNestedInfo;
// At first glance, you would think that each nested exception has
// been unwound by it's corresponding NestedExceptionHandler. But that's
// not necessarily the case. The following assertion cannot be made here,
// and the loop is necessary.
//
//_ASSERTE(pPrevNestedInfo == 0 || (DWORD)pPrevNestedInfo >= limit);
//
// Make sure we've unwound any nested exceptions that we're going to skip over.
//
while (pPrevNestedInfo && pPrevNestedInfo->m_StackAddress < limit)
{
STRESS_LOG1(LF_EH, LL_INFO100, "UnwindExInfo: PopExInfo(): popping nested ExInfo at 0x%p\n", pPrevNestedInfo->m_StackAddress);
if (pPrevNestedInfo->m_hThrowable != NULL)
{
pPrevNestedInfo->DestroyExceptionHandle();
}
#ifndef TARGET_UNIX
// Free the Watson bucket details when ExInfo
// is being released
pPrevNestedInfo->GetWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // TARGET_UNIX
pPrevNestedInfo->m_StackTraceInfo.FreeStackTrace();
#ifdef DEBUGGING_SUPPORTED
if (g_pDebugInterface != NULL)
{
g_pDebugInterface->DeleteInterceptContext(pPrevNestedInfo->m_DebuggerExState.GetDebuggerInterceptContext());
}
#endif
// Get the next nested handler detail...
ExInfo* pPrev = pPrevNestedInfo->m_pPrevNestedInfo;
if (pPrevNestedInfo->IsHeapAllocated())
{
delete pPrevNestedInfo;
}
pPrevNestedInfo = pPrev;
}
// either clear the one we're about to copy over or the topmost one
m_StackTraceInfo.FreeStackTrace();
if (pPrevNestedInfo)
{
// found nested handler info that is above the esp restore point so succesfully caught nested
STRESS_LOG2(LF_EH, LL_INFO100, "UnwindExInfo: resetting nested ExInfo to 0x%p stackaddress:0x%p\n", pPrevNestedInfo, pPrevNestedInfo->m_StackAddress);
// Remember if this ExInfo is heap allocated or not.
BOOL isHeapAllocated = pPrevNestedInfo->IsHeapAllocated();
// Copy pPrevNestedInfo to 'this', clearing pPrevNestedInfo in the process.
CopyAndClearSource(pPrevNestedInfo);
if (isHeapAllocated)
{
delete pPrevNestedInfo; // Now delete the old record if we needed to.
}
}
else
{
STRESS_LOG0(LF_EH, LL_INFO100, "UnwindExInfo: clearing topmost ExInfo\n");
// We just do a basic Init of the current top ExInfo here.
Init();
#ifndef TARGET_UNIX
// Init the Watson buckets as well
GetWatsonBucketTracker()->ClearWatsonBucketDetails();
#endif // TARGET_UNIX
}
}
#endif // DACCESS_COMPILE
#ifdef DACCESS_COMPILE
void
ExInfo::EnumMemoryRegions(CLRDataEnumMemoryFlags flags)
{
SUPPORTS_DAC;
// ExInfo is embedded so don't enum 'this'.
OBJECTHANDLE_EnumMemoryRegions(m_hThrowable);
m_pExceptionRecord.EnumMem();
m_pContext.EnumMem();
}
#endif // #ifdef DACCESS_COMPILE
void ExInfo::SetExceptionCode(const EXCEPTION_RECORD *pCER)
{
#ifndef DACCESS_COMPILE
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_FORBID_FAULT;
_ASSERTE(pCER != NULL);
m_ExceptionCode = pCER->ExceptionCode;
if (IsInstanceTaggedSEHCode(pCER->ExceptionCode) && ::WasThrownByUs(pCER, pCER->ExceptionCode))
{
m_ExceptionFlags.SetWasThrownByUs();
}
else
{
m_ExceptionFlags.ResetWasThrownByUs();
}
#else // DACCESS_COMPILE
// This method is invoked by the X86 version of CLR's exception handler for
// managed code. There is no reason why DAC would be invoking this.
DacError(E_UNEXPECTED);
#endif // !DACCESS_COMPILE
}
#endif // !FEATURE_EH_FUNCLETS
| 31.898361
| 158
| 0.687429
|
davidsh
|
58e39b090824caa2296db363e3210b40126cde16
| 2,898
|
hpp
|
C++
|
include/LightBulbApp/Repositories/TrainingPlanRepository.hpp
|
domin1101/ANNHelper
|
50acb5746d6dad6777532e4c7da4983a7683efe0
|
[
"Zlib"
] | 5
|
2016-02-04T06:14:42.000Z
|
2017-02-06T02:21:43.000Z
|
include/LightBulbApp/Repositories/TrainingPlanRepository.hpp
|
domin1101/ANNHelper
|
50acb5746d6dad6777532e4c7da4983a7683efe0
|
[
"Zlib"
] | 41
|
2015-04-15T21:05:45.000Z
|
2015-07-09T12:59:02.000Z
|
include/LightBulbApp/Repositories/TrainingPlanRepository.hpp
|
domin1101/LightBulb
|
50acb5746d6dad6777532e4c7da4983a7683efe0
|
[
"Zlib"
] | null | null | null |
#pragma once
#ifndef _TRAININGPLANREPOSITORY_H_
#define _TRAININGPLANREPOSITORY_H_
// Library includes
#include <vector>
#include <memory>
// Includes
#include "LightBulb/Event/Observable.hpp"
namespace LightBulb
{
class AbstractTrainingPlan;
/**
* \brief All events the training plan repository can throw.
*/
enum TrainingPlanRepositoryEvents : unsigned int
{
/**
* \brief Is thrown if the training plans have been changed.
*/
EVT_TP_CHANGED
};
/**
* \brief A repository which stores all training plans which are currently executed in the LightBulbApp.
*/
class TrainingPlanRepository : public LightBulb::Observable<TrainingPlanRepositoryEvents, TrainingPlanRepository>
{
template <class Archive>
friend void serialize(Archive& archive, TrainingPlanRepository& trainingPlanRepository);
private:
/**
* \brief The training plan storage.
*/
std::vector<std::unique_ptr<AbstractTrainingPlan>> trainingPlans;
public:
/**
* \brief Returns all training plans.
* \return A vector of all training plans.
*/
const std::vector<std::unique_ptr<AbstractTrainingPlan>>& getTrainingPlans() const;
/**
* \brief Returns the index of a given training plan.
* \param trainingPlan The training plan.
* \return The index of the training plan in the training plan storage vector.
*/
int getIndexOfTrainingPlan(const AbstractTrainingPlan& trainingPlan) const;
/**
* \brief Adds a new training plan to the repository.
* \param trainingPlan The new training plan.
*/
void Add(AbstractTrainingPlan* trainingPlan);
/**
* \brief Saves the training plan with the given index as a file.
* \param path The path where to store the file.
* \param trainingPlanIndex The index of the training plan to save.
*/
void save(const std::string& path, int trainingPlanIndex) const;
/**
* \brief Loads a training plan from file and stores it in the repository.
* \param path The path of the file to load.
*/
AbstractTrainingPlan& load(const std::string& path);
/**
* \brief Returns the training plan with the given name.
* \param name The name to search for.
* \return The training plan with the given name.
* \note If no training plan can be found, an exception is thrown.
*/
AbstractTrainingPlan& getByName(const std::string& name) const;
/**
* \brief Sets the name of the training plan with the given index.
* \param trainingPlanIndex The index of the training plan.
* \param newName The new name.
*/
void setTrainingPlanName(int trainingPlanIndex, const std::string& newName);
/**
* \brief Returns if a training plan with the given name exists.
* \param name The name to search for.
* \return True, if a training plan with this name exists.
*/
bool exists(const std::string& name) const;
void clear();
};
}
#include "LightBulbApp/IO/TrainingPlanRepositoryIO.hpp"
#endif
| 31.5
| 114
| 0.722222
|
domin1101
|
58e3c50f3103af4afd1da0237a20460b57faf4cc
| 831
|
cc
|
C++
|
openssl-examples/lib/openssl++/certificate_stack.cc
|
falk-werner/playground
|
501b425d4c8161bdd89ad92b78a4741d81af9acb
|
[
"MIT"
] | null | null | null |
openssl-examples/lib/openssl++/certificate_stack.cc
|
falk-werner/playground
|
501b425d4c8161bdd89ad92b78a4741d81af9acb
|
[
"MIT"
] | null | null | null |
openssl-examples/lib/openssl++/certificate_stack.cc
|
falk-werner/playground
|
501b425d4c8161bdd89ad92b78a4741d81af9acb
|
[
"MIT"
] | null | null | null |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#include <openssl++/certificate_stack.hpp>
#include <openssl++/exception.hpp>
namespace openssl
{
CertificateStack::CertificateStack()
: stack(sk_X509_new_null())
{
if (nullptr == stack)
{
throw new OpenSSLException("failed to create CertificateStack");
}
}
CertificateStack::~CertificateStack()
{
sk_X509_free(stack);
}
CertificateStack::operator STACK_OF(X509) *()
{
return stack;
}
void CertificateStack::push(X509 * certificate)
{
int rc = sk_X509_push(stack, certificate);
if (0 == rc)
{
throw new OpenSSLException("failed to push certificate to stack");
}
}
}
| 20.775
| 74
| 0.685921
|
falk-werner
|
58e494b05e6f6f66ea3c8f2bc66f07a8795c3bd9
| 1,889
|
cpp
|
C++
|
Source/FishEngine/Component/Rigidbody.cpp
|
yushroom/FishEngine_-Experiment
|
81e4c06f20f6b94dc561b358f8a11a092678aeeb
|
[
"MIT"
] | 1
|
2018-12-20T02:38:44.000Z
|
2018-12-20T02:38:44.000Z
|
Source/FishEngine/Component/Rigidbody.cpp
|
yushroom/FishEngine_-Experiment
|
81e4c06f20f6b94dc561b358f8a11a092678aeeb
|
[
"MIT"
] | null | null | null |
Source/FishEngine/Component/Rigidbody.cpp
|
yushroom/FishEngine_-Experiment
|
81e4c06f20f6b94dc561b358f8a11a092678aeeb
|
[
"MIT"
] | 1
|
2018-10-25T19:40:22.000Z
|
2018-10-25T19:40:22.000Z
|
#include <FishEngine/Component/Rigidbody.hpp>
#include <FishEngine/Transform.hpp>
#include <FishEngine/GameObject.hpp>
#include <FishEngine/Component/BoxCollider.hpp>
#include <FishEngine/Component/SphereCollider.hpp>
#include <FishEngine/Physics/PhysxAPI.hpp>
using namespace physx;
inline physx::PxVec3 PxVec3(const FishEngine::Vector3& v)
{
return physx::PxVec3(v.x, v.y, v.z);
}
namespace FishEngine
{
void Rigidbody::Initialize(PxShape* shape)
{
auto& px = PhysxWrap::GetInstance();
auto t = GetTransform();
const Vector3& p = t->GetPosition();
const auto& q = t->GetRotation();
m_physxRigidDynamic = px.physics->createRigidDynamic(PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)));
m_physxRigidDynamic->userData = (void*)this;
m_physxRigidDynamic->setMass(m_Mass);
if (shape)
{
m_physxRigidDynamic->attachShape(*shape);
shape->release();
}
}
void Rigidbody::Start()
{
auto& px = PhysxWrap::GetInstance();
Collider* collider = GetGameObject()->GetComponent<Collider>();
if (collider != nullptr)
Initialize(collider->GetPhysicsShape());
else
Initialize(nullptr);
auto t = GetTransform();
const Vector3 p = t->GetPosition();
const auto& q = t->GetRotation();
m_physxRigidDynamic->setGlobalPose(PxTransform(p.x, p.y, p.z, PxQuat(q.x, q.y, q.z, q.w)));
PxRigidBodyExt::updateMassAndInertia(*m_physxRigidDynamic, 10.0f);
m_physxRigidDynamic->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_UseGravity);
px.scene->addActor(*m_physxRigidDynamic);
}
void Rigidbody::Update()
{
const auto& t = m_physxRigidDynamic->getGlobalPose();
GetTransform()->SetPosition(t.p.x, t.p.y, t.p.z);
GetTransform()->SetRotation(Quaternion(t.q.x, t.q.y, t.q.z, t.q.w));
}
void Rigidbody::OnDestroy()
{
m_physxRigidDynamic = nullptr;
}
bool Rigidbody::IsInitialized() const
{
return m_physxRigidDynamic != nullptr;
}
}
| 27.376812
| 111
| 0.712546
|
yushroom
|
58e7c849efc2e4c6af1e6793bc4ed54321b23997
| 6,475
|
cc
|
C++
|
wasp_exec/src/waspexecutor.cc
|
tuloski/wasp_exec
|
00ac1e3d00e974c380a9d498a346b50996bee2e7
|
[
"MIT"
] | null | null | null |
wasp_exec/src/waspexecutor.cc
|
tuloski/wasp_exec
|
00ac1e3d00e974c380a9d498a346b50996bee2e7
|
[
"MIT"
] | null | null | null |
wasp_exec/src/waspexecutor.cc
|
tuloski/wasp_exec
|
00ac1e3d00e974c380a9d498a346b50996bee2e7
|
[
"MIT"
] | null | null | null |
#include "ros/ros.h"
#include <boost/thread.hpp>
#include "std_msgs/String.h"
#include <iostream>
#include <sstream>
#include <queue>
#include "lrs_msgs_tst/ConfirmReq.h"
#include "mms_msgs/Cmd.h"
#include "lrs_srvs_exec/TSTCreateExecutor.h"
#include "lrs_msgs_tst/OperatorRequest.h"
#include "executors/flyto.h"
#include "executors/takeoff.h"
#include "executors/land.h"
#include "executors/takepictures.h"
#include "executors/scangroundsingle.h"
#include "executors/rotateyaw.h"
#include "executors/leashing.h"
#include "executors/start_data_stream.h"
#include "executors/stop_data_stream.h"
#include "executors/operator_control.h"
#include "executors/inairgoal.h"
#include "executors/inairtest.h"
#include "guidance_node_amsl/Reference.h"
#include "executil.h"
std::map<std::string, Executor *> execmap;
std::map<std::string, boost::thread *> threadmap;
ros::NodeHandle * global_nh;
ros::Publisher * global_confirm_pub;
ros::Publisher * global_tell_operator_content_pub;
ros::Publisher * global_tell_operator_content_pub_proxy;
ros::Publisher * global_cmd_pub;
int16_t global_seq = 1;
//reference_class global_last_reference;
guidance_node_amsl::Reference latest_reference;
boost::mutex mutex;
boost::mutex seq_mutex; //mutex to handle shared variable seq
boost::mutex ref_mutex; //mutex to handle shared class reference_class
boost::mutex thread_map_lock;
using namespace std;
void callbackReference(const guidance_node_amsl::Reference::ConstPtr& msg){
{
boost::mutex::scoped_lock lock(ref_mutex);
//ROS_INFO ("WaspExecutor::Received Reference: %d - %d",msg->Latitude, msg->Longitude);
latest_reference.Latitude = msg->Latitude;
latest_reference.Longitude = msg->Longitude;
latest_reference.AltitudeRelative = msg->AltitudeRelative;
latest_reference.Yawangle = msg->Yawangle;
latest_reference.frame = msg->frame;
}
}
bool create_executor (lrs_srvs_exec::TSTCreateExecutor::Request &req,
lrs_srvs_exec::TSTCreateExecutor::Response &res ) {
boost::mutex::scoped_lock lock(mutex);
ROS_INFO("quadexecutor: create_executor: %s %d - %d", req.ns.c_str(), req.id, req.run_prepare);
ostringstream os;
os << req.ns << "-" << req.id;
if (execmap.find (os.str()) != execmap.end()) {
ROS_INFO ("Executor already exists, overwrites it: %s %d", req.ns.c_str(), req.id);
}
string type = get_node_type (req.ns, req.id);
bool found = false;
Executor * cres = check_exec(type, req.ns, req.id);
if (cres) {
execmap[os.str()] = cres;
found = true;
}
if (type == "fly-to") {
execmap[os.str()] = new Exec::FlyTo (req.ns, req.id);
found = true;
}
if (type == "take-off") {
execmap[os.str()] = new Exec::TakeOff (req.ns, req.id);
found = true;
}
if (type == "land") {
execmap[os.str()] = new Exec::Land (req.ns, req.id);
found = true;
}
if (type == "take-pictures") {
execmap[os.str()] = new Exec::TakePictures (req.ns, req.id);
found = true;
}
if (type == "scan-ground-single") {
execmap[os.str()] = new Exec::ScanGroundSingle (req.ns, req.id);
found = true;
}
if (type == "yaw") {
execmap[os.str()] = new Exec::RotateYaw (req.ns, req.id);
found = true;
}
if (type == "leashing") {
execmap[os.str()] = new Exec::Leashing (req.ns, req.id);
found = true;
}
/*if (type == "stop-data-stream") { ///FUCKING IMPOSSIBLE ERROR ON THIS
execmap[os.str()] = new Exec::StopDataStream (req.ns, req.id);
found = true;
}*/
if (type == "start-data-stream") {
execmap[os.str()] = new Exec::StartDataStream (req.ns, req.id);
found = true;
}
if (type == "operator-control") {
execmap[os.str()] = new Exec::OperatorControl (req.ns, req.id);
found = true;
}
if (type == "in-air-goal") {
execmap[os.str()] = new Exec::InAirGoal (req.ns, req.id);
found = true;
}
if (type == "in-air-test") {
execmap[os.str()] = new Exec::InAirTest (req.ns, req.id);
found = true;
}
if (found) {
res.success = true;
res.error = 0;
if (req.run_prepare) {
bool prep = execmap[os.str()]->prepare ();
if (!prep) {
res.success = false;
res.error = 2;
}
}
} else {
ROS_ERROR ("Could not create executor of type: %s", type.c_str());
res.success = false;
res.error = 1;
}
return true;
}
int main(int argc, char **argv) {
ros::init(argc, argv, "waspexecutor");
ros::NodeHandle n;
global_nh = &n;
ros::Publisher confirm_pub = n.advertise<lrs_msgs_tst::ConfirmReq>("confirm_request", 1, true); // queue size 1 and latched
global_confirm_pub = &confirm_pub;
ros::Publisher content_pub = n.advertise<lrs_msgs_tst::OperatorRequest>("/operator", 1);
ros::Publisher content_pub_proxy = n.advertise<lrs_msgs_tst::OperatorRequest>("/operator_proxy", 1);
global_tell_operator_content_pub = &content_pub;
global_tell_operator_content_pub_proxy = &content_pub_proxy;
ros::Publisher cmd_pub = n.advertise<mms_msgs::Cmd>("sent_command", 10); // command topic
global_cmd_pub = &cmd_pub;
ros::Subscriber reference_sub; //subscriber to reference topic
reference_sub = n.subscribe("reference", 10, callbackReference);
std::vector<ros::ServiceServer> services;
std::string prefix = "tst_executor/";
services.push_back (n.advertiseService(prefix + "destroy_executor", destroy_executor));
services.push_back (n.advertiseService(prefix + "create_executor", create_executor));
services.push_back (n.advertiseService(prefix + "executor_check", executor_check));
services.push_back (n.advertiseService(prefix + "executor_continue", executor_continue));
services.push_back (n.advertiseService(prefix + "executor_expand", executor_expand));
services.push_back (n.advertiseService(prefix + "executor_is_delegation_expandable", executor_is_delegation_expandable));
services.push_back (n.advertiseService(prefix + "executor_request_pause", executor_request_pause));
services.push_back (n.advertiseService(prefix + "executor_get_constraints", executor_get_constraints));
services.push_back (n.advertiseService(prefix + "start_executor", start_executor));
services.push_back (n.advertiseService(prefix + "abort_executor", abort_executor));
services.push_back (n.advertiseService(prefix + "pause_executor", pause_executor));
services.push_back (n.advertiseService(prefix + "continue_executor", continue_executor));
services.push_back (n.advertiseService(prefix + "enough_executor", enough_executor));
ROS_INFO("Ready to be an executor factory");
ros::spin();
return 0;
}
| 32.375
| 125
| 0.707181
|
tuloski
|
58ebde0ceaa882d8d5f0035f5039c41409d992aa
| 524
|
cpp
|
C++
|
Easing/PolygonEquation.cpp
|
DiegoSLTS/EasingFunctions
|
38951f19a3069c9ac20aee482dfe1f8c0953408d
|
[
"MIT"
] | null | null | null |
Easing/PolygonEquation.cpp
|
DiegoSLTS/EasingFunctions
|
38951f19a3069c9ac20aee482dfe1f8c0953408d
|
[
"MIT"
] | null | null | null |
Easing/PolygonEquation.cpp
|
DiegoSLTS/EasingFunctions
|
38951f19a3069c9ac20aee482dfe1f8c0953408d
|
[
"MIT"
] | null | null | null |
#include "PolygonEquation.h"
#include <math.h>
PolygonEquation::PolygonEquation(int grade) : grade(grade) {}
PolygonEquation::~PolygonEquation() {}
double PolygonEquation::Evaluate() const {
float temp = GetTime();
switch(this->ease) {
case EasingType::IN:
return pow(temp, grade);
case EasingType::OUT:
return 1 - pow(1 - temp, grade);
case EasingType::IN_OUT:
if (temp < 0.5)
return pow(temp, grade) * (1 << (grade - 1));
return 1 - pow(1 - temp, grade) * (1 << (grade - 1));
default:
return 0;
}
}
| 22.782609
| 61
| 0.652672
|
DiegoSLTS
|
58ef2e13fb05b3a6506e4dd43ff1752365fc36cd
| 1,271
|
cc
|
C++
|
src/base/tests/Exception_unittest.cc
|
plantree/Slack
|
469fff18792a6d4d20c409f0331e3c93117c5ddf
|
[
"MIT"
] | 2
|
2019-07-15T08:34:38.000Z
|
2019-08-07T12:27:23.000Z
|
src/base/tests/Exception_unittest.cc
|
plantree/Slack
|
469fff18792a6d4d20c409f0331e3c93117c5ddf
|
[
"MIT"
] | null | null | null |
src/base/tests/Exception_unittest.cc
|
plantree/Slack
|
469fff18792a6d4d20c409f0331e3c93117c5ddf
|
[
"MIT"
] | null | null | null |
/*
* @Author: py.wang
* @Date: 2019-06-06 17:19:02
* @Last Modified by: py.wang
* @Last Modified time: 2019-06-06 18:34:59
*/
#include "src/base/Exception.h"
#include "src/base/CurrentThread.h"
#include <vector>
#include <string>
#include <functional>
#include <stdio.h>
class Bar
{
public:
void test(std::vector<std::string> names = {})
{
printf("Stack: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
// lambda
[] {
printf("Stack inside lambda: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
} ();
// function
std::function<void ()> func([] {
printf("Stack inside function: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
});
func();
func = std::bind(&Bar::callback, this);
func();
throw slack::Exception("oops");
}
private:
void callback()
{
printf("Stack inside std::bind: \n%s\n", slack::CurrentThread::stackTrace(true).c_str());
}
};
void foo()
{
Bar b;
b.test();
}
int main()
{
try
{
foo();
}
catch (const slack::Exception &ex)
{
printf("reason: %s\n", ex.what());
printf("stack trace: \n%s\n", ex.stackTrace());
}
}
| 19.859375
| 100
| 0.543666
|
plantree
|
58f34ecd609e36c29fc423ba6154ebfa776c18a3
| 1,282
|
cpp
|
C++
|
Example/serialization_13/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/serialization_13/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
Example/serialization_13/main.cpp
|
KwangjoJeong/Boost
|
29c4e2422feded66a689e3aef73086c5cf95b6fe
|
[
"MIT"
] | null | null | null |
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/export.hpp>
#include <iostream>
#include <sstream>
std::stringstream ss;
class animal
{
public:
animal() = default;
animal(int legs) : legs_{legs} {}
virtual int legs() const { return legs_; }
virtual ~animal() = default;
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version) { ar & legs_; }
int legs_;
};
class bird : public animal
{
public:
bird() = default;
bird(int legs, bool can_fly) :
animal{legs}, can_fly_{can_fly} {}
bool can_fly() const { return can_fly_; }
private:
friend class boost::serialization::access;
template <typename Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & boost::serialization::base_object<animal>(*this);
ar & can_fly_;
}
bool can_fly_;
};
void save()
{
boost::archive::text_oarchive oa{ss};
oa.register_type<bird>();
animal *a = new bird{2, false};
oa << a;
delete a;
}
void load()
{
boost::archive::text_iarchive ia{ss};
ia.register_type<bird>();
animal *a;
ia >> a;
std::cout << a->legs() << '\n';
delete a;
}
int main()
{
save();
load();
}
| 18.314286
| 73
| 0.664587
|
KwangjoJeong
|
58f5e87c88fc029411d0193072ec526dc6ec06db
| 894
|
cpp
|
C++
|
numeric/modulo.cpp
|
ankushkhanna1998/competitive-programming
|
97c772f3bc029dcd9f573f2e3d616ba068eab8b5
|
[
"MIT"
] | 3
|
2020-06-02T07:39:24.000Z
|
2020-09-02T14:04:52.000Z
|
numeric/modulo.cpp
|
ankushkhanna1998/competitive-programming
|
97c772f3bc029dcd9f573f2e3d616ba068eab8b5
|
[
"MIT"
] | null | null | null |
numeric/modulo.cpp
|
ankushkhanna1998/competitive-programming
|
97c772f3bc029dcd9f573f2e3d616ba068eab8b5
|
[
"MIT"
] | null | null | null |
const int64_t MOD = static_cast<int64_t>(1e9 + 7);
inline int64_t add(int64_t a, const int64_t b, const int64_t M = MOD) {
return ((a += b) >= M ? a - M : a);
}
inline int64_t sub(int64_t a, const int64_t b, const int64_t M = MOD) {
return ((a -= b) < 0 ? a + M : a);
}
inline int64_t mul(const int64_t a, const int64_t b, const int64_t M = MOD) {
return a * b % M;
}
inline int64_t power(int64_t a, int64_t b, const int64_t M = MOD) {
assert(b >= 0);
int64_t ans = 1;
while (b) {
if (b & 1) {
ans = mul(ans, a, M);
}
a = mul(a, a, M);
b >>= 1;
}
return ans;
}
inline int64_t inverse(int64_t a, const int64_t M = MOD) {
int64_t b = M, u = 0, v = 1;
while (a) {
int64_t t = b / a;
b -= t * a; swap(a, b);
u -= t * v; swap(u, v);
}
assert(b == 1);
return sub(u, 0, M);
}
| 23.526316
| 77
| 0.506711
|
ankushkhanna1998
|
58f696aa6218731be901e86298876227be963492
| 17,565
|
cpp
|
C++
|
src/Physics/Vehicle.cpp
|
NotCamelCase/Grad-Project-Arcade-Sim
|
4574cf1a11878829c75dec1aaa9834d40221cdbc
|
[
"MIT"
] | 7
|
2015-01-12T21:46:22.000Z
|
2021-11-19T19:15:37.000Z
|
src/Physics/Vehicle.cpp
|
NotCamelCase/Grad-Project-Arcade-Sim
|
4574cf1a11878829c75dec1aaa9834d40221cdbc
|
[
"MIT"
] | null | null | null |
src/Physics/Vehicle.cpp
|
NotCamelCase/Grad-Project-Arcade-Sim
|
4574cf1a11878829c75dec1aaa9834d40221cdbc
|
[
"MIT"
] | 3
|
2015-07-28T08:32:19.000Z
|
2021-02-19T11:16:48.000Z
|
/*
The MIT License (MIT)
Copyright (c) 2015 Tayfun Kayhan
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 "Physics\Vehicle.h"
#include <Ogre.h>
#include <btBulletDynamicsCommon.h>
#include "Physics\BtOgrePG.h"
#include "Physics\BtOgreGP.h"
#include "Physics\BtOgreExtras.h"
#include "World\GameObjectManager.h"
#include "Physics\PhysicsManager.h"
#include "Event\EventManager.h"
#include "Audio\AudioManager.h"
#include "Audio\SoundEffect.h"
#include "Network\NetworkManager.h"
#include "Player\PlayerManager.h"
#include "Player\RaceManager.h"
#include "Network\GameClient.h"
#include "Physics\Waypoint.h"
#include "Player\Player.h"
#include "GODLoader.h"
#include "InputMap.h"
#include "Utils.h"
#define FOLLOW_CAMERA_OFFSET Vector3(0, -12.5, 25)
#define LIGHT_OFFSET Vector3(0, -20, 20)
#define AIR_DENSITY 1.2f
#define CHASE_CAM_AUTO 1
#define CHASE_CAM_LIMITED 0
using namespace Ogre;
Vehicle::Vehicle(GameObjectManager* mng, SceneNode* node, Entity* entity, const String& id)
: PhysicsObject(mng, node, entity, id),
m_vehicleRaycaster(NULL), m_btVehicle(NULL), m_ownerPlayer(NULL),
m_engineForce(0), m_brakeForce(0), m_steering(0), m_sceneMgr(NULL),
m_engineSound(NULL), m_brakeSound(NULL), m_props(NULL), m_raceTimer(NULL),
m_vehicleState(VehicleState::INIT), m_lastPassedWaypointIndex(-1), m_latestWaypointPos(NULL)
{
m_sceneMgr = m_manager->getSceneManager();
m_props = GODLoader::getSingleton().getGameObjectDefinitionByTag(m_tag);
const String engineSound = m_props->getParameters()["engineSound"];
m_engineSound = AudioManager::getSingleton().createSoundEffect(engineSound, AudioType::SOUND_2D_LOOPING);
assert(m_engineSound != NULL && "Vehicle engine sound is NULL!");
const String brakeSound = m_props->getParameters()["brakeSound"];
m_brakeSound = AudioManager::getSingleton().createSoundEffect(brakeSound);
assert(m_engineSound != NULL && "Vehicle brake sound is NULL!");
updateSounds();
// Get location indexes of Waypoints from GameObjectManager's CheckPoints
for (const GameObject* cp : m_manager->getGameObjects())
{
if (cp->getType() == GameObjectType::TYPE_CHECKPOINT)
{
const int wpIndex = StringConverter::parseInt(cp->getID());
Waypoint* waypoint = new Waypoint(wpIndex);
m_trackWaypoints.insert(std::make_pair(wpIndex, waypoint));
}
}
EventManager::getSingleton().registerListener(EventType::COLLISION_STARTED, this);
EventManager::getSingleton().registerListener(EventType::COLLISION_TIME, this);
EventManager::getSingleton().registerListener(EventType::COLLISION_ENDED, this);
EventManager::getSingleton().registerListener(EventType::START_OFF_FIRE, this);
EventManager::getSingleton().registerListener(EventType::VEHICLE_UPSIDE_DOWN, this);
m_raceTimer = new Timer();
m_logger->logMessage("Vehicle created");
}
Vehicle::~Vehicle()
{
AudioManager::getSingleton().release(m_engineSound);
AudioManager::getSingleton().release(m_brakeSound);
SAFE_DELETE(m_btVehicle);
SAFE_DELETE(m_vehicleRaycaster);
SAFE_DELETE(m_raceTimer);
for (auto& it : m_trackWaypoints)
{
#if _DEBUG
Waypoint* wp = NULL;
wp = it.second;
if (wp != NULL)
m_logger->logMessage("Destroying Waypoint of index: " + wp->getLocationIndex());
#endif
SAFE_DELETE(it.second);
}
m_trackWaypoints.clear();
for (int i = 0; i < WHEEL_COUNT; i++)
{
m_sceneMgr->destroyRibbonTrail(m_trailMO[i]);
}
m_logger->logMessage("Tire trails destroyed");
EventManager::getSingleton().unregisterListener(EventType::COLLISION_STARTED, this);
EventManager::getSingleton().unregisterListener(EventType::COLLISION_TIME, this);
EventManager::getSingleton().unregisterListener(EventType::COLLISION_ENDED, this);
EventManager::getSingleton().unregisterListener(EventType::START_OFF_FIRE, this);
EventManager::getSingleton().unregisterListener(EventType::VEHICLE_UPSIDE_DOWN, this);
m_logger->logMessage("Vehicle destroyed");
}
int Vehicle::getCurrentSpeed() const
{
return m_btVehicle->getCurrentSpeedKmHour();
}
void Vehicle::applyDynamicAirPressure(int* currentSpeed)
{
float v = *currentSpeed * (1.0f / 3.6f);
float q = 0.5f * AIR_DENSITY * v * v;
m_rigidBody->applyCentralForce(btVector3(0, -4.5 * q, 0));
}
void Vehicle::initFineTuningValues()
{
m_maxReverse = -1 * StringConverter::parseInt(m_props->getParameters()["maxReverseSpeed"]);
m_steeringIdeal = StringConverter::parseReal(m_props->getParameters()["steeringIncrementIdeal"]);
m_idealBrakeGain = StringConverter::parseReal(m_props->getParameters()["brakeGainIdeal"]);
m_boostLimit = StringConverter::parseInt(m_props->getParameters()["startUpBoostLimit"]);
m_boostGain = StringConverter::parseInt(m_props->getParameters()["startUpBoost"]);
m_logger->logMessage("Assigned initial Vehicle physics paramaters");
}
void Vehicle::update(Real delta)
{
switch (m_vehicleState)
{
case VehicleState::INIT_COMPLETE:
initFineTuningValues();
setupVisuals();
m_vehicleState = VehicleState::IDLE;
break;
case VehicleState::IDLE:
if (m_rigidBody->getActivationState() != DISABLE_SIMULATION)
{
m_rigidBody->forceActivationState(DISABLE_SIMULATION);
m_logger->logMessage("Vehicle chassis simulation disabled");
}
updatePhysics(delta);
break;
case VehicleState::IN_RACE:
updatePhysics(delta);
break;
case VehicleState::END_RACE:
break;
default:
break;
}
syncVehicle();
updateSounds();
updatePlayerStats();
}
void Vehicle::updatePhysics(Real delta)
{
int currentSpeed = getCurrentSpeed();
applyDynamicAirPressure(¤tSpeed);
bool tireTrailVis = false;
unsigned int keyFlag = NULL;
if (!m_ownerPlayer->isLocal())
{
GameClient* remoteClient = NetworkManager::getSingleton().getGameClientByPlayer(m_ownerPlayer);
assert(remoteClient && "Error finding remote GameClient by Player");
keyFlag = remoteClient->getKeyFlags();
m_logger->logMessage("Checking input with client data");
}
if (InputMap::isKeyActive(InputType::BRAKE, keyFlag))
{
if (currentSpeed <= 0.f)
{
if (currentSpeed > m_maxReverse)
{
m_brakeForce = 0.f;
m_engineForce += -m_speedGain;
}
else {
m_brakeForce = 0.f;
handleNeutral(¤tSpeed);
}
}
else {
tireTrailVis = true;
adjustBrake(¤tSpeed);
m_brakeForce += m_brakeGain;
m_engineForce = 0.f;
}
}
else if (InputMap::isKeyActive(InputType::ACCELERATE, keyFlag))
{
adjustEngineForce(¤tSpeed);
m_engineForce += m_speedGain;
if (m_engineForce > m_maxEngineForce)
m_engineForce = m_maxEngineForce;
m_brakeForce = 0.f;
}
else
{
handleNeutral(¤tSpeed);
}
if (InputMap::isKeyActive(InputType::STEER_LEFT, keyFlag))
{
adjustSteering(¤tSpeed);
m_steering += m_steeringIncrement;
if (m_steering > m_steeringClamp)
m_steering = m_steeringClamp;
}
else if (InputMap::isKeyActive(InputType::STEER_RIGHT, keyFlag))
{
adjustSteering(¤tSpeed);
m_steering -= m_steeringIncrement;
if (m_steering < -m_steeringClamp)
m_steering = -m_steeringClamp;
}
else
{
// TODO: Further investigate steering relief reduction !!!
static Real neutralSteering = 0.02;
if (Math::Abs(m_steering) < neutralSteering)
m_steering = 0.0f;
else if (m_steering > 0.0f)
m_steering -= neutralSteering;
else
m_steering += neutralSteering;
}
// DOUBT: Should unroll the loop ?!
for (int i = 0; i < m_btVehicle->getNumWheels(); i++)
{
if (i < 2)
{
m_btVehicle->setSteeringValue(m_steering, i);
}
else
{
m_btVehicle->applyEngineForce(m_engineForce, i);
m_btVehicle->setBrake(m_brakeForce, i);
}
RibbonTrail* trail = (RibbonTrail*) m_trailMO[i];
assert(trail && "Error indexing RibbonTrail");
if (!tireTrailVis && trail)
{
trail->clearAllChains();
}
trail->setVisible(tireTrailVis);
}
}
bool Vehicle::updatePlayerStats()
{
PlayerStats* stats = m_ownerPlayer->getPlayerStats();
stats->vehicleSpeed = getCurrentSpeed();
const unsigned long currentTiming = m_raceTimer->getMilliseconds();
const unsigned long sumSec = currentTiming / 1000;
stats->min = sumSec / 60;
stats->sec = sumSec % 60;
stats->splitSec = (currentTiming - (sumSec * 1000)) / 10;
return true;
}
void Vehicle::syncVehicle()
{
for (int i = 0; i < m_wheels.size(); i++)
{
m_btVehicle->updateWheelTransform(i, true);
const btTransform& w = m_btVehicle->getWheelInfo(i).m_worldTransform;
SceneNode* node = m_wheels[i]->getNode();
node->setPosition(w.getOrigin()[0], w.getOrigin()[1], w.getOrigin()[2]);
node->setOrientation(w.getRotation().getW(), w.getRotation().getX(), w.getRotation().getY(), w.getRotation().getZ());
}
}
void Vehicle::adjustSteering(int* currentSpeed)
{
static const int fd = 1000;
static const int bd = 500;
if (*currentSpeed >= m_steeringReductionSpeed)
{
const float step = (m_steeringIdeal - m_steeringReduced) / fd;
const float asi = std::max(m_steeringReduced + step, (m_steeringIncrement - step));
m_steeringIncrement = asi;
}
else
{
if (*currentSpeed <= (m_steeringReductionSpeed / 2)) m_steeringIncrement = m_steeringIdeal;
else {
const float step = (m_steeringIdeal - m_steeringReduced) / bd;
const float asi = std::min(m_steeringIdeal, (m_steeringIncrement + step));
m_steeringIncrement = asi;
}
}
}
void Vehicle::adjustBrake(int* currentSpeed)
{
static const int fd = 100;
static const int bd = 75;
if (*currentSpeed >= m_brakeReductionSpeed)
{
const float step = (m_idealBrakeGain - m_brakeReduced) / fd;
const float abf = std::max(m_brakeReduced + step, (m_brakeGain - step));
m_brakeGain = abf;
}
else {
const float step = (m_idealBrakeGain - m_steeringReduced) / bd;
const float abf = std::min(m_idealBrakeGain, (m_brakeGain + step));
m_brakeGain = abf;
}
}
void Vehicle::adjustEngineForce(int* currentSpeed)
{
if (*currentSpeed < m_boostLimit)
{
m_speedGain += m_boostGain;
}
}
void Vehicle::updateSounds()
{
if (m_btVehicle && m_vehicleState != VehicleState::END_RACE)
{
const int cv = getCurrentSpeed();
if (InputMap::isKeyActive(InputType::BRAKE))
{
if (!m_brakeSound->isPlaying() && cv >= 30.f) m_brakeSound->play();
}
else {
m_brakeSound->stop();
}
if (!m_engineSound->isPlaying()) m_engineSound->play(); m_engineSound->setVolume(.6);
const float factor = cv / 100.f;
m_engineSound->setPitch(std::max(0.2f, std::min(factor, 2.f)));
}
}
void Vehicle::onEvent(int type, void* data)
{
CollisionListener::onEvent(type, data);
switch (type)
{
case EventType::VEHICLE_UPSIDE_DOWN:
if (m_ownerPlayer->isLocal())
readjustVehicle();
break;
case EventType::START_OFF_FIRE:
if (m_raceTimer == NULL)
m_raceTimer = new Timer();
else
m_raceTimer->reset();
m_rigidBody->forceActivationState(DISABLE_DEACTIVATION);
m_logger->logMessage("Vehicle chassis simulation enabled");
m_vehicleState = VehicleState::IN_RACE;
m_ownerPlayer->setPlayerState(PlayerState::RACING);
break;
default:
break;
}
}
void Vehicle::onCollisionStart(CollisionEventData* colData)
{
PhysicsObject* other = getOtherOffCollision(colData);
switch (other->getType())
{
case GameObjectType::TYPE_CHECKPOINT:
if (m_vehicleState != VehicleState::IN_RACE) // Skip CountDown CheckPoint collisions
{
break;
}
const int wpIndex = StringConverter::parseInt(other->getID());
if (m_lastPassedWaypointIndex < 0)
{
if (wpIndex != 2)
break;
}
else if (m_lastPassedWaypointIndex == wpIndex)
{
break;
}
// Store last checkpoint's position so when crashed, vehicle will be moved onto it
m_latestWaypointPos = const_cast<Vector3*> (&other->getNode()->_getDerivedPosition());
Waypoint* passedWaypoint = NULL;
auto finder = m_trackWaypoints.find(wpIndex);
if (finder == m_trackWaypoints.end())
{
assert(passedWaypoint != NULL && "Indexed Waypoint couldn't be fetched!");
break;
}
passedWaypoint = finder->second;
passedWaypoint->onPass();
m_logger->logMessage("Waypoint " + StringConverter::toString(wpIndex) + " visited");
if (passedWaypoint->isPassed())
{
m_trackWaypoints.erase(wpIndex);
m_manager->destroy(other);
}
PlayerStats* stats = m_ownerPlayer->getPlayerStats();
if (m_trackWaypoints.empty()) // Player completed track
{
m_engineSound->stop();
m_brakeSound->stop();
m_logger->logMessage("Vehicle Sound FX stopped");
SoundEffect* celebration = AudioManager::getSingleton().createSoundEffect("finish_line.aiff");
celebration->play();
stats->currentLap++;
assert(stats->currentLap <= MAX_LAP_COUNT);
const unsigned long overallTime = m_raceTimer->getMilliseconds();
// Check to prevent 1-lapped track ending
if (stats->currentLap == 1)
{
stats->lapTimes[0] = overallTime;
}
else
{
// If the track is not 1-lapped, previous lap timing is current - sum of all previous laps' timing
stats->lapTimes[stats->currentLap - 1] = overallTime - RaceManager::getSingleton().computePrevLapsSum(m_ownerPlayer);
}
m_vehicleState = VehicleState::END_RACE;
m_manager->getPhysicsManager()->destroyVehicle(this);
EventManager::getSingleton().notify(EventType::TRACK_COMPLETE, m_ownerPlayer);
}
else
{
if (wpIndex == 1) // Passing first waypoint whose location index is 1 means one lap's completed.
{
if (m_lastPassedWaypointIndex > 0)
{
stats->currentLap++;
assert(stats->currentLap <= MAX_LAP_COUNT && "Lap count exceeds PlayerStats!");
const unsigned long overallTime = m_raceTimer->getMilliseconds();
if (stats->currentLap == 1)
{
stats->lapTimes[0] = overallTime;
}
else
{
stats->lapTimes[stats->currentLap - 1] = overallTime - RaceManager::getSingleton().computePrevLapsSum(m_ownerPlayer);
}
EventManager::getSingleton().notify(EventType::LAP_COMPLETE, m_ownerPlayer);
}
}
}
m_lastPassedWaypointIndex = wpIndex;
break;
}
}
void Vehicle::onCollisionTime(CollisionEventData* colData)
{
PhysicsObject* other = getOtherOffCollision(colData);
}
void Vehicle::onCollisionEnd(CollisionEventData* data)
{
PhysicsObject* other = getOtherOffCollision(data);
}
void Vehicle::handleNeutral(int* currentSpeed)
{
// TODO: Handle neutral vehicle !!!
m_engineForce = 0.f;
if (*currentSpeed != 0)
{
if (*currentSpeed >= 100)
m_brakeForce += (m_brakeGain * .005);
else
m_brakeForce += (m_brakeGain * .0025);
}
}
bool Vehicle::readjustVehicle()
{
static const btVector3& zero = btVector3(0, 0, 0);
m_rigidBody->forceActivationState(DISABLE_SIMULATION);
m_logger->logMessage("Vehicle chassis disabled !");
if (m_vehicleState != VehicleState::IN_RACE) return false;
m_rigidBody->setLinearVelocity(zero);
m_rigidBody->setAngularVelocity(zero);
btTransform currentTransform = m_btVehicle->getChassisWorldTransform();
btVector3& pos = currentTransform.getOrigin();
btQuaternion rot = currentTransform.getRotation();
pos.setY(pos.y() + 2.5);
float angle = 0.f;
if (pos.x() * pos.x() + pos.z() * pos.z() > 0)
{
angle += Math::ATan2(-pos.x(), -pos.z()).valueDegrees();
}
rot.setRotation(btVector3(0, 1, 0), angle);
currentTransform.setRotation(rot);
if (m_lastPassedWaypointIndex < 0 || m_latestWaypointPos == NULL)
{
const Vector3& pos = m_manager->getGameObjectByID(StringConverter::toString(m_trackWaypoints.find(1)->second->getLocationIndex()))->getNode()->_getDerivedPosition();
m_latestWaypointPos = const_cast<Vector3*> (&pos);
}
currentTransform.setOrigin(BtOgre::Convert::toBullet(*m_latestWaypointPos));
m_rigidBody->setWorldTransform(currentTransform);
m_rigidBody->forceActivationState(DISABLE_DEACTIVATION);
m_logger->logMessage("Vehicle chassis enabled!");
m_logger->logMessage("Vehicle readjusted!");
return false;
}
void Vehicle::setupVisuals()
{
for (size_t i = 0; i < WHEEL_COUNT; i++)
{
NameValuePairList params;
params["numberOfChains"] = "1";
params["maxElements"] = "100";
RibbonTrail* trail = (RibbonTrail*) m_sceneMgr->createMovableObject("RibbonTrail", ¶ms);
m_sceneMgr->getRootSceneNode()->attachObject(trail);
trail->setMaterialName("TireTrail");
trail->setTrailLength(100);
trail->setInitialColour(0, 0.1, 0.1, 0.1);
//trail->setInitialColour(0, 0.1, 0.1, 0.1, 0);
trail->setColourChange(0, 0.08, 0.08, 0.08, 0.08);
trail->setFaceCamera(false, Vector3::UNIT_Y);
//trail->setUseTextureCoords(true);
trail->setCastShadows(false);
trail->setUseVertexColours(true);
trail->setInitialWidth(0, 1);
trail->setRenderQueueGroup(m_entity->getRenderQueueGroup() + 1);
trail->addNode(m_wheels[i]->getNode());
m_trailMO[i] = trail;
}
m_logger->logMessage("Vehicle visuals set up");
}
| 28.842365
| 167
| 0.728779
|
NotCamelCase
|
58fa12fcd221fec27eca3ae7f5202804d6b04b2a
| 3,172
|
hpp
|
C++
|
src/libblockchain/transaction_sponsoring.hpp
|
publiqnet/publiq.pp
|
0865494edaa22ea2e3238aaf01cdb9e457535933
|
[
"MIT"
] | 4
|
2019-11-20T17:27:57.000Z
|
2021-01-05T09:46:20.000Z
|
src/libblockchain/transaction_sponsoring.hpp
|
publiqnet/publiq.pp
|
0865494edaa22ea2e3238aaf01cdb9e457535933
|
[
"MIT"
] | null | null | null |
src/libblockchain/transaction_sponsoring.hpp
|
publiqnet/publiq.pp
|
0865494edaa22ea2e3238aaf01cdb9e457535933
|
[
"MIT"
] | 2
|
2019-01-10T14:10:26.000Z
|
2020-03-01T05:55:05.000Z
|
#pragma once
#include "global.hpp"
#include "message.hpp"
#include "node.hpp"
#include "state.hpp"
#include <string>
#include <vector>
namespace publiqpp
{
// sponsoring stuff
std::vector<std::string> action_owners(BlockchainMessage::SponsorContentUnit const& sponsor_content_unit);
std::vector<std::string> action_participants(BlockchainMessage::SponsorContentUnit const& sponsor_content_unit);
void action_validate(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
bool check_complete);
bool action_is_complete(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit);
bool action_can_apply(publiqpp::detail::node_internals const& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
state_layer layer);
void action_apply(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
state_layer layer);
void action_revert(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::SponsorContentUnit const& sponsor_content_unit,
state_layer layer);
// cancel sponsoring stuff
std::vector<std::string> action_owners(BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit);
std::vector<std::string> action_participants(BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit);
void action_validate(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
bool check_complete);
bool action_is_complete(BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit);
bool action_can_apply(publiqpp::detail::node_internals const& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
state_layer layer);
void action_apply(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
state_layer layer);
void action_revert(publiqpp::detail::node_internals& impl,
BlockchainMessage::SignedTransaction const& signed_transaction,
BlockchainMessage::CancelSponsorContentUnit const& cancel_sponsor_content_unit,
state_layer layer);
}
| 48.8
| 125
| 0.728247
|
publiqnet
|
58fbaa3a1b2267f5ad48045b5966096805c1ac18
| 601
|
cpp
|
C++
|
999_Practice_Set_2/Day_012/074_pair_sum_problem.cpp
|
Binamra7/Data-Structure-and-Algorithms
|
1232fdeba041c678b4c651f6a702d50b344ed4cc
|
[
"MIT"
] | 126
|
2019-12-22T17:49:08.000Z
|
2021-12-14T18:45:51.000Z
|
999_Practice_Set_2/Day_012/074_pair_sum_problem.cpp
|
Divyanshi-03/Data-Structure-and-Algorithms
|
21b02dd312105411621242731106411defbd6ddb
|
[
"MIT"
] | 7
|
2019-12-25T18:03:41.000Z
|
2021-02-20T06:25:27.000Z
|
999_Practice_Set_2/Day_012/074_pair_sum_problem.cpp
|
Divyanshi-03/Data-Structure-and-Algorithms
|
21b02dd312105411621242731106411defbd6ddb
|
[
"MIT"
] | 54
|
2019-12-26T06:28:39.000Z
|
2022-02-01T05:04:43.000Z
|
// Check if there exists two elements in an array such that their sum is equal to given k.
#include <iostream>
using namespace std;
bool pairSum(int arr[], int n, int k)
{
for(int i=0; i<n-1; i++)
{
for(int j=i+1; j<n; j++)
{
if(arr[i] + arr[j] == k)
{
cout<<i<<" & "<<j<<endl;
return true;
}
}
}
return false;
}
int main()
{
int n;
cin>>n;
int k;
cin>>k;
int arr[n];
for(int i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<pairSum(arr, n, k)<<endl;
}
| 15.410256
| 90
| 0.432612
|
Binamra7
|
58fff242aa8aa3db3d4faceb6c54aa4fac6556f2
| 966
|
hpp
|
C++
|
utils/resource_loader.hpp
|
UnnamedOrange/osu-kps
|
b893d1fb75f001ac6bb5951182590dc0096a1e0e
|
[
"MIT"
] | 21
|
2021-02-15T17:10:50.000Z
|
2022-01-23T05:02:12.000Z
|
utils/resource_loader.hpp
|
UnnamedOrange/osu-kps
|
b893d1fb75f001ac6bb5951182590dc0096a1e0e
|
[
"MIT"
] | 4
|
2021-02-15T16:23:52.000Z
|
2021-12-30T14:04:01.000Z
|
utils/resource_loader.hpp
|
UnnamedOrange/osu-kps
|
b893d1fb75f001ac6bb5951182590dc0096a1e0e
|
[
"MIT"
] | 2
|
2021-07-23T02:29:11.000Z
|
2021-09-05T04:09:55.000Z
|
// Copyright (c) UnnamedOrange. Licensed under the MIT Licence.
// See the LICENSE file in the repository root for full licence text.
#pragma once
#include <vector>
#include <string_view>
#include <stdexcept>
#include <Windows.h>
#undef min
#undef max
class resource_loader
{
public:
static auto load(const wchar_t* resource_name, const wchar_t* type_name)
{
HINSTANCE hInstance = GetModuleHandleW(nullptr);
HRSRC hResInfo = FindResourceW(hInstance,
resource_name, type_name);
if (!hResInfo)
throw std::runtime_error("fail to FindResourceW.");
HGLOBAL hResource = LoadResource(hInstance, hResInfo);
if (!hResource)
throw std::runtime_error("fail to LoadResource.");
DWORD dwSize = SizeofResource(hInstance, hResInfo);
if (!dwSize)
throw std::runtime_error("fail to SizeofResource.");
BYTE* p = reinterpret_cast<BYTE*>(LockResource(hResource));
std::vector<BYTE> ret(p, p + dwSize);
FreeResource(hResource);
return ret;
}
};
| 26.833333
| 73
| 0.736025
|
UnnamedOrange
|
4502d349f350bfdd903d9c815ad937a7a387f148
| 1,547
|
cpp
|
C++
|
src/source/zombye/gameplay/states/play_state.cpp
|
kasoki/project-zombye
|
30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05
|
[
"MIT"
] | 1
|
2019-05-29T01:37:44.000Z
|
2019-05-29T01:37:44.000Z
|
src/source/zombye/gameplay/states/play_state.cpp
|
atomicptr/project-zombye
|
30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05
|
[
"MIT"
] | 1
|
2015-08-31T22:44:27.000Z
|
2015-08-31T22:44:27.000Z
|
src/source/zombye/gameplay/states/play_state.cpp
|
kasoki/project-zombye
|
30d3dc0b7e6a929162fa0ddfb77dd10bc9bf4f05
|
[
"MIT"
] | null | null | null |
#include <cmath>
#include <glm/gtc/matrix_transform.hpp>
#include <SDL2/SDL.h>
#include <zombye/core/game.hpp>
#include <zombye/ecs/entity_manager.hpp>
#include <zombye/gameplay/states/play_state.hpp>
#include <zombye/input/input_manager.hpp>
#include <zombye/input/input_system.hpp>
#include <zombye/input/joystick.hpp>
#include <zombye/input/mouse.hpp>
#include <zombye/physics/shapes/box_shape.hpp>
#include <zombye/physics/physics_component.hpp>
#include <zombye/rendering/animation_component.hpp>
#include <zombye/rendering/camera_component.hpp>
#include <zombye/rendering/rendering_system.hpp>
#include <zombye/scripting/scripting_system.hpp>
#include <zombye/utils/logger.hpp>
#include <zombye/utils/state_machine.hpp>
zombye::play_state::play_state(zombye::state_machine *sm) : sm_(sm) {
auto input = sm->get_game()->input();
input_ = input->create_manager();
input_->register_actions(*sm->get_game(), "scripts/input/play_state.as");
input_->load_config(*sm->get_game(), "config/input/play_state.json");
}
void zombye::play_state::enter() {
zombye::log("enter play state");
auto& game = *sm_->get_game();
auto& scripting_system = game.scripting_system();
scripting_system.begin_module("MyModule");
scripting_system.load_script("scripts/test.as");
scripting_system.end_module();
scripting_system.exec("void main()", "MyModule");
}
void zombye::play_state::leave() {
zombye::log("leave play state");
}
void zombye::play_state::update(float delta_time) {
input_->handle_input();
}
| 31.571429
| 77
| 0.740142
|
kasoki
|
4505cdbd048ad5797de47fbbefcacffec70c99d9
| 3,815
|
cpp
|
C++
|
tests/test_queries.cpp
|
sinkarl/asp_db
|
8dc5b40257b438872a689f5894416ae80db7d7ca
|
[
"MIT"
] | null | null | null |
tests/test_queries.cpp
|
sinkarl/asp_db
|
8dc5b40257b438872a689f5894416ae80db7d7ca
|
[
"MIT"
] | null | null | null |
tests/test_queries.cpp
|
sinkarl/asp_db
|
8dc5b40257b438872a689f5894416ae80db7d7ca
|
[
"MIT"
] | null | null | null |
#include "asp_db/db_queries_setup.h"
#include "asp_db/db_queries_setup_select.h"
#include "asp_db/db_tables.h"
#include "asp_db/db_where.h"
#include "library_tables.h"
#include "gtest/gtest.h"
#include <filesystem>
#include <iostream>
#include <numeric>
#include <assert.h>
LibraryDBTables ldb;
TEST(db_where_tree, DBTableBetween) {
// text field
WhereTreeConstructor<table_book> adb(&ldb);
// todo: не прозрачна связь между параметром шаблона и id столбца
auto between_t = adb.Between(BOOK_TITLE, "a", "z");
std::string btstr = std::string(BOOK_TITLE_NAME) + " between 'a' and 'z'";
EXPECT_STRCASEEQ(between_t->GetString().c_str(), btstr.c_str());
// int field
auto between_p = adb.Between(BOOK_PUB_YEAR, 1920, 1985);
std::string bpstr =
std::string(BOOK_PUB_YEAR_NAME) + " between 1920 and 1985";
EXPECT_STRCASEEQ(between_p->GetString().c_str(), bpstr.c_str());
// вынесены в test_excpression.cpp
}
TEST(db_where_tree, DBTable2Operations) {
WhereTreeConstructor<table_author> adb(&ldb);
auto eq_t = adb.Eq(AUTHOR_NAME, "Leo Tolstoy");
std::string eqtstr = std::string(AUTHOR_NAME_NAME) + " = 'Leo Tolstoy'";
EXPECT_STRCASEEQ(eq_t->GetString().c_str(), eqtstr.c_str());
// todo: add cases for other operators
}
TEST(db_where_tree, DBTableAnd) {
WhereTreeConstructor<table_book> adb(&ldb);
auto eq_t1 = adb.Eq(BOOK_TITLE, "Hobbit");
// todo: how about instatnces for enums???
auto eq_t2 = adb.Eq(BOOK_LANG, (int)lang_eng);
auto gt_t3 = adb.Gt(BOOK_PUB_YEAR, 1900);
// check
// and1
auto and1 = adb.And(eq_t1, eq_t2);
std::string and1_s = "(" + std::string(BOOK_TITLE_NAME) + " = 'Hobbit'" +
") AND (" + BOOK_LANG_NAME + " = 2)";
EXPECT_STRCASEEQ(and1->GetString().c_str(), and1_s.c_str());
// and2
auto and2 = adb.And(eq_t1, gt_t3);
std::string and2_s = "(" + std::string(BOOK_TITLE_NAME) + " = 'Hobbit'" +
") AND (" + BOOK_PUB_YEAR_NAME + " > 1900)";
EXPECT_STRCASEEQ(and2->GetString().c_str(), and2_s.c_str());
// and3
auto and3 = adb.And(eq_t1, eq_t2, gt_t3);
std::string and3_s = "((" + std::string(BOOK_TITLE_NAME) + " = 'Hobbit'" +
") AND (" + BOOK_LANG_NAME + " = 2" +
")) AND (" BOOK_PUB_YEAR_NAME + " > 1900)";
EXPECT_STRCASEEQ(and3->GetString().c_str(), and3_s.c_str());
// check nullptr
// and4
wns::node_ptr null_t4 = nullptr;
eq_t1 = adb.Eq(BOOK_TITLE, "Hobbit");
auto and4 = adb.And(eq_t1, null_t4);
std::string and4_s = std::string(BOOK_TITLE_NAME) + " = 'Hobbit'";
EXPECT_STRCASEEQ(and4->GetString().c_str(), and4_s.c_str());
// and5
wns::node_ptr null_t5 = nullptr;
auto and5 = adb.And(null_t4, null_t5);
EXPECT_STRCASEEQ(and5->GetString().c_str(), "");
}
TEST(WhereTreeConstructor, Init) {
WhereTreeConstructor<table_translation> ts(&ldb);
WhereTree<table_translation> wt(ts);
wt.Init(ts.And(ts.Ge(TRANS_ID, 3), ts.Lt(TRANS_ID, 10),
ts.Eq(TRANS_LANG, int(lang_rus))));
// проверим результат инициализации
std::string wts = std::string("((") + TRANS_ID_NAME + " >= 3) AND (" +
TRANS_ID_NAME + " < 10)) AND (" + TRANS_LANG_NAME + " = " +
std::to_string(int(lang_rus)) + ")";
EXPECT_STRCASEEQ(wt.GetWhereTree()->GetString().c_str(), wts.c_str());
// продолжим
wt.AddOr(ts.And(ts.Gt(TRANS_ID, 13), ts.Lt(TRANS_ID, 15)));
// снова проверим
std::string wfs = std::string("(((") + TRANS_ID_NAME + " >= 3) AND (" +
TRANS_ID_NAME + " < 10)) AND (" + TRANS_LANG_NAME + " = " +
std::to_string(int(lang_rus)) + ")) OR ((" + TRANS_ID_NAME +
" > 13" + ") AND (" + TRANS_ID_NAME + " < 15))";
EXPECT_STRCASEEQ(wt.GetWhereTree()->GetString().c_str(), wfs.c_str());
}
| 37.772277
| 80
| 0.630406
|
sinkarl
|
450634b23083e5eadbd140eda6fe4f83cbf77aaf
| 4,278
|
cpp
|
C++
|
Lab3/src/Utils.cpp
|
Farmijo/VA
|
3a62ef2e3e2f30d97f3dad55a5e0aa8a118d8c1b
|
[
"MIT"
] | null | null | null |
Lab3/src/Utils.cpp
|
Farmijo/VA
|
3a62ef2e3e2f30d97f3dad55a5e0aa8a118d8c1b
|
[
"MIT"
] | null | null | null |
Lab3/src/Utils.cpp
|
Farmijo/VA
|
3a62ef2e3e2f30d97f3dad55a5e0aa8a118d8c1b
|
[
"MIT"
] | null | null | null |
#include "Utils.h"
#include <sstream>
#ifdef WIN32
#include <windows.h>
#else
#include <sys/time.h>
#endif
#include "includes.h"
#include "Application.h"
#include "Camera.h"
long getTime()
{
#ifdef WIN32
return GetTickCount();
#else
struct timeval tv;
gettimeofday( &tv, NULL );
return (int)( tv.tv_sec * 1000 + ( tv.tv_usec / 1000 ) );
#endif
}
//Draw the grid
void drawGrid( float dist )
{
int num_lines = 20;
glLineWidth( 1 );
glColor3f( 0.5, 0.5, 0.5 );
glDisable( GL_TEXTURE_2D );
glBegin( GL_LINES );
for( int i = 0; i <= num_lines >> 1; ++i )
{
float a = float(dist * num_lines) * 0.5f;
float b = i * dist;
if( i == num_lines >> 1 )
glColor3f( 1.f, 0.25f, 0.25f );
else if( i % 2 )
glColor3f( 0.25f, 0.25f, 0.25f );
else
glColor3f( 0.5f, 0.5f, 0.5f );
glVertex3f( a, b, -a );
glVertex3f( -a, b, -a );
glVertex3f( a, -b, -a );
glVertex3f( -a, -b, -a );
glVertex3f( b, a, -a );
glVertex3f( b, -a, -a );
glVertex3f( -b, a, -a );
glVertex3f( -b, -a, -a );
glVertex3f( a, b, a );
glVertex3f( -a, b, a );
glVertex3f( a, -b, a );
glVertex3f( -a, -b, a );
glVertex3f( b, a, a );
glVertex3f( b, -a, a );
glVertex3f( -b, a, a );
glVertex3f( -b, -a, a );
glVertex3f( a, -a, b );
glVertex3f( -a, -a, b );
glVertex3f( a, -a, -b );
glVertex3f( -a, -a, -b );
glVertex3f( b, -a, a );
glVertex3f( b, -a, -a );
glVertex3f( -b, -a, a );
glVertex3f( -b, -a, -a );
glVertex3f( -a, a, b );
glVertex3f( -a, -a, b );
glVertex3f( -a, a, -b );
glVertex3f( -a, -a, -b );
glVertex3f( -a, b, a );
glVertex3f( -a, b, -a );
glVertex3f( -a, -b, a );
glVertex3f( -a, -b, -a );
glVertex3f( a, a, b );
glVertex3f( a, -a, b );
glVertex3f( a, a, -b );
glVertex3f( a, -a, -b );
glVertex3f( a, b, a );
glVertex3f( a, b, -a );
glVertex3f( a, -b, a );
glVertex3f( a, -b, -a );
}
glEnd();
glColor3f( 1, 1, 1 );
}
//this function is used to access OpenGL Extensions (special features not supported by all cards)
void* getGLProcAddress( const char* name )
{
return SDL_GL_GetProcAddress( name );
}
//Retrieve the current path of the application
#ifdef __APPLE__
#include "CoreFoundation/CoreFoundation.h"
#endif
#ifdef WIN32
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif
std::string getPath()
{
std::string fullpath;
// ----------------------------------------------------------------------------
// This makes relative paths work in C++ in Xcode by changing directory to the Resources folder inside the .app bundle
#ifdef __APPLE__
CFBundleRef mainBundle = CFBundleGetMainBundle();
CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL( mainBundle );
char path[ PATH_MAX ];
if( !CFURLGetFileSystemRepresentation( resourcesURL, TRUE, (UInt8 *)path, PATH_MAX ) )
{
// error!
}
CFRelease( resourcesURL );
chdir( path );
fullpath = path;
#else
char cCurrentPath[ 1024 ];
if( !GetCurrentDir( cCurrentPath, sizeof( cCurrentPath ) ) )
return "";
cCurrentPath[ sizeof( cCurrentPath ) - 1 ] = '\0';
fullpath = cCurrentPath;
#endif
return fullpath;
}
bool checkGLErrors()
{
#ifdef _DEBUG
GLenum errCode;
const GLubyte *errString;
if( ( errCode = glGetError() ) != GL_NO_ERROR )
{
errString = gluErrorString( errCode );
std::cerr << "OpenGL Error: " << errString << std::endl;
return false;
}
#endif
return true;
}
std::vector<std::string> &split( const std::string &s, char delim, std::vector<std::string> &elems )
{
std::stringstream ss( s );
std::string item;
while( std::getline( ss, item, delim ) )
{
elems.push_back( item );
}
return elems;
}
std::vector<std::string> split( const std::string &s, char delim )
{
std::vector<std::string> elems;
split( s, delim, elems );
return elems;
}
Vector2 getDesktopSize( int display_index )
{
SDL_DisplayMode current;
// Get current display mode of all displays.
int should_be_zero = SDL_GetCurrentDisplayMode( display_index, ¤t );
return Vector2( float( current.w ), float( current.h ) );
}
std::string addCurrentPath( const std::string& p_sInputFile )
{
const char* cCurrentPath = SDL_GetBasePath();
std::stringstream asePathfile;
asePathfile << cCurrentPath << p_sInputFile;
return asePathfile.str();
}
| 21.826531
| 119
| 0.625993
|
Farmijo
|
4508cb48c16844eb379ebe2492f4d32313d48d1b
| 9,011
|
cpp
|
C++
|
src/BldRecons/DualContouring/HistGrid.cpp
|
liuxinren/UrbanReconstruction
|
079d9b0c9089aa9cdb15d31d76155e50a5e72f00
|
[
"MIT"
] | 94
|
2017-07-20T05:32:07.000Z
|
2022-03-02T03:38:54.000Z
|
src/BldRecons/DualContouring/HistGrid.cpp
|
GucciPrada/UrbanReconstruction
|
8b058349fd860ea9029623a92d705dd93a4e4878
|
[
"MIT"
] | 3
|
2017-09-12T00:07:05.000Z
|
2020-03-08T21:12:36.000Z
|
src/BldRecons/DualContouring/HistGrid.cpp
|
GucciPrada/UrbanReconstruction
|
8b058349fd860ea9029623a92d705dd93a4e4878
|
[
"MIT"
] | 38
|
2017-07-25T06:00:52.000Z
|
2022-03-19T10:01:06.000Z
|
#include "StdAfx.h"
#include "HistGrid.h"
#include "Grid\StreamingGrid.h"
#include "Streaming\SPBReader.h"
#include "nr\nr.h"
#include "nr\nrutil.h"
CHistGrid::CHistGrid(void)
{
m_nGridNumber[ 0 ] = m_nGridNumber[ 1 ] = 0;
}
CHistGrid::~CHistGrid(void)
{
}
void CHistGrid::Init( char filename[], char histfilename[] )
{
LoadFromHist( histfilename );
CStreamingGrid grid;
CSPBReader reader;
reader.OpenFile( filename );
reader.RegisterGrid( & grid );
reader.ReadHeader();
reader.CloseFile();
m_cBoundingBox = grid.m_cBoundingBox;
m_nGridNumber[ 0 ] = ( int )( m_cBoundingBox.GetLength( 0 ) / m_cHeader.center_distance ) + 1;
m_nGridNumber[ 1 ] = ( int )( m_cBoundingBox.GetLength( 1 ) / m_cHeader.center_distance ) + 1;
}
void CHistGrid::LoadFromHist( char filename[] )
{
m_cReader.OpenFile( filename );
m_cHeader = m_cReader.ReadHeader();
m_vecCenter.resize( m_cHeader.number );
m_vecHistogram.resize( m_cHeader.number );
for ( int i = 0; i < m_cHeader.number; i++ ) {
m_cReader.ReadCenter( m_vecCenter[ i ] );
m_cReader.ReadHistogram( m_vecHistogram[ i ] );
}
m_cReader.CloseFile();
}
CHistogram & CHistGrid::LocateHistogram( CVector3D & v )
{
CVector3D diff = v - m_cBoundingBox.m_vMin;
int x = ( int )( diff[0] / m_cHeader.center_distance );
if ( x < 0 )
x = 0;
if ( x >= m_nGridNumber[ 0 ] )
x = m_nGridNumber[ 0 ] - 1;
int y = ( int )( diff[1] / m_cHeader.center_distance );
if ( y < 0 )
y = 0;
if ( y >= m_nGridNumber[ 1 ] )
y = m_nGridNumber[ 1 ] - 1;
return m_vecHistogram[ x * m_nGridNumber[ 1 ] + y ];
}
void CHistGrid::Simplify( CDCContourer & contourer, double error_tolerance, double minimum_length )
{
m_pMesh = & contourer.m_cMesh;
m_pBoundary = & contourer.m_cBoundary;
m_pGrid = contourer.m_pGrid;
m_dbErrorTolerance = error_tolerance;
m_dbMinimumLength = minimum_length;
m_pBoundary->Init( m_pMesh );
for ( int i = 0; i < ( int )m_pBoundary->m_vecBoundary.size(); i++ ) {
FittingPrincipalDirection( m_pBoundary->m_vecBoundarySeq[ i ] );
FixVertices( m_pBoundary->m_vecBoundarySeq[ i ] );
}
}
void CHistGrid::FittingPrincipalDirection( int ibdr )
{
CMeshBoundary::CAuxBoundary & bdr = m_pBoundary->m_vecBoundary[ ibdr ];
int loop_num = ( int )bdr.vi.size();
std::vector< AuxVertex > verts( bdr.vi.size() );
std::vector< AuxLine > lines;
bool line_added = true;
while ( line_added ) {
line_added = false;
AuxLine max_line;
max_line.acc_length = 0.0;
max_line.acc_error = 0.0;
for ( int i = 0; i < ( int )bdr.vi.size(); i++ ) {
int vi = bdr.vi[ i ];
if ( verts[ i ].t == FT_Free || ( verts[ i ].t == FT_HalfFixed && verts[ i ].li[ 1 ] != -1 ) ) {
CVector3D loc( m_pMesh->m_vecVertex[ vi ].v );
std::vector< double > & peak = LocateHistogram( loc ).m_vecPeak;
for ( int j = 0; j < ( int )peak.size(); j++ ) {
CLine temp_line;
temp_line.p = CVector3D( m_pMesh->m_vecVertex[ vi ].v );
temp_line.d = CVector3D( cos( peak[j] ), sin( peak[j] ), 0.0 );
int k_forward = 0, k_backward = 0;
int iteration_step = m_pBoundary->m_vecGroupInfo[ vi ].fixed ? 1 : 3;
double acc_length = 0.0;
double acc_error = 0.0;
for ( int step = 0; step < iteration_step; step++ ) {
acc_length = 0.0;
acc_error = 0.0;
if ( ( acc_error = temp_line.dis( CVector3D( m_pMesh->m_vecVertex[ vi ].v ) ) ) > m_dbErrorTolerance ) {
k_forward = k_backward = 0;
break;
}
for ( k_forward = 1; k_forward < loop_num; k_forward++ ) {
int idx = ( i + k_forward ) % loop_num;
double error = temp_line.dis( CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) );
if ( m_pBoundary->m_vecGroupInfo[ bdr.vi[ idx ] ].fixed
|| verts[ idx ].t == FT_Fixed
|| ( verts[ idx ].t == FT_HalfFixed && verts[ idx ].li[1] != -1 )
|| error > m_dbErrorTolerance )
{
break;
} else if ( verts[ idx ].t == FT_HalfFixed )
{
if ( lines[ verts[ idx ].li[ 0 ] ].pi == j ) {
break;
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_forward - 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
k_forward++;
break;
}
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_forward - 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
}
}
if ( k_forward < loop_num ) {
for ( k_backward = -1; k_backward > -loop_num; k_backward-- ) {
int idx = ( i + k_backward + loop_num ) % loop_num;
double error = temp_line.dis( CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) );
if ( m_pBoundary->m_vecGroupInfo[ bdr.vi[ idx ] ].fixed
|| verts[ idx ].t == FT_Fixed
|| ( verts[ idx ].t == FT_HalfFixed && verts[ idx ].li[1] != -1 )
|| error > m_dbErrorTolerance )
{
break;
} else if ( verts[ idx ].t == FT_HalfFixed )
{
if ( lines[ verts[ idx ].li[ 0 ] ].pi == j ) {
break;
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_backward + loop_num + 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
k_backward--;
break;
}
} else {
CVector3D vdiff = CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ idx ] ].v ) - CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k_backward + loop_num + 1 ) % loop_num ] ].v );
vdiff.pVec[2] = 0.0;
acc_length += vdiff.length();
acc_error += error;
}
}
k_backward++;
}
if ( m_pBoundary->m_vecGroupInfo[ vi ].fixed == false ) {
// use iteration
// update temp_line.p
if ( acc_length > m_dbMinimumLength ) {
temp_line.p = CVector3D( 0.0, 0.0, 0.0 );
for ( int k = k_backward; k < k_forward; k++ ) {
temp_line.p += CVector3D( m_pMesh->m_vecVertex[ bdr.vi[ ( i + k + loop_num ) % loop_num ] ].v );
}
temp_line.p /= ( double )( k_forward - k_backward );
}
}
}
int k_number = k_forward - k_backward;
if ( acc_length > m_dbMinimumLength && IsBetterMaxLine( acc_length, acc_error, max_line ) ) {
//printf_s( "%8.6f\n", peak[ j ] );
max_line.l = temp_line;
max_line.pi = j;
max_line.acc_length = acc_length;
max_line.vi.clear();
for ( int k = k_backward; k < k_forward; k++ ) {
max_line.vi.push_back( ( i + k + loop_num ) % loop_num );
}
}
}
}
}
if ( max_line.acc_length > m_dbMinimumLength && ( int )max_line.vi.size() < loop_num ) {
// push max_line to aux
int line_idx = ( int )lines.size();
lines.push_back( max_line );
for ( int i = 0; i <= ( int )( max_line.vi.size() - 1 ); i += ( int )( max_line.vi.size() - 1 ) ) {
verts[ max_line.vi[ i ] ].t = FT_HalfFixed;
if ( verts[ max_line.vi[ i ] ].li[ 0 ] == -1 ) {
verts[ max_line.vi[ i ] ].li[ 0 ] = line_idx;
} else {
verts[ max_line.vi[ i ] ].li[ 1 ] = line_idx;
}
}
for ( int i = 1; i < ( int )max_line.vi.size() - 1; i++ ) {
verts[ max_line.vi[ i ] ].t = FT_Fixed;
verts[ max_line.vi[ i ] ].li[ 0 ] = line_idx;
}
line_added = true;
}
}
FittingSimplify( bdr, verts, lines );
}
void CHistGrid::FittingSimplify( CMeshBoundary::CAuxBoundary & bdr, std::vector< AuxVertex > & verts, std::vector< AuxLine > & lines )
{
for ( int i = 0; i < ( int )bdr.vi.size(); i++ ) {
int vi = bdr.vi[ i ];
CVector3D v( m_pMesh->m_vecVertex[ vi ].v );
if ( verts[ i ].t == FT_Fixed || ( verts[ i ].t == FT_HalfFixed && verts[ i ].li[ 1 ] == -1 ) ) {
v = lines[ verts[ i ].li[ 0 ] ].l.project( v );
} else if ( verts[ i ].t == FT_HalfFixed ) {
CVector3D inter = lines[ verts[ i ].li[ 0 ] ].l ^ lines[ verts[ i ].li[ 1 ] ].l;
inter.pVec[ 2 ] = v.pVec[ 2 ];
if ( ( inter - v ).length() < m_dbErrorTolerance * 1.414 ) {
v = inter;
}
} else {
// do nothing
}
m_pMesh->m_vecVertex[ vi ].v[ 0 ] = v.pVec[ 0 ];
m_pMesh->m_vecVertex[ vi ].v[ 1 ] = v.pVec[ 1 ];
}
}
void CHistGrid::FixVertices( int ibdr )
{
CMeshBoundary::CAuxBoundary & bdr = m_pBoundary->m_vecBoundary[ ibdr ];
for ( int i = 0; i < ( int )bdr.vi.size(); i++ ) {
int vi = bdr.vi[ i ];
CMeshBoundary::CVertexGroupInfo & hi = m_pBoundary->m_vecGroupInfo[ vi ];
for ( int j = 0; j < hi.number; j++ ) {
int vvi = vi - hi.index + j;
m_pMesh->m_vecVertex[ vvi ].v[ 0 ] = m_pMesh->m_vecVertex[ vi ].v[ 0 ];
m_pMesh->m_vecVertex[ vvi ].v[ 1 ] = m_pMesh->m_vecVertex[ vi ].v[ 1 ];
m_pBoundary->m_vecGroupInfo[ vvi ].fixed = true;
}
}
}
| 31.506993
| 177
| 0.577183
|
liuxinren
|
4509d3c0968ba0bba96943f5365a8882fdc6d99b
| 11,188
|
cpp
|
C++
|
view/src/dialogs/create_strategy_dialog.cpp
|
Rapprise/b2s-trader
|
ac8a3c2221d15c4df8df63842d20dafd6801e535
|
[
"BSD-2-Clause"
] | 21
|
2020-06-07T20:34:47.000Z
|
2021-08-10T20:19:59.000Z
|
view/src/dialogs/create_strategy_dialog.cpp
|
Rapprise/b2s-trader
|
ac8a3c2221d15c4df8df63842d20dafd6801e535
|
[
"BSD-2-Clause"
] | null | null | null |
view/src/dialogs/create_strategy_dialog.cpp
|
Rapprise/b2s-trader
|
ac8a3c2221d15c4df8df63842d20dafd6801e535
|
[
"BSD-2-Clause"
] | 4
|
2020-07-13T10:19:44.000Z
|
2022-03-11T12:15:43.000Z
|
/*
* Copyright (c) 2020, Rapprise.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY 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 "include/dialogs/create_strategy_dialog.h"
#include "include/dialogs/bb_advanced_settings_dialog.h"
#include "include/dialogs/bb_settings_dialog.h"
#include "include/dialogs/ema_settings_dialog.h"
#include "include/dialogs/moving_average_crossing_settings_dialog.h"
#include "include/dialogs/rsi_settings_dialog.h"
#include "include/dialogs/sma_settings_dialog.h"
#include "include/dialogs/stochastic_oscillator_dialog.h"
namespace auto_trader {
namespace view {
namespace dialogs {
CreateStrategyDialog::CreateStrategyDialog(common::AppListener &appListener,
common::GuiListener &guiListener, DialogType dialogType,
QWidget *parent)
: QDialog(parent),
appListener_(appListener),
guiListener_(guiListener),
dialogType_(dialogType) {
dialog_.setupUi(this);
dialog_.listView->setSelectionMode(QAbstractItemView::ExtendedSelection);
dialog_.listView_2->setSelectionMode(QAbstractItemView::SingleSelection);
dialog_.listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
dialog_.listView_2->setEditTriggers(QAbstractItemView::NoEditTriggers);
customStrategySettings_ = std::make_unique<model::CustomStrategySettings>();
strategySettingsFactory_ = std::make_unique<model::StrategySettingsFactory>();
initStrategiesList();
sizeHint();
checkOkButtonStatus(QString());
connect(dialog_.pushButton, SIGNAL(clicked()), this, SLOT(selectStrategy()));
connect(dialog_.pushButton_2, SIGNAL(clicked()), this, SLOT(removeStrategy()));
connect(dialog_.pushButton_3, SIGNAL(clicked()), this, SLOT(editStrategy()));
connect(dialog_.buttonBox, SIGNAL(accepted()), this, SLOT(closeDialog()));
connect(dialog_.buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
connect(dialog_.lineEdit, SIGNAL(textChanged(const QString &)), this,
SLOT(checkOkButtonStatus(const QString &)));
connect(this, SIGNAL(strategiesNumberChanged(const QString &)), this,
SLOT(checkOkButtonStatus(const QString &)));
}
void CreateStrategyDialog::setupDefaultParameters(const model::CustomStrategySettings &settings) {
customStrategyName_ = settings.name_;
dialog_.textEdit->insertPlainText(QString::fromStdString(settings.description_));
dialog_.lineEdit->setText(QString::fromStdString(customStrategyName_));
for (int index = 0; index < settings.strategies_.size(); index++) {
auto strategy = settings.strategies_.at(index).get();
selectedStrategiesList_->append(QString::fromStdString(strategy->name_));
strategySettings_.insert(std::make_pair<>(strategy->strategiesType_, strategy->clone()));
}
selectedStrategiesModel_->setStringList(*selectedStrategiesList_);
checkOkButtonStatus(QString());
}
void CreateStrategyDialog::selectStrategy() {
for (const QModelIndex &index : dialog_.listView->selectionModel()->selectedIndexes()) {
auto selectedStrategy = currentStrategiesModel_->data(index).toString();
if (selectedStrategiesList_->indexOf(selectedStrategy) == -1) {
selectedStrategiesList_->append(selectedStrategy);
common::StrategiesType type =
common::convertStrategyTypeFromString(selectedStrategy.toStdString());
const std::string strategyName = selectedStrategy.toStdString();
auto strategySettings = strategySettingsFactory_->createStrategySettings(type);
strategySettings->strategiesType_ = type;
strategySettings->name_ = strategyName;
strategySettings_.insert(std::make_pair<>(type, std::move(strategySettings)));
}
}
selectedStrategiesModel_->setStringList(*selectedStrategiesList_);
emit strategiesNumberChanged(QString());
}
void CreateStrategyDialog::removeStrategy() {
QModelIndex modelIndex = dialog_.listView_2->currentIndex();
QString itemText = modelIndex.data(Qt::DisplayRole).toString();
common::StrategiesType type = common::convertStrategyTypeFromString(itemText.toStdString());
strategySettings_.erase(type);
int indexToRemove = selectedStrategiesList_->indexOf(itemText);
selectedStrategiesList_->removeAt(indexToRemove);
selectedStrategiesModel_->setStringList(*selectedStrategiesList_);
emit strategiesNumberChanged(QString());
}
void CreateStrategyDialog::editStrategy() {
QModelIndex modelIndex = dialog_.listView_2->currentIndex();
QString itemText = modelIndex.data(Qt::DisplayRole).toString();
common::StrategiesType type = common::convertStrategyTypeFromString(itemText.toStdString());
openEditStrategySettingsDialog(type);
}
void CreateStrategyDialog::initStrategiesList() {
currentStrategiesList_ = new QStringList();
selectedStrategiesList_ = new QStringList();
auto lastElement = (unsigned short)common::StrategiesType::UNKNOWN;
for (unsigned short index = 0; index < lastElement; ++index) {
auto type = (common::StrategiesType)index;
// TODO: Add MACD indicator to UI
if (type != common::StrategiesType::CUSTOM && type != common::StrategiesType::MACD) {
const std::string strategyStr = common::convertStrategyTypeToString(type);
currentStrategiesList_->append(QString::fromStdString(strategyStr));
}
}
currentStrategiesModel_ = new QStringListModel(*currentStrategiesList_, this);
selectedStrategiesModel_ = new QStringListModel(*selectedStrategiesList_, this);
dialog_.listView->setModel(currentStrategiesModel_);
dialog_.listView_2->setModel(selectedStrategiesModel_);
}
void CreateStrategyDialog::openEditStrategySettingsDialog(common::StrategiesType type) {
auto &strategySettings = strategySettings_[type];
switch (type) {
case common::StrategiesType::BOLLINGER_BANDS: {
auto bbSettings = dynamic_cast<model::BollingerBandsSettings *>(strategySettings.get());
auto dialog = new BBSettingsDialog(*bbSettings, appListener_, guiListener_,
BBSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::BOLLINGER_BANDS_ADVANCED: {
auto bbAdvancedSettings =
dynamic_cast<model::BollingerBandsAdvancedSettings *>(strategySettings.get());
auto dialog = new BBAdvancedSettingsDialog(*bbAdvancedSettings, appListener_, guiListener_,
BBAdvancedSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::SMA: {
auto smaSettings = dynamic_cast<model::SmaSettings *>(strategySettings.get());
auto dialog = new SmaSettingsDialog(*smaSettings, appListener_, guiListener_,
SmaSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::EMA: {
auto emaSettings = dynamic_cast<model::EmaSettings *>(strategySettings.get());
auto dialog = new EmaSettingsDialog(*emaSettings, appListener_, guiListener_,
EmaSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::RSI: {
auto rsiSettings = dynamic_cast<model::RsiSettings *>(strategySettings.get());
auto dialog = new RsiSettingsDialog(*rsiSettings, appListener_, guiListener_,
RsiSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::MA_CROSSING: {
auto maCrossings =
dynamic_cast<model::MovingAveragesCrossingSettings *>(strategySettings.get());
auto dialog = new MovingAverageCrossingSettingsDialog(
*maCrossings, appListener_, guiListener_, MovingAverageCrossingSettingsDialog::CREATE,
this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
case common::StrategiesType::STOCHASTIC_OSCILLATOR: {
auto stochasticOscillator =
dynamic_cast<model::StochasticOscillatorSettings *>(strategySettings.get());
auto dialog =
new StochasticOscillatorSettingsDialog(*stochasticOscillator, appListener_, guiListener_,
StochasticOscillatorSettingsDialog::CREATE, this);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
} break;
default:
break;
}
}
void CreateStrategyDialog::closeDialog() {
customStrategySettings_->name_ = dialog_.lineEdit->text().toStdString();
customStrategySettings_->description_ = dialog_.textEdit->toPlainText().toStdString();
customStrategySettings_->strategiesType_ = common::StrategiesType::CUSTOM;
for (auto &strategy : strategySettings_) {
auto strategySetting = std::move(strategy.second);
customStrategySettings_->strategies_.push_back(std::move(strategySetting));
}
refreshStrategySettings();
accept();
}
void CreateStrategyDialog::refreshStrategySettings() {
switch (dialogType_) {
case DialogType::CREATE: {
guiListener_.createCustomStrategy(std::move(customStrategySettings_));
} break;
case DialogType::EDIT: {
guiListener_.editCustomStrategy(std::move(customStrategySettings_), customStrategyName_);
} break;
default:
break;
}
}
void CreateStrategyDialog::checkOkButtonStatus(const QString &text) {
bool isStrategiesEmpty = selectedStrategiesList_->isEmpty();
bool isStrategyNameEmpty = dialog_.lineEdit->text().isEmpty();
bool isButtonDisabled = isStrategiesEmpty || isStrategyNameEmpty;
dialog_.buttonBox->button(QDialogButtonBox::StandardButton::Ok)->setDisabled(isButtonDisabled);
}
} // namespace dialogs
} // namespace view
} // namespace auto_trader
| 44.752
| 99
| 0.734448
|
Rapprise
|
4510d4458aa07eb868185955251224615ae7b445
| 2,034
|
cpp
|
C++
|
sandbox-app/source/camera_controller.cpp
|
Kostu96/k2d-engine
|
8150230034cf4afc862fcc1a3c262c27d544feed
|
[
"MIT"
] | null | null | null |
sandbox-app/source/camera_controller.cpp
|
Kostu96/k2d-engine
|
8150230034cf4afc862fcc1a3c262c27d544feed
|
[
"MIT"
] | null | null | null |
sandbox-app/source/camera_controller.cpp
|
Kostu96/k2d-engine
|
8150230034cf4afc862fcc1a3c262c27d544feed
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2021-2022 Konstanty Misiak
*
* SPDX-License-Identifier: MIT
*/
#include "camera_controller.hpp"
CameraController::CameraController(float aspectRatio) :
m_aspectRatio(aspectRatio),
m_zoomLevel(1.f),
m_camera(-aspectRatio*2.f, aspectRatio*2.f, -2.f, 2.f),
m_cameraPosition(0.f, 0.f),
m_cameraMoveSpeed(2.f) {}
void CameraController::onUpdate(float dt)
{
glm::vec2 move{};
if (k2d::Input::isKeyPressed(k2d::Key::W))
move.y = m_cameraMoveSpeed;
else if (k2d::Input::isKeyPressed(k2d::Key::S))
move.y = -m_cameraMoveSpeed;
if (k2d::Input::isKeyPressed(k2d::Key::A))
move.x = -m_cameraMoveSpeed;
else if (k2d::Input::isKeyPressed(k2d::Key::D))
move.x = m_cameraMoveSpeed;
if (move.x != 0.f || move.y != 0)
{
move = glm::normalize(move);
m_cameraPosition += move * dt * m_zoomLevel;
m_camera.setPosition(m_cameraPosition);
}
}
void CameraController::onEvent(k2d::Event& event)
{
k2d::EventDispatcher dispatcher(event);
dispatcher.dispatch<k2d::MouseScrollEvent>(K2D_BIND_EVENT_FUNC(CameraController::onMouseScroll));
dispatcher.dispatch<k2d::WindowResizeEvent>(K2D_BIND_EVENT_FUNC(CameraController::onWindowResize));
}
bool CameraController::onMouseScroll(k2d::MouseScrollEvent& event)
{
m_zoomLevel -= (event.getYOffset() * 0.05f);
if (m_zoomLevel < 0.01f)
m_zoomLevel = 0.01f;
else if (m_zoomLevel > 10.f)
m_zoomLevel = 10.f;
m_camera.setProjection(
-m_aspectRatio * m_zoomLevel * 2.f, m_aspectRatio * m_zoomLevel * 2.f,
-m_zoomLevel * 2.f, m_zoomLevel * 2.f
);
return true;
}
bool CameraController::onWindowResize(k2d::WindowResizeEvent& event)
{
m_aspectRatio = static_cast<float>(event.getWidth()) / static_cast<float>(event.getHeight());
m_camera.setProjection(
-m_aspectRatio * m_zoomLevel * 2.f, m_aspectRatio * m_zoomLevel * 2.f,
-m_zoomLevel * 2.f, m_zoomLevel * 2.f
);
return false;
}
| 29.478261
| 103
| 0.666175
|
Kostu96
|
451303bf0bff68686094fb1683725c2755543be8
| 11,453
|
hpp
|
C++
|
include/snowflake/ecs/component_storage.hpp
|
robclu/glow
|
4f14f4c43ecb29cbb8a75aad50cc3b776519a7a2
|
[
"MIT"
] | 1
|
2021-12-08T09:23:55.000Z
|
2021-12-08T09:23:55.000Z
|
include/snowflake/ecs/component_storage.hpp
|
robclu/snowflake
|
4f14f4c43ecb29cbb8a75aad50cc3b776519a7a2
|
[
"MIT"
] | null | null | null |
include/snowflake/ecs/component_storage.hpp
|
robclu/snowflake
|
4f14f4c43ecb29cbb8a75aad50cc3b776519a7a2
|
[
"MIT"
] | null | null | null |
//==--- snowflake/ecs/component_storage.hpp ---------------- -*- C++ -*- ---==//
//
// Snowflake
//
// Copyright (c) 2020 Rob Clucas
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//==------------------------------------------------------------------------==//
//
/// \file component_storage.hpp
/// \brief This file defines storage for component.
//
//==------------------------------------------------------------------------==//
#ifndef SNOWFLAKE_ECS_COMPONENT_STORAGE_HPP
#define SNOWFLAKE_ECS_COMPONENT_STORAGE_HPP
#include "sparse_set.hpp"
namespace snowflake {
/**
* Implemenatation of a storage class for components. This is essentially just
* a wrapper around a SparseSet which stores the entities and components such
* that they are ordered the same way, and both contiguously.
*
* \note The ordering of the components and the entities are the same, so random
* access into the containers is valid.
*
* \note The order of insertion into the container is not preserved.
*
* \see SparseSet
*
* \tparam Entity The type of the entity.
* \tparam Component The type of the component.
* \tparam EntityAllocator The type of the entity allocator.
*/
template <
typename Entity,
typename Component,
typename EntityAllocator = wrench::ObjectPoolAllocator<Entity>>
class ComponentStorage : public SparseSet<Entity, EntityAllocator> {
// clang-format off
/** Storage type for the entities */
using Entities = SparseSet<Entity, EntityAllocator>;
/** Defines the type for the components. */
using Components = std::vector<Component>;
// clang-format on
public:
// clang-format off
/** The size type. */
using SizeType = size_t;
/** The iterator type used for the components. */
using Iterator = ReverseIterator<Components, false>;
/** The const iterator type for the components. */
using ConstIterator = ReverseIterator<Components, true>;
/** The reverse iterator type for the components. */
using ReverseIterator = Component*;
/** The const reverse iterator type for the components. */
using ConstReverseIterator = const Component*;
// clang-format on
/** The page size for the storage. */
static constexpr size_t page_size = Entities::page_size;
/**
* Default constructor for storage -- this does not use an allocator for
* entities.
*/
ComponentStorage() noexcept = default;
/**
* Constructor which sets the allocator for the entities.
* \param allocator The allocator for the entities.
*/
ComponentStorage(EntityAllocator* allocator) noexcept : Entities{allocator} {}
/**
* Reserves enough space to emplace \p size compoennts.
* \param size The number of entities to reserve.
*/
auto reserve(SizeType size) noexcept -> void {
components_.reserve(size);
Entities::reserve(size);
}
/**
* Emplaces a component into the storage.
*
* \note If the entity is already assosciated with this component, then this
* will cause undefined behaviour in release, or assert in debug.
*
* \param entity The entity to emplace the component for.
* \param args Arguments for the construciton of the component.
* \tparam Args The type of the args.
*/
template <typename... Args>
auto emplace(const Entity& entity, Args&&... args) -> void {
// Many components are aggregates, and emplace back doesn't work with
// aggregates, so we need to differentiate.
if constexpr (std::is_aggregate_v<Component>) {
if constexpr (constexpr_component_id_v<Component>) {
components_.push_back(Component{{}, std::forward<Args>(args)...});
} else {
components_.push_back(Component{std::forward<Args>(args)...});
}
} else {
components_.emplace_back(std::forward<Args>(args)...);
}
Entities::emplace(entity);
}
/**
* Removes the component assosciated with the entity from the storage.
*
* \note If the entity does not exist then this will assert in debug builds,
* while in release builds it will cause undefined behaviour.
*
* \param entity The entity to remove.
*/
auto erase(const Entity& entity) noexcept -> void {
auto back = std::move(components_.back());
components_[Entities::index(entity)] = std::move(back);
components_.pop_back();
Entities::erase(entity);
}
/**
* Swaps two components in the storage.
*
*
* \note If either of the entities assosciated with the components are not
* present then this will cause undefined behaviour in release, or
* assert in debug.
*
* \param a A component to swap with.
* \param b A component to swap with.
*/
auto swap(const Entity& a, const Entity& b) noexcept -> void {
std::swap(components_[Entities::index(a)], components_[Entities::index(b)]);
Entities::swap(a, b);
}
/**
* Gets the component assosciated with the given entity.
*
* \note If the entity does not exist, this causes endefined behaviour in
* release, or asserts in debug.
*
* \param entity The entity to get the component for.
* \return A reference to the component.
*/
auto get(const Entity& entity) -> Component& {
return components_[Entities::index(entity)];
}
/**
* Gets the component assosciated with the given entity.
*
* \note If the entity does not exist, this causes endefined behaviour in
* release, or asserts in debug.
*
* \param entity The entity to get the component for.
* \return A const reference to the component.
*/
auto get(const Entity& entity) const -> const Component& {
return components_[Entities::index(entity)];
}
/*==--- [iteration] ------------------------------------------------------==*/
/**
* Returns an iterator to the beginning of the components.
*
* The returned iterator points to the *most recently inserted* component and
* iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto begin() noexcept -> Iterator {
using size_type = typename Iterator::difference_type;
return Iterator{components_, static_cast<size_type>(components_.size())};
}
/**
* Returns an iterator to the end of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto end() noexcept -> Iterator {
using size_type = typename Iterator::difference_type;
return Iterator{components_, size_type{0}};
}
/**
* Returns a const iterator to the beginning of components.
*
* The returned iterator points to the *most recently inserted* component and
* iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto cbegin() const noexcept -> ConstIterator {
using size_type = typename ConstIterator::difference_type;
return ConstIterator{
components_, static_cast<size_type>(components_.size())};
}
/**
* Returns a const iterator to the end of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *most* recent to *least* recently inserted.
*
* This iterator *is not* invalidated by insertion, but may be invalidated by
* deletion.
*
* \return An iterator to the most recent component.
*/
snowflake_nodiscard auto cend() const noexcept -> ConstIterator {
using size_type = typename ConstIterator::difference_type;
return ConstIterator{components_, size_type{0}};
}
/**
* Returns a reverse iterator to the beginning of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *lest* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto rbegin() const noexcept -> ReverseIterator {
return components_.data();
}
/**
* Returns a reverse iterator to the end of the set.
*
* The returned iterator points to the *most recently inserted* component
* and iterates from *least* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto rend() const noexcept -> ReverseIterator {
return rbegin() + components_.size();
}
/**
* Returns a const reverse iterator to the beginning of the components.
*
* The returned iterator points to the *least recently inserted* component
* and iterates from *lest* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto crbegin() const noexcept -> ConstReverseIterator {
return components_.data();
}
/**
* Returns a const reverse iterator to the end of the set.
*
* The returned iterator points to the *most recently inserted* component
* and iterates from *least* recent to *most* recently inserted.
*
* This iterator *is* invalidated by insertion and deletion.
*
* \return An iterator to the least recent entity in the sparse set.
*/
snowflake_nodiscard auto crend() const noexcept -> ConstReverseIterator {
return rbegin() + components_.size();
}
/*==--- [algorithms] -----------------------------------------------------==*/
/**
* Finds a component, if it exists.
*
* If the component doesn't exist, this returns an iterator to the end of the
* set, otherwise it returns an iterator to the found component.
*
* \param entity The entity to find.
* \return A valid iterator if found, otherwise an iterator to the end of the
* storage.
*/
snowflake_nodiscard auto find(const Entity& entity) noexcept -> Iterator {
return Entities::exists(entity)
? --Iterator(end() - Entities::index(entity))
: end();
}
/**
* Finds a component, if it exists.
*
* If the component doesn't exist, this returns an iterator to the end of the
* set, otherwise it returns an iterator to the found component.
*
* \param entity The entity to find.
* \return A valid iterator if found, otherwise an iterator to the end of the
* storage.
*/
snowflake_nodiscard auto
find(const Entity& entity) const noexcept -> ConstIterator {
return Entities::exists(entity)
? --ConstIterator(end() - Entities::index(entity))
: end();
}
private:
Components components_ = {}; //!< Container of components.
};
} // namespace snowflake
#endif // SNOWFLAKE_ECS_COMPONENT_STORAGE_HPP
| 33.985163
| 80
| 0.660788
|
robclu
|
931d42551fb51e265e6a60e0d6555d15cbe5056b
| 467
|
cpp
|
C++
|
minggu-2/Modul_3/tugas-2(3.5).cpp
|
samuelbudi03/praktikum_algoritma_1
|
cf359ec3ad84399f90d3e39207e7d1feb95b4fa9
|
[
"MIT"
] | null | null | null |
minggu-2/Modul_3/tugas-2(3.5).cpp
|
samuelbudi03/praktikum_algoritma_1
|
cf359ec3ad84399f90d3e39207e7d1feb95b4fa9
|
[
"MIT"
] | null | null | null |
minggu-2/Modul_3/tugas-2(3.5).cpp
|
samuelbudi03/praktikum_algoritma_1
|
cf359ec3ad84399f90d3e39207e7d1feb95b4fa9
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main(){
int x,y,z,m,n;
x = 9 + 4; /* menghitung 9+4 */
y = 9 -4; /* menghitung 9-4 */
z = 9 * 4; /* menghitung 9*4 */
m = 9 / 4; /* menghitung 9/4 */
m2 = 9.0 / 4.0; /* menghitung 9/4 */
n = 9 % 4; /* menghitung 9%4 */
clrscr();
cout << "Nilai dari 9 + 4 = "<< x;
cout << "\nNilai dari 9 -4 = "<< y;
cout << "\nNilai dari 9 * 4= "<< z;
cout << "\nNilai dari 9 / 4= "<< m;
cout << "\nNilai dari 9 mod 4= "<< n;
return 0;
}
| 24.578947
| 37
| 0.513919
|
samuelbudi03
|
931eecdd1ec71cbf5845a36e58701fff3e6b2dfd
| 4,704
|
cpp
|
C++
|
Pattern - 2 Pointers/Pattern - 2 or 3 or 4 Sum Related Problems/3 Sum.cpp
|
Edith-3000/Algorithmic-Implementations
|
7ff8cd615fd453a346b4e851606d47c26f05a084
|
[
"MIT"
] | 8
|
2021-02-13T17:07:27.000Z
|
2021-08-20T08:20:40.000Z
|
Pattern - 2 Pointers/Pattern - 2 or 3 or 4 Sum Related Problems/3 Sum.cpp
|
Edith-3000/Algorithmic-Implementations
|
7ff8cd615fd453a346b4e851606d47c26f05a084
|
[
"MIT"
] | null | null | null |
Pattern - 2 Pointers/Pattern - 2 or 3 or 4 Sum Related Problems/3 Sum.cpp
|
Edith-3000/Algorithmic-Implementations
|
7ff8cd615fd453a346b4e851606d47c26f05a084
|
[
"MIT"
] | 5
|
2021-02-17T18:12:20.000Z
|
2021-10-10T17:49:34.000Z
|
// Problem: https://leetcode.com/problems/3sum/
// Ref: https://www.youtube.com/watch?v=onLoX6Nhvmg
// https://www.geeksforgeeks.org/find-triplets-array-whose-sum-equal-zero/
/****************************************************************************************************/
// METHOD - 1 (Using Hashing)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
vvi _3_sum(vi &v) {
vvi res;
int n = (int)v.size();
if(n == 0) return res;
map<int, int> m;
for(int i = 0; i < n; i++) m[v[i]]++;
set<vi> s;
for(int i = 0; i < n; i++) {
m[v[i]]--;
for(int j = i + 1; j < n; j++) {
m[v[j]]--;
int x = v[i] + v[j];
x = -x;
if(m[x] > 0) {
vi tmp(3);
tmp[0] = v[i]; tmp[1] = v[j]; tmp[2] = x;
sort(tmp.begin(), tmp.end());
s.insert(tmp);
}
m[v[j]]++;
}
m[v[i]]++;
}
for(auto vec: s) res.pb(vec);
return res;
}
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
vvi res = _3_sum(v);
for(auto vec: res) {
for(auto x: vec) cout << x << " ";
cout << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
// TC: O(n^2 x log(m))
// SC: O(n + m), where m are the possible triplets
/*****************************************************************************************************/
// METHOD - 2 (Using 2 Pointers)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define ull unsigned long long
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define PI 3.1415926535897932384626
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << ", " << #y << "=" << y << endl
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<ull> vull;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
typedef vector<vi> vvi;
typedef vector<vll> vvll;
typedef vector<vull> vvull;
mt19937_64 rang(chrono::high_resolution_clock::now().time_since_epoch().count());
int rng(int lim) {
uniform_int_distribution<int> uid(0,lim-1);
return uid(rang);
}
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
vvi _3_sum(vi &v) {
vvi res;
int n = (int)v.size();
if(n == 0) return res;
sort(v.begin(), v.end());
for(int i = 0; i + 2 < n; i++) {
// to avoid duplicacy
if(i and v[i] == v[i-1]) continue;
// from here it is normal 2 sum problem
int lo = i + 1, hi = n - 1, sum = 0 - v[i];
while(lo < hi) {
if(v[lo] + v[hi] == sum) {
vi tmp(3);
tmp[0] = v[i]; tmp[1] = v[lo]; tmp[2] = v[hi];
res.pb(tmp);
// to avoid duplicacy
while(lo < hi and v[lo] == v[lo+1]) lo++;
while(lo < hi and v[hi] == v[hi-1]) hi--;
lo++; hi--;
}
else if(v[lo] + v[hi] < sum) lo++;
else hi--;
}
}
return res;
}
void solve()
{
int n; cin >> n;
vi v(n);
for(int i = 0; i < n; i++) cin >> v[i];
vvi res = _3_sum(v);
for(auto vec: res) {
for(auto x: vec) cout << x << " ";
cout << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
srand(chrono::high_resolution_clock::now().time_since_epoch().count());
// #ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
// #endif
int t = 1;
// int test = 1;
// cin >> t;
while(t--) {
// cout << "Case #" << test++ << ": ";
solve();
}
return 0;
}
// TC: O(n^2)
// SC: O(m), where m are the possible triplets
| 22.188679
| 103
| 0.533376
|
Edith-3000
|
932a0d7c5d3ce6e1df92a4b6caeaa2412214f2a8
| 3,676
|
cpp
|
C++
|
src/Column.cpp
|
raincheque/qwelk
|
e78ee0ccf7a7f1af91d823d0563b0af360933237
|
[
"MIT"
] | 25
|
2017-11-22T13:48:05.000Z
|
2021-12-29T05:49:01.000Z
|
src/Column.cpp
|
netboy3/qwelk-vcvrack-plugins
|
e78ee0ccf7a7f1af91d823d0563b0af360933237
|
[
"MIT"
] | 12
|
2017-11-20T20:45:27.000Z
|
2021-12-08T20:35:06.000Z
|
src/Column.cpp
|
netboy3/qwelk-vcvrack-plugins
|
e78ee0ccf7a7f1af91d823d0563b0af360933237
|
[
"MIT"
] | 4
|
2018-01-11T21:02:12.000Z
|
2019-09-29T12:32:50.000Z
|
#include "qwelk.hpp"
#define CHANNELS 4
struct ModuleColumn : Module {
enum ParamIds {
PARAM_MASTER,
PARAM_AVG,
PARAM_WEIGHTED,
NUM_PARAMS
};
enum InputIds {
IN_SIG,
IN_UPSTREAM = IN_SIG + CHANNELS,
NUM_INPUTS = IN_UPSTREAM + CHANNELS
};
enum OutputIds {
OUT_SIDE,
OUT_DOWNSTREAM = OUT_SIDE + CHANNELS,
NUM_OUTPUTS = OUT_DOWNSTREAM + CHANNELS
};
enum LightIds {
NUM_LIGHTS
};
bool allow_neg_weights = false;
ModuleColumn() {
config(NUM_PARAMS, NUM_INPUTS, NUM_OUTPUTS, NUM_LIGHTS);
configParam(ModuleColumn::PARAM_AVG, 0.0, 1.0, 1.0, "");
configParam(ModuleColumn::PARAM_WEIGHTED, 0.0, 1.0, 1.0, "");
}
void process(const ProcessArgs& args) override;
};
void ModuleColumn::process(const ProcessArgs& args)
{
bool avg = params[PARAM_AVG].getValue() == 0.0;
bool weighted = params[PARAM_WEIGHTED].getValue() == 0.0;
float total = 0;
float on_count = 0;
for (int i = 0; i < CHANNELS; ++i) {
float in_upstream = inputs[IN_UPSTREAM + i].getVoltage();
float in_sig = inputs[IN_SIG + i].getVoltage();
// just forward the input signal as the side stream,
// used for chaining multiple Columns together
outputs[OUT_SIDE + i].setVoltage(in_sig);
if (inputs[IN_UPSTREAM + i].isConnected()) {
if (weighted)
on_count += allow_neg_weights ? in_upstream : fabs(in_upstream);
else if (in_upstream != 0.0)
on_count += 1;
}
if (!weighted && in_sig != 0.0)
on_count += 1;
float product = weighted ? (in_upstream * in_sig) : (in_upstream + in_sig);
total += product;
outputs[OUT_DOWNSTREAM + i].setVoltage(avg ? ((on_count != 0) ? (total / on_count) : 0) : (total));
}
}
struct MenuItemAllowNegWeights : MenuItem {
ModuleColumn *col;
void onAction(const event::Action &e) override
{
col->allow_neg_weights ^= true;
}
void step () override
{
rightText = (col->allow_neg_weights) ? "✔" : "";
}
};
struct WidgetColumn : ModuleWidget {
WidgetColumn(ModuleColumn *module) {
setModule(module);
setPanel(APP->window->loadSvg(asset::plugin(pluginInstance, "res/Column.svg")));
addChild(createWidget<ScrewSilver>(Vec(15, 0)));
addChild(createWidget<ScrewSilver>(Vec(15, 365)));
addParam(createParam<CKSS>(Vec(3.5, 30), module, ModuleColumn::PARAM_AVG));
addParam(createParam<CKSS>(Vec(42, 30), module, ModuleColumn::PARAM_WEIGHTED));
float x = 2.5, xstep = 15, ystep = 23.5;
for (int i = 0; i < CHANNELS; ++i)
{
float y = 80 + i * 80;
addInput(createInput<PJ301MPort>(Vec(x + xstep, y - ystep), module, ModuleColumn::IN_UPSTREAM + i));
addOutput(createOutput<PJ301MPort>(Vec(x + xstep*2, y), module, ModuleColumn::OUT_SIDE + i));
addInput(createInput<PJ301MPort>(Vec(x, y), module, ModuleColumn::IN_SIG + i));
addOutput(createOutput<PJ301MPort>(Vec(x + xstep, y + ystep), module, ModuleColumn::OUT_DOWNSTREAM + i));
}
}
void appendContextMenu(Menu *menu) override {
if (module) {
ModuleColumn *column = dynamic_cast<ModuleColumn *>(module);
assert(column);
MenuLabel *spacer = new MenuLabel();
menu->addChild(spacer);
MenuItemAllowNegWeights *item = new MenuItemAllowNegWeights();
item->text = "Allow Negative Weights";
item->col = column;
menu->addChild(item);
}
}
};
Model *modelColumn = createModel<ModuleColumn, WidgetColumn>("Column");
| 29.886179
| 113
| 0.613983
|
raincheque
|
932e4ac2c56cf29fda71c25188d7f8d7af643ffe
| 4,501
|
hpp
|
C++
|
samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp
|
btempleton/sg-aics3mac-plugins
|
e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67
|
[
"Intel",
"Unlicense"
] | 1
|
2021-10-09T18:23:44.000Z
|
2021-10-09T18:23:44.000Z
|
samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp
|
btempleton/sg-aics3mac-plugins
|
e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67
|
[
"Intel",
"Unlicense"
] | null | null | null |
samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp
|
btempleton/sg-aics3mac-plugins
|
e5332b11ef8ce03a7e842c9df3fe1ce9145c0b67
|
[
"Intel",
"Unlicense"
] | null | null | null |
//========================================================================================
//
// $File: //ai/ai13/devtech/sdk/public/samplecode/MarkedObjects/Source/MarkedObjectsPreferences.hpp $
//
// $Revision: #3 $
//
// Copyright 1987-2007 Adobe Systems Incorporated. All rights reserved.
//
// NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
// with the terms of the Adobe license agreement accompanying it. If you have received
// this file from a source other than Adobe, then your use, modification, or
// distribution of it requires the prior written permission of Adobe.
//
//========================================================================================
#ifndef __MarkedObjectsPreferences_hpp__
#define __MarkedObjectsPreferences_hpp__
#include "MarkedObjectsPlugin.hpp"
class MarkedObjectsDialog;
class MarkedObjectsPreferencesDialog : public BaseADMDialog
{
private:
ASRealPoint subLoc;
string subFontName;
AIReal subFontSize;
ASRealPoint labelLoc;
string labelFontName;
AIReal labelFontSize;
string labelDefaultText;
long precision;
AIBoolean autoSort;
public:
MarkedObjectsPreferencesDialog();
virtual ~MarkedObjectsPreferencesDialog();
int Modal(SPPluginRef pluginRef, char* name, int dialogID, ADMDialogStyle style = kADMModalDialogStyle, int options = 0);
ASErr Init();
void Notify( IADMNotifier notifier );
void Destroy();
ASRealPoint GetSubStringLocation( void ) { return subLoc; }
const string GetSubStringFontName( void ) { return subFontName; }
AIReal GetSubStringFontSize( void ) { return subFontSize; }
ASRealPoint GetLabelStringLocation( void ) { return labelLoc; }
const string GetLabelStringFontName( void ) { return labelFontName; }
AIReal GetLabelStringFontSize( void ) { return labelFontSize; }
const string GetLabelStringDefaultText( void ) { return labelDefaultText; }
void SetSubStringLocation( ASRealPoint inPoint ) { subLoc = inPoint; }
void SetSubStringFontName( const string fontName ) { subFontName = fontName; }
void SetSubStringFontSize( AIReal fontSize ) { subFontSize = fontSize; }
void SetLabelStringLocation( ASRealPoint inPoint ) { labelLoc = inPoint; }
void SetLabelStringFontName( const string fontName ) { labelFontName = fontName; }
void SetLabelStringFontSize( AIReal fontSize ) { labelFontSize = fontSize; }
void SetLabelStringDefaultText( const string newText ) { labelDefaultText = newText; }
void SetPrecision( long p ) { precision = p; }
long GetPrecision( void ) { return precision; }
void SetAutoSort( AIBoolean as ) { autoSort = as; }
AIBoolean GetAutoSort( void ) { return autoSort; }
};
class MarkedObjectsPreferences
{
private:
MarkedObjectsDialog* moDialog;
ASRealPoint subLoc;
string subFontName;
AIReal subFontSize;
ASRealPoint labelLoc;
string labelFontName;
AIReal labelFontSize;
string labelDefaultText;
long precision;
AIBoolean autoSort;
public:
MarkedObjectsPreferences();
~MarkedObjectsPreferences();
void SetDialogPreferences( MarkedObjectsDialog* dp );
int DoModalPrefs( void );
ASRealPoint GetSubStringLocation( void ) { return subLoc; }
const string GetSubStringFontName( void ) { return subFontName; }
AIReal GetSubStringFontSize( void ) { return subFontSize; }
ASRealPoint GetLabelStringLocation( void ) { return labelLoc; }
const string GetLabelStringFontName( void ) { return labelFontName; }
AIReal GetLabelStringFontSize( void ) { return labelFontSize; }
const string GetLabelStringDefaultText( void ) { return labelDefaultText; }
void SetSubStringLocation( ASRealPoint inPoint ) { subLoc = inPoint; }
void SetSubStringFontName( const string fontName ) { subFontName = fontName; }
void SetSubStringFontSize( AIReal fontSize ) { subFontSize = fontSize; }
void SetLabelStringLocation( ASRealPoint inPoint ) { labelLoc = inPoint; }
void SetLabelStringFontName( const string fontName ) { labelFontName = fontName; }
void SetLabelStringFontSize( AIReal fontSize ) { labelFontSize = fontSize; }
void SetLabelStringDefaultText( const string newText ) { labelDefaultText = newText; }
void SetPrecision( long p ) { precision = p; }
long GetPrecision( void ) { return precision; }
void SetAutoSort( AIBoolean as ) { autoSort = as; }
AIBoolean GetAutoSort( void ) { return autoSort; }
};
extern MarkedObjectsPreferences* gPreferences;
#endif
// end MarkedObjectsPreferences.hpp
| 36.008
| 122
| 0.723617
|
btempleton
|
932f2c75359c94129abe01a1e6953136184ff83b
| 2,907
|
cpp
|
C++
|
trie/src/node.cpp
|
Arghnews/wordsearch_solver
|
cf25db64ca3d1facd9191aad075654f124f0d580
|
[
"MIT"
] | null | null | null |
trie/src/node.cpp
|
Arghnews/wordsearch_solver
|
cf25db64ca3d1facd9191aad075654f124f0d580
|
[
"MIT"
] | null | null | null |
trie/src/node.cpp
|
Arghnews/wordsearch_solver
|
cf25db64ca3d1facd9191aad075654f124f0d580
|
[
"MIT"
] | null | null | null |
#include "wordsearch_solver/trie/node.hpp"
#include <algorithm>
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <bitset>
#include <cassert>
#include <cstddef>
#include <limits>
#include <memory>
#include <ostream>
#include <string_view>
namespace trie {
const Node* search(const Node& node, std::string_view word) {
const Node* p = &node;
for (; !word.empty(); word.remove_prefix(1)) {
p = p->test(word.front());
if (!p) {
return nullptr;
}
}
return p;
}
Node::Node(const bool is_end_of_word) : is_end_of_word_(is_end_of_word) {}
std::ostream& operator<<(std::ostream& os, const Node& node) {
fmt::memory_buffer buff;
fmt::format_to(buff, "{{");
for (const auto& edge : node.edges_) {
fmt::format_to(buff, "{}", edge.c);
}
fmt::format_to(buff, "{}", node.is_end_of_word() ? "|" : " ");
fmt::format_to(buff, "}}");
return os << fmt::to_string(buff);
}
Node* Node::add_char(const char c) {
// assert(c >= 97 && c < 123);
// Note comparator lambda here compares an edge and a char, not two edges
// Insertion is sorted
auto it = std::lower_bound(
edges_.begin(), edges_.end(), c,
[](const auto& edge0, const char c) { return edge0.c < c; });
if (it == edges_.end() || it->c > c) {
it = edges_.emplace(it, Edge{std::make_unique<Node>(), c});
}
assert(it->child.get() != nullptr);
return it->child.get();
}
void Node::set_is_end_of_word(const bool is_end_of_word) {
is_end_of_word_ = is_end_of_word;
}
/** Test if a node has an edge containing the character @p c
*
* @note We use linear search here. Could use binary search. For the English
* alphabet, nodes tend to be fairly sparse and small, especially once beyond
* the first few letters. On the massive_wordsearch benchmark,
* using binary search is noticably (~8%) slower.
*/
const Node* Node::test(const char c) const {
const auto it = std::find_if(edges_.begin(), edges_.end(),
[c](const auto& edge) { return edge.c == c; });
// const auto it = std::lower_bound(
// edges_.begin(), edges_.end(), c,
// [](const auto& edge, const char c) { return edge.c < c; });
// if (it == edges_.end() || it->c != c) {
if (it == edges_.end()) {
return nullptr;
}
return it->child.get();
}
bool Node::any() const { return !edges_.empty(); }
bool Node::is_end_of_word() const { return is_end_of_word_; }
const Node::Edges& Node::edges() const { return edges_; }
// Node::PrecedingType Node::preceding() const
// {
// return preceding_;
// }
} // namespace trie
// void print_sizes()
// {
// fmt::print("bits_: {}\n", sizeof(bits_));
// fmt::print("preceding_: {}\n", sizeof(preceding_));
// fmt::print("is_end_of_word_: {}\n", sizeof(is_end_of_word_));
// fmt::print("sizeof(Node): {}\n", sizeof(Node));
// // static_assert(sizeof(Node) <= 8);
// static_assert(alignof(Node) == 8);
// }
| 28.223301
| 78
| 0.631579
|
Arghnews
|
932f521504f0babcf1b37c09669703f82bee9981
| 8,154
|
hpp
|
C++
|
include/RootMotion/FinalIK/IKExecutionOrder.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
include/RootMotion/FinalIK/IKExecutionOrder.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
include/RootMotion/FinalIK/IKExecutionOrder.hpp
|
marksteward/BeatSaber-Quest-Codegen
|
a76f063f71cef207a9f048ad7613835f554911a7
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.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: RootMotion::FinalIK
namespace RootMotion::FinalIK {
// Forward declaring type: IK
class IK;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Animator
class Animator;
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0x29
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.IKExecutionOrder
// [TokenAttribute] Offset: FFFFFFFF
class IKExecutionOrder : public UnityEngine::MonoBehaviour {
public:
// [TooltipAttribute] Offset: 0xEA0294
// public RootMotion.FinalIK.IK[] IKComponents
// Size: 0x8
// Offset: 0x18
::Array<RootMotion::FinalIK::IK*>* IKComponents;
// Field size check
static_assert(sizeof(::Array<RootMotion::FinalIK::IK*>*) == 0x8);
// [TooltipAttribute] Offset: 0xEA02CC
// public UnityEngine.Animator animator
// Size: 0x8
// Offset: 0x20
UnityEngine::Animator* animator;
// Field size check
static_assert(sizeof(UnityEngine::Animator*) == 0x8);
// private System.Boolean fixedFrame
// Size: 0x1
// Offset: 0x28
bool fixedFrame;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Creating value type constructor for type: IKExecutionOrder
IKExecutionOrder(::Array<RootMotion::FinalIK::IK*>* IKComponents_ = {}, UnityEngine::Animator* animator_ = {}, bool fixedFrame_ = {}) noexcept : IKComponents{IKComponents_}, animator{animator_}, fixedFrame{fixedFrame_} {}
// Deleting conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept = delete;
// Get instance field: public RootMotion.FinalIK.IK[] IKComponents
::Array<RootMotion::FinalIK::IK*>* _get_IKComponents();
// Set instance field: public RootMotion.FinalIK.IK[] IKComponents
void _set_IKComponents(::Array<RootMotion::FinalIK::IK*>* value);
// Get instance field: public UnityEngine.Animator animator
UnityEngine::Animator* _get_animator();
// Set instance field: public UnityEngine.Animator animator
void _set_animator(UnityEngine::Animator* value);
// Get instance field: private System.Boolean fixedFrame
bool _get_fixedFrame();
// Set instance field: private System.Boolean fixedFrame
void _set_fixedFrame(bool value);
// private System.Boolean get_animatePhysics()
// Offset: 0x18374F8
bool get_animatePhysics();
// private System.Void Start()
// Offset: 0x1837594
void Start();
// private System.Void Update()
// Offset: 0x1837604
void Update();
// private System.Void FixedUpdate()
// Offset: 0x18376C0
void FixedUpdate();
// private System.Void LateUpdate()
// Offset: 0x18376FC
void LateUpdate();
// private System.Void FixTransforms()
// Offset: 0x1837638
void FixTransforms();
// public System.Void .ctor()
// Offset: 0x1837788
// Implemented from: UnityEngine.MonoBehaviour
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static IKExecutionOrder* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::IKExecutionOrder::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<IKExecutionOrder*, creationType>()));
}
}; // RootMotion.FinalIK.IKExecutionOrder
#pragma pack(pop)
static check_size<sizeof(IKExecutionOrder), 40 + sizeof(bool)> __RootMotion_FinalIK_IKExecutionOrderSizeCheck;
static_assert(sizeof(IKExecutionOrder) == 0x29);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::IKExecutionOrder*, "RootMotion.FinalIK", "IKExecutionOrder");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::get_animatePhysics
// Il2CppName: get_animatePhysics
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::get_animatePhysics)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "get_animatePhysics", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::Start
// Il2CppName: Start
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::Start)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::FixedUpdate
// Il2CppName: FixedUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::FixedUpdate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "FixedUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::LateUpdate
// Il2CppName: LateUpdate
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::LateUpdate)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "LateUpdate", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::FixTransforms
// Il2CppName: FixTransforms
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (RootMotion::FinalIK::IKExecutionOrder::*)()>(&RootMotion::FinalIK::IKExecutionOrder::FixTransforms)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(RootMotion::FinalIK::IKExecutionOrder*), "FixTransforms", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: RootMotion::FinalIK::IKExecutionOrder::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 50.645963
| 226
| 0.719034
|
marksteward
|
93304097224c1c3b55474e6a5746b7978d452391
| 4,853
|
cpp
|
C++
|
Core/logging/src/Logger.cpp
|
ChewyGumball/bengine
|
a993471b1b135bcfe848de25ec539d93ed97445f
|
[
"MIT"
] | null | null | null |
Core/logging/src/Logger.cpp
|
ChewyGumball/bengine
|
a993471b1b135bcfe848de25ec539d93ed97445f
|
[
"MIT"
] | null | null | null |
Core/logging/src/Logger.cpp
|
ChewyGumball/bengine
|
a993471b1b135bcfe848de25ec539d93ed97445f
|
[
"MIT"
] | null | null | null |
#include "Core/Logging/Logger.h"
#define SPDLOG_FMT_EXTERNAL
#include <spdlog/spdlog.h>
#include <spdlog/sinks/stdout_color_sinks.h>
#include <thread>
// We don't use the Core contaienrs here so that we don't have any external dependencies, allowing this library to be
// used by any other library.
#include <unordered_map>
#include <unordered_set>
namespace {
std::mutex* LoggerCreationMutex;
std::mutex* FilterMutex;
std::mutex* SinkMutex;
std::mutex* DisplayNameMutex;
void InitLocks() {
if(LoggerCreationMutex == nullptr) {
LoggerCreationMutex = new std::mutex();
FilterMutex = new std::mutex();
SinkMutex = new std::mutex();
DisplayNameMutex = new std::mutex();
}
}
std::unordered_map<std::string, Core::LogLevel>& Filters() {
static std::unordered_map<std::string, Core::LogLevel> FilterMap;
return FilterMap;
}
std::unordered_set<spdlog::sink_ptr>& Sinks() {
static std::unordered_set<spdlog::sink_ptr> SinkMap{std::make_shared<spdlog::sinks::stdout_color_sink_mt>()};
return SinkMap;
}
std::unordered_map<const Core::LogCategory*, std::string>& DisplayNames() {
static std::unordered_map<const Core::LogCategory*, std::string> DisplayNameMap;
return DisplayNameMap;
}
std::string& GetDisplayName(const Core::LogCategory* category) {
InitLocks();
std::scoped_lock lock(*DisplayNameMutex);
std::string& displayName = DisplayNames()[category];
if(displayName.empty()) {
const Core::LogCategory* currentCategory = category;
while(currentCategory != nullptr) {
displayName = std::string(currentCategory->name) + displayName;
currentCategory = currentCategory->parent;
}
}
return displayName;
}
Core::LogLevel GlobalLogLevel = Core::LogLevel::Trace;
} // namespace
namespace Core::LogManager {
void SetGlobalMinimumLevel(LogLevel minimumLevel) {
if(minimumLevel == GlobalLogLevel) {
return;
}
GlobalLogLevel = minimumLevel;
spdlog::drop_all();
}
void SetCategoryLevel(const LogCategory& category, LogLevel minimumLevel) {
SetCategoryLevel(GetDisplayName(&category), minimumLevel);
}
void SetCategoryLevel(const std::string& loggerName, LogLevel minimumLevel) {
InitLocks();
{
std::scoped_lock lock(*FilterMutex);
Filters()[loggerName] = minimumLevel;
}
// We drop all loggers so they get recreated with the filter levels
// since we don't know all the children of the logger that just changed
spdlog::drop_all();
}
void AddSinks(const std::vector<spdlog::sink_ptr>& sinks) {
InitLocks();
{
std::scoped_lock lock(*SinkMutex);
for(auto& sink : sinks) {
Sinks().emplace(sink);
}
}
// We drop all loggers so they get recreated with the new sinks
spdlog::drop_all();
}
std::shared_ptr<spdlog::logger> GetLogger(const LogCategory& category) {
std::string& displayName = GetDisplayName(&category);
std::shared_ptr<spdlog::logger> logger = spdlog::get(displayName);
if(logger == nullptr) {
InitLocks();
std::scoped_lock creationLock(*LoggerCreationMutex);
// Check again, just in case there was a race to create the logger
logger = spdlog::get(displayName);
if(logger != nullptr) {
return logger;
}
{
std::scoped_lock lock(*SinkMutex);
logger = std::make_shared<spdlog::logger>(displayName, Sinks().begin(), Sinks().end());
spdlog::register_logger(logger);
}
{
std::scoped_lock lock(*FilterMutex);
LogLevel level = GlobalLogLevel;
const LogCategory* currentCategory = &category;
while(currentCategory != nullptr) {
auto filter = Filters().find(GetDisplayName(currentCategory));
if(filter != Filters().end() && filter->second > level) {
level = filter->second;
}
currentCategory = currentCategory->parent;
}
logger->set_level(MapLevel(level));
}
}
return logger;
}
spdlog::level::level_enum MapLevel(LogLevel level) {
switch(level) {
case LogLevel::Always: return spdlog::level::level_enum::off;
case LogLevel::Critical: return spdlog::level::level_enum::critical;
case LogLevel::Error: return spdlog::level::level_enum::err;
case LogLevel::Warning: return spdlog::level::level_enum::warn;
case LogLevel::Info: return spdlog::level::level_enum::info;
case LogLevel::Debug: return spdlog::level::level_enum::debug;
case LogLevel::Trace: return spdlog::level::level_enum::trace;
default: return spdlog::level::level_enum::off;
}
}
} // namespace Core::LogManager
| 30.522013
| 117
| 0.650319
|
ChewyGumball
|
9330ecd5ab8c292836145ebf50f8b8ea1be465e9
| 2,406
|
hpp
|
C++
|
libs/GFX/ResourceManager.hpp
|
KillianG/R-Type
|
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
|
[
"MIT"
] | 1
|
2019-08-14T12:31:50.000Z
|
2019-08-14T12:31:50.000Z
|
libs/GFX/ResourceManager.hpp
|
KillianG/R-Type
|
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
|
[
"MIT"
] | null | null | null |
libs/GFX/ResourceManager.hpp
|
KillianG/R-Type
|
e3fd801ae58fcea49ac75c400ec0a2837cb0da2e
|
[
"MIT"
] | null | null | null |
#include <utility>
//
// Created by nhyarlathotep on 14/11/18.
//
#pragma once
#include <memory>
#include <iostream>
#include <type_traits>
#include <unordered_map>
#include <experimental/filesystem>
#include <SFML/Audio/Music.hpp>
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/Texture.hpp>
#include "../LOG/Logger.hpp"
#include "Singleton.hpp"
namespace fs = std::experimental::filesystem;
template<typename Resource>
class ResourceHolder{
public:
explicit ResourceHolder() noexcept = default;
template<typename ...Args>
std::shared_ptr<Resource> openFromFile(const std::string &id, Args &&...args) {
auto res = new Resource();
if (!res->openFromFile(std::forward<Args>(args)...)) {
throw std::runtime_error("Impossible to loadFromFile file");
}
_resources.emplace(id, std::shared_ptr<Resource>(res));
return get(id);
}
template<typename ...Args>
std::shared_ptr<Resource> loadFromFile(const std::string &id, Args &&...args) {
auto res = new Resource();
if (!res->loadFromFile(std::forward<Args>(args)...)) {
throw std::runtime_error("Impossible to loadFromFile file");
}
_resources.emplace(id, std::shared_ptr<Resource>(res));
return get(id);
}
std::shared_ptr<Resource> get(const std::string &id) {
return _resources.at(id);
}
private:
std::unordered_map<std::string, std::shared_ptr<Resource>> _resources;
};
class ResourceManager : public gfx::Singleton<ResourceManager> {
friend class gfx::Singleton<ResourceManager>;
public:
std::shared_ptr<sf::Font> loadFont(fs::path &&filename);
std::shared_ptr<sf::Music> loadMusic(fs::path &&filename);
std::shared_ptr<sf::Texture> loadTexture(fs::path &&filename);
std::shared_ptr<sf::Font> getFont(const std::string &id);
std::shared_ptr<sf::Music> getMusic(const std::string &id);
std::shared_ptr<sf::Texture> getTexture(const std::string &id);
private:
/**
* @brief Set the root assets path
*/
explicit ResourceManager(fs::path &&resourceDirectoryPath = (fs::current_path() / "assets")) noexcept;
ResourceManager(const ResourceManager &rMgr){}
fs::path _resourceDirectoryPath;
ResourceHolder<sf::Font> _fontRegistry;
ResourceHolder<sf::Music> _musicRegistry;
ResourceHolder<sf::Texture> _textureRegistry;
};
| 29.341463
| 106
| 0.674564
|
KillianG
|
933122662c79f3b7e7e0b405a5d2253f8845e3d0
| 1,053
|
hpp
|
C++
|
organism.hpp
|
piero0/myNEAT
|
b2c5a4e98274d20fd18765a624ad5f8347ffaaa1
|
[
"MIT"
] | null | null | null |
organism.hpp
|
piero0/myNEAT
|
b2c5a4e98274d20fd18765a624ad5f8347ffaaa1
|
[
"MIT"
] | 1
|
2018-02-14T20:48:18.000Z
|
2018-03-18T15:04:03.000Z
|
organism.hpp
|
piero0/myNEAT
|
b2c5a4e98274d20fd18765a624ad5f8347ffaaa1
|
[
"MIT"
] | null | null | null |
#pragma once
#include "genome.hpp"
namespace pneat {
class Organism {
Genome g;
float fitness;
float thresh;
float normFitness;
public:
Organism(const Genome& g);
Genome& getGenome() { return g; }
void setFitness(float fitness) { this->fitness = fitness; }
float getFitness() const { return fitness; }
float getThresh() const { return thresh; }
float setThresh(float lastThresh, float totalFitness) {
normFitness = fitness/totalFitness;
thresh = lastThresh + normFitness;
return normFitness;
}
void dump();
void dumpGraph(std::string name);
static float adder(const float& sum, const Organism& org) {
return sum + org.fitness;
}
static bool compareThresh(const Organism& o, const float& th) {
return o.thresh <= th;
}
};
}
| 28.459459
| 76
| 0.509972
|
piero0
|
9338808403d50b9feeba727c2b0840807a4d42be
| 16,112
|
hpp
|
C++
|
src/rynx/math/vector.hpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | 11
|
2019-08-19T08:44:14.000Z
|
2020-09-22T20:04:46.000Z
|
src/rynx/math/vector.hpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
src/rynx/math/vector.hpp
|
Apodus/rynx
|
3e1babc2f2957702ba2b09d78be3a959f2f4ea18
|
[
"MIT"
] | null | null | null |
#pragma once
#ifdef _WIN32
#include <intrin.h>
#endif
#include <rynx/system/assert.hpp>
#include <rynx/math/math.hpp>
#include <rynx/tech/serialization.hpp>
#include <cinttypes>
#include <cmath>
#include <limits>
#include <string>
#pragma warning (disable : 4201) // language extension used, anonymous structs
#define RYNX_VECTOR_SIMD 0
namespace rynx {
// generic 3d vector template.
template <class T>
struct alignas(16) vec3 {
vec3(T x = 0, T y = 0, T z = 0) : x(x), y(y), z(z) {}
vec3(const vec3&) = default;
vec3(vec3&&) = default;
vec3& operator = (vec3&&) = default;
vec3& operator = (const vec3&) = default;
template<typename U> explicit operator vec3<U>() const { return vec3<U>(static_cast<U>(x), static_cast<U>(y), static_cast<U>(z)); }
vec3 normal() { T l = length() + std::numeric_limits<float>::epsilon(); return *this * (1.0f / l); }
vec3& normalize() { T l = length() + std::numeric_limits<float>::epsilon(); *this *= 1.0f / l; return *this; }
vec3& operator*=(T scalar) { x *= scalar; y *= scalar; z *= scalar; return *this; }
vec3& operator/=(T scalar) { x /= scalar; y /= scalar; z /= scalar; return *this; }
vec3& operator+=(vec3<T> other) { x += other.x; y += other.y; z += other.z; return *this; }
vec3& operator-=(vec3<T> other) { x -= other.x; y -= other.y; z -= other.z; return *this; }
vec3& operator*=(vec3<T> other) { x *= other.x; y *= other.y; z *= other.z; return *this; }
vec3& operator/=(vec3<T> other) { x /= other.x; y /= other.y; z /= other.z; return *this; }
vec3 operator+(const vec3<T>& other) const { return vec3(x + other.x, y + other.y, z + other.z); }
vec3 operator-(const vec3<T>& other) const { return vec3(x - other.x, y - other.y, z - other.z); }
vec3 operator*(const vec3<T>& other) const { return vec3(x * other.x, y * other.y, z * other.z); }
vec3 operator/(const vec3<T>& other) const { return vec3(x / other.x, y / other.y, z / other.z); }
vec3 operator*(const T & scalar) const { return vec3(x * scalar, y * scalar, z * scalar); }
vec3 operator/(const T & scalar) const { return vec3(x / scalar, y / scalar, z / scalar); }
vec3 operator-() const { return vec3(-x, -y, -z); }
bool operator != (const vec3 & other) { return (x != other.x) | (y != other.y) | (z != other.z); }
bool operator == (const vec3 & other) { return !((*this) != other); }
vec3& set(T xx, T yy, T zz) { x = xx; y = yy; z = zz; return *this; }
vec3 cross(const vec3 & other) const { return vec3(y * other.z - z * other.y, z * other.x - x * other.z, x * other.y - y * other.x); }
vec3 normal2d() const { return vec3(-y, +x, 0); }
float cross2d(const vec3 & other) const { return x * other.y - y * other.x; }
T dot(const vec3 & other) const { return x * other.x + y * other.y + z * other.z; }
T length() const { return math::sqrt_approx(length_squared()); }
T length_squared() const { return dot(*this); }
operator std::string() const {
return std::string("(") + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")";
}
T x;
T y;
T z;
};
namespace serialization {
template<typename T> struct Serialize<rynx::vec3<T>> {
template<typename IOStream>
void serialize(const rynx::vec3<T>& s, IOStream& writer) {
writer(s.x);
writer(s.y);
writer(s.z);
}
template<typename IOStream>
void deserialize(rynx::vec3<T>& s, IOStream& reader) {
reader(s.x);
reader(s.y);
reader(s.z);
}
};
}
#if defined(_WIN32) && RYNX_VECTOR_SIMD
template<>
struct alignas(16) vec3<float> {
vec3(__m128 vec) : xmm(vec) {}
vec3(const vec3& other) : xmm(other.xmm) {}
vec3(float x = 0, float y = 0, float z = 0) { set(x, y, z); }
template<typename U> explicit operator vec3<U>() const { return vec3<U>(static_cast<U>(x), static_cast<U>(y), static_cast<U>(z)); }
vec3 operator * (const vec3& v) const { return vec3(_mm_mul_ps(xmm, v.xmm)); }
vec3 operator + (const vec3& v) const { return vec3(_mm_add_ps(xmm, v.xmm)); }
vec3 operator - (const vec3& v) const { return vec3(_mm_sub_ps(xmm, v.xmm)); }
vec3 operator / (const vec3& v) const { return vec3(_mm_div_ps(xmm, v.xmm)); }
vec3& operator *= (const vec3& v) { xmm = _mm_mul_ps(xmm, v.xmm); return *this; }
vec3& operator += (const vec3& v) { xmm = _mm_add_ps(xmm, v.xmm); return *this; }
vec3& operator -= (const vec3& v) { xmm = _mm_sub_ps(xmm, v.xmm); return *this; }
vec3& operator /= (const vec3& v) { xmm = _mm_div_ps(xmm, v.xmm); return *this; }
vec3 operator -() const { return operator *(-1.0f); }
vec3 operator * (float s) const {
const __m128 scalar = _mm_set1_ps(s);
return _mm_mul_ps(xmm, scalar);
}
vec3& operator *= (float s) {
const __m128 scalar = _mm_set1_ps(s);
return operator *= (scalar);
}
vec3 operator / (float scalar) const { return operator*(1.0f / scalar); }
vec3& operator /= (float scalar) { return operator *= (1.0f / scalar); }
float length() const {
return _mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(xmm, xmm, 0xff)));
}
float length_squared() const {
return _mm_cvtss_f32(_mm_dp_ps(xmm, xmm, 0xff));
}
vec3 cross(const vec3 v2) const {
__m128 t1 = _mm_shuffle_ps(xmm, xmm, 0xc9);
__m128 t2 = _mm_shuffle_ps(xmm, xmm, 0xd2);
__m128 t3 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xd2);
__m128 t4 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xc9);
__m128 t5 = _mm_mul_ps(t1, t3);
__m128 t6 = _mm_mul_ps(t2, t4);
return _mm_sub_ps(t5, t6);
}
operator std::string() const {
return std::string("(") + std::to_string(x) + ", " + std::to_string(y) + ", " + std::to_string(z) + ")";
}
vec3 normal() { w = 0; float l = length() + std::numeric_limits<float>::epsilon(); return *this * (1.0f / l); }
vec3& normalize() { w = 0; float l = length() + std::numeric_limits<float>::epsilon(); *this *= 1.0f / l; return *this; }
// vec3 normal() const { return _mm_div_ps(xmm, _mm_sqrt_ps(_mm_dp_ps(xmm, xmm, 0xff))); }
// vec3& normalize() { xmm = normal().xmm; return *this; }
vec3 normal2d() const { return vec3(-y, +x, 0); }
float cross2d(vec3 other) const { return x * other.y - y * other.x; }
bool operator != (const vec3& other) {
__m128i vcmp = _mm_castps_si128(_mm_cmpneq_ps(xmm, other.xmm));
int32_t test = _mm_movemask_epi8(vcmp);
return test != 0;
}
bool operator == (const vec3& other) { return !((*this) != other); }
vec3& set(float xx, float yy, float zz) { xmm = _mm_set_ps(0.0f, zz, yy, xx); return *this; }
float dot(const vec3& other) const {
__m128 r1 = _mm_mul_ps(xmm, other.xmm);
__m128 shuf = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(2, 3, 0, 1));
__m128 sums = _mm_add_ps(r1, shuf);
shuf = _mm_movehl_ps(shuf, sums);
sums = _mm_add_ss(sums, shuf);
return _mm_cvtss_f32(sums);
}
union {
__m128 xmm;
struct {
float x;
float y;
float z;
float w;
};
};
};
#endif
// not simd representation of four consecutive float values.
struct floats4 {
#pragma warning (disable : 4201)
float x, y, z, w;
floats4(float x, const vec3<float>& other) : x(x), y(other.x), z(other.y), w(other.z) {}
floats4(const vec3<float>& other, float w) : x(other.x), y(other.y), z(other.z), w(w) {}
floats4(const floats4& other) : x(other.x), y(other.y), z(other.z), w(other.w) {}
constexpr floats4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) {}
floats4() : x(0), y(0), z(0), w(0) {}
floats4 operator*(float scalar) const { return floats4(x * scalar, y * scalar, z * scalar, w * scalar); }
floats4 operator/(float scalar) const { return operator*(1.0f / scalar); }
floats4 operator+(float scalar) const { return floats4(x + scalar, y + scalar, z + scalar, w + scalar); }
floats4 operator-(float scalar) const { return floats4(x - scalar, y - scalar, z - scalar, w - scalar); }
floats4 operator/(const floats4& other) const { return floats4(x / other.x, y / other.y, z / other.z, w / other.w); }
floats4 operator*(const floats4& other) const { return floats4(x * other.x, y * other.y, z * other.z, w * other.w); }
floats4 operator+(const floats4& other) const { return floats4(x + other.x, y + other.y, z + other.z, w + other.w); }
floats4 operator-(const floats4& other) const { return floats4(x - other.x, y - other.y, z - other.z, w - other.w); }
floats4 operator-() { return floats4(-x, -y, -z, -w); }
floats4& operator+=(const floats4& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; }
floats4& operator-=(const floats4& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; }
/*
const float& operator [](int index) const {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return data[index];
}
float& operator [](int index) {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return data[index];
}
*/
};
namespace serialization {
template<> struct Serialize<rynx::floats4> {
template<typename IOStream>
void serialize(const rynx::floats4& s, IOStream& writer) {
writer(s.x);
writer(s.y);
writer(s.z);
writer(s.w);
}
template<typename IOStream>
void deserialize(rynx::floats4& s, IOStream& reader) {
reader(s.x);
reader(s.y);
reader(s.z);
reader(s.w);
}
};
}
template <class T>
struct alignas(16) vec4 {
vec4(const vec4 & other) : x(other.x), y(other.y), z(other.z), w(other.w) {}
vec4(vec3<float> other, float w) : x(other.x), y(other.y), z(other.z), w(w) {}
vec4(float w, vec3<float> other) : x(w), y(other.x), z(other.y), w(other.z) {}
constexpr vec4(T x = 0, T y = 0, T z = 0, T w = 0) : x(x), y(y), z(z), w(w) {}
template<typename U> explicit operator vec4<U>() const { return vec4<U>(static_cast<U>(x), static_cast<U>(y), static_cast<U>(z), static_cast<U>(w)); }
operator floats4() const { return floats4(x, y, z, w); }
vec3<T> xyz() const { return vec3<T>(x, y, z); }
vec4 normal() { T l = 1.0f / length(); return *this * l; }
vec4& normalize() { T l = 1.0f / length(); *this *= l; return *this; }
vec4& operator*=(T scalar) { x *= scalar; y *= scalar; z *= scalar; w *= scalar; return *this; }
vec4& operator/=(T scalar) { x /= scalar; y /= scalar; z /= scalar; w /= scalar; return *this; }
vec4& operator+=(const vec4 & other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; }
vec4& operator-=(const vec4 & other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; }
vec4 operator+(const vec4 & other) const { return vec4(x + other.x, y + other.y, z + other.z, w + other.w); }
vec4 operator-(const vec4 & other) const { return vec4(x - other.x, y - other.y, z - other.z, w - other.w); }
vec4 operator*(const vec4 & other) const { return vec4(x * other.x, y * other.y, z * other.z, w * other.w); }
vec4 operator*(T scalar) const { return vec4(x * scalar, y * scalar, z * scalar, w * scalar); }
vec4 operator/(T scalar) const { return vec4(x / scalar, y / scalar, z / scalar, w / scalar); }
vec4 operator-() const { return vec4(-x, -y, -z, -w); }
bool operator != (const vec4 & other) { return (x != other.x) | (y != other.y) | (z != other.z) | (w != other.w); }
bool operator == (const vec4 & other) { return !((*this) != other); }
vec4& set(T xx, T yy, T zz, T ww) { x = xx; y = yy; z = zz; w = ww; return *this; }
T dot(const vec4<T> & other) const { return x * other.x + y * other.y + z * other.z + w * other.w; }
T length() const { return math::sqrt_approx(length_squared()); }
T length_squared() const { return dot(*this); }
const T& operator [](int index) const {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return *((&x) + index);
}
T& operator [](int index) {
rynx_assert(index >= 0 && index < 4, "index out of bounds");
return *((&x) + index);
}
T x, y, z, w;
};
namespace serialization {
template<typename T> struct Serialize<rynx::vec4<T>> {
template<typename IOStream>
void serialize(const rynx::vec4<T>& s, IOStream& writer) {
writer(s.x);
writer(s.y);
writer(s.z);
writer(s.w);
}
template<typename IOStream>
void deserialize(rynx::vec4<T>& s, IOStream& reader) {
reader(s.x);
reader(s.y);
reader(s.z);
reader(s.w);
}
};
}
#if defined(_WIN32) && RYNX_VECTOR_SIMD
template<>
struct vec4<float> {
union {
struct {
float x, y, z, w;
};
struct {
float r, g, b, a;
};
__m128 xmm;
};
vec4() : vec4(0.0f) {}
vec4(__m128 v) : xmm(v) {}
vec4(float v) : xmm(_mm_set_ps(0, v, v, v)) {}
vec4(float x, float y, float z, float w = 0.0f) : xmm(_mm_set_ps(w, z, y, x)) {}
vec4(vec3<float> const& other, float w = 0.0f) : xmm(_mm_set_ps(w, other.z, other.y, other.x)) {}
operator __m128() const { return xmm; }
vec4 operator * (const vec4& v) const { return vec4(_mm_mul_ps(xmm, v.xmm)); }
vec4 operator + (const vec4& v) const { return vec4(_mm_add_ps(xmm, v.xmm)); }
vec4 operator - (const vec4& v) const { return vec4(_mm_sub_ps(xmm, v.xmm)); }
vec4 operator / (const vec4& v) const { return vec4(_mm_div_ps(xmm, v.xmm)); }
vec4& operator *= (const vec4& v) { xmm = _mm_mul_ps(xmm, v.xmm); return *this; }
vec4& operator += (const vec4& v) { xmm = _mm_add_ps(xmm, v.xmm); return *this; }
vec4& operator -= (const vec4& v) { xmm = _mm_sub_ps(xmm, v.xmm); return *this; }
vec4& operator /= (const vec4& v) { xmm = _mm_div_ps(xmm, v.xmm); return *this; }
vec4 operator -() const { return operator *(-1.0f); }
floats4 to_floats() const {
floats4 result;
_mm_storeu_ps(result.data, xmm);
return result;
}
operator floats4() const {
return to_floats();
}
vec3<float> xyz() const {
return vec3<float>(x, y, z);
}
vec4 cross(const vec4& v2) const {
__m128 t1 = _mm_shuffle_ps(xmm, xmm, 0xc9);
__m128 t2 = _mm_shuffle_ps(xmm, xmm, 0xd2);
__m128 t3 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xd2);
__m128 t4 = _mm_shuffle_ps(v2.xmm, v2.xmm, 0xc9);
__m128 t5 = _mm_mul_ps(t1, t3);
__m128 t6 = _mm_mul_ps(t2, t4);
return _mm_sub_ps(t5, t6);
}
vec4 operator * (float s) const {
const __m128 scalar = _mm_set1_ps(s);
return _mm_mul_ps(xmm, scalar);
}
vec4& operator *= (float s) {
const __m128 scalar = _mm_set1_ps(s);
return operator *= (scalar);
}
vec4 operator / (float scalar) const { return operator*(1.0f / scalar); }
vec4& operator /= (float scalar) { return operator *= (1.0f / scalar); }
float length() const {
return _mm_cvtss_f32(_mm_sqrt_ss(_mm_dp_ps(xmm, xmm, 0xff)));
}
float length_squared() const {
return _mm_cvtss_f32(_mm_dp_ps(xmm, xmm, 0xff));
}
vec4 normal() const {
return _mm_div_ps(xmm, _mm_sqrt_ps(_mm_dp_ps(xmm, xmm, 0xff)));
}
vec4& normalize() { xmm = normal().xmm; return *this; }
bool operator != (const vec4& other) {
__m128i vcmp = _mm_castps_si128(_mm_cmpneq_ps(xmm, other.xmm));
int32_t test = _mm_movemask_epi8(vcmp);
return test != 0;
}
bool operator == (const vec4& other) { return !((*this) != other); }
vec4& set(float xx, float yy, float zz, float ww = 0.0f) { xmm = _mm_set_ps(ww, zz, yy, xx); return *this; }
float dot(const vec4& other) const {
__m128 r1 = _mm_mul_ps(xmm, other.xmm);
__m128 shuf = _mm_shuffle_ps(r1, r1, _MM_SHUFFLE(2, 3, 0, 1));
__m128 sums = _mm_add_ps(r1, shuf);
shuf = _mm_movehl_ps(shuf, sums);
sums = _mm_add_ss(sums, shuf);
return _mm_cvtss_f32(sums);
}
float horizontal_add() const {
__m128 t1 = _mm_movehl_ps(xmm, xmm);
__m128 t2 = _mm_add_ps(xmm, t1);
__m128 t3 = _mm_shuffle_ps(t2, t2, 1);
__m128 t4 = _mm_add_ss(t2, t3);
return _mm_cvtss_f32(t4);
}
vec4 normal2d() const { return vec4(_mm_shuffle_ps(xmm, xmm, _MM_SHUFFLE(3, 3, 0, 1))) * vec4(-1, +1, 0, 0); }
float cross2d(const vec4& other) const {
// TODO: this is madness.
floats4 kek1 = *this;
floats4 kek2 = other;
return kek1.x * kek2.y - kek1.y * kek2.x;
}
};
#endif
inline vec3<float> operator * (float x, const vec3<float>& other) {
return other * x;
}
using vec4f = vec4<float>;
using vec3f = vec3<float>;
}
| 35.964286
| 152
| 0.614883
|
Apodus
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.