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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cacd3ca5294a1eac1712614a021b6ae74d5de9df | 3,362 | cpp | C++ | src/webpagehandler.cpp | lbussy/bootstrap | 502e16fe4e4d5430f890126e69a174ac288cdc32 | [
"MIT"
] | null | null | null | src/webpagehandler.cpp | lbussy/bootstrap | 502e16fe4e4d5430f890126e69a174ac288cdc32 | [
"MIT"
] | null | null | null | src/webpagehandler.cpp | lbussy/bootstrap | 502e16fe4e4d5430f890126e69a174ac288cdc32 | [
"MIT"
] | null | null | null | /* Copyright (C) 2019-2020 Lee C. Bussy (@LBussy)
This file is part of Lee Bussy's Bootstrap (bootstrap).
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 "webpagehandler.h"
AsyncWebServer server(PORT);
void initWebServer()
{
setRegPageAliases();
setActionPageHandlers();
setEditor();
// File not found handler
server.onNotFound([](AsyncWebServerRequest *request) {
if (request->method() == HTTP_OPTIONS)
{
request->send(200);
}
else
{
Log.verbose(F("Serving 404." CR));
request->send(404, "text/plain", "Page not found.");
}
});
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
server.begin();
Log.notice(F("Async HTTP server started on port %l." CR), PORT);
#ifdef ESP8266
Log.verbose(F("Open: http://%s.local to view controller application." CR), WiFi.hostname().c_str());
#elif defined ESP32
Log.verbose(F("Open: http://%s.local to view controller application." CR), WiFi.getHostname());
#endif
}
void setRegPageAliases()
{
// Regular page aliases
server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.htm").setCacheControl("max-age=600");
server.serveStatic("/index/", SPIFFS, "/").setDefaultFile("index.htm").setCacheControl("max-age=600");
server.serveStatic("/404/", SPIFFS, "/").setDefaultFile("404.htm").setCacheControl("max-age=600");
}
void setActionPageHandlers()
{
// Action Page Handlers
server.on("/heap/", HTTP_GET, [](AsyncWebServerRequest *request) {
uint32_t _heap = ESP.getFreeHeap();
String heap = "Current heap: " + String(_heap);
request->send(200, F("text/plain"), heap);
});
server.on("/ping/", HTTP_GET, [](AsyncWebServerRequest *request) {
Log.verbose(F("Processing /ping/." CR));
request->send(200, F("text/plain"), F("Ok."));
});
}
void setEditor()
{
// Setup SPIFFS editor
#ifdef ESP32
server.addHandler(new SPIFFSEditor(SPIFFS, SPIFFSEDITUSER, SPIFFSEDITPW));
#elif defined(ESP8266)
server.addHandler(new SPIFFSEditor(SPIFFSEDITUSER, SPIFFSEDITPW));
#endif
server.on("/edit/", HTTP_GET, [](AsyncWebServerRequest *request) {
request->redirect("/edit");
});
}
void stopWebServer()
{
server.reset();
server.end();
Log.notice(F("Web server stopped." CR));
}
| 32.960784 | 106 | 0.686794 | lbussy |
cacd85485fb5586aa4d9a6e632809a98e9daa43e | 714 | cpp | C++ | labtasks/lab6/main.cpp | asharbinkhalil/DATASTRUCTURES | 884acdc3b4f87e2ea883344fcebe7a6ea9b41b7e | [
"MIT"
] | null | null | null | labtasks/lab6/main.cpp | asharbinkhalil/DATASTRUCTURES | 884acdc3b4f87e2ea883344fcebe7a6ea9b41b7e | [
"MIT"
] | null | null | null | labtasks/lab6/main.cpp | asharbinkhalil/DATASTRUCTURES | 884acdc3b4f87e2ea883344fcebe7a6ea9b41b7e | [
"MIT"
] | null | null | null |
#include"doubly circular.cpp"
#include <iostream>
using namespace std;
int main()
{
doublylinkedlist obj;
for (int i = 1; i <=10; i++)
obj.add_to_end(i);
cout << "INITIAL LIST IS\n\n";
obj.display();
cout << "\nIS soterd: " << obj.Issorted(obj.head) << "\n";
cout << "\nmiddle element is :"<<obj.returnmiddle(obj.head)<<"\n";
obj.reverse();
obj.display();
cout << "\nADDED 100 AT START and 200 at last by funtions: \n";
obj.add_to_head(100);
obj.add_to_end(200);
obj.display();
cout << "\nIS soterd: " << obj.Issorted(obj.head) << "\n";
cout << "\nDELETED 100 AT START and 200 at last by funtions: \n";
obj.deletehead();
obj.deletetail();
obj.display();
} | 22.3125 | 68 | 0.603641 | asharbinkhalil |
cacfbe0bb45cd121f8882c925bae03b2d43df478 | 4,546 | inl | C++ | SM_Test.inl | xzrunner/sm | e31351c4fcd4470efa4dbec5bb6ee02c21ae42f8 | [
"MIT"
] | null | null | null | SM_Test.inl | xzrunner/sm | e31351c4fcd4470efa4dbec5bb6ee02c21ae42f8 | [
"MIT"
] | null | null | null | SM_Test.inl | xzrunner/sm | e31351c4fcd4470efa4dbec5bb6ee02c21ae42f8 | [
"MIT"
] | null | null | null | #ifndef _SPATIAL_MATH_TEST_INL_
#define _SPATIAL_MATH_TEST_INL_
//#include "SM_Calc.h"
#include "sm_const.h"
#include <float.h>
#include <algorithm>
namespace sm
{
inline
bool is_between(float bound0, float bound1, float test)
{
if (bound0 < bound1) {
return test < bound1 + FLT_EPSILON && test > bound0 - FLT_EPSILON;
} else {
return test < bound0 + FLT_EPSILON && test > bound1 - FLT_EPSILON;
}
}
inline
bool is_point_at_line_left(const vec2& v, const vec2& s, const vec2& e)
{
return (v.y - s.y) * (e.x - s.x) - (v.x - s.x) * (e.y - s.y) > FLT_EPSILON;
}
inline
bool is_point_in_rect(const vec2& v, const rect& r)
{
if (!r.IsValid()) {
return false;
}
return v.x > r.xmin && v.x < r.xmax
&& v.y > r.ymin && v.y < r.ymax;
}
inline
bool is_point_on_rect(const vec2& v, const rect& r)
{
if (!r.IsValid()) {
return false;
}
return v.x == r.xmin || v.y == r.xmax || v.y == r.ymin || v.y == r.ymax;
}
inline
bool is_point_in_area(const vec2& v, const std::vector<vec2>& area)
{
bool odd_nodes = false;
for (size_t i = 0, n = area.size(), j = n - 1; i < n; ++i)
{
if (((area[i].y < v.y && area[j].y >= v.y) ||
(area[j].y < v.y && area[i].y >= v.y)) &&
(area[i].x <= v.x || area[j].x <= v.x))
{
odd_nodes ^= (area[i].x + (v.y - area[i].y) / (area[j].y - area[i].y) * (area[j].x - area[i].x) < v.x);
}
j = i;
}
return odd_nodes;
}
inline
bool is_point_in_circle(const vec2& v, const vec2& center, float radius)
{
return (v - center).LengthSquared() < radius * radius;
}
inline
bool is_point_in_convex(const vec2& pos, const std::vector<vec2>& convex)
{
return is_point_in_convex(pos, &convex[0], convex.size());
}
inline
bool is_point_in_convex(const vec2& pos, const vec2* convex, size_t num)
{
if (num < 3) {
return false;
}
int count = 0;
for (int i = 0; i < num; ++i)
{
vec2 s = convex[i],
e = i == num - 1 ? convex[0] : convex[i + 1];
if (is_point_at_line_left(pos, s, e)) {
++count;
}
}
return count == num || count == 0;
}
inline
bool is_point_intersect_polyline(const vec2& point, const std::vector<vec2>& polyline)
{
rect r(point, SM_LARGE_EPSILON, SM_LARGE_EPSILON);
return is_rect_intersect_polyline(r, polyline, true);
}
inline
bool is_segment_intersect_segment(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1)
{
return is_point_at_line_left(s0, s1, e1) != is_point_at_line_left(e0, s1, e1)
&& is_point_at_line_left(s1, s0, e0) != is_point_at_line_left(e1, s0, e0);
}
inline
bool is_two_line_parallel(const vec2& s0, const vec2& e0, const vec2& s1, const vec2& e1)
{
float denominatorX = (e1.y - s1.y) * (e0.x - s0.x) - (e0.y - s0.y) * (e1.x - s1.x),
denominatorY = (e1.x - s1.x) * (e0.y - s0.y) - (e0.x - s0.x) * (e1.y - s1.y);
return fabs(denominatorX) < FLT_EPSILON || fabs(denominatorY) < FLT_EPSILON;
}
inline
bool is_rect_contain_point(const rect& r, const vec2& v)
{
if (!r.IsValid()) {
return false;
}
return v.x >= r.xmin && v.x <= r.xmax
&& v.y >= r.ymin && v.y <= r.ymax;
}
inline
bool is_rect_contain_rect(const rect& outer, const rect& inner)
{
if (!inner.IsValid() || !outer.IsValid()) {
return false;
}
return inner.xmin >= outer.xmin && inner.xmax <= outer.xmax
&& inner.ymin >= outer.ymin && inner.ymax <= outer.ymax;
}
inline
bool is_rect_intersect_rect(const rect& r0, const rect& r1)
{
if (!r0.IsValid() || !r1.IsValid()) {
return false;
}
return !(r0.xmin >= r1.xmax || r0.xmax <= r1.xmin || r0.ymin >= r1.ymax || r0.ymax <= r1.ymin);
}
inline
bool is_rect_intersect_polyline(const rect& r, const std::vector<vec2>& poly, bool loop)
{
if (!r.IsValid() || poly.size() < 2) {
return false;
}
for (size_t i = 0, n = poly.size() - 1; i < n; ++i)
{
if (is_rect_intersect_segment(r, poly[i], poly[i+1]))
return true;
}
if (loop && is_rect_intersect_segment(r, poly[poly.size() - 1], poly[0])) {
return true;
}
return false;
}
inline
bool is_rect_intersect_polygon(const rect& rect, const std::vector<vec2>& poly)
{
if (!rect.IsValid() || poly.size() < 3) {
return false;
}
if (is_point_in_area(rect.Center(), poly) || is_point_in_rect(poly[0], rect)) {
return true;
}
std::vector<vec2> poly2;
poly2.push_back(vec2(rect.xmin, rect.ymin));
poly2.push_back(vec2(rect.xmax, rect.ymin));
poly2.push_back(vec2(rect.xmax, rect.ymax));
poly2.push_back(vec2(rect.xmin, rect.ymax));
return is_polygon_intersect_polygon(poly, poly2);
}
}
#endif // _SPATIAL_MATH_TEST_INL_ | 24.05291 | 106 | 0.624945 | xzrunner |
cad38c0546f3b67129a5ecd1164f651f254dba8c | 7,368 | cpp | C++ | Engine/PipelineCompiler/glsl/Ray.cpp | azhirnov/GraphicsGenFramework-modular | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | 12 | 2017-12-23T14:24:57.000Z | 2020-10-02T19:52:12.000Z | Engine/PipelineCompiler/glsl/Ray.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | Engine/PipelineCompiler/glsl/Ray.cpp | azhirnov/ModularGraphicsFramework | 348be601f1991f102defa0c99250529f5e44c4d3 | [
"BSD-2-Clause"
] | null | null | null | // This is generated file, don't change anything!
#include "glsl_source_vfs.h"
namespace glsl_vfs
{
extern void VFS_Math3D_Ray (OUT String &src)
{
src << R"#(/*
3D Ray
license: free
*/
#include <Math/Quaternion.glsl>
#include <Math3D/Line3.glsl>
#include <Math/Math.glsl>
#include <Math/Utils.glsl>
struct Ray
{
real3 origin; // camera (eye, light, ...) position
real3 pos; // current position
real3 dir; // normalized direction
};
Ray Ray_Create (const real3 origin, const real3 direction);
// from camera
//Ray Ray_FromScreen (const real3 origin, const real nearPlane, const int2 screenSize, const int2 screenCoord);
Ray Ray_FromScreen (const real3 origin, const quat rotation, const real fovX, const real nearPlane,
const int2 screenSize, const int2 screenCoord);
Ray Ray_FromSphereScreen (const real3 origin, const real fovX, const real nearPlane, const int2 screenSize, const int2 screenCoord);
// TODO: rename
Ray Ray_From (const real3 leftBottom, const real3 rightBottom, const real3 leftTop, const real3 rightTop,
const real3 origin, const real nearPlane, const float2 unormCoord);
real3 Ray_CalcX (const Ray ray, const real2 pointYZ);
real3 Ray_CalcY (const Ray ray, const real2 pointXZ);
real3 Ray_CalcZ (const Ray ray, const real2 pointXY);
bool Ray_Contains (const Ray ray, const real3 point);
void Ray_Rotate (inout Ray ray, const quat rotation);
void Ray_Move (inout Ray ray, const real length);
real Ray_Length (const Ray ray);
void Ray_SetLength (inout Ray ray, const real length);
Line3 Ray_ToLine (const Ray ray, const real length);
//-----------------------------------------------------------------------------
/*
=================================================
Ray_Create
=================================================
*/
Ray Ray_Create (const real3 origin, const real3 direction)
{
Ray result;
result.origin = origin;
result.pos = origin;
result.dir = direction;
return result;
}
/*
=================================================
Ray_FromScreen
----
create ray for raytracing, raymarching, ...
=================================================
*
Ray Ray_FromScreen (const real3 origin, const real nearPlane, const int2 screenSize, const int2 screenCoord)
{
// project screen point to plane
const int2 scr_center = screenSize / 2;
const real2 point = real2( screenCoord - scr_center ) / real2( scr_center );
const real3 vec = real3( point.x, nearPlane, point.y );
Ray ray;
ray.origin = origin;
ray.dir = Normalize( vec );
ray.pos = ray.origin + ray.dir * nearPlane;
return ray;
}
/*
=================================================
Ray_FromScreen
----
create ray for raytracing, raymarching, ...
=================================================
*/
Ray Ray_FromScreen (const real3 origin, const quat rotation, const real fovX, const real nearPlane,
const int2 screenSize, const int2 screenCoord)
{
real2 scr_size = real2(screenSize);
real2 coord = real2(screenCoord);
real ratio = scr_size.y / scr_size.x;
real fovY = fovX * ratio;
real2 scale = nearPlane / Cos( real2(fovX, fovY) * 0.5 );
real2 uv = (coord - scr_size * 0.5) / (scr_size.x * 0.5) * scale;
Ray ray;
ray.origin = origin;
ray.dir = Normalize( QMul( rotation, Normalize( real3(uv.x, 1.0, uv.y) ) ) );
ray.pos = origin + ray.dir * nearPlane;
return ray;
}
/*
=================================================
Ray_FromSphereScreen
----
used when target image projected to sphere
with horizontal angle 'fovX'
=================================================
*/
Ray Ray_FromSphereScreen (const real3 origin, const real fovX, const real nearPlane, const int2 screenSize, const int2 screenCoord)
{
// project screen point to sphere
const int2 scr_center = screenSize / 2;
const real2 point = real2( screenCoord - scr_center ) / real2( scr_center );
const real scr_ratio = real( screenSize.y ) / real( screenSize.x );
const real2 sphere_size = real2( 1.0, scr_ratio ) * fovX * nearPlane;
const real2 angle = point * sphere_size * 0.5 / nearPlane;
const real3 vec = SphericalToCartesian( angle, nearPlane );
Ray ray;
ray.origin = origin;
ray.dir = Normalize( vec );
ray.pos = ray.origin + ray.dir * nearPlane;
return ray;
}
/*
=================================================
Ray_From
----
create ray from frustum rays and origin
=================================================
*/
Ray Ray_From (const real3 leftBottom, const real3 rightBottom, const real3 leftTop, const real3 rightTop,
const real3 origin, const real nearPlane, const float2 unormCoord)
{
const real2 coord = unormCoord;
const real3 vec = Lerp( Lerp( leftBottom, rightBottom, coord.x ),
Lerp( leftTop, rightTop, coord.x ),
coord.y );
Ray ray;
ray.origin = origin;
ray.dir = Normalize( vec );
ray.pos = ray.origin + ray.dir * nearPlane;
return ray;
}
/*
=================================================
Ray_CalcX
=================================================
*/
real3 Ray_CalcX (const Ray ray, const real2 pointYZ)
{
const real x = ray.pos.x + ray.dir.x * (pointYZ[1] - ray.pos.z) / ray.dir.z;
return real3( x, pointYZ[0], pointYZ[1] );
}
/*
=================================================
Ray_CalcY
=================================================
*/
real3 Ray_CalcY (const Ray ray, const real2 pointXZ)
{
const real y = ray.pos.y + ray.dir.y * (pointXZ[1] - ray.pos.z) / ray.dir.z;
return real3( pointXZ[0], y, pointXZ[1] );
}
/*
=================================================
Ray_CalcZ
=================================================
*/
real3 Ray_CalcZ (const Ray ray, const real2 pointXY)
{
const real z = ray.pos.z + ray.dir.z * (pointXY[0] - ray.pos.x) / ray.dir.x;
return real3( pointXY[0], pointXY[1], z );
}
/*
=================================================
Ray_Contains
=================================================
*/
bool Ray_Contains (const Ray ray, const real3 point)
{
// z(x), z(y)
const real2 z = ray.pos.zz + ray.dir.zz * (point.xy - ray.pos.xy) / ray.dir.xy;
// z(x) == z(y) and z(x) == point.z
return Equals( z.x, z.y ) and Equals( z.x, point.z );
}
/*
=================================================
Ray_Rotate
=================================================
*/
void Ray_Rotate (inout Ray ray, const quat rotation)
{
// ray.origin - const
ray.dir = Normalize( QMul( rotation, ray.dir ) );
ray.pos = Distance( ray.origin, ray.pos ) * ray.dir;
}
/*
=================================================
Ray_Move
=================================================
*/
void Ray_Move (inout Ray ray, const real length)
{
ray.pos += ray.dir * length;
}
/*
=================================================
Ray_Length
=================================================
*/
real Ray_Length (const Ray ray)
{
return Distance( ray.origin, ray.pos );
}
/*
=================================================
Ray_SetLength
=================================================
*/
void Ray_SetLength (inout Ray ray, const real length)
{
ray.pos = ray.origin + ray.dir * length;
}
/*
=================================================
Ray_ToLine
=================================================
*/
Line3 Ray_ToLine (const Ray ray, const real length)
{
Line3 result;
result.begin = ray.pos;
result.end = ray.pos + ray.dir * length;
return result;
}
)#";
}
} // glsl_vfs
| 26.408602 | 133 | 0.552389 | azhirnov |
cad4f12e8bdfa96d187c14abd05833c0c6918917 | 14,187 | cpp | C++ | unittests/VMRuntime/HeapSnapshotTest.cpp | mganandraj/hermes | cb54b87f9dd4c6de26196a35e21f5af88383cc65 | [
"MIT"
] | null | null | null | unittests/VMRuntime/HeapSnapshotTest.cpp | mganandraj/hermes | cb54b87f9dd4c6de26196a35e21f5af88383cc65 | [
"MIT"
] | null | null | null | unittests/VMRuntime/HeapSnapshotTest.cpp | mganandraj/hermes | cb54b87f9dd4c6de26196a35e21f5af88383cc65 | [
"MIT"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "hermes/VM/HeapSnapshot.h"
#include "TestHelpers.h"
#include "gtest/gtest.h"
#include "hermes/Parser/JSONParser.h"
#include "hermes/Support/Allocator.h"
#include "hermes/VM/CellKind.h"
#include "hermes/VM/GC.h"
#include "hermes/VM/GCPointer-inline.h"
#include "hermes/VM/HermesValue.h"
#include "hermes/VM/SymbolID.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
using namespace hermes::vm;
using namespace hermes::parser;
// Only the main NCGen needs to support snapshots
#ifdef HERMESVM_GC_NONCONTIG_GENERATIONAL
namespace hermes {
namespace unittest {
namespace heapsnapshottest {
// Forward declaration to allow IsGCObject.
struct DummyObject;
} // namespace heapsnapshottest
} // namespace unittest
namespace vm {
template <>
struct IsGCObject<unittest::heapsnapshottest::DummyObject>
: public std::true_type {};
} // namespace vm
namespace unittest {
namespace heapsnapshottest {
struct DummyObject final : public GCCell {
static const VTable vt;
GCPointer<DummyObject> other;
const uint32_t x;
const uint32_t y;
GCHermesValue hvBool;
GCHermesValue hvDouble;
GCHermesValue hvUndefined;
GCHermesValue hvEmpty;
GCHermesValue hvNative;
GCHermesValue hvNull;
DummyObject(GC *gc) : GCCell(gc, &vt), other(), x(1), y(2) {
hvBool.setNonPtr(HermesValue::encodeBoolValue(true));
hvDouble.setNonPtr(HermesValue::encodeNumberValue(3.14));
hvNative.setNonPtr(HermesValue::encodeNativeValue(0xE));
hvUndefined.setNonPtr(HermesValue::encodeUndefinedValue());
hvEmpty.setNonPtr(HermesValue::encodeEmptyValue());
hvNull.setNonPtr(HermesValue::encodeNullValue());
}
void setPointer(DummyRuntime &rt, DummyObject *obj) {
other.set(&rt, obj, &rt.gc);
}
static DummyObject *create(DummyRuntime &runtime) {
return new (runtime.alloc(sizeof(DummyObject)))
DummyObject(&runtime.getHeap());
}
static bool classof(const GCCell *cell) {
return cell->getKind() == CellKind::UninitializedKind;
}
};
const VTable DummyObject::vt{CellKind::UninitializedKind, sizeof(DummyObject)};
static void DummyObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) {
const auto *self = static_cast<const DummyObject *>(cell);
mb.addField("HermesBool", &self->hvBool);
mb.addField("HermesDouble", &self->hvDouble);
mb.addField("HermesUndefined", &self->hvUndefined);
mb.addField("HermesEmpty", &self->hvEmpty);
mb.addField("HermesNative", &self->hvNative);
mb.addField("HermesNull", &self->hvNull);
mb.addField("other", &self->other);
}
static MetadataTableForTests getMetadataTable() {
static const Metadata storage[] = {
buildMetadata(CellKind::UninitializedKind, DummyObjectBuildMeta)};
return MetadataTableForTests(storage);
}
static ::testing::AssertionResult testListOfStrings(
JSONArray::iterator begin,
JSONArray::iterator end,
std::initializer_list<llvm::StringRef> strs) {
EXPECT_EQ(static_cast<unsigned long>(end - begin), strs.size());
auto strsIt = strs.begin();
for (auto it = begin; it != end; ++it) {
EXPECT_EQ(llvm::cast<JSONString>(*it)->str(), *strsIt);
++strsIt;
}
return ::testing::AssertionSuccess();
}
static ::testing::AssertionResult testListOfStrings(
const JSONArray &arr,
std::initializer_list<llvm::StringRef> strs) {
return testListOfStrings(arr.begin(), arr.end(), strs);
}
static void testNode(
JSONArray::iterator nodes,
JSONArray &strings,
HeapSnapshot::NodeType type,
llvm::StringRef name,
HeapSnapshot::NodeID id,
size_t selfSize,
size_t edgeCount,
size_t traceNodeID,
const char *file,
int line) {
// Need two levels of cast for enums because Windows complains about casting
// doubles to enums.
auto actualType = static_cast<HeapSnapshot::NodeType>(
static_cast<unsigned>(llvm::cast<JSONNumber>(*nodes)->getValue()));
if (actualType != type) {
ADD_FAILURE_AT(file, line)
<< "\tExpected type: " << ::testing::PrintToString(type)
<< "\n\t Actual type: " << ::testing::PrintToString(actualType);
}
nodes++;
auto actualName = llvm::cast<JSONString>(
strings[llvm::cast<JSONNumber>(*nodes)->getValue()])
->str();
if (actualName != name) {
ADD_FAILURE_AT(file, line)
<< "\tExpected name: " << ::testing::PrintToString(name)
<< "\n\t Actual name: " << ::testing::PrintToString(actualName);
}
nodes++;
auto actualID = static_cast<HeapSnapshot::NodeID>(
llvm::cast<JSONNumber>(*nodes)->getValue());
if (actualID != id) {
ADD_FAILURE_AT(file, line)
<< "\tExpected ID: " << ::testing::PrintToString(id)
<< "\n\t Actual ID: " << ::testing::PrintToString(actualID);
}
nodes++;
auto actualSelfSize =
static_cast<size_t>(llvm::cast<JSONNumber>(*nodes)->getValue());
if (actualSelfSize != selfSize) {
ADD_FAILURE_AT(file, line)
<< "\tExpected self size: " << ::testing::PrintToString(selfSize)
<< "\n\t Actual self size: "
<< ::testing::PrintToString(actualSelfSize);
}
nodes++;
auto actualEdgeCount =
static_cast<size_t>(llvm::cast<JSONNumber>(*nodes)->getValue());
if (actualEdgeCount != edgeCount) {
ADD_FAILURE_AT(file, line)
<< "\tExpected edge count: " << ::testing::PrintToString(edgeCount)
<< "\n\t Actual edge count: "
<< ::testing::PrintToString(actualEdgeCount);
}
nodes++;
auto actualTraceNodeID =
static_cast<size_t>(llvm::cast<JSONNumber>(*nodes)->getValue());
if (actualTraceNodeID != traceNodeID) {
ADD_FAILURE_AT(file, line)
<< "\tExpected trace node ID: " << ::testing::PrintToString(traceNodeID)
<< "\n\t Actual trace node ID: "
<< ::testing::PrintToString(actualTraceNodeID);
}
nodes++;
}
#define TEST_NODE(...) testNode(__VA_ARGS__, __FILE__, __LINE__)
static ::testing::AssertionResult testEdge(
JSONArray::iterator edges,
JSONArray &nodes,
JSONArray &strings,
HeapSnapshot::EdgeType type,
llvm::StringRef name,
size_t index,
size_t toNode,
const char *file,
int line) {
// Need two levels of cast for enums because Windows complains about casting
// doubles to enums.
auto actualType = static_cast<HeapSnapshot::EdgeType>(
static_cast<unsigned>(llvm::cast<JSONNumber>(*edges)->getValue()));
if (actualType != type) {
ADD_FAILURE_AT(file, line)
<< "\tExpected type: " << ::testing::PrintToString(type)
<< "\n\t Actual type: " << ::testing::PrintToString(actualType);
}
edges++;
switch (actualType) {
case HeapSnapshot::EdgeType::Internal: {
auto actualName = llvm::cast<JSONString>(
strings[llvm::cast<JSONNumber>(*edges)->getValue()])
->str();
if (actualName != name) {
ADD_FAILURE_AT(file, line)
<< "\tExpected name: " << ::testing::PrintToString(name)
<< "\n\t Actual name: " << ::testing::PrintToString(actualName);
}
edges++;
break;
}
default: {
auto actualIndex = llvm::cast<JSONNumber>(*edges)->getValue();
if (actualIndex != index) {
ADD_FAILURE_AT(file, line)
<< "\tExpected index: " << ::testing::PrintToString(index)
<< "\n\t Actual index: " << ::testing::PrintToString(actualIndex);
}
edges++;
break;
}
}
uint32_t actualToNode = llvm::cast<JSONNumber>(*edges)->getValue();
assert(
actualToNode % HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT == 0 &&
"Invalid to node pointer");
actualToNode /= HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT;
if (actualToNode != toNode) {
ADD_FAILURE_AT(file, line)
<< "\tExpected node: " << ::testing::PrintToString(toNode)
<< "\n\t Actual node: " << ::testing::PrintToString(actualToNode);
}
edges++;
return ::testing::AssertionSuccess();
}
#define TEST_EDGE(...) testEdge(__VA_ARGS__, __FILE__, __LINE__)
TEST(HeapSnapshotTest, SnapshotTest) {
auto runtime = DummyRuntime::create(
getMetadataTable(),
GCConfig::Builder()
.withInitHeapSize(1024)
.withMaxHeapSize(1024 * 100)
.build());
DummyRuntime &rt = *runtime;
auto &gc = rt.gc;
GCScope gcScope(&rt);
auto dummy = rt.makeHandle(DummyObject::create(rt));
auto *dummy2 = DummyObject::create(rt);
dummy->setPointer(rt, dummy2);
std::string result("");
llvm::raw_string_ostream str(result);
gc.collect();
gc.createSnapshot(str, true);
str.flush();
ASSERT_FALSE(result.empty());
const auto blockSize = dummy->getAllocatedSize();
JSONFactory::Allocator alloc;
JSONFactory jsonFactory{alloc};
SourceErrorManager sm;
JSONParser parser{jsonFactory, result, sm};
auto optSnapshot = parser.parse();
ASSERT_TRUE(optSnapshot) << "Heap snapshot is not valid JSON";
// Too verbose to check every key, so let llvm::cast do the checks.
JSONObject *root = llvm::cast<JSONObject>(optSnapshot.getValue());
JSONObject *snapshot = llvm::cast<JSONObject>(root->at("snapshot"));
EXPECT_EQ(llvm::cast<JSONNumber>(snapshot->at("node_count"))->getValue(), 0);
EXPECT_EQ(llvm::cast<JSONNumber>(snapshot->at("edge_count"))->getValue(), 0);
EXPECT_EQ(
llvm::cast<JSONNumber>(snapshot->at("trace_function_count"))->getValue(),
0);
JSONObject *meta = llvm::cast<JSONObject>(snapshot->at("meta"));
EXPECT_EQ(
llvm::cast<JSONArray>(meta->at("trace_function_info_fields"))->size(), 0);
EXPECT_EQ(llvm::cast<JSONArray>(meta->at("trace_node_fields"))->size(), 0);
EXPECT_EQ(llvm::cast<JSONArray>(meta->at("sample_fields"))->size(), 0);
EXPECT_EQ(llvm::cast<JSONArray>(meta->at("location_fields"))->size(), 0);
JSONArray &nodeFields = *llvm::cast<JSONArray>(meta->at("node_fields"));
JSONArray &nodeTypes = *llvm::cast<JSONArray>(meta->at("node_types"));
JSONArray &edgeFields = *llvm::cast<JSONArray>(meta->at("edge_fields"));
JSONArray &edgeTypes = *llvm::cast<JSONArray>(meta->at("edge_types"));
// Check that node_fields/types are correct.
EXPECT_TRUE(testListOfStrings(
nodeFields,
{"type", "name", "id", "self_size", "edge_count", "trace_node_id"}));
const JSONArray &nodeTypeEnum = *llvm::cast<JSONArray>(nodeTypes[0]);
EXPECT_TRUE(testListOfStrings(
nodeTypeEnum,
{"hidden",
"array",
"string",
"object",
"code",
"closure",
"regexp",
"number",
"native",
"synthetic",
"concatenated string",
"sliced string",
"symbol",
"bigint"}));
EXPECT_TRUE(testListOfStrings(
nodeTypes.begin() + 1,
nodeTypes.end(),
{"string", "number", "number", "number", "number"}));
// Check that edge_fields/types are correct.
EXPECT_TRUE(
testListOfStrings(edgeFields, {"type", "name_or_index", "to_node"}));
const JSONArray &edgeTypeEnum = *llvm::cast<JSONArray>(edgeTypes[0]);
EXPECT_TRUE(testListOfStrings(
edgeTypeEnum,
{"context",
"element",
"property",
"internal",
"hidden",
"shortcut",
"weak"}));
EXPECT_TRUE(testListOfStrings(
edgeTypes.begin() + 1, edgeTypes.end(), {"string_or_number", "node"}));
// Check the nodes and edges.
JSONArray &nodes = *llvm::cast<JSONArray>(root->at("nodes"));
JSONArray &edges = *llvm::cast<JSONArray>(root->at("edges"));
JSONArray &strings = *llvm::cast<JSONArray>(root->at("strings"));
EXPECT_EQ(llvm::cast<JSONArray>(root->at("trace_function_infos"))->size(), 0);
EXPECT_EQ(llvm::cast<JSONArray>(root->at("trace_tree"))->size(), 0);
EXPECT_EQ(llvm::cast<JSONArray>(root->at("samples"))->size(), 0);
EXPECT_EQ(llvm::cast<JSONArray>(root->at("locations"))->size(), 0);
// First node is the roots object.
auto nextNode = nodes.begin();
TEST_NODE(
nextNode,
strings,
HeapSnapshot::NodeType::Synthetic,
"(GC Roots)",
static_cast<HeapSnapshot::NodeID>(GC::IDTracker::ReservedObjectID::Root),
0,
1,
0);
nextNode += HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT;
// Next node is the custom root section.
TEST_NODE(
nextNode,
strings,
HeapSnapshot::NodeType::Synthetic,
"(Custom)",
static_cast<HeapSnapshot::NodeID>(
GC::IDTracker::ReservedObjectID::Custom),
0,
1,
0);
nextNode += HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT;
// Next node is the first dummy object.
TEST_NODE(
nextNode,
strings,
HeapSnapshot::NodeType::Object,
cellKindStr(dummy->getKind()),
gc.getObjectID(dummy.get()),
blockSize,
1,
0);
nextNode += HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT;
// Next node is the second dummy, which is only reachable via the first
// dummy.
TEST_NODE(
nextNode,
strings,
HeapSnapshot::NodeType::Object,
cellKindStr(dummy->getKind()),
gc.getObjectID(dummy->other),
blockSize,
0,
0);
nextNode += HeapSnapshot::V8_SNAPSHOT_NODE_FIELD_COUNT;
EXPECT_EQ(nextNode, nodes.end());
auto nextEdge = edges.begin();
// Pointer from root to root section.
TEST_EDGE(
nextEdge,
nodes,
strings,
HeapSnapshot::EdgeType::Element,
"(Custom)",
1,
1);
nextEdge += HeapSnapshot::V8_SNAPSHOT_EDGE_FIELD_COUNT;
// Pointer from root section to first dummy.
TEST_EDGE(
nextEdge, nodes, strings, HeapSnapshot::EdgeType::Element, "", 0, 2);
nextEdge += HeapSnapshot::V8_SNAPSHOT_EDGE_FIELD_COUNT;
// Pointer from first dummy to second dummy.
TEST_EDGE(
nextEdge,
nodes,
strings,
HeapSnapshot::EdgeType::Internal,
"other",
1,
3);
nextEdge += HeapSnapshot::V8_SNAPSHOT_EDGE_FIELD_COUNT;
EXPECT_EQ(nextEdge, edges.end());
// String table is checked by the nodes and edges checks.
}
} // namespace heapsnapshottest
} // namespace unittest
} // namespace hermes
#endif
| 32.097285 | 80 | 0.659266 | mganandraj |
cad7cf147f5e6187c088499b1a4cdacbffae7f1c | 5,702 | hpp | C++ | lib/inquisitive/shl.hpp | fcharlie/FileViewer | 56861b3d3a62ea16becea965bc3bc0198f28e26a | [
"MIT"
] | 3 | 2019-03-19T09:24:09.000Z | 2021-05-17T11:21:24.000Z | lib/inquisitive/shl.hpp | fcharlie/FileViewer | 56861b3d3a62ea16becea965bc3bc0198f28e26a | [
"MIT"
] | null | null | null | lib/inquisitive/shl.hpp | fcharlie/FileViewer | 56861b3d3a62ea16becea965bc3bc0198f28e26a | [
"MIT"
] | 1 | 2019-11-20T05:11:30.000Z | 2019-11-20T05:11:30.000Z | ////////////////
#ifndef INQUISITIVE_SHELLLINK_HPP
#define INQUISITIVE_SHELLLINK_HPP
#include <cstdint>
namespace shl {
// Shell link flags
// Thanks:
// https://github.com/reactos/reactos/blob/bfcbda227f99c1b59e8ed71f5e0f59f793d496a1/sdk/include/reactos/undocshell.h#L800
enum : uint32_t {
SldfNone = 0x00000000,
HasLinkTargetIDList = 0x00000001,
HasLinkInfo = 0x00000002,
HasName = 0x00000004,
HasRelativePath = 0x00000008,
HasWorkingDir = 0x00000010,
HasArguments = 0x00000020,
HasIconLocation = 0x00000040,
IsUnicode = 0x00000080,
ForceNoLinkInfo = 0x00000100,
HasExpString = 0x00000200,
RunInSeparateProcess = 0x00000400,
Unused1 = 0x00000800,
HasDrawinID = 0x00001000,
RunAsUser = 0x00002000,
HasExpIcon = 0x00004000,
NoPidlAlias = 0x00008000,
Unused2 = 0x00010000,
RunWithShimLayer = 0x00020000,
ForceNoLinkTrack = 0x00040000,
EnableTargetMetadata = 0x00080000,
DisableLinkPathTarcking = 0x00100000,
DisableKnownFolderTarcking = 0x00200000,
DisableKnownFolderAlia = 0x00400000,
AllowLinkToLink = 0x00800000,
UnaliasOnSave = 0x01000000,
PreferEnvironmentPath = 0x02000000,
KeepLocalIDListForUNCTarget = 0x04000000,
PersistVolumeIDRelative = 0x08000000,
SldfInvalid = 0x0ffff7ff,
Reserved = 0x80000000
};
#pragma pack(1)
/*
SHELL_LINK = SHELL_LINK_HEADER [LINKTARGET_IDLIST] [LINKINFO]
[STRING_DATA] *EXTRA_DATA
*/
struct filetime_t {
uint32_t low;
uint32_t high;
};
struct shell_link_t {
uint32_t dwSize;
uint8_t uuid[16];
uint32_t linkflags;
uint32_t fileattr;
filetime_t createtime;
filetime_t accesstime;
filetime_t writetime;
uint32_t filesize;
uint32_t iconindex;
uint32_t showcommand;
uint16_t hotkey;
uint16_t reserved1;
uint32_t reserved2;
uint32_t reserved3;
};
enum link_info_flags : uint32_t {
VolumeIDAndLocalBasePath = 0x00000001,
CommonNetworkRelativeLinkAndPathSuffix = 0x00000002
};
struct shl_link_info_t {
/* Size of the link info data */
uint32_t cbSize;
/* Size of this structure (ANSI: = 0x0000001C) */
uint32_t cbHeaderSize;
/* Specifies which fields are present/populated (SLI_*) */
uint32_t dwFlags;
/* Offset of the VolumeID field (SHELL_LINK_INFO_VOLUME_ID) */
uint32_t cbVolumeIDOffset;
/* Offset of the LocalBasePath field (ANSI, NULL-terminated string) */
uint32_t cbLocalBasePathOffset;
/* Offset of the CommonNetworkRelativeLink field (SHELL_LINK_INFO_CNR_LINK) */
uint32_t cbCommonNetworkRelativeLinkOffset;
/* Offset of the CommonPathSuffix field (ANSI, NULL-terminated string) */
uint32_t cbCommonPathSuffixOffset;
};
struct shl_link_infow_t {
/* Size of the link info data */
uint32_t cbSize;
/* Size of this structure (Unicode: >= 0x00000024) */
uint32_t cbHeaderSize;
/* Specifies which fields are present/populated (SLI_*) */
uint32_t dwFlags;
/* Offset of the VolumeID field (SHELL_LINK_INFO_VOLUME_ID) */
uint32_t cbVolumeIDOffset;
/* Offset of the LocalBasePath field (ANSI, NULL-terminated string) */
uint32_t cbLocalBasePathOffset;
/* Offset of the CommonNetworkRelativeLink field (SHELL_LINK_INFO_CNR_LINK) */
uint32_t cbCommonNetworkRelativeLinkOffset;
/* Offset of the CommonPathSuffix field (ANSI, NULL-terminated string) */
uint32_t cbCommonPathSuffixOffset;
/* Offset of the LocalBasePathUnicode field (Unicode, NULL-terminated string)
*/
uint32_t cbLocalBasePathUnicodeOffset;
/* Offset of the CommonPathSuffixUnicode field (Unicode, NULL-terminated
* string) */
uint32_t cbCommonPathSuffixUnicodeOffset;
};
// BlockSize (4 bytes): A 32-bit, unsigned integer that specifies the size of
// the KnownFolderDataBlock structure. This value MUST be 0x0000001C.
// BlockSignature (4 bytes): A 32-bit, unsigned integer that specifies the
// signature of the KnownFolderDataBlock extra data section. This value MUST be
// 0xA000000B.
// KnownFolderID (16 bytes): A value in GUID packet representation ([MS-DTYP]
// section 2.3.4.2) that specifies the folder GUID ID.
// Offset (4 bytes): A 32-bit, unsigned integer that specifies the location of
// the ItemID of the first child segment of the IDList specified by
// KnownFolderID. This value is the offset, in bytes, into the link target
// IDList.
struct shl_cnr_link_t {
/* Size of the CommonNetworkRelativeLink field (>= 0x00000014) */
uint32_t cbSize;
/* Specifies which fields are present/populated (SLI_CNR_*) */
uint32_t dwFlags;
/* Offset of the NetName field (ANSI, NULL–terminated string) */
uint32_t cbNetNameOffset;
/* Offset of the DeviceName field (ANSI, NULL–terminated string) */
uint32_t cbDeviceNameOffset;
/* Type of the network provider (WNNC_NET_* defined in winnetwk.h) */
uint32_t dwNetworkProviderType;
};
struct shl_cnr_linkw_t {
/* Size of the CommonNetworkRelativeLink field (>= 0x00000014) */
uint32_t cbSize;
/* Specifies which fields are present/populated (SLI_CNR_*) */
uint32_t dwFlags;
/* Offset of the NetName field (ANSI, NULL–terminated string) */
uint32_t cbNetNameOffset;
/* Offset of the DeviceName field (ANSI, NULL–terminated string) */
uint32_t cbDeviceNameOffset;
/* Type of the network provider (WNNC_NET_* defined in winnetwk.h) */
uint32_t dwNetworkProviderType;
/* Offset of the NetNameUnicode field (Unicode, NULL–terminated string) */
uint32_t cbNetNameUnicodeOffset;
/* Offset of the DeviceNameUnicode field (Unicode, NULL–terminated string) */
uint32_t cbDeviceNameUnicodeOffset;
};
struct knwonfolder_t {
uint32_t blocksize; // LE 0x0000001C
uint32_t blocksignature;
uint8_t knownfolderid[16];
uint32_t offset;
};
/*
IDList ItemIDSize (2 bytes):
Data (variable):
*/
#pragma pack()
} // namespace shl
#endif
| 32.033708 | 121 | 0.757804 | fcharlie |
cad9ac4979bb4ea96e2ea2f65d09442ce3691cfd | 20,724 | cpp | C++ | FaceDemo_DXUT/Source/Model.cpp | GameTechDev/FaceTracking | 56223359cb00a66b6dcd882dadd6e6f6a47da9ea | [
"Apache-2.0"
] | 39 | 2017-04-11T10:01:59.000Z | 2022-01-12T15:13:45.000Z | FaceDemo_DXUT/Source/Model.cpp | shengguo78/FaceMe | 7f87583312545f16557624d3c99b2521e95d9670 | [
"Apache-2.0"
] | 2 | 2017-03-21T22:13:20.000Z | 2021-04-19T16:38:03.000Z | FaceDemo_DXUT/Source/Model.cpp | shengguo78/FaceMe | 7f87583312545f16557624d3c99b2521e95d9670 | [
"Apache-2.0"
] | 16 | 2017-03-16T12:20:50.000Z | 2020-03-21T04:13:55.000Z | /////////////////////////////////////////////////////////////////////////////////////////////
// Copyright 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/////////////////////////////////////////////////////////////////////////////////////////////
#include "Model.h"
#include "Sample.h"
const std::string Model::ROOT_FRAME_NAME = "Root";
const std::wstring Model::NEUTRAL_FACE_FILE_NAME = L"Neutral.X";
const unsigned int Model::MATERIAL_NUMBER = 3;
const std::wstring Model::GetFacialFileName(ActionUnit action)
{
switch (action)
{
case MOUTH_OPEN: return L"MouthOpen.X";
case MOUTH_LEFT_RAISE: return L"MouthSmileL.X";
case MOUTH_RIGHT_RAISE: return L"MouthSmileR.X";
case MOUTH_LEFT: return L"MouthRight.X";
case MOUTH_RIGHT: return L"MouthLeft.X";
case EYELID_CLOSE_L: return L"EyeLid_Close_L.X";
case EYELID_CLOSE_R: return L"EyeLid_Close_R.X";
case EYELID_OPEN_L: return L"EyeLid_Open_L.X";
case EYELID_OPEN_R: return L"EyeLid_Open_R.X";
case EYEBROW_Up_L: return L"EyeBrow_up_L.X";
case EYEBROW_Up_R: return L"EyeBrow_up_R.X";
case EYEBROW_DOWN_L: return L"EyeBrow_Down_L.X";
case EYEBROW_DOWN_R: return L"EyeBrow_Down_R.X";
case EYEBALL_TURN_L: return L"EyeBall_Turn_L.X";
case EYEBALL_TURN_R: return L"EyeBall_Turn_R.X";
case EYEBALL_TURN_U: return L"EyeBall_Turn_U.X";
case EYEBALL_TRUN_D: return L"EyeBall_Turn_D.X";
default: return L"";
}
}
Model::Model()
: mInit(false)
, mEffect(0)
, mRootFrame(0)
, mFaceFrame(0)
, mEyesFrame(0)
, mEyelashFrame(0)
, mBoneMatrices(0)
, mNumBoneMatricesMax(0)
, mFMEManager(0)
{
for (size_t i = 0; i < (size_t)ACTION_NUM; ++i)
{
mAnimController[i] = 0;
}
}
Model::~Model()
{
}
bool Model::Init(IFaceMotionEmulator* manager)
{
assert(!mInit);
if (mInit)
return true;
if (!RecreateShader())
return false;
const std::wstring fileDir = L"Data\\Model\\";
// load animation model
for (size_t i = 0; i < (size_t)ACTION_NUM; ++i)
{
std::wstring filePath = fileDir + GetFacialFileName(ActionUnit(i));
if (!LoadXFile(filePath, &(mAnimController[i])))
continue;
}
// load neutral model
if (!LoadXFile(fileDir + Model::NEUTRAL_FACE_FILE_NAME, 0))
return false;
if (!InitNeutralFrameInfo(mRootFrame))
return false;
if (!InitMaterials())
return false;
mFMEManager = manager;
mInit = true;
return true;
}
bool Model::InitMaterials()
{
IDirect3DDevice9* device = DXUTGetD3D9Device();
assert(device);
mMaterials[0].mTechniqueName = "solid";
mMaterials[1].mTechniqueName = "eyeball";
mMaterials[2].mTechniqueName = "translucent";
// Texture objects are in managed pool, so it is safe if device lost happens
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Face_D.tga", &mMaterials[0].mDiffuseTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Face_N.tga", &mMaterials[0].mNormalTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Face_S.tga", &mMaterials[0].mSpecularTexture));
_VERY_RET(D3DXCreateCubeTextureFromFile(device, L"Data\\Model\\Environ.dds", &mMaterials[0].mEnvironTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyes_D.tga", &mMaterials[1].mDiffuseTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyes_N.tga", &mMaterials[1].mNormalTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyes_S.tga", &mMaterials[1].mSpecularTexture));
//_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyes_Mask.tga", &mMaterials[1].mMaskTexture));
_VERY_RET(D3DXCreateCubeTextureFromFile(device, L"Data\\Model\\Environ.dds", &mMaterials[1].mEnvironTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyelash_D.tga", &mMaterials[2].mDiffuseTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyelash_N.tga", &mMaterials[2].mNormalTexture));
_VERY_RET(D3DXCreateTextureFromFile(device, L"Data\\Model\\Eyelash_S.tga", &mMaterials[2].mSpecularTexture));
_VERY_RET(D3DXCreateCubeTextureFromFile(device, L"Data\\Model\\Environ.dds", &mMaterials[2].mEnvironTexture));
return true;
}
bool Model::InitNeutralFrameInfo(D3DXFRAME_EXT* frame)
{
if (!frame)
return false;
// we need to init SRTTransform for the first time
frame->mLocalTransform.fromMatrix(frame->TransformationMatrix);
// record frame pointer
const std::string name = frame->Name;
mFrameObjMap[name] = frame;
// record frame transformation
SRTTransform trans(frame->TransformationMatrix);
mNeutralFrameTransMap[name] = trans;
// all children
if (frame->pFrameFirstChild)
{
if (!InitNeutralFrameInfo((D3DXFRAME_EXT*)frame->pFrameFirstChild))
return false;
}
// all siblings
if (frame->pFrameSibling)
{
if (!InitNeutralFrameInfo((D3DXFRAME_EXT*)frame->pFrameSibling))
return false;
}
return true;
}
void Model::Destroy()
{
assert(mInit);
if (!mInit)
return;
SAFE_RELEASE(mEffect);
DestroyModel();
DestroyMaterials();
for (size_t i = 0; i < (size_t)ACTION_NUM; ++i)
{
SAFE_RELEASE(mAnimController[i]);
}
SAFE_DELETE_ARRAY(mBoneMatrices);
mInit = false;
}
void Model::DestroyMaterials()
{
for (size_t i = 0; i < MATERIAL_NUMBER; ++i)
{
mMaterials[i].Destroy();
}
}
void Model::PreUpdate(double time, float elapsedTime)
{
if (!mInit)
return;
if(!mFMEManager->QueryFaceBoneTransforms(this))
return;
if(mFMEManager->QueryFaceOrientation(mPoseAngles))
Root_Face_Root();
}
void Model::Update(double time, float elapsedTime)
{
if (!mInit)
return;
Sample* app = Sample::GetInstance();
if (!app)
return;
if (!mRootFrame)
return;
UpdateFrameMatrices(mRootFrame, &app->GetWorldMatrix());
}
void Model::PostUpdate(double time, float elapsedTime)
{
if (!mInit)
return;
// we can add logic that happens after update
}
bool Model::RecreateShader()
{
IDirect3DDevice9* device = DXUTGetD3D9Device();
assert(device);
DWORD shaderFlags = D3DXFX_NOT_CLONEABLE;
#if defined(DEBUG) || defined(_DEBUG)
shaderFlags |= D3DXSHADER_DEBUG;
#endif
ID3DXEffect* effect = 0;
LPD3DXBUFFER buff = 0;
if (FAILED(D3DXCreateEffectFromFile(device, L"Data\\Shader\\Face.fx", 0, 0, shaderFlags,
0, &effect, &buff)))
{
OutputDebugStringA("====================== BEGIN SHADER ERROR ======================\n");
OutputDebugStringA((const char*)buff->GetBufferPointer());
OutputDebugStringA("====================== END SHADER ERROR ======================\n");
assert(0 && "Failed to create effect");
SAFE_RELEASE(buff);
return false;
}
if (buff && buff->GetBufferPointer())
{
OutputDebugStringA("====================== BEGIN SHADER WARNING ======================\n");
OutputDebugStringA((const char*)buff->GetBufferPointer());
OutputDebugStringA("====================== END SHADER WARNING ======================\n");
SAFE_RELEASE(buff);
}
SAFE_RELEASE(mEffect);
mEffect = effect;
OutputDebugStringA("\nShader recreated\n");
return true;
}
void Model::Draw()
{
assert(mInit);
if (!mInit)
return;
Sample* app = Sample::GetInstance();
assert(app);
HRESULT hr;
D3DXMATRIX viewProjMatrix;
D3DXMatrixMultiply(&viewProjMatrix, &app->GetViewMatrix(), &app->GetProjMatrix());
V(mEffect->SetMatrix("ViewProjMatix", &viewProjMatrix));
V(mEffect->SetVector("EyePos", &app->GetCameraPos()));
// draw face
DrawFrame(mFaceFrame, mMaterials[0]);
// draw eyes
DrawFrame(mEyesFrame, mMaterials[1]);
// draw eyelash
DrawFrame(mEyelashFrame, mMaterials[2]);
}
bool Model::LoadXFile(const std::wstring& filePath, ID3DXAnimationController** animController)
{
// release first
DestroyModel();
// Load the mesh
AllocateHierarchyExt alloc(&mNumBoneMatricesMax, &mBoneMatrices);
IDirect3DDevice9* device = DXUTGetD3D9Device();
assert(device);
ID3DXAnimationController* controller = 0;
_VERY_RET(D3DXLoadMeshHierarchyFromX(filePath.c_str(), D3DXMESH_MANAGED, device,
&alloc, 0, (LPD3DXFRAME*)&mRootFrame, &controller));
_VERY_RET(SetupBoneMatrixPointers(mRootFrame));
_VERY_RET(D3DXFrameCalculateBoundingSphere(mRootFrame, &mModelSphere.mCenter, &mModelSphere.mRadius));
// search for the meshes we want to render
mFaceFrame = FindFrame(mRootFrame, "head");
mEyesFrame = FindFrame(mRootFrame, "eye");
mEyelashFrame = FindFrame(mRootFrame, "eyelash");
assert(mFaceFrame && mEyesFrame && mEyelashFrame);
if (!mFaceFrame || !mEyesFrame|| !mEyelashFrame)
return false;
if (animController)
*animController = controller;
return true;
}
void Model::DestroyModel()
{
if (!mRootFrame)
return;
AllocateHierarchyExt alloc(&mNumBoneMatricesMax, &mBoneMatrices);
D3DXFrameDestroy(mRootFrame, &alloc);
}
void Model::UpdateFrameMatrices(D3DXFRAME_EXT* frame, const D3DXMATRIXA16* parentMatrix)
{
if (parentMatrix)
{
D3DXMATRIXA16 localTrans;
frame->mLocalTransform.toMatrix(localTrans);
D3DXMatrixMultiply(&frame->mCombinedTransformationMatrix, &localTrans, parentMatrix);
}
else
frame->mLocalTransform.toMatrix(frame->mCombinedTransformationMatrix);
if (frame->pFrameSibling)
{
UpdateFrameMatrices((D3DXFRAME_EXT*)frame->pFrameSibling, parentMatrix);
}
if (frame->pFrameFirstChild)
{
UpdateFrameMatrices((D3DXFRAME_EXT*)frame->pFrameFirstChild, &frame->mCombinedTransformationMatrix);
}
}
void Model::HandleLostDevice()
{
if (mEffect)
mEffect->OnLostDevice();
}
void Model::HandleResetDevice()
{
if (mEffect)
mEffect->OnResetDevice();
}
void Model::SetFrameLocalTransform(const std::string& frameName, const SRTTransform& trans)
{
assert(mInit);
D3DXFRAME_EXT* frame = GetFrame(frameName);
if (!frame)
return;
frame->mLocalTransform = trans;
}
void Model::ApplyAnimation(ActionUnit face, double time)
{
assert(mInit);
if (!mInit)
return;
ID3DXKeyframedAnimationSet* anim = GetAnimation(face);
if (!anim)
return;
// for each frame, set the transform from animation
for (FrameObjectMap::const_iterator iter = mFrameObjMap.begin();
iter != mFrameObjMap.end(); ++iter)
{
const std::string& frameName = iter->first;
if (frameName == Model::ROOT_FRAME_NAME)
continue; // skip root frame
// get frame's transformation from animation
SRTTransform trans;
GetFrameAnimTransformByTime(trans, face, frameName, time);
// set local transformation to frame
//SetFrameLocalTransform(frameName, trans);
D3DXFRAME_EXT* frame = iter->second;
assert(frame);
frame->mLocalTransform = trans;
}
anim->Release();
}
void Model::DrawMeshContainer(D3DXMESHCONTAINER_EXT* meshContainer, const MaterialParam& mat)
{
if (!meshContainer->pSkinInfo)
return;
HRESULT hr;
LPD3DXBONECOMBINATION boneComb;
UINT matrixIndex;
UINT paletteEntry;
D3DXMATRIXA16 matTemp;
IDirect3DDevice9* device = DXUTGetD3D9Device();
assert(device);
boneComb = reinterpret_cast<LPD3DXBONECOMBINATION>(meshContainer->mBoneCombinationBuf->GetBufferPointer());
for (unsigned int i = 0; i < meshContainer->mNumAttributeGroups; i++)
{
// first calculate all the world matrices
for (paletteEntry = 0; paletteEntry < meshContainer->mNumPaletteEntries; ++paletteEntry)
{
matrixIndex = boneComb[i].BoneId[paletteEntry];
if (matrixIndex != UINT_MAX)
{
D3DXMatrixMultiply(&mBoneMatrices[paletteEntry], &meshContainer->mBoneOffsetMatrices[matrixIndex],
meshContainer->mBoneMatrixPtrs[matrixIndex]);
}
}
mEffect->SetTechnique(mat.mTechniqueName.c_str());
V(mEffect->SetMatrixArray("BoneMatrices", mBoneMatrices, meshContainer->mNumPaletteEntries));
if (mat.mDiffuseTexture)
V(mEffect->SetTexture("DiffuseTexture", mat.mDiffuseTexture));
if (mat.mNormalTexture)
V(mEffect->SetTexture("NormalTexture", mat.mNormalTexture));
if (mat.mSpecularTexture)
V(mEffect->SetTexture("SpecularTexture", mat.mSpecularTexture));
if (mat.mMaskTexture)
V(mEffect->SetTexture("MaskTexture", mat.mMaskTexture));
if (mat.mEnvironTexture)
V(mEffect->SetTexture("EnvironTexture", mat.mEnvironTexture));
// Set CurNumBones to select the correct vertex shader for the number of bones
V(mEffect->SetInt("BoneNumber", meshContainer->mNumInfl - 1));
// Start the effect now all parameters have been updated
unsigned int numPasses;
V(mEffect->Begin(&numPasses, D3DXFX_DONOTSAVESTATE));
for (unsigned int j = 0; j < numPasses; j++)
{
V(mEffect->BeginPass(j));
// draw the subset with the current world matrix palette and material state
V(meshContainer->MeshData.pMesh->DrawSubset(i));
V(mEffect->EndPass());
}
V(mEffect->End());
V(device->SetVertexShader(0));
}
}
void Model::DrawFrame(D3DXFRAME_EXT* frame, const MaterialParam& mat)
{
if (!frame)
return;
D3DXMESHCONTAINER_EXT* meshContainer;
meshContainer = (D3DXMESHCONTAINER_EXT*)frame->pMeshContainer;
while (meshContainer)
{
DrawMeshContainer(meshContainer, mat);
meshContainer = (D3DXMESHCONTAINER_EXT*)meshContainer->pNextMeshContainer;
}
}
HRESULT Model::SetupBoneMatrixPointers(D3DXFRAME_EXT* frame)
{
HRESULT hr;
if (frame->pMeshContainer)
{
hr = SetupBoneMatrixPointersOnMesh((D3DXMESHCONTAINER_EXT*)frame->pMeshContainer);
if (FAILED(hr))
return hr;
}
if (frame->pFrameSibling)
{
hr = SetupBoneMatrixPointers((D3DXFRAME_EXT*)frame->pFrameSibling);
if (FAILED(hr))
return hr;
}
if (frame->pFrameFirstChild)
{
hr = SetupBoneMatrixPointers((D3DXFRAME_EXT*)frame->pFrameFirstChild);
if (FAILED(hr))
return hr;
}
return S_OK;
}
HRESULT Model::SetupBoneMatrixPointersOnMesh(D3DXMESHCONTAINER_EXT* meshContainer)
{
if (meshContainer->pSkinInfo)
{
unsigned int boneNum = meshContainer->pSkinInfo->GetNumBones();
meshContainer->mBoneMatrixPtrs = new D3DXMATRIX*[boneNum];
if (!meshContainer->mBoneMatrixPtrs)
return E_OUTOFMEMORY;
for (unsigned int i = 0; i < boneNum; i++)
{
D3DXFRAME_EXT* frame = (D3DXFRAME_EXT*)D3DXFrameFind(mRootFrame, meshContainer->pSkinInfo->GetBoneName(i));
if (!frame)
return E_FAIL;
meshContainer->mBoneMatrixPtrs[i] = &frame->mCombinedTransformationMatrix;
}
}
return S_OK;
}
D3DXFRAME_EXT* Model::FindFrame(D3DXFRAME_EXT* startFrame, const std::string& frameName)
{
assert(startFrame);
if (!startFrame)
return 0;
D3DXFRAME_EXT* frame = 0;
if (frameName == startFrame->Name)
return startFrame;
// search all siblings
if (startFrame->pFrameSibling)
{
frame = FindFrame((D3DXFRAME_EXT*)startFrame->pFrameSibling, frameName);
if (frame)
return frame;
}
// search all children
if (startFrame->pFrameFirstChild)
{
frame = FindFrame((D3DXFRAME_EXT*)startFrame->pFrameFirstChild, frameName);
if (frame)
return frame;
}
return 0;
}
bool Model::GetFrameAnimTransformByTime(SRTTransform& transform, ActionUnit face, const std::string& frameName, double time) const
{
assert(mInit);
ID3DXKeyframedAnimationSet* anim = GetAnimation(face);
if (!anim)
return false;
unsigned int index;
HRESULT hr = anim->GetAnimationIndexByName(frameName.c_str(), &index);
if (FAILED(hr))
{
anim->Release();
return false;
}
time = anim->GetPeriodicPosition(time);
// get scale, rotation, translation for this bone from the animation
anim->GetSRT(time, index, &transform.mScale, &transform.mRotation, &transform.mTranslation);
anim->Release();
return true;
}
bool Model::GetFrameAnimTransformByPercentage(SRTTransform& transform, ActionUnit face, const std::string& frameName, float percentage) const
{
assert(mInit);
ID3DXKeyframedAnimationSet* anim = GetAnimation(face);
if (!anim)
return false;
unsigned int index;
HRESULT hr = anim->GetAnimationIndexByName(frameName.c_str(), &index);
if (FAILED(hr))
{
anim->Release();
return false;
}
double totalTime = anim->GetPeriod();
double time = totalTime * TClamp(double(percentage), 0.0, 1.0);
//time = anim->GetPeriodicPosition(time);
// get scale, rotation, translation for this bone from the animation
anim->GetSRT(time, index, &transform.mScale, &transform.mRotation, &transform.mTranslation);
anim->Release();
return true;
}
ID3DXKeyframedAnimationSet* Model::GetAnimation(ActionUnit face) const
{
assert(mInit);
assert(face < ActionUnit::ACTION_NUM);
//assert(mAnimController[face]);
if (face >= ACTION_NUM || !mAnimController[face])
return 0;
ID3DXKeyframedAnimationSet* animSet;
mAnimController[face]->GetAnimationSet(0, (ID3DXAnimationSet**)&animSet);
// NOTE: the receiver needs to release it!
return animSet;
}
double Model::GetAnimationLength(ActionUnit face) const
{
assert(mInit);
ID3DXKeyframedAnimationSet* anim = GetAnimation(face);
if (!anim)
return 0.0;
double period = anim->GetPeriod();
anim->Release();
return period;
}
bool Model::GetFrameNeutralTransform(SRTTransform& transform, const std::string& frameName) const
{
assert(mInit);
FrameTransformMap::const_iterator iter = mNeutralFrameTransMap.find(frameName);
if (iter == mNeutralFrameTransMap.end())
return false;
transform = iter->second;
return true;
}
void Model::MaterialParam::Destroy()
{
SAFE_RELEASE(mDiffuseTexture);
SAFE_RELEASE(mNormalTexture);
SAFE_RELEASE(mSpecularTexture);
SAFE_RELEASE(mMaskTexture);
SAFE_RELEASE(mEnvironTexture);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
void Model::Root_Face_Root()
{
D3DXQUATERNION extRot;
D3DXQuaternionRotationYawPitchRoll(&extRot, D3DXToRadian(mPoseAngles.yaw), D3DXToRadian(mPoseAngles.pitch), D3DXToRadian(mPoseAngles.roll));
D3DXFRAME_EXT* frame = GetFrame("Face_Root");
D3DXQuaternionMultiply(&frame->mLocalTransform.mRotation, &frame->mLocalTransform.mRotation, &extRot);
}
bool Model::GetCurrentActionBoneTransforms(FME::ActionUnit inActionName, float inWeight, FME::FaceBoneTransformMap& outCurrentActionBones)
{
if(!mAnimController[inActionName])
return false;
for (FrameObjectMap::const_iterator iter = mFrameObjMap.begin(); iter != mFrameObjMap.end(); ++iter)
{
const std::string frameName = iter->first;
if (frameName == Model::ROOT_FRAME_NAME)
continue; // skip root frame
SRTTransform trans;
if (!GetFrameAnimTransformByPercentage(trans, inActionName, frameName, inWeight))
continue;
outCurrentActionBones[iter->first] = trans.ToFaceBoneTransform();
}
return true;
}
bool Model::GetNeutralFaceBoneTransforms(FME::FaceBoneTransformMap& outNeutralFaceBones)
{
// for each frame
bool ret = false;
for (FrameObjectMap::const_iterator iter = mFrameObjMap.begin(); iter != mFrameObjMap.end(); ++iter)
{
const std::string frameName = iter->first;
if (frameName == Model::ROOT_FRAME_NAME)
continue; // skip root frame
SRTTransform trans;
if (!GetFrameNeutralTransform(trans, frameName)) continue;
outNeutralFaceBones[iter->first] = trans.ToFaceBoneTransform();
ret = true;
}
return ret;
}
bool Model::SetCombinedFaceBoneTransforms(FME::FaceBoneTransformMap& inCombinedFaceBones)
{
// for each frame
for (FrameObjectMap::const_iterator iter = mFrameObjMap.begin(); iter != mFrameObjMap.end(); ++iter)
{
const std::string frameName = iter->first;
D3DXFRAME_EXT* frame = iter->second;
assert(frame);
if (frameName == Model::ROOT_FRAME_NAME)
continue; // skip root frame
FaceBoneTransformMap::iterator it = inCombinedFaceBones.find(frameName);
if( it != inCombinedFaceBones.end() )
frame->mLocalTransform = SRTTransform(it->second);
}
return true;
} | 26.26616 | 556 | 0.69089 | GameTechDev |
cada2279889b6ae2ac463c2fcb7a475c316b8842 | 10,960 | cpp | C++ | platforms/posix/cpSerial_I.cpp | asc135/CodePort | 306d40d0a6d5ccb249b22249f2b3702ac09c021b | [
"BSD-3-Clause"
] | null | null | null | platforms/posix/cpSerial_I.cpp | asc135/CodePort | 306d40d0a6d5ccb249b22249f2b3702ac09c021b | [
"BSD-3-Clause"
] | null | null | null | platforms/posix/cpSerial_I.cpp | asc135/CodePort | 306d40d0a6d5ccb249b22249f2b3702ac09c021b | [
"BSD-3-Clause"
] | null | null | null | // ----------------------------------------------------------------------------
// CodePort++
//
// A Portable Operating System Abstraction Library
// Copyright 2011 Amardeep S. Chana. All rights reserved.
// Use of this software is bound by the terms of the Modified BSD License.
//
// Module Name: cpSerial_I.cpp
//
// Description: Serial Communications Facility.
//
// Platform: posix
//
// History:
// 2011-04-30 asc Creation.
// 2012-08-10 asc Moved identifiers to cp namespace.
// 2012-12-11 asc Added timeout parameter to SendData() and recvData().
// 2013-12-18 asc Updated to new output parameter type for Tokenize().
// ----------------------------------------------------------------------------
#include <sys/time.h>
#include <fcntl.h>
#include <cstdlib>
#include "cpUtil.h"
#include "cpSerial.h"
namespace cp
{
// constructor
Serial::Serial(String const &Name, String const &DevicePath, String const &Params) :
IoDev(Name)
{
m_Device.Device = DevicePath;
m_Device.Wait = true;
ParamSet(Params);
m_Valid = OpenPort();
// save the existing port mode for restoring at object destruction
ModeSave();
// set the line parameters
ParamSet(Params);
}
// destructor
Serial::~Serial()
{
ModeRest();
}
// ----------------------------------------------------------------------------
// Function Name: SendData
//
// Description: sends data to the serial port
//
// Inputs: pBuf - pointer to target buffer
// SndLen - number of bytes to send
// BytesWritten - number of bytes previously written
// Timeout - I/O timeout
//
// Outputs: none
//
// Returns: number of characters sent or < 0 if error
// ----------------------------------------------------------------------------
int Serial::SendData(char const *pBuf, size_t SndLen, size_t BytesWritten, uint32_t Timeout)
{
(void)Timeout;
return ::write(m_dWrite, pBuf + BytesWritten, SndLen - BytesWritten);
}
// ----------------------------------------------------------------------------
// Function Name: RecvData
//
// Description: receive data from the serial port
//
// Inputs: pBuf - pointer to target buffer
// RcvLen - number of bytes to read
// BytesRead - number of bytes previously read
// Timeout - I/O timeout
//
// Outputs: none
//
// Returns: number of characters read or < 0 if error
// ----------------------------------------------------------------------------
int Serial::RecvData(char *pBuf, size_t RcvLen, size_t BytesRead, uint32_t Timeout)
{
(void)Timeout;
return ::read(m_dRead, pBuf + BytesRead, RcvLen - BytesRead);
}
// flush device I/O buffers
void Serial::Flush()
{
// (.)(.) need to implement serial buffer Flush()
}
// cancel pended I/O operations
void Serial::Cancel()
{
m_Device.Wait = false;
sleep(3);
m_Device.Wait = true;
}
// set the port communications parameters
void Serial::ParamSet()
{
termios settings;
uint32_t DataRate;
uint32_t WordSize;
uint32_t StopBits;
// set non-blocking mode (redundant with O_NDELAY in the open() call but needed for portability
fcntl(m_Device.Desc, F_SETFL, FNDELAY);
// get the existing port settings
tcgetattr(m_Device.Desc, &settings);
// set the data rate
switch (m_Device.DataRate)
{
case 115200:
DataRate = B115200;
break;
case 57600:
DataRate = B57600;
break;
case 38400:
DataRate = B38400;
break;
case 19200:
DataRate = B19200;
break;
case 9600:
DataRate = B9600;
break;
case 4800:
DataRate = B4800;
break;
case 2400:
DataRate = B2400;
break;
case 1200:
DataRate = B1200;
break;
case 600:
DataRate = B600;
break;
case 300:
DataRate = B300;
break;
case 200:
DataRate = B200;
break;
case 150:
DataRate = B150;
break;
case 134:
DataRate = B134;
break;
case 110:
DataRate = B110;
break;
case 75:
DataRate = B75;
break;
case 50:
DataRate = B50;
break;
default:
DataRate = B9600;
}
cfsetispeed(&settings, DataRate);
cfsetospeed(&settings, DataRate);
// calculate the retry interval in microseconds
// it is the transfer time of ten characters
m_Device.Interval = static_cast<uint32_t>(1.0e+8 / m_Device.DataRate);
// enable the receiver and set local mode
settings.c_cflag |= (CLOCAL | CREAD);
// set the word size
switch (m_Device.WordSize)
{
case 5:
WordSize = CS5;
break;
case 6:
WordSize = CS6;
break;
case 7:
WordSize = CS7;
break;
case 8:
WordSize = CS8;
break;
default:
WordSize = CS8;
}
settings.c_cflag &= ~CSIZE;
settings.c_cflag |= WordSize;
// clear the parity flags
settings.c_cflag &= ~(PARENB | PARODD);
settings.c_iflag &= ~(ISTRIP | INPCK);
// set the parity
switch (m_Device.Parity)
{
case 0: // no parity
break;
case 1: // odd parity
settings.c_cflag |= (PARENB | PARODD);
settings.c_iflag |= (ISTRIP | INPCK);
break;
case 2: // even parity
settings.c_cflag |= PARENB;
settings.c_iflag |= (ISTRIP | INPCK);
break;
default: // no parity
break;
}
// set the stop bits
switch (m_Device.StopBits)
{
case 1: // 1 stop bit
StopBits = 0;
break;
case 2: // 2 stop bits
StopBits = CSTOPB;
break;
default: // 1 stop bit
StopBits = 0;
}
settings.c_cflag &= ~CSTOPB;
settings.c_cflag |= StopBits;
// set raw mode
settings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
settings.c_iflag &= ~(INLCR | ICRNL | IUCLC);
settings.c_oflag &= ~OPOST;
// clear the handshaking mode
settings.c_iflag &= ~(IXON | IXOFF | IXANY);
settings.c_cflag &= ~CRTSCTS;
// set the handshaking
switch (m_Device.FlowCtrl)
{
case 0: // no flow control
break;
case 1: // xon_xoff
settings.c_iflag |= (IXON | IXOFF | IXANY);
settings.c_cflag &= ~CRTSCTS;
break;
case 2: // rts_cts
settings.c_iflag &= ~(IXON | IXOFF | IXANY);
settings.c_cflag |= CRTSCTS;
break;
default: // no flow control
break;
}
// flush the buffers and apply new attributes
tcsetattr(m_Device.Desc, TCSAFLUSH, &settings);
}
// set the port communications parameters from a string
bool Serial::ParamSet(String const &Params)
{
bool rv = false;
StringVec_t configs;
StringVec_t::iterator i;
char c;
cp::Tokenize(Params, ",", configs);
// should be five items: data rate, parity, word length, stop bits, flow
if (configs.size() == 5)
{
i = configs.begin();
// set data rate
m_Device.DataRate = strtoul(i->c_str(), NULL, 10);
// set parity
++i;
if (i->size() > 0)
{
c = (*i)[0];
}
else
{
c = 0;
}
switch (c)
{
case 'n':
case 'N':
m_Device.Parity = 0;
break;
case 'o':
case 'O':
m_Device.Parity = 1;
break;
case 'e':
case 'E':
m_Device.Parity = 2;
break;
default:
m_Device.Parity = 0;
}
// set word length
++i;
m_Device.WordSize = strtoul(i->c_str(), NULL, 10);
// set stop bits
++i;
m_Device.StopBits = strtoul(i->c_str(), NULL, 10);
// set flow control
++i;
if (i->size() > 0)
{
c = (*i)[0];
}
else
{
c = 0;
}
switch (c)
{
case 'n': // no flow control
case 'N':
m_Device.FlowCtrl = 0;
break;
case 'x': // xon_xoff software flow control
case 'X':
m_Device.FlowCtrl = 1;
break;
case 'r': // rts_cts hardware flow control
case 'R':
m_Device.FlowCtrl = 2;
break;
default:
m_Device.FlowCtrl = 0;
}
rv = true;
}
// apply the parsed parameters to the port
if (rv)
{
ParamSet();
}
return rv;
}
// get the number of characters waiting to be read
bool Serial::GetCharsWaiting(uint32_t &Count)
{
bool rv = false;
Count = 0;
return rv;
}
// get the state of the CTS signal line
bool Serial::GetCtsState(bool &State)
{
bool rv = false;
State = false;
return rv;
}
// set the state of the DTR signal line
bool Serial::SetDtrState(bool State)
{
bool rv = false;
(void)State;
return rv;
}
// set the state of the RTS signal line
bool Serial::SetRtsState(bool State)
{
bool rv = false;
(void)State;
return rv;
}
// open the device for I/O
bool Serial::OpenPort()
{
m_dWrite = open(m_Device.Device.c_str(), O_WRONLY | O_NOCTTY | O_NDELAY);
if (m_dWrite == k_InvalidDescriptor)
{
return false;
}
m_dRead = open(m_Device.Device.c_str(), O_RDONLY | O_NOCTTY | O_NDELAY);
if (m_dRead == k_InvalidDescriptor)
{
close(m_dWrite);
m_dWrite = k_InvalidDescriptor;
return false;
}
return true;
}
// close the device
bool Serial::ClosePort()
{
bool rv = true;
if (m_dWrite != k_InvalidDescriptor)
{
rv = rv && (close(m_dWrite) != k_Error);
m_dWrite = k_InvalidDescriptor;
}
if (m_dRead != k_InvalidDescriptor)
{
rv = rv && (close(m_dRead) != k_Error);
m_dRead = k_InvalidDescriptor;
}
return rv;
}
// set I/O to character mode
void Serial::ModeChar()
{
termios mode;
// disable echo and turn off line mode
tcgetattr(m_Device.Desc, &mode);
mode.c_lflag &= ~(ECHO | ICANON);
tcsetattr(m_Device.Desc, TCSANOW, &mode);
}
// set I/O to line edit mode
void Serial::ModeLine()
{
termios mode;
// enable echo and turn on line mode
tcgetattr(m_Device.Desc, &mode);
mode.c_lflag |= (ECHO | ICANON);
tcsetattr(m_Device.Desc, TCSANOW, &mode);
}
// save current I/O mode
void Serial::ModeSave()
{
// store current term I/O settings
tcgetattr(m_Device.Desc, &m_Device.Original);
}
// set I/O to saved mode
void Serial::ModeRest()
{
// restore term I/O settings to saved values
tcsetattr(m_Device.Desc, TCSANOW, &m_Device.Original);
}
} // namespace cp
| 20.485981 | 99 | 0.534672 | asc135 |
cada34855b5e48b60a5a1eca02b6cc5a2856d40a | 13,716 | hpp | C++ | monitor/power_off_action.hpp | ibm-openbmc/phosphor-fan-presence | a899aa0cbdb7904d177fc5bb85aa605e4ff13747 | [
"Apache-2.0"
] | null | null | null | monitor/power_off_action.hpp | ibm-openbmc/phosphor-fan-presence | a899aa0cbdb7904d177fc5bb85aa605e4ff13747 | [
"Apache-2.0"
] | null | null | null | monitor/power_off_action.hpp | ibm-openbmc/phosphor-fan-presence | a899aa0cbdb7904d177fc5bb85aa605e4ff13747 | [
"Apache-2.0"
] | 1 | 2019-09-27T15:20:57.000Z | 2019-09-27T15:20:57.000Z | #pragma once
#include "logging.hpp"
#include "power_interface.hpp"
#include "sdbusplus.hpp"
#include <fmt/format.h>
#include <sdeventplus/clock.hpp>
#include <sdeventplus/event.hpp>
#include <sdeventplus/utility/timer.hpp>
#include <chrono>
namespace phosphor::fan::monitor
{
/**
* @class PowerOffAction
*
* This is the base class for a power off action, which is
* used by the PowerOffRule class to do different types of
* power offs based on fan failures.
*
* The power off is started with the start() method, and the
* derived class may or may not allow it to be stopped with
* the cancel() method, which is really only useful when
* there is a delay before the power off.
*
* It uses the PowerInterfaceBase object pointer to perform
* the D-Bus call to do the power off, so it can be mocked
* for testing.
*/
class PowerOffAction
{
public:
using PrePowerOffFunc = std::function<void()>;
PowerOffAction() = delete;
virtual ~PowerOffAction() = default;
PowerOffAction(const PowerOffAction&) = delete;
PowerOffAction& operator=(const PowerOffAction&) = delete;
PowerOffAction(PowerOffAction&&) = delete;
PowerOffAction& operator=(PowerOffAction&&) = delete;
/**
* @brief Constructor
*
* @param[in] name - The action name. Used for tracing.
* @param[in] powerInterface - The object used to invoke the power off.
* @param[in] powerOffFunc - A function to call right before the power
* off occurs (after any delays). May be
* empty if no function is necessary.
*/
PowerOffAction(const std::string& name,
std::shared_ptr<PowerInterfaceBase> powerInterface,
PrePowerOffFunc& powerOffFunc) :
_name(name),
_powerIface(std::move(powerInterface)),
_event(sdeventplus::Event::get_default()),
_prePowerOffFunc(powerOffFunc)
{}
/**
* @brief Starts the power off.
*
* Though this occurs in the child class, usually this
* involves starting a timer and then powering off when it
* times out.
*/
virtual void start() = 0;
/**
* @brief Attempts to cancel the power off, if the derived
* class allows it, and assuming the power off hasn't
* already happened.
*
* The 'force' parameter is mainly for use when something else
* powered off the system so this action doesn't need to run
* anymore even if it isn't usually cancelable.
*
* @param[in] force - If the cancel should be forced
*
* @return bool - If the cancel was allowed/successful
*/
virtual bool cancel(bool force) = 0;
/**
* @brief Returns the name of the action
*
* @return const std::string& - The name
*/
const std::string& name() const
{
return _name;
}
protected:
/**
* @brief Create a BMC Dump
*/
void createBmcDump() const
{
try
{
util::SDBusPlus::callMethod(
"xyz.openbmc_project.Dump.Manager",
"/xyz/openbmc_project/dump/bmc",
"xyz.openbmc_project.Dump.Create", "CreateDump",
std::vector<std::pair<std::string,
std::variant<std::string, uint64_t>>>());
}
catch (const sdbusplus::exception::exception&)
{}
}
/**
* @brief The name of the action, which is set by the
* derived class.
*/
const std::string _name;
/**
* @brief The object used to invoke the power off with.
*/
std::shared_ptr<PowerInterfaceBase> _powerIface;
/**
* @brief The event loop object. Needed by timers.
*/
sdeventplus::Event _event;
/**
* @brief A function that will be called right before
* the power off.
*/
PrePowerOffFunc _prePowerOffFunc;
};
/**
* @class HardPowerOff
*
* This class is derived from the PowerOffAction class
* and will execute a hard power off after some delay.
*/
class HardPowerOff : public PowerOffAction
{
public:
HardPowerOff() = delete;
~HardPowerOff() = default;
HardPowerOff(const HardPowerOff&) = delete;
HardPowerOff& operator=(const HardPowerOff&) = delete;
HardPowerOff(HardPowerOff&&) = delete;
HardPowerOff& operator=(HardPowerOff&&) = delete;
/**
* @brief Constructor
*
* @param[in] delay - The amount of time in seconds to wait before
* doing the power off
* @param[in] powerInterface - The object to use to do the power off
* @param[in] func - A function to call right before the power
* off occurs (after the delay). May be
* empty if no function is necessary.
*/
HardPowerOff(uint32_t delay,
std::shared_ptr<PowerInterfaceBase> powerInterface,
PrePowerOffFunc func) :
PowerOffAction("Hard Power Off: " + std::to_string(delay) + "s",
powerInterface, func),
_delay(delay),
_timer(_event, std::bind(std::mem_fn(&HardPowerOff::powerOff), this))
{}
/**
* @brief Starts a timer upon the expiration of which the
* hard power off will be done.
*/
void start() override
{
_timer.restartOnce(_delay);
}
/**
* @brief Cancels the timer. This is always allowed.
*
* @param[in] force - If the cancel should be forced or not
* (not checked in this case)
* @return bool - Always returns true
*/
bool cancel(bool) override
{
if (_timer.isEnabled())
{
_timer.setEnabled(false);
}
// Can always be canceled
return true;
}
/**
* @brief Performs the hard power off.
*/
void powerOff()
{
if (_prePowerOffFunc)
{
_prePowerOffFunc();
}
getLogger().log(
fmt::format("Action '{}' executing hard power off", name()));
_powerIface->hardPowerOff();
createBmcDump();
}
private:
/**
* @brief The number of seconds to wait between starting the
* action and doing the power off.
*/
std::chrono::seconds _delay;
/**
* @brief The Timer object used to handle the delay.
*/
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic> _timer;
};
/**
* @class SoftPowerOff
*
* This class is derived from the PowerOffAction class
* and will execute a soft power off after some delay.
*/
class SoftPowerOff : public PowerOffAction
{
public:
SoftPowerOff() = delete;
~SoftPowerOff() = default;
SoftPowerOff(const SoftPowerOff&) = delete;
SoftPowerOff& operator=(const SoftPowerOff&) = delete;
SoftPowerOff(SoftPowerOff&&) = delete;
SoftPowerOff& operator=(SoftPowerOff&&) = delete;
/**
* @brief Constructor
*
* @param[in] delay - The amount of time in seconds to wait before
* doing the power off
* @param[in] powerInterface - The object to use to do the power off
* @param[in] func - A function to call right before the power
* off occurs (after the delay). May be
* empty if no function is necessary.
*/
SoftPowerOff(uint32_t delay,
std::shared_ptr<PowerInterfaceBase> powerInterface,
PrePowerOffFunc func) :
PowerOffAction("Soft Power Off: " + std::to_string(delay) + "s",
powerInterface, func),
_delay(delay),
_timer(_event, std::bind(std::mem_fn(&SoftPowerOff::powerOff), this))
{}
/**
* @brief Starts a timer upon the expiration of which the
* soft power off will be done.
*/
void start() override
{
_timer.restartOnce(_delay);
}
/**
* @brief Cancels the timer. This is always allowed.
*
* @param[in] force - If the cancel should be forced or not
* (not checked in this case)
* @return bool - Always returns true
*/
bool cancel(bool) override
{
if (_timer.isEnabled())
{
_timer.setEnabled(false);
}
// Can always be canceled
return true;
}
/**
* @brief Performs the soft power off.
*/
void powerOff()
{
if (_prePowerOffFunc)
{
_prePowerOffFunc();
}
getLogger().log(
fmt::format("Action '{}' executing soft power off", name()));
_powerIface->softPowerOff();
createBmcDump();
}
private:
/**
* @brief The number of seconds to wait between starting the
* action and doing the power off.
*/
std::chrono::seconds _delay;
/**
* @brief The Timer object used to handle the delay.
*/
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic> _timer;
};
/**
* @class EpowPowerOff
*
* This class is derived from the PowerOffAction class and does the following:
* 1) On start, the service mode timer is started. This timer can be
* canceled if the cause is no longer satisfied (fans work again).
* 2) When this timer expires:
* a) The thermal alert D-Bus property is set, this can be used as
* an EPOW alert to the host that a power off is imminent.
* b) The meltdown timer is started. This timer cannot be canceled,
* and on expiration a hard power off occurs.
*/
class EpowPowerOff : public PowerOffAction
{
public:
EpowPowerOff() = delete;
~EpowPowerOff() = default;
EpowPowerOff(const EpowPowerOff&) = delete;
EpowPowerOff& operator=(const EpowPowerOff&) = delete;
EpowPowerOff(EpowPowerOff&&) = delete;
EpowPowerOff& operator=(EpowPowerOff&&) = delete;
/**
* @brief Constructor
*
* @param[in] serviceModeDelay - The service mode timeout.
* @param[in] meltdownDelay - The meltdown delay timeout.
* @param[in] powerInterface - The object to use to do the power off
* @param[in] func - A function to call right before the power
* off occurs (after the delay). May be
* empty if no function is necessary.
*/
EpowPowerOff(uint32_t serviceModeDelay, uint32_t meltdownDelay,
std::shared_ptr<PowerInterfaceBase> powerInterface,
PrePowerOffFunc func) :
PowerOffAction("EPOW Power Off: " + std::to_string(serviceModeDelay) +
"s/" + std::to_string(meltdownDelay) + "s",
powerInterface, func),
_serviceModeDelay(serviceModeDelay), _meltdownDelay(meltdownDelay),
_serviceModeTimer(
_event,
std::bind(std::mem_fn(&EpowPowerOff::serviceModeTimerExpired),
this)),
_meltdownTimer(
_event,
std::bind(std::mem_fn(&EpowPowerOff::meltdownTimerExpired), this))
{}
/**
* @brief Starts the service mode timer.
*/
void start() override
{
getLogger().log(
fmt::format("Action {}: Starting service mode timer", name()));
_serviceModeTimer.restartOnce(_serviceModeDelay);
}
/**
* @brief Called when the service mode timer expires.
*
* Sets the thermal alert D-Bus property and starts the
* meltdown timer.
*/
void serviceModeTimerExpired()
{
getLogger().log(fmt::format(
"Action {}: Service mode timer expired, starting meltdown timer",
name()));
_powerIface->thermalAlert(true);
_meltdownTimer.restartOnce(_meltdownDelay);
}
/**
* @brief Called when the meltdown timer expires.
*
* Executes a hard power off.
*/
void meltdownTimerExpired()
{
getLogger().log(fmt::format(
"Action {}: Meltdown timer expired, executing hard power off",
name()));
if (_prePowerOffFunc)
{
_prePowerOffFunc();
}
_powerIface->hardPowerOff();
createBmcDump();
}
/**
* @brief Attempts to cancel the action
*
* The service mode timer can be canceled. The meltdown
* timer cannot.
*
* @param[in] force - To force the cancel (like if the
* system powers off).
*
* @return bool - If the cancel was successful
*/
bool cancel(bool force) override
{
if (_serviceModeTimer.isEnabled())
{
_serviceModeTimer.setEnabled(false);
}
if (_meltdownTimer.isEnabled())
{
if (force)
{
_meltdownTimer.setEnabled(false);
}
else
{
getLogger().log("Cannot cancel running meltdown timer");
return false;
}
}
return true;
}
private:
/**
* @brief The number of seconds to wait until starting the uncancelable
* meltdown timer.
*/
std::chrono::seconds _serviceModeDelay;
/**
* @brief The number of seconds to wait after the service mode
* timer expires before a hard power off will occur.
*/
std::chrono::seconds _meltdownDelay;
/**
* @brief The service mode timer.
*/
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic>
_serviceModeTimer;
/**
* @brief The meltdown timer.
*/
sdeventplus::utility::Timer<sdeventplus::ClockId::Monotonic> _meltdownTimer;
};
} // namespace phosphor::fan::monitor
| 28.754717 | 80 | 0.587562 | ibm-openbmc |
cadc4e62da08b60e41eeb86ad6c94ee324c7f09f | 962 | cpp | C++ | Codeforces/#700#div2/B/B.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | 1 | 2022-01-26T14:50:07.000Z | 2022-01-26T14:50:07.000Z | Codeforces/#700#div2/B/B.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | Codeforces/#700#div2/B/B.cpp | Tudor67/Competitive-Programming | ae4dc6ed8bf76451775bf4f740c16394913f3ff1 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void solve(istream& cin, ostream& cout){
long long A, B, N;
cin >> A >> B >> N;
vector<long long> a(N);
for(int i = 0; i < N; ++i){
cin >> a[i];
}
vector<long long> b(N);
for(int i = 0; i < N; ++i){
cin >> b[i];
}
B += *max_element(a.begin(), a.end());
for(int i = 0; i < N; ++i){
long long k = (b[i] / A) + (b[i] % A > 0);
B -= k * a[i];
if(B <= 0){
break;
}
}
if(B >= 1){
cout << "YES" << "\n";
}else{
cout << "NO" << "\n";
}
}
int main(int argc, char** argv){
#ifndef ONLINE_JUDGE
ifstream cin(string(argv[1]) + ".in");
ofstream cout(string(argv[1]) + ".out");
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int tests;
cin >> tests;
while(tests > 0){
solve(cin, cout);
tests -= 1;
}
return 0;
} | 18.5 | 50 | 0.430353 | Tudor67 |
cae61631fc2e1d96734d249f161a08201968ef17 | 935 | hpp | C++ | SSSP/ESSENS/Core/Basic_SetOps/Level0/permute_elements.hpp | DynamicSSSP/sc18 | 3070cd5ad7107a3985a7a386ddf99b7f018c178a | [
"MIT"
] | 4 | 2018-12-19T08:40:39.000Z | 2021-02-22T17:31:41.000Z | SSSP/ESSENS/Core/Basic_SetOps/Level0/permute_elements.hpp | DynamicSSSP/HIPC18 | 3070cd5ad7107a3985a7a386ddf99b7f018c178a | [
"MIT"
] | null | null | null | SSSP/ESSENS/Core/Basic_SetOps/Level0/permute_elements.hpp | DynamicSSSP/HIPC18 | 3070cd5ad7107a3985a7a386ddf99b7f018c178a | [
"MIT"
] | null | null | null | #ifndef PERMUTE_ELEMENTS_HPP
#define PERMUTE_ELEMENTS_HPP
#include "structure_defs.hpp"
using namespace std;
/****** Permute a Vector of Integers *******/
int factorial(int i)
{
int fact=1;
while(1)
{ fact=fact*i;
i=i-1;
if(i==0) {break;}
}
return fact;
}
//Assume list is sorted
vector<int> permute_elements(int nodes, int max_val)
{
vector<int> perm_num;
vector<int> mynums;
mynums.clear();
for(int j=0;j<nodes; j++)
{mynums.push_back(j);}
srand (time(NULL));
int iters=rand()%max_val+10000;
int i=0;
perm_num=mynums;
while(i!=iters)
{
int a=rand()%mynums.size();
int b=rand()%mynums.size();
int temp=perm_num[a];
perm_num[a]=perm_num[b];
perm_num[b]=temp;
i++;
}
return perm_num;
}
/******* End of Functions **************/
#endif
| 15.847458 | 52 | 0.531551 | DynamicSSSP |
cae73d2d702da93c54498b519e260b40ca4e21c0 | 1,593 | cpp | C++ | Arduino/OtaFabMechanum/src/functionsApi/watchSensorTest.cpp | sibafb/osoyoo_mechanum_wheel_robot | 5ea1cde6b4164aef19adca5ce733b5dc257b9254 | [
"Apache-2.0"
] | null | null | null | Arduino/OtaFabMechanum/src/functionsApi/watchSensorTest.cpp | sibafb/osoyoo_mechanum_wheel_robot | 5ea1cde6b4164aef19adca5ce733b5dc257b9254 | [
"Apache-2.0"
] | null | null | null | Arduino/OtaFabMechanum/src/functionsApi/watchSensorTest.cpp | sibafb/osoyoo_mechanum_wheel_robot | 5ea1cde6b4164aef19adca5ce733b5dc257b9254 | [
"Apache-2.0"
] | null | null | null | /**
* @file watchSensorTest.cpp
* @brief
* 周囲検知のデバッグモジュール
* @date 2020/12/24 まずcでファイル分割をかく
*/
#include <Arduino.h>
#include "./../lib/debugPrint.h"
#include "./../lib/pinAssignment.h"
#include "./../hardWareDriver/ultraSonicSensor.h"
#include "./../hardWareDriver/servoDriver.h"
#include "functionsApi.h"
void watchSensorTest(){
//servoWrite(120);
//delay(100);
int scanval = ultraSonicSensorWatch();
delay(500);
//DebugLogPrintln("scanval:" + String(scanval) + "[cm]");
}
typedef struct {
int AREA;
int VALUE;
}SCAN_DATA;
static int servoPosition = 90;
void watchSurroundTest(){
/*0,20,40,60,80,100,120,140,160*/
const int AREA_DIVISION = 9;
/* init */
SCAN_DATA ScanArray[AREA_DIVISION];
ScanArray[0].AREA = 10;
for(int i=0; i < AREA_DIVISION;i++){
ScanArray[i].AREA = ScanArray[0].AREA + i*20;//by 20 degree.
}
/* scan */
if(getServoPosition() <= 90){
for(int i=0; i < AREA_DIVISION;i++){
servoSmoothWrite(ScanArray[i].AREA,5,1);
delay(20);
ScanArray[i].VALUE = ultraSonicSensorWatch();//by degree.
delay(20);
}
}else{
for(int i= AREA_DIVISION-1 ; i >=0 ;i--){
servoSmoothWrite(ScanArray[i].AREA,5,1);
delay(20);
ScanArray[i].VALUE = ultraSonicSensorWatch();//by degree.
delay(20);
}
}
/* output */
DebugLogPrint("ScanValArray:L[");
for(int i=0; i< AREA_DIVISION-1;i++ ){
DebugLogPrint("\t"+String(ScanArray[i].VALUE)+",");
}
DebugLogPrint("\t"+String(ScanArray[AREA_DIVISION-1].VALUE)+" ");
DebugLogPrintln("]R");
}
| 23.086957 | 67 | 0.617075 | sibafb |
cae9e917d3e512f0a74bdefecf361d57657832cc | 1,053 | cc | C++ | core/median_map_filter.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2017-07-27T15:08:19.000Z | 2017-07-27T15:08:19.000Z | core/median_map_filter.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | null | null | null | core/median_map_filter.cc | Arpan-2109/caroline | 23aba9ac9a35697c02358aeb88ed121d3d97a99c | [
"MIT"
] | 1 | 2020-10-01T08:46:10.000Z | 2020-10-01T08:46:10.000Z | // Copyright (c) 2014 The Caroline authors. All rights reserved.
// Use of this source file is governed by a MIT license that can be found in the
// LICENSE file.
/// @author Sirotkin Dmitry <dmitriy.v.sirotkin@gmail.com
#include <vector>
#include "core/median_map_filter.h"
#include "core/depth_map.h"
namespace core {
MedianMapFilter::MedianMapFilter() {}
DepthMap MedianMapFilter::filter(const DepthMap &map) {
cv::Mat mat(map.width(), map.height(), CV_32F);
for (int i = 0; i < map.width(); i++) {
for (int j = 0; j < map.height(); j++) {
mat.at<float>(i, j, 0) = map.Depth(i, j);
}
}
cv::Mat smooth = mat.clone();
for (int i = 1; i <= KernelSize_; i = i + 2)
cv::medianBlur(mat, smooth, i);
DepthMap newMap(map.width(), map.height());
for (int i = 0; i < map.width(); i++) {
for (int j = 0; j < map.height(); j++) {
newMap.SetDepth(i, j, smooth.at<float>(i, j));
}
}
return newMap;
}
void MedianMapFilter::SetKernel(int KernelSize) {
KernelSize_ = KernelSize;
}
} // namespace core
| 27 | 80 | 0.623932 | Arpan-2109 |
caebe5497d52e7ba9072c422fe2303d21edd0b75 | 2,045 | cpp | C++ | Weasel/src/Weasel/Platform/OpenGL/OpenGLVertexArray.cpp | MissNalgas/Minesweeper | 4e7671547f6805cd02ca9be06116c3f0e99788db | [
"Unlicense"
] | null | null | null | Weasel/src/Weasel/Platform/OpenGL/OpenGLVertexArray.cpp | MissNalgas/Minesweeper | 4e7671547f6805cd02ca9be06116c3f0e99788db | [
"Unlicense"
] | null | null | null | Weasel/src/Weasel/Platform/OpenGL/OpenGLVertexArray.cpp | MissNalgas/Minesweeper | 4e7671547f6805cd02ca9be06116c3f0e99788db | [
"Unlicense"
] | null | null | null | #include "wspch.h"
#include "OpenGLVertexArray.h"
#include <glad/glad.h>
namespace Weasel {
static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType type)
{
switch (type)
{
case Weasel::ShaderDataType::Float: return GL_FLOAT;
case Weasel::ShaderDataType::Float2: return GL_FLOAT;
case Weasel::ShaderDataType::Float3: return GL_FLOAT;
case Weasel::ShaderDataType::Float4: return GL_FLOAT;
case Weasel::ShaderDataType::Mat3: return GL_FLOAT;
case Weasel::ShaderDataType::Mat4: return GL_FLOAT;
case Weasel::ShaderDataType::Int: return GL_INT;
case Weasel::ShaderDataType::Int2: return GL_INT;
case Weasel::ShaderDataType::Int3: return GL_INT;
case Weasel::ShaderDataType::Int4: return GL_INT;
case Weasel::ShaderDataType::Bool: return GL_BOOL;
}
}
OpenGLVertexArray::OpenGLVertexArray()
{
WS_PROFILE_FUNCTION();
glCreateVertexArrays(1, &m_RendererID);
}
OpenGLVertexArray::~OpenGLVertexArray()
{
WS_PROFILE_FUNCTION();
glDeleteVertexArrays(1, &m_RendererID);
}
void OpenGLVertexArray::Bind() const
{
WS_PROFILE_FUNCTION();
glBindVertexArray(m_RendererID);
}
void OpenGLVertexArray::Unbind() const
{
WS_PROFILE_FUNCTION();
glBindVertexArray(0);
}
void OpenGLVertexArray::AddVertexBuffer(const Ref<VertexBuffer>& vertexbuffer)
{
glBindVertexArray(m_RendererID);
vertexbuffer->Bind();
WS_CORE_ASSERT(vertexbuffer->GetLayout().GetElements().size(), "Vertex buffer has no layout!");
uint32_t index = 0;
const auto& layout = vertexbuffer->GetLayout();
for (const auto& element : layout)
{
glEnableVertexAttribArray(index);
glVertexAttribPointer(index, element.GetComponentCount(), ShaderDataTypeToOpenGLBaseType(element.Type), element.Normalized ? GL_TRUE : GL_FALSE, layout.GetStride(), (const void*)element.Offset);
index++;
}
m_VertexBuffers.push_back(vertexbuffer);
}
void OpenGLVertexArray::SetIndexBuffer(const Ref<IndexBuffer>& indexbuffer)
{
glBindVertexArray(m_RendererID);
indexbuffer->Bind();
m_IndexBuffer = indexbuffer;
}
} | 25.886076 | 197 | 0.754034 | MissNalgas |
caee70d781803e3d17623c2efb3639df1aa57019 | 4,333 | cpp | C++ | Source/Pathfinder/PathfinderCharacter.cpp | bernhardrieder/A-Star-Pathfinder-UE4 | d4ec8c7bf6ed2345de2f3bdac84dd6e93d28f476 | [
"Unlicense"
] | null | null | null | Source/Pathfinder/PathfinderCharacter.cpp | bernhardrieder/A-Star-Pathfinder-UE4 | d4ec8c7bf6ed2345de2f3bdac84dd6e93d28f476 | [
"Unlicense"
] | null | null | null | Source/Pathfinder/PathfinderCharacter.cpp | bernhardrieder/A-Star-Pathfinder-UE4 | d4ec8c7bf6ed2345de2f3bdac84dd6e93d28f476 | [
"Unlicense"
] | null | null | null | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "Pathfinder.h"
#include "PathfinderCharacter.h"
#include "Runtime/CoreUObject/Public/UObject/ConstructorHelpers.h"
#include "Runtime/Engine/Classes/Components/DecalComponent.h"
#include "Kismet/HeadMountedDisplayFunctionLibrary.h"
#include "Hexagon.h"
#include "PathfinderPlayerController.h"
APathfinderCharacter::APathfinderCharacter()
{
// Set size for player capsule
GetCapsuleComponent()->InitCapsuleSize(42.f, 96.0f);
// Don't rotate character to camera direction
bUseControllerRotationPitch = false;
bUseControllerRotationYaw = false;
bUseControllerRotationRoll = false;
// Configure character movement
GetCharacterMovement()->bOrientRotationToMovement = true; // Rotate character to moving direction
GetCharacterMovement()->RotationRate = FRotator(0.f, 640.f, 0.f);
GetCharacterMovement()->bConstrainToPlane = true;
GetCharacterMovement()->bSnapToPlaneAtStart = true;
// Create a camera boom...
CameraBoom = CreateDefaultSubobject<USpringArmComponent>(TEXT("CameraBoom"));
CameraBoom->SetupAttachment(RootComponent);
CameraBoom->bAbsoluteRotation = true; // Don't want arm to rotate when character does
CameraBoom->TargetArmLength = MaxZoomIn;
CameraBoom->RelativeRotation = FRotator(-60.f, 0.f, 0.f);
CameraBoom->bDoCollisionTest = false; // Don't want to pull camera in when it collides with level
m_currentCameraZoom = CameraBoom->TargetArmLength;
// Create a camera...
TopDownCameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("TopDownCamera"));
TopDownCameraComponent->SetupAttachment(CameraBoom, USpringArmComponent::SocketName);
TopDownCameraComponent->bUsePawnControlRotation = false; // Camera does not rotate relative to arm
// Create a decal in the world to show the cursor's location
CursorToWorld = CreateDefaultSubobject<UDecalComponent>("CursorToWorld");
CursorToWorld->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UMaterial> DecalMaterialAsset(TEXT("Material'/Game/TopDownCPP/Blueprints/M_Cursor_Decal.M_Cursor_Decal'"));
if (DecalMaterialAsset.Succeeded())
{
CursorToWorld->SetDecalMaterial(DecalMaterialAsset.Object);
}
CursorToWorld->DecalSize = FVector(16.0f, 32.0f, 32.0f);
CursorToWorld->SetRelativeRotation(FRotator(90.0f, 0.0f, 0.0f).Quaternion());
// Activate ticking in order to update the cursor every frame.
PrimaryActorTick.bCanEverTick = true;
PrimaryActorTick.bStartWithTickEnabled = true;
}
void APathfinderCharacter::BeginPlay()
{
Super::BeginPlay();
CameraBoom->TargetArmLength = MaxZoomIn;
m_currentCameraZoom = CameraBoom->TargetArmLength;
}
void APathfinderCharacter::Tick(float DeltaSeconds)
{
Super::Tick(DeltaSeconds);
if (CursorToWorld != nullptr)
{
if (APlayerController* PC = Cast<APlayerController>(GetController()))
{
FHitResult TraceHitResult;
PC->GetHitResultUnderCursor(ECC_Visibility, true, TraceHitResult);
FVector CursorFV = TraceHitResult.ImpactNormal;
FRotator CursorR = CursorFV.Rotation();
CursorToWorld->SetWorldLocation(TraceHitResult.Location);
CursorToWorld->SetWorldRotation(CursorR);
m_possibleDestination = Cast<AHexagon>(TraceHitResult.Actor.Get());
}
}
}
void APathfinderCharacter::SetupPlayerInputComponent(UInputComponent* InputComponent)
{
Super::SetupPlayerInputComponent(InputComponent);
InputComponent->BindAction("ZoomIn", IE_Pressed, this, &APathfinderCharacter::CameraZoomIn);
InputComponent->BindAction("ZoomOut", IE_Pressed, this, &APathfinderCharacter::CameraZoomOut);
InputComponent->BindAction("SetDestination", IE_Pressed, this, &APathfinderCharacter::OnSetDestinationPressed);
}
void APathfinderCharacter::OnSetDestinationPressed()
{
auto controller = Cast<APathfinderPlayerController>(GetController());
controller->SetNewDestination(m_possibleDestination);
}
void APathfinderCharacter::CameraZoomIn()
{
m_currentCameraZoom = m_currentCameraZoom - ZoomDelta;
if (m_currentCameraZoom <= MaxZoomIn)
m_currentCameraZoom = MaxZoomIn;
CameraBoom->TargetArmLength = m_currentCameraZoom;
}
void APathfinderCharacter::CameraZoomOut()
{
m_currentCameraZoom = m_currentCameraZoom + ZoomDelta;
if (m_currentCameraZoom >= MaxZoomOut)
m_currentCameraZoom = MaxZoomOut;
CameraBoom->TargetArmLength = m_currentCameraZoom;
}
| 36.411765 | 149 | 0.794138 | bernhardrieder |
caeec9baab4e33c02cb959ca888225199bfdd92d | 1,171 | cpp | C++ | Blue-Flame-Engine/Core/BF/Platform/API/DirectX/DXShader.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | 2 | 2020-10-12T13:40:05.000Z | 2021-09-17T08:37:03.000Z | Blue-Flame-Engine/Core/BF/Platform/API/DirectX/DXShader.cpp | 21423236/Blue-Flame-Engine | cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b | [
"MIT"
] | null | null | null | Blue-Flame-Engine/Core/BF/Platform/API/DirectX/DXShader.cpp | 21423236/Blue-Flame-Engine | cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b | [
"MIT"
] | null | null | null | #include "DXShader.h"
#include "BF/IO/FileLoader.h"
#include "BF/Engine.h"
#include "DXError.h"
namespace BF
{
namespace Platform
{
namespace API
{
namespace DirectX
{
using namespace std;
using namespace BF::IO;
DXShader::DXShader() :
VS(nullptr), PS(nullptr), VSData(nullptr), PSData(nullptr), VSsize(0), PSsize(0)
{
}
DXShader::~DXShader()
{
}
void DXShader::Load(const string& vertexShaderFilePath, const string& pixelShaderFilePath)
{
VSData = FileLoader::LoadBinaryFile(vertexShaderFilePath, &VSsize);
PSData = FileLoader::LoadBinaryFile(pixelShaderFilePath, &PSsize);
DXCall(Engine::GetContext().GetDXContext().GetDevice()->CreateVertexShader(VSData, VSsize, 0, &VS));
DXCall(Engine::GetContext().GetDXContext().GetDevice()->CreatePixelShader(PSData, PSsize, 0, &PS));
}
void DXShader::Bind() const
{
Engine::GetContext().GetDXContext().GetContext()->VSSetShader(VS, 0, 0);
Engine::GetContext().GetDXContext().GetContext()->PSSetShader(PS, 0, 0);
}
void DXShader::CleanUp() const
{
VS->Release();
PS->Release();
}
}
}
}
} | 23.897959 | 105 | 0.64731 | FantasyVII |
caf28994b14a4698800d3b90916897859e7b4d4c | 454 | cpp | C++ | opencl/source/gen11/gpgpu_walker_gen11.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 778 | 2017-09-29T20:02:43.000Z | 2022-03-31T15:35:28.000Z | opencl/source/gen11/gpgpu_walker_gen11.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 478 | 2018-01-26T16:06:45.000Z | 2022-03-30T10:19:10.000Z | opencl/source/gen11/gpgpu_walker_gen11.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 215 | 2018-01-30T08:39:32.000Z | 2022-03-29T11:08:51.000Z | /*
* Copyright (C) 2019-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/gen11/hw_info.h"
#include "opencl/source/command_queue/gpgpu_walker_bdw_and_later.inl"
#include "opencl/source/command_queue/hardware_interface_bdw_and_later.inl"
namespace NEO {
template class HardwareInterface<ICLFamily>;
template class GpgpuWalkerHelper<ICLFamily>;
template struct EnqueueOperation<ICLFamily>;
} // namespace NEO
| 20.636364 | 75 | 0.790749 | troels |
caf35afbf6559b10cddaf79f442732a0019207b5 | 908 | cpp | C++ | src/bloom.cpp | salonmor/blog | 1c51d1c6143d3688c30dda907df55dd6ba955a55 | [
"0BSD"
] | 94 | 2019-02-17T09:25:28.000Z | 2022-03-31T03:25:14.000Z | src/bloom.cpp | salonmor/blog | 1c51d1c6143d3688c30dda907df55dd6ba955a55 | [
"0BSD"
] | 5 | 2020-09-05T09:38:59.000Z | 2021-11-29T15:38:57.000Z | src/bloom.cpp | salonmor/blog | 1c51d1c6143d3688c30dda907df55dd6ba955a55 | [
"0BSD"
] | 29 | 2019-02-17T09:25:36.000Z | 2022-03-17T08:53:38.000Z | #include <iostream>
#include <ios>
#include <string>
#include "bloom.hpp"
using namespace std;
int main()
{
auto set1 = {"Martin", "Vorbrodt", "C++", "Blog"};
auto set2 = {"Not", "In", "The", "Set"};
bloom_filter<string, 5> bloom(128);
for(auto s : set1) bloom.add(s);
std::boolalpha(cout);
cout << "bloom_filter<string, 5> bloom(128);" << endl;
for(auto s : set1) cout << "\tContains \"" << s << "\"\t: " << bloom.contains(s) << endl;
for(auto s : set2) cout << "\tContains \"" << s << "\"\t: " << bloom.contains(s) << endl;
cout << endl;
fixed_bloom_filter<string, 128, 1> fixed_bloom;
for(auto s : set1) fixed_bloom.add(s);
cout << "fixed_bloom_filter<string, 128, 1> fixed_bloom;" << endl;
for(auto s : set1) cout << "\tContains \"" << s << "\"\t: " << fixed_bloom.contains(s) << endl;
for(auto s : set2) cout << "\tContains \"" << s << "\"\t: " << fixed_bloom.contains(s) << endl;
}
| 31.310345 | 96 | 0.589207 | salonmor |
caf35bd099d4c8f7ad313018d743fb2b76dada35 | 601,426 | cpp | C++ | qikkDB_test/DispatcherTests.cpp | veselyja/qikkdb-community | 680f62632ba85e468beee672624b80a61ed40f55 | [
"Apache-2.0"
] | 15 | 2020-06-30T13:43:42.000Z | 2022-02-02T12:52:33.000Z | qikkDB_test/DispatcherTests.cpp | veselyja/qikkdb-community | 680f62632ba85e468beee672624b80a61ed40f55 | [
"Apache-2.0"
] | 1 | 2020-11-28T22:29:35.000Z | 2020-12-22T10:28:25.000Z | qikkDB_test/DispatcherTests.cpp | qikkDB/qikkdb | 4ee657c7d2bfccd460d2f0d2c84a0bbe72d9a80a | [
"Apache-2.0"
] | 1 | 2020-06-30T12:41:37.000Z | 2020-06-30T12:41:37.000Z | #include <cmath>
#include <functional>
#include <iostream>
#include <fstream>
#include <gtest/gtest.h>
#include "../qikkDB/DatabaseGenerator.h"
#include "../qikkDB/ColumnBase.h"
#include "../qikkDB/BlockBase.h"
#include "../qikkDB/PointFactory.h"
#include "../qikkDB/ComplexPolygonFactory.h"
#include "../qikkDB/Database.h"
#include "../qikkDB/Table.h"
#include "../qikkDB/QueryEngine/Context.h"
#include "../qikkDB/GpuSqlParser/GpuSqlCustomParser.h"
#include "../qikkDB/messages/QueryResponseMessage.pb.h"
#include "../qikkDB/QueryEngine/OrderByType.h"
#include "../qikkDB/GpuSqlParser/LoadColHelper.h"
#include "DispatcherObjs.h"
/////////////////////
// ">" operator
/////////////////////
// INT ">"
// Test values from integer column to be greater than the constant value
TEST(DispatcherTests, IntGtColumnConst)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = -1000;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " > " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] > filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value to be greater than the values from integer column
TEST(DispatcherTests, IntGtConstColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = -1000;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " > " + columnName + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (filterValue > data[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test values from integer column to be greater than the values from another integer column
TEST(DispatcherTests, IntGtColumnColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName1 = "colInteger1";
std::string columnName2 = "colInteger2";
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName2 + " FROM " + tableName + " WHERE " +
columnName2 + " > " + columnName1 + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger2 = tables.at(tableName).GetColumns().at(columnName2);
auto& colInteger = tables.at(tableName).GetColumns().at(columnName1);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->GetData();
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data2[i] > data[i])
{
expectedResult.push_back(data2[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName2);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a bigger constant value to be greater than a smaller constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntGtConstConstTrue)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 10;
int32_t filterValue2 = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " > " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a smaller constant value to be greater than a bigger contant value which will result in FALSE statement in WHERE clause
TEST(DispatcherTests, IntGtConstConstFalse)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 5;
int32_t filterValue2 = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " > " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// There is FALSE statement in WHERE clause, so there should not be any results
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG ">"
TEST(DispatcherTests, LongGtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 > 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 > 500000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 > 500000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongGtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 > colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (500000000 > static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (500000000 > (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongGtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong2 FROM TableA WHERE colLong2 > colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) >
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 >
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongGtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 10 > 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongGtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 > 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT ">"
TEST(DispatcherTests, FloatGtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 > 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) > 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatGtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.5 > colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<float>(j % 1024 + 0.1111) < 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if (static_cast<float>((j % 1024 + 0.1111) * -1) < 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * -1));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatGtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat2 FROM TableA WHERE colFloat2 > colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 2048 + 0.1111)) > (static_cast<float>(j % 1024 + 0.1111)))
{
expectedResult.push_back(static_cast<float>(j % 2048 + 0.1111));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat2");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatGtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 10 > 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatGtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 > 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE ">"
TEST(DispatcherTests, DoubleGtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 > 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) > 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) > 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleGtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.5 > colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) < 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) < 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleGtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble2 FROM TableA WHERE colDouble2 > colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 2048 + 0.1111111) > (j % 1024 + 0.1111111))
{
expectedResult.push_back(j % 2048 + 0.1111111);
}
}
else
{
if (((j % 2048 + 0.1111111) * (-1)) > ((j % 1024 + 0.1111111) * (-1)))
{
expectedResult.push_back((j % 2048 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble2");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleGtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 10 > 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleGtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 > 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// "<" operator
/////////////////////
// INT "<"
// Test values from integer column to be lower than the constant value
TEST(DispatcherTests, IntLtColumnConst)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 1000;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " < " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] < filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value to be lower than the values from integer column
TEST(DispatcherTests, IntLtConstColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 1000;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " < " + columnName + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (filterValue < data[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test values from integer column to be lower than the values from another integer column
TEST(DispatcherTests, IntLtColumnColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName1 = "colInteger1";
std::string columnName2 = "colInteger2";
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName1 + " FROM " + tableName + " WHERE " +
columnName1 + " < " + columnName2 + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger2 = tables.at(tableName).GetColumns().at(columnName2);
auto& colInteger1 = tables.at(tableName).GetColumns().at(columnName1);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->GetData();
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger1.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] < data2[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName1);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a smaller constant value to be lower than a bigger constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntLtConstConstTrue)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 5;
int32_t filterValue2 = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " < " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a bigger constant value to be lower than a smaller contant value which will result in FALSE statement in WHERE clause
TEST(DispatcherTests, IntLtConstConstFalse)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 10;
int32_t filterValue2 = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " < " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// There is FALSE statement in WHERE clause, so there should not be any results
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG "<"
TEST(DispatcherTests, LongLtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 < 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 < 500000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 < 500000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongLtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 < colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (500000000 < static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (500000000 < (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongLtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 < colLong2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) >
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 >
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongLtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 < 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongLtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 10 < 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT "<"
TEST(DispatcherTests, FloatLtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 < 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<float>(j % 1024 + 0.1111) < 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if (static_cast<float>((j % 1024 + 0.1111) * -1) < 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * -1));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatLtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.5 < colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<float>(j % 1024 + 0.1111) > 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if (static_cast<float>((j % 1024 + 0.1111) * -1) > 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * -1));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatLtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 < colFloat2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) < (static_cast<float>(j % 2048 + 0.1111)))
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 1024 + 0.1111) * (-1))) <
(static_cast<float>((j % 2048 + 0.1111) * (-1))))
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatLtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 < 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatLtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 10 < 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE "<"
TEST(DispatcherTests, DoubleLtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 < 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) < 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) < 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleLtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.5 < colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) > 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) > 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleLtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 < colDouble2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) < (j % 2048 + 0.1111111))
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) < ((j % 2048 + 0.1111111) * (-1)))
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleLtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 < 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleLtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 10 < 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// ">=" operator
/////////////////////
// INT ">="
// Test values from integer column to be greater or equal with the constant value
TEST(DispatcherTests, IntEqGtColumnConst)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " >= " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] >= filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value to be greater or equal with the values from integer column
TEST(DispatcherTests, IntEqGtConstColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " >= " + columnName + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (filterValue >= data[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test values from integer column to be greater or equal with the values from another integer column
TEST(DispatcherTests, IntEqGtColumnColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName1 = "colInteger1";
std::string columnName2 = "colInteger2";
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName2 + " FROM " + tableName + " WHERE " +
columnName2 + " >= " + columnName1 + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger2 = tables.at(tableName).GetColumns().at(columnName2);
auto& colInteger = tables.at(tableName).GetColumns().at(columnName1);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->GetData();
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data2[i] >= data[i])
{
expectedResult.push_back(data2[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName2);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a bigger constant value to be greater or equal with a smaller constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntEqGtConstConstTrue)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 10;
int32_t filterValue2 = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " >= " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a constant value to be greater or equal with the same constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntEqGtConstConstTrue2)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " >= " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test the smaller constant value to be greater or equal with a bigger constant value which will result in FALSE statement in WHERE clause
TEST(DispatcherTests, IntEqGtConstConstFalse)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 5;
int32_t filterValue2 = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " >= " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// There is FALSE statement in WHERE clause, so there should not be any results
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG ">="
TEST(DispatcherTests, LongEqGtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 >= 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 >= 500000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 >= 500000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqGtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 >= colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (500000000 >= static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (500000000 >= (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqGtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong2 FROM TableA WHERE colLong2 >= colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) >=
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 >=
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqGtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 10 >= 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqGtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 >= 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT ">="
TEST(DispatcherTests, FloatEqGtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 >= 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) >= 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 1024 + 0.1111) * (-1))) >= 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqGtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.5 >= colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) <= 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 1024 + 0.1111) * (-1))) <= 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqGtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat2 FROM TableA WHERE colFloat2 >= colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 2048 + 0.1111)) >= (static_cast<float>(j % 1024 + 0.1111)))
{
expectedResult.push_back(static_cast<float>(j % 2048 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 2048 + 0.1111) * (-1))) >=
(static_cast<float>((j % 1024 + 0.1111) * (-1))))
{
expectedResult.push_back(static_cast<float>((j % 2048 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat2");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqGtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 10 >= 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqGtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 >= 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE ">="
TEST(DispatcherTests, DoubleEqGtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 >= 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) >= 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqGtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.5 >= colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) <= 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) <= 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqGtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble2 FROM TableA WHERE colDouble2 >= colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 2048 + 0.1111111) >= (j % 1024 + 0.1111111))
{
expectedResult.push_back(j % 2048 + 0.1111111);
}
}
else
{
if (((j % 2048 + 0.1111111) * (-1)) >= ((j % 1024 + 0.1111111) * (-1)))
{
expectedResult.push_back((j % 2048 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble2");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqGtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 10 >= 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqGtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 >= 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// "<=" operator
/////////////////////
// INT "<="
// Test values from integer column to be lower or equal with the constant value
TEST(DispatcherTests, IntEqLtColumnConst)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " <= " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] <= filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value to be lower or equal with the values from integer column
TEST(DispatcherTests, IntEqLtConstColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 500;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " <= " + columnName + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (filterValue <= data[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test values from integer column to be lower or equal with the values from another integer column
TEST(DispatcherTests, IntEqLtColumnColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName1 = "colInteger1";
std::string columnName2 = "colInteger2";
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName1 + " FROM " + tableName + " WHERE " +
columnName1 + " <= " + columnName2 + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger2 = tables.at(tableName).GetColumns().at(columnName2);
auto& colInteger = tables.at(tableName).GetColumns().at(columnName1);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->GetData();
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] <= data2[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName1);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a smaller constant value to be lower or equal with a bigger constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntEqLtConstConstTrue)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 5;
int32_t filterValue2 = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " <= " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a constant value to be lower or equal with a the same constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntEqLtConstConstTrue2)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " <= " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test the bigger constant value to be greater or equal with a smaller constant value which will result in FALSE statement in WHERE clause
TEST(DispatcherTests, IntEqLtConstConstFalse)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 10;
int32_t filterValue2 = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " <= " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// There is FALSE statement in WHERE clause, so there should not be any results
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG "<="
TEST(DispatcherTests, LongEqLtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 <= 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 <= 500000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 <= 500000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqLtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 <= colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (500000000 <= static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (500000000 <= (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqLtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 <= colLong2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) >=
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 >=
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqLtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 <= 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqLtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 10 <= 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT "<="
TEST(DispatcherTests, FloatEqLtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 <= 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) <= 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 1024 + 0.1111) * (-1))) <= 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqLtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.5 <= colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) >= 5.5)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 1024 + 0.1111) * (-1))) >= 5.5)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqLtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 <= colFloat2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<float>(j % 1024 + 0.1111)) <= (static_cast<float>(j % 2048 + 0.1111)))
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if ((static_cast<float>((j % 1024 + 0.1111) * (-1))) <=
(static_cast<float>((j % 2048 + 0.1111) * (-1))))
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqLtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 <= 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqLtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 10 <= 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE "<="
TEST(DispatcherTests, DoubleEqLtColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 <= 5.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) <= 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) <= 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqLtConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.5 <= colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) >= 5.5)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) >= 5.5)
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqLtColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 <= colDouble2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) <= (j % 2048 + 0.1111111))
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) <= ((j % 2048 + 0.1111111) * (-1)))
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqLtConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 <= 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqLtConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 10 <= 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// "=" operator
/////////////////////
// INT "="
// Test values from integer column to be equal with the constant value
TEST(DispatcherTests, IntEqColumnConst)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " = " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] == filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value to be equal with the values from integer column
TEST(DispatcherTests, IntEqConstColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " = " + columnName + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (filterValue == data[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
/// <summary>
/// Test values from integer column to be equal with the values from another integer column
/// </summary>
TEST(DispatcherTests, IntEqColumnColumn)
{
Context::getInstance();
const std::string tableName = "TableA";
const std::string columnName1 = "colInteger1";
const std::string columnName2 = "colInteger2";
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName2 + " FROM " + tableName + " WHERE " +
columnName2 + " = " + columnName1 + ";");
const auto resultPtr = parser.Parse(); // Execute query
const auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
const auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
const auto& colInteger2 = tables.at(tableName).GetColumns().at(columnName2);
const auto& colInteger1 = tables.at(tableName).GetColumns().at(columnName1);
const auto blocks1 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
const auto blocks2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
// Check, if columns have the same number of blocks:
ASSERT_EQ(blocks1.size(), blocks2.size());
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocks1.size(); j++)
{
const auto data1 = dynamic_cast<ColumnBase<int32_t>*>(colInteger1.get())->GetBlocksList().at(j)->GetData();
const auto data2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->GetData();
const auto dataLength1 =
dynamic_cast<ColumnBase<int32_t>*>(colInteger1.get())->GetBlocksList().at(j)->BlockCapacity();
const auto dataLength2 =
dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->BlockCapacity();
// Check, if columns have the same block capacity:
ASSERT_EQ(dataLength1, dataLength2);
for (int32_t i = 0; i < dataLength1; i++)
{
if (data2[i] == data1[i])
{
expectedResult.push_back(data2[i]);
}
}
}
const auto& payloads = result->payloads().at(tableName + "." + columnName2);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a constant value to be equal with the same constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntEqConstConstTrue)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " = " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value to be equal with another constant value which will result in FALSE statement in WHERE clause
TEST(DispatcherTests, IntEqConstConstFalse)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 5;
int32_t filterValue2 = 10;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " = " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// There is FALSE statement in WHERE clause, so there should not be any results
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG "="
TEST(DispatcherTests, LongEqColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 = 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongEqConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 = colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongEqColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong2 FROM TableA WHERE colLong2 = colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) ==
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1) ==
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 = 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongEqConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 = 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT "="
TEST(DispatcherTests, FloatEqColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 = 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if (std::abs((static_cast<float>(j % 1024 + 0.1111)) - 5.1111) < 0.00005)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.1111 = colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if (std::abs((static_cast<float>(j % 1024 + 0.1111)) - 5.1111) < 0.00005)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat2 FROM TableA WHERE colFloat2 = colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (std::abs((static_cast<float>(j % 2048 + 0.1111)) - (static_cast<float>(j % 1024 + 0.1111))) < 0.00005)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 2048 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 2048 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat2");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 = 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatEqConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 = 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE "="
/*
TEST(DispatcherTests, DoubleEqColumnConst) //FIXME test is good, but kernel uses '==' which is not good enough for doubles, but this is probably imposible to fix
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colDouble1";
int32_t filterValue = 5.11111110000;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " = " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colDouble = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<double>*>(colDouble.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<double> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<double>*>(colDouble.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<double>*>(colDouble.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] == filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
*/
/*
TEST(DispatcherTests, DoubleEqConstColumn) //FIXME test is good, but kernel uses '==' which is not good enough for doubles, but this is probably imposible to fix
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colDouble1 FROM TableA WHERE 5.1111111 = colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if (std::abs((j % 1024 + 0.1111111) - 5.1111111) < 0.00000005)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) : expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto &payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
*/
TEST(DispatcherTests, DoubleEqColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble2 FROM TableA WHERE colDouble2 = colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (std::abs((j % 2048 + 0.1111111) - (j % 1024 + 0.1111111)) < 0.00000005)
{
(j % 2) ? expectedResult.push_back(j % 2048 + 0.1111111) :
expectedResult.push_back((j % 2048 + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble2");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 = 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleEqConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 = 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// "!=" operator
/////////////////////
// INT "!="
// Test values from integer column not to be equal with the constant value
TEST(DispatcherTests, IntNotEqColumnConst)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
columnName + " != " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data[i] != filterValue)
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value not to be equal with the values from integer column
TEST(DispatcherTests, IntNotEqConstColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " != " + columnName + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (filterValue != data[i])
{
expectedResult.push_back(data[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test values from integer column not to be equal with the values from another integer column
TEST(DispatcherTests, IntNotEqColumnColumn)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName1 = "colInteger1";
std::string columnName2 = "colInteger2";
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName2 + " FROM " + tableName + " WHERE " +
columnName2 + " != " + columnName1 + ";");
auto resultPtr = parser.Parse(); // Execute query
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger2 = tables.at(tableName).GetColumns().at(columnName2);
auto& colInteger = tables.at(tableName).GetColumns().at(columnName1);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data2 = dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->GetData();
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger2.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
if (data2[i] != data[i])
{
expectedResult.push_back(data2[i]);
}
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName2);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int32_t i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test a bigger constant value not to be equal with a smaller constant value which will result in TRUE statement in WHERE clause
TEST(DispatcherTests, IntNotEqConstConstTrue)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue1 = 10;
int32_t filterValue2 = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue1) + " != " + std::to_string(filterValue2) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// Table has columns, column have blocks of data
auto& tables = DispatcherObjs::GetInstance().database.get()->GetTables();
auto& colInteger = tables.at(tableName).GetColumns().at(columnName);
auto blocksNum = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList();
// Filter data from database on CPU manually, so we have expected results
std::vector<int32_t> expectedResult;
for (int32_t j = 0; j < blocksNum.size(); j++)
{
auto data = dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->GetData();
auto dataLength =
dynamic_cast<ColumnBase<int32_t>*>(colInteger.get())->GetBlocksList().at(j)->BlockCapacity();
for (int32_t i = 0; i < dataLength; i++)
{
// There is a TRUE statement in WHERE cluase, so all the elements in the column should be returned
expectedResult.push_back(data[i]);
}
}
auto& payloads = result->payloads().at(tableName + "." + columnName);
// Check, if the query result have the expected number of returned values (results)
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
// Check the correctness of the returned values element by element
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// Test constant value not to be equal with the same constant value which will result in FALSE statement in WHERE clause
TEST(DispatcherTests, IntNotEqConstConstFalse)
{
Context::getInstance();
std::string tableName = "TableA";
std::string columnName = "colInteger1";
int32_t filterValue = 5;
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT " + columnName + " FROM " + tableName + " WHERE " +
std::to_string(filterValue) + " != " + std::to_string(filterValue) + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
// There is FALSE statement in WHERE clause, so there should not be any results
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG "!="
TEST(DispatcherTests, LongNotEqColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 != 50000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 50000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 50000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongNotEqConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE -500000000 != colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != -500000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != -500000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongNotEqColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong2 FROM TableA WHERE colLong2 != colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) !=
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 !=
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongNotEqConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 != 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongNotEqConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 != 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT "!="
TEST(DispatcherTests, FloatNotEqColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 != 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if (std::abs((static_cast<float>(j % 1024 + 0.1111)) - 5.1111) > 0.00005)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatNotEqConstColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.1111 != colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if (std::abs((static_cast<float>(j % 1024 + 0.1111)) - 5.1111) > 0.00005)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatNotEqColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat2 FROM TableA WHERE colFloat2 != colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (std::abs((static_cast<float>(j % 2048 + 0.1111)) - (static_cast<float>(j % 1024 + 0.1111))) > 0.00005)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 2048 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 2048 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat2");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatNotEqConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 != 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatNotEqConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5 != 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE "!="
/*
TEST(DispatcherTests, DoubleNotEqColumnConst) //FIXME test is good, but kernel uses '!=' which is not good enough for doubles, but this is probably imposible to fix
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colDouble1 FROM TableA WHERE colDouble1 != 5.1111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (std::abs((j % 1024 + 0.1111111) - 5.1111111) > std::numeric_limits<double>::epsilon())
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (std::abs(((j % 1024 + 0.1111111) * (-1)) - 5.1111111) > std::numeric_limits<double>::epsilon())
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto &payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
*/
/*
TEST(DispatcherTests, DoubleNotEqConstColumn) //FIXME test is good, but kernel uses '!=' which is not good enough for doubles, but this is probably imposible to fix
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT colDouble1 FROM TableA WHERE 5.1111111 != colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (std::abs((j % 1024 + 0.1111111) - 5.1111111) > std::numeric_limits<double>::epsilon())
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
if (std::abs(((j % 1024 + 0.1111111) * (-1)) - 5.1111111) > std::numeric_limits<double>::epsilon())
{
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
}
auto &payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
*/
TEST(DispatcherTests, DoubleNotEqColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble2 FROM TableA WHERE colDouble2 != colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (std::abs((j % 2048 + 0.1111111) - (j % 1024 + 0.1111111)) > std::numeric_limits<double>::epsilon())
{
(j % 2) ? expectedResult.push_back(j % 2048 + 0.1111111) :
expectedResult.push_back((j % 2048 + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble2");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleNotEqConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 != 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleNotEqConstConstFalse)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5 != 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// AND
/////////////////////
// INT AND
TEST(DispatcherTests, IntAndColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 AND 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if ((j % 1024) != 0)
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntAndColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntAndConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 5 AND colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
if ((j % 1024) != 0)
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntAndConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 0 AND colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntAndColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 AND colInteger2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 2048 != 0) && (j % 1024 != 0))
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntAndConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 10 AND 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024) : expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntAndConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 5 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntAndConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 0 AND 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntAndConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 0 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG AND
TEST(DispatcherTests, LongAndColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 AND 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 0)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 0)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongAndColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongAndConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 AND colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 0)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 0)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongAndConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 0 AND colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongAndColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 AND colLong2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048 != 0) &&
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 0))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 != 0) &&
((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 0))
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongAndConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 10 AND 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongAndConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongAndConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 0 AND 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongAndConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 0 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT AND
TEST(DispatcherTests, FloatAndColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 AND 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((static_cast<float>(j % 1024 + 0.1111)) > std::numeric_limits<float>::epsilon())
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatAndColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, FloatAndConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.1111 AND colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((static_cast<float>(j % 1024 + 0.1111)) > std::numeric_limits<float>::epsilon())
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatAndConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 0 AND colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, FloatAndColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat2 AND colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((static_cast<float>(j % 2048 + 0.1111) > std::numeric_limits<float>::epsilon()) &&
(static_cast<float>(j % 1024 + 0.1111) > std::numeric_limits<float>::epsilon()))
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatAndConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 10.1111 AND 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatAndConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.1111 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, FloatAndConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 0 AND 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, FloatAndConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 0 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE AND
TEST(DispatcherTests, DoubleAndColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 AND 5.1111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (((j % 1024 + 0.1111111)) > std::numeric_limits<double>::epsilon())
{
(j % 2) ? expectedResult.push_back((j % 1024 + 0.1111111)) :
expectedResult.push_back(((j % 1024 + 0.1111111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleAndColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, DoubleAndConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.1111111 AND colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (((j % 1024 + 0.1111111)) > std::numeric_limits<double>::epsilon())
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleAndConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 0 AND colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, DoubleAndColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble2 AND colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 2048 + 0.1111111 > std::numeric_limits<double>::epsilon()) &&
(j % 1024 + 0.1111111 > std::numeric_limits<double>::epsilon()))
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleAndConstConstTrue)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 10.1111111 AND 5.1111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleAndConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.11111111 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, DoubleAndConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 0 AND 5.11111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, DoubleAndConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 0 AND 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// OR
/////////////////////
// INT OR
TEST(DispatcherTests, IntOrColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 OR 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024) : expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 1024) != 0)
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 5 OR colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024) : expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 0 OR colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 1024) != 0)
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 OR colInteger2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 2048 != 0) || (j % 1024 != 0))
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrConstConstNonZeroValues)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 10 OR 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024) : expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 10 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024) : expectedResult.push_back((j % 1024) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 0 OR 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024) : expectedResult.push_back((j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntOrConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE 0 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// LONG OR
TEST(DispatcherTests, LongOrColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 OR 500000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 0)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 0)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 500000000 OR colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 0 OR colLong1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 0)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 0)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 OR colLong2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048 != 0) ||
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 != 0))
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 2048) * -1 != 0) ||
((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 != 0))
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrConstConstNonZeroValues)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 10 OR 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 5 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 0 OR 5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongOrConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE 0 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// FLOAT OR
TEST(DispatcherTests, FloatOrColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 OR 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((static_cast<float>(j % 1024 + 0.1111)) > std::numeric_limits<float>::epsilon())
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.1111 OR colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 0 OR colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((static_cast<float>(j % 1024 + 0.1111)) > std::numeric_limits<float>::epsilon())
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat2 OR colFloat1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((static_cast<float>(j % 2048 + 0.1111) > std::numeric_limits<float>::epsilon()) ||
(static_cast<float>(j % 1024 + 0.1111) > std::numeric_limits<float>::epsilon()))
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrConstConstNonZeroValues)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 10.1111 OR 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 5.1111 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 0 OR 5.1111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111)) :
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatOrConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE 0 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
// DOUBLE OR
TEST(DispatcherTests, DoubleOrColumnConstNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 OR 5.1111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024 + 0.1111111)) :
expectedResult.push_back(((j % 1024 + 0.1111111) * (-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrColumnConstZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (((j % 1024 + 0.1111111)) > std::numeric_limits<double>::epsilon())
{
(j % 2) ? expectedResult.push_back((j % 1024 + 0.1111111)) :
expectedResult.push_back(((j % 1024 + 0.1111111) * (-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrConstColumnNonZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.1111111 OR colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrConstColumnZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 0 OR colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (((j % 1024 + 0.1111111)) > std::numeric_limits<double>::epsilon())
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrColumnColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble2 OR colDouble1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 2048 + 0.1111111 > std::numeric_limits<double>::epsilon()) ||
(j % 1024 + 0.1111111 > std::numeric_limits<double>::epsilon()))
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrConstConstNonZeroValues)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 10.1111111 OR 5.1111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrConstConstFalseRightZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 5.11111111 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrConstConstFalseLeftZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 0 OR 5.11111111;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111111) :
expectedResult.push_back((j % 1024 + 0.1111111) * ((-1)));
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleOrConstConstFalseBothZero)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE 0 OR 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
/////////////////////
// NEGATION
/////////////////////
// INT NEGATION
TEST(DispatcherTests, IntNegation)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE !(colInteger1 > 5);");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (j % 1024 <= 5)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if ((j % 1024) * -1 <= 5)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
// LONG NEGATION
TEST(DispatcherTests, LongNegation)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE !(colLong1 > 500000000);");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024 <= 500000000)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 <= 500000000)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
// FLOAT NEGATION
TEST(DispatcherTests, FloatNegation)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE !(colFloat1 > 6.5555);");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<float>(j % 1024 + 0.1111) <= 6.5555)
{
expectedResult.push_back(static_cast<float>(j % 1024 + 0.1111));
}
}
else
{
if (static_cast<float>((j % 1024 + 0.1111) * -1) <= 6.5555)
{
expectedResult.push_back(static_cast<float>((j % 1024 + 0.1111) * -1));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
// DOUBLE NEGATION
TEST(DispatcherTests, DoubleNegation)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE !(colDouble1 > 9.66666666);");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111111) <= 9.66666666)
{
expectedResult.push_back((j % 1024 + 0.1111111));
}
}
else
{
if (((j % 1024 + 0.1111111) * (-1)) <= 9.66666666)
{
expectedResult.push_back(((j % 1024 + 0.1111111) * (-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
///////////
TEST(DispatcherTests, IntAddColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 + 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
expectedResult.push_back(j % 1024 + 5);
}
else
{
expectedResult.push_back(((j % 1024) * -1) + 5);
}
}
}
auto& payloads = result->payloads().at("colInteger1+5");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntAddColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 + 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (j % 1024 + 5 > 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if ((j % 1024 + 5) * -1 > 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntAddColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 + 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((j % 1024) + 5) < 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if ((((j % 1024) * -1) + 5) < 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LongAddColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 + 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) + 5) :
expectedResult.push_back((((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)) * -1) + 5);
}
}
auto& payloads = result->payloads().at("colLong1+5");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongAddColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 + 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) + 5) > 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)) * -1 + 5) > 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongAddColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 + 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) + 5) < 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024)) * -1 + 5) < 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, FloatAddColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 + 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024) + 5.1111) :
expectedResult.push_back(((j % 1024) + 0.1111) * (-1) + 5);
}
}
auto& payloads = result->payloads().at("colFloat1+5");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatAddColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 + 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((j % 1024) + 5.1111) > 500)
{
expectedResult.push_back((j % 1024) + 0.1111);
}
}
else
{
if (((((j % 1024) + 0.1111) * (-1)) + 5) > 500)
{
expectedResult.push_back(((j % 1024) + 0.1111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatAddColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 + 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((j % 1024) + 5.1111) < 500)
{
expectedResult.push_back((j % 1024) + 0.1111);
}
}
else
{
if ((((j % 1024) + 0.1111) * (-1) + 5) < 500)
{
expectedResult.push_back(((j % 1024) + 0.1111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, DoubleAddColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 + 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024) + 5.1111111) :
expectedResult.push_back(((j % 1024) + 0.1111111) * (-1) + 5);
}
}
auto& payloads = result->payloads().at("colDouble1+5");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleAddColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 + 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (j % 1024 + 5.1111111 > 500)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleAddColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 + 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
double temp = j % 1024 + 0.1111111;
if (temp + 5 < 500)
{
expectedResult.push_back(j % 1024 + 0.1111111);
}
}
else
{
double temp = ((j % 1024) + 0.1111111) * -1;
if (temp + 5 < 500)
{
expectedResult.push_back((j % 1024 + 0.1111111) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, IntSubColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 - 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024) - 5) :
expectedResult.push_back(((j % 1024) * -1) - 5);
}
}
auto& payloads = result->payloads().at("colInteger1-5");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntSubColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 - 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (j % 1024 - 5 > 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if (((j % 1024) * -1) - 5 > 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntSubColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 - 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (j % 1024 - 5 < 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if (((j % 1024) * -1) - 5 < 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LongSubColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 - 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) - 5) :
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 - 5);
}
}
auto& payloads = result->payloads().at("colLong1-5");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongSubColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 - 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) - 5) > 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 - 5) > 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongSubColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 - 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) - 5) < 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1 - 5) < 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, FloatSubColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 - 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(j % 1024 + 0.1111 - 5) :
expectedResult.push_back(((j % 1024 + 0.1111) * -1) - 5);
}
}
auto& payloads = result->payloads().at("colFloat1-5");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_TRUE(std::abs(expectedResult[i] - payloads.floatpayload().floatdata()[i]) < 0.0005);
}
}
TEST(DispatcherTests, FloatSubColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 - 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111 - 5) > 500)
{
expectedResult.push_back((j % 1024) + 0.1111);
}
}
else
{
if ((((j % 1024 + 0.1111) * -1) - 5) > 500)
{
expectedResult.push_back((j % 1024 + 0.1111) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatSubColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 - 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (j % 1024 + 0.1111 - 5 < 500)
{
expectedResult.push_back((j % 1024) + 0.1111);
}
}
else
{
if (((j % 1024 + 0.1111) * -1) - 5 < 500)
{
expectedResult.push_back(((j % 1024) + 0.1111) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, DoubleSubColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 - 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024) + 0.1111111 - 5) :
expectedResult.push_back((((j % 1024) + 0.1111111) * (-1)) - 5);
}
}
auto& payloads = result->payloads().at("colDouble1-5");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleSubColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 - 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((((j % 1024) + 0.1111111) - 5) > 500)
{
expectedResult.push_back((j % 1024) + 0.1111111);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleSubColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 - 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((j % 1024) + 0.1111111 - 5) < 500)
{
expectedResult.push_back((j % 1024) + 0.1111111);
}
}
else
{
if ((((j % 1024) + 0.1111111) * (-1) - 5) < 500)
{
expectedResult.push_back(((j % 1024) + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
// multiply tests:
TEST(DispatcherTests, IntMulColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 * 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024) * 5) :
expectedResult.push_back(((j % 1024) * 5) * ((-1)));
}
}
auto& payloads = result->payloads().at("colInteger1*5");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntMulColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 * 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((j % 1024) * 5) > 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if (((j % 1024) * -1) * 5 > 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntMulColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 * 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((j % 1024) * 5) < 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if (((j % 1024) * -1) * 5 < 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LongMulColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 * 2 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * 2) :
expectedResult.push_back(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) * 2);
}
}
auto& payloads = result->payloads().at("colLong1*2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongMulColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 * 2 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * 2) > 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongMulColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 * 2 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * 2) < 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if ((((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) * 2) < 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, FloatMulColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 * 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(((j % 1024) + 0.1111) * 5) :
expectedResult.push_back((((j % 1024) + 0.1111) * 5) * ((-1)));
}
}
auto& payloads = result->payloads().at("colFloat1*5");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_TRUE(std::abs(expectedResult[i] - payloads.floatpayload().floatdata()[i]) < 0.0005);
}
}
TEST(DispatcherTests, FloatMulColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 * 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111) * 5 > 500)
{
expectedResult.push_back(j % 1024 + 0.1111);
}
}
else
{
if (((j % 1024 + 0.1111) * -1) * 5 > 500)
{
expectedResult.push_back((j % 1024 + 0.1111) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatMulColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 * 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((j % 1024 + 0.1111) * 5 < 500)
{
expectedResult.push_back(j % 1024 + 0.1111);
}
}
else
{
if (((j % 1024 + 0.1111) * -1) * 5 < 500)
{
expectedResult.push_back((j % 1024 + 0.1111) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, DoubleMulColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 * 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(((j % 1024) + 0.1111111) * 5) :
expectedResult.push_back((((j % 1024) + 0.1111111) * 5) * ((-1)));
}
}
auto& payloads = result->payloads().at("colDouble1*5");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleMulColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 * 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((((j % 1024) + 0.1111111) * 5) > 500)
{
expectedResult.push_back((j % 1024) + 0.1111111);
}
}
else
{
if (((((j % 1024) + 0.1111111) * (-1)) * 5) > 500)
{
expectedResult.push_back(((j % 1024) + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleMulColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 * 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((((j % 1024) + 0.1111111) * 5) < 500)
{
expectedResult.push_back((j % 1024) + 0.1111111);
}
}
else
{
if (((((j % 1024) + 0.1111111) * (-1)) * 5) < 500)
{
expectedResult.push_back(((j % 1024) + 0.1111111) * ((-1)));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
// divide tests:
TEST(DispatcherTests, IntDivColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 / 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<int32_t>((j % 1024) / 5)) :
expectedResult.push_back(static_cast<int32_t>(((j % 1024) / 5) * (-1)));
}
}
auto& payloads = result->payloads().at("colInteger1/5");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntDivColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 / 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntDivColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 / 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int32_t>((j % 1024) / 5) < 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if (static_cast<int32_t>((j % 1024) * -1) / 5 < 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LongDivColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 / 2 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<int64_t>(
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) / 2)) :
expectedResult.push_back(static_cast<int64_t>(
((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) / 2));
}
}
auto& payloads = result->payloads().at("colLong1/2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongDivColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 / 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) / 5)) > 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (static_cast<int64_t>(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) / 5) > 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongDivColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 / 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) / 5)) < 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (static_cast<int64_t>(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) / 5) < 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, FloatDivColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 / 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
expectedResult.push_back((j % 1024 + 0.1111) / 5);
}
else
{
expectedResult.push_back(((j % 1024 + 0.1111) * -1) / 5);
}
}
}
auto& payloads = result->payloads().at("colFloat1/5");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloatDivColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 / 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, FloatDivColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colFloat1 / 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((((j % 1024) + 0.1111) / 5) < 500)
{
(j % 2) ? expectedResult.push_back((j % 1024) + 0.1111) :
expectedResult.push_back(((j % 1024) + 0.1111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, DoubleDivColumnConst) // FIXME Dispatch je chybny, treba ho opravit, test je dobry
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 / 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(((j % 1024) + 0.1111111) / 5) :
expectedResult.push_back((((j % 1024) + 0.1111111) * -1) / 5);
}
}
auto& payloads = result->payloads().at("colDouble1/5");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, DoubleDivColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 / 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, DoubleDivColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colDouble1 FROM TableA WHERE colDouble1 / 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<double> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((((j % 1024) + 0.1111111) / 5) < 500)
{
(j % 2) ? expectedResult.push_back((j % 1024) + 0.1111111) :
expectedResult.push_back(((j % 1024) + 0.1111111) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colDouble1");
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResult.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_DOUBLE_EQ(expectedResult[i], payloads.doublepayload().doubledata()[i]);
}
}
TEST(DispatcherTests, IntDivColumnConstFloat) // FIXME chyba je v CUDA kerneli, ma vracat float
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 / 5.0 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back((j % 1024) / 5.0) :
expectedResult.push_back(((j % 1024) * -1) / 5.0);
}
}
auto& payloads = result->payloads().at("colInteger1/5.0");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, IntDivColumnConstGtConstFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 / 5.0 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntDivColumnConstLtConstFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 / 5.0 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if ((j % 1024) / 5.0 < 500)
{
(j % 2) ? expectedResult.push_back(j % 1024) :
expectedResult.push_back((j % 1024) * ((-1)));
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LongDivColumnConstFloat) // FIXME test je dobry, kernel treba spravi tak aby to pretypoval na double
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 / 2.0 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ?
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) / 2.0) :
expectedResult.push_back(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) / 2.0);
}
}
auto& payloads = result->payloads().at("colLong1/2.0");
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResult.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResult[i], payloads.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, LongDivColumnConstGtConstFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 / 5.0 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if ((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) / 5.0 > 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) / 5.0 > 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongDivColumnConstLtConstFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 / 5.0 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) / 5.0) < 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) / 5.0 < 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
// modulo tests:
// divide tests:
TEST(DispatcherTests, IntModColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 % 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<int32_t>((j % 1024) % 5)) :
expectedResult.push_back(static_cast<int32_t>(((j % 1024) % 5) * (-1)));
}
}
auto& payloads = result->payloads().at("colInteger1%5");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, IntModColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 % 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IntModColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 % 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int32_t>((j % 1024) % 5) < 500)
{
expectedResult.push_back(j % 1024);
}
}
else
{
if (static_cast<int32_t>(((j % 1024) * -1) % 5) < 500)
{
expectedResult.push_back((j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResult.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LongModColumnConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 % 2 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
(j % 2) ? expectedResult.push_back(static_cast<int64_t>(
(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) % 2)) :
expectedResult.push_back(static_cast<int64_t>(
(static_cast<int64_t>((2 * pow(10, j % 19)) + j % 1024) % 2) * (-1)));
}
}
auto& payloads = result->payloads().at("colLong1%2");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, LongModColumnConstGtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 % 5 > 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LongModColumnConstLtConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colLong1 FROM TableA WHERE colLong1 % 5 < 500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int64_t> expectedResult;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (static_cast<int64_t>(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) % 5)) < 500)
{
expectedResult.push_back(static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024);
}
}
else
{
if (static_cast<int64_t>(((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1) % 5) < 500)
{
expectedResult.push_back((static_cast<int64_t>(2 * pow(10, j % 19)) + j % 1024) * -1);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colLong1");
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResult.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResult[i], payloads.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, ShowDatabases)
{
Context::getInstance();
GpuSqlCustomParser parser(nullptr, "SHOW DATABASES;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedDatabaseNames;
for (auto& database : Database::GetDatabaseNames())
{
expectedDatabaseNames.push_back(database);
}
auto& payloadsDatabases = result->payloads().at("Databases");
ASSERT_EQ(expectedDatabaseNames.size(), payloadsDatabases.stringpayload().stringdata_size());
for (int i = 0; i < expectedDatabaseNames.size(); i++)
{
ASSERT_EQ(expectedDatabaseNames[i], payloadsDatabases.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, ShowTables)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SHOW TABLES;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedTableNames;
for (auto& table : DispatcherObjs::GetInstance().database->GetTables())
{
expectedTableNames.push_back(table.first);
}
auto& payloadsTables = result->payloads().at(DispatcherObjs::GetInstance().database->GetName());
ASSERT_EQ(expectedTableNames.size(), payloadsTables.stringpayload().stringdata_size());
for (int i = 0; i < expectedTableNames.size(); i++)
{
ASSERT_EQ(expectedTableNames[i], payloadsTables.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, ShowColumns)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SHOW COLUMNS FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedColumnNames;
std::vector<std::string> expectedColumnTypes;
for (auto& column : DispatcherObjs::GetInstance().database->GetTables().at("TableA").GetColumns())
{
expectedColumnNames.push_back(column.first);
expectedColumnTypes.push_back(::GetStringFromColumnDataType(column.second->GetColumnType()));
}
auto& payloadsColumnNames = result->payloads().at("TableA_columns");
auto& payloadsColumnTypes = result->payloads().at("TableA_types");
ASSERT_EQ(expectedColumnNames.size(), payloadsColumnNames.stringpayload().stringdata_size());
ASSERT_EQ(expectedColumnTypes.size(), payloadsColumnTypes.stringpayload().stringdata_size());
for (int i = 0; i < expectedColumnNames.size(); i++)
{
ASSERT_EQ(expectedColumnNames[i], payloadsColumnNames.stringpayload().stringdata()[i]);
}
for (int i = 0; i < expectedColumnTypes.size(); i++)
{
ASSERT_EQ(expectedColumnTypes[i], payloadsColumnTypes.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, DateTimeNow)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT YEAR(NOW()), MONTH(NOW()), DAY(NOW()), HOUR(NOW()), "
"MINUTE(NOW()) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsYear;
std::vector<int32_t> expectedResultsMonth;
std::vector<int32_t> expectedResultsDay;
std::vector<int32_t> expectedResultsHour;
std::vector<int32_t> expectedResultsMinute;
std::vector<int32_t> expectedResultsSecond;
std::time_t epochTime = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::tm* localTime = gmtime(&epochTime);
expectedResultsYear.push_back(localTime->tm_year + 1900);
expectedResultsMonth.push_back(localTime->tm_mon + 1);
expectedResultsDay.push_back(localTime->tm_mday);
expectedResultsHour.push_back(localTime->tm_hour);
expectedResultsMinute.push_back(localTime->tm_min);
auto& payloadsYear = result->payloads().at("YEAR(NOW())");
auto& payloadsMonth = result->payloads().at("MONTH(NOW())");
auto& payloadsDay = result->payloads().at("DAY(NOW())");
auto& payloadsHour = result->payloads().at("HOUR(NOW())");
auto& payloadsMinute = result->payloads().at("MINUTE(NOW())");
for (int i = 0; i < expectedResultsYear.size(); i++)
{
ASSERT_EQ(expectedResultsYear[i], payloadsYear.intpayload().intdata()[i]);
}
for (int i = 0; i < expectedResultsYear.size(); i++)
{
ASSERT_EQ(expectedResultsMonth[i], payloadsMonth.intpayload().intdata()[i]);
}
for (int i = 0; i < expectedResultsYear.size(); i++)
{
ASSERT_EQ(expectedResultsDay[i], payloadsDay.intpayload().intdata()[i]);
}
for (int i = 0; i < expectedResultsYear.size(); i++)
{
ASSERT_EQ(expectedResultsHour[i], payloadsHour.intpayload().intdata()[i]);
}
for (int i = 0; i < expectedResultsYear.size(); i++)
{
ASSERT_EQ(expectedResultsMinute[i], payloadsMinute.intpayload().intdata()[i]);
}
}
// DateTime tests
TEST(DispatcherTests, DateTimeCol)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT YEAR(colLong3), MONTH(colLong3), DAY(colLong3), "
"HOUR(colLong3), MINUTE(colLong3), SECOND(colLong3) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsYear;
std::vector<int32_t> expectedResultsMonth;
std::vector<int32_t> expectedResultsDay;
std::vector<int32_t> expectedResultsHour;
std::vector<int32_t> expectedResultsMinute;
std::vector<int32_t> expectedResultsSecond;
for (int i = 0; i < 2; i++)
{
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsYear.push_back(static_cast<int32_t>(k % 1000) + 2000);
expectedResultsMonth.push_back(static_cast<int32_t>((k % 12) + 1));
expectedResultsDay.push_back(static_cast<int32_t>(((k % 28) + 1)));
expectedResultsHour.push_back(static_cast<int32_t>((k % 24)));
expectedResultsMinute.push_back(static_cast<int32_t>(((k + 1) % 60)));
expectedResultsSecond.push_back(static_cast<int32_t>((k + 2) % 60));
}
}
auto& payloadsYear = result->payloads().at("YEAR(colLong3)");
auto& payloadsMonth = result->payloads().at("MONTH(colLong3)");
auto& payloadsDay = result->payloads().at("DAY(colLong3)");
auto& payloadsHour = result->payloads().at("HOUR(colLong3)");
auto& payloadsMinute = result->payloads().at("MINUTE(colLong3)");
auto& payloadsSecond = result->payloads().at("SECOND(colLong3)");
ASSERT_EQ(payloadsYear.intpayload().intdata_size(), expectedResultsYear.size());
ASSERT_EQ(payloadsMonth.intpayload().intdata_size(), expectedResultsMonth.size());
ASSERT_EQ(payloadsDay.intpayload().intdata_size(), expectedResultsDay.size());
ASSERT_EQ(payloadsHour.intpayload().intdata_size(), expectedResultsHour.size());
ASSERT_EQ(payloadsMinute.intpayload().intdata_size(), expectedResultsMinute.size());
ASSERT_EQ(payloadsSecond.intpayload().intdata_size(), expectedResultsSecond.size());
for (int i = 0; i < payloadsYear.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsYear[i], payloadsYear.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsYear.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsMonth[i], payloadsMonth.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsYear.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsDay[i], payloadsDay.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsYear.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsHour[i], payloadsHour.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsYear.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsMinute[i], payloadsMinute.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsYear.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsSecond[i], payloadsSecond.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, DayOfWeekConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT WEEKDAY('2020-05-12 02:00:00'), DAYOFWEEK('2020-05-12 "
"02:00:00') FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsWeekday;
std::vector<int32_t> expectedResultsDayOfWeek;
for (int i = 0; i < 2; i++)
{
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsWeekday.push_back(1);
expectedResultsDayOfWeek.push_back(3);
}
}
auto& payloadsWeekday = result->payloads().at("WEEKDAY(1589241600)");
auto& payloadsDayOfWeek = result->payloads().at("DAYOFWEEK(1589241600)");
ASSERT_EQ(payloadsWeekday.intpayload().intdata_size(), expectedResultsWeekday.size());
ASSERT_EQ(payloadsDayOfWeek.intpayload().intdata_size(), expectedResultsDayOfWeek.size());
for (int i = 0; i < payloadsWeekday.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsWeekday[i], payloadsWeekday.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsDayOfWeek.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsDayOfWeek[i], payloadsDayOfWeek.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, RetPolygons)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colPolygon1 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPolygons;
auto column =
dynamic_cast<ColumnBase<QikkDB::Types::ComplexPolygon>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colPolygon1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsPolygons.push_back(ComplexPolygonFactory::WktFromPolygon(block->GetData()[k], true));
}
}
auto& payloads = result->payloads().at("TableA.colPolygon1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPolygons.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPolygons[i], payloads.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, RetPolygonsWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colPolygon1 FROM TableA WHERE colInteger1 < 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPolygons;
auto column =
dynamic_cast<ColumnBase<QikkDB::Types::ComplexPolygon>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colPolygon1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((k % 1024) * (k % 2 ? 1 : -1) < 20)
{
expectedResultsPolygons.push_back(
ComplexPolygonFactory::WktFromPolygon(block->GetData()[k], true));
}
}
}
auto& payloads = result->payloads().at("TableA.colPolygon1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPolygons.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPolygons[i], payloads.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, RetPoints)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colPoint1 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPoints;
auto column = dynamic_cast<ColumnBase<QikkDB::Types::Point>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colPoint1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsPoints.push_back(PointFactory::WktFromPoint(block->GetData()[k], true));
}
}
auto& payloads = result->payloads().at("TableA.colPoint1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPoints.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPoints[i], payloads.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, RetPointsWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colPoint1 FROM TableA WHERE colInteger1 < 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPoints;
auto column = dynamic_cast<ColumnBase<QikkDB::Types::Point>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colPoint1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (k % 2)
{
if ((k % 1024) < 20)
{
expectedResultsPoints.push_back(PointFactory::WktFromPoint(block->GetData()[k], true));
}
}
else
{
if (((k % 1024) * -1) < 20)
{
expectedResultsPoints.push_back(PointFactory::WktFromPoint(block->GetData()[k], true));
}
}
}
}
auto& payloads = result->payloads().at("TableA.colPoint1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPoints.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPoints[i], payloads.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, RetString)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colString1 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colString1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
auto& payloads = result->payloads().at("TableA.colString1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsStrings.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsStrings[i], payloads.stringpayload().stringdata()[i]) << " at row " << i;
}
}
TEST(DispatcherTests, RetStringWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colString1 FROM TableA WHERE colInteger1 < 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colString1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (k % 2)
{
if ((k % 1024) < 20)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
else
{
if (((k % 1024) * -1) < 20)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
}
}
auto& payloads = result->payloads().at("TableA.colString1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsStrings.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsStrings[i], payloads.stringpayload().stringdata()[i]) << " at row " << i;
}
}
TEST(DispatcherTests, RetDate)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT DATE(colLong3) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<int64_t>*>(
DispatcherObjs::GetInstance().database->GetTables().at("TableA").GetColumns().at("colLong3").get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
time_t t = block->GetData()[k];
auto tm = std::gmtime(&t);
std::stringstream ss;
ss << std::put_time(tm, "%Y-%m-%d %H:%M:%S");
expectedResultsStrings.push_back(ss.str());
}
}
auto& payloads = result->payloads().at("DATE(colLong3)");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsStrings.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsStrings[i], payloads.stringpayload().stringdata()[i]) << " at row " << i;
}
}
TEST(DispatcherTests, RetDateWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT DATE(colLong3) FROM TableA WHERE DATE(colLong3) = "
"\"2000-01-01 00:01:02\";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<int64_t>*>(
DispatcherObjs::GetInstance().database->GetTables().at("TableA").GetColumns().at("colLong3").get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
time_t t = block->GetData()[k];
auto tm = std::gmtime(&t);
std::stringstream ss;
ss << std::put_time(tm, "%Y-%m-%d %H:%M:%S");
if (ss.str() == "2000-01-01 00:01:02")
{
expectedResultsStrings.push_back(ss.str());
}
}
}
auto& payloads = result->payloads().at("DATE(colLong3)");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsStrings.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsStrings[i], payloads.stringpayload().stringdata()[i]) << " at row " << i;
}
}
TEST(DispatcherTests, PointFromColCol)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT POINT(colInteger1, colFloat1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPoints;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::ostringstream wktStream;
wktStream << std::fixed;
wktStream << std::setprecision(4);
wktStream << "POINT(" << static_cast<float>(blockInt->GetData()[k]) << " "
<< blockFloat->GetData()[k] << ")";
expectedResultsPoints.push_back(wktStream.str());
}
}
auto& payloads = result->payloads().at("POINT(colInteger1,colFloat1)");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPoints.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPoints[i], payloads.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, PointFromColConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT POINT(colInteger1, 4.5) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPoints;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::ostringstream wktStream;
wktStream << std::fixed;
wktStream << std::setprecision(4);
wktStream << "POINT(" << static_cast<float>(blockInt->GetData()[k]) << " 4.5000"
<< ")";
expectedResultsPoints.push_back(wktStream.str());
}
}
auto& payloads = result->payloads().at("POINT(colInteger1,4.5)");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPoints.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPoints[i], payloads.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, PointFromConstCol)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT POINT(7, colFloat1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPoints;
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::ostringstream wktStream;
wktStream << std::fixed;
wktStream << std::setprecision(4);
wktStream << "POINT("
<< "7.0000 " << blockFloat->GetData()[k] << ")";
expectedResultsPoints.push_back(wktStream.str());
}
}
auto& payloads = result->payloads().at("POINT(7,colFloat1)");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPoints.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPoints[i], payloads.stringpayload().stringdata()[i]);
}
}
// Aggregation tests
TEST(DispatcherTests, AggregationMin)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT MIN(colInteger1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("MIN(colInteger1)");
// Get the input column
const std::vector<BlockBase<int32_t>*>& inputColumn1Blocks =
reinterpret_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get())
->GetBlocksList();
// Find min on CPU
int32_t expectedResult = std::numeric_limits<int32_t>::max();
for (int i = 0; i < TEST_BLOCK_COUNT; i++)
{
for (int j = 0; j < TEST_BLOCK_SIZE; j++)
{
int32_t value = inputColumn1Blocks[i]->GetData()[j];
if (value < expectedResult)
{
expectedResult = value;
}
}
}
ASSERT_EQ(payloads.intpayload().intdata_size(), 1);
ASSERT_EQ(payloads.intpayload().intdata()[0], expectedResult);
}
TEST(DispatcherTests, AggregationMax)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT MAX(colInteger1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("MAX(colInteger1)");
// Get the input column
const std::vector<BlockBase<int32_t>*>& inputColumn1Blocks =
reinterpret_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get())
->GetBlocksList();
// Find min on CPU
int32_t expectedResult = std::numeric_limits<int32_t>::min();
for (int i = 0; i < TEST_BLOCK_COUNT; i++)
{
for (int j = 0; j < TEST_BLOCK_SIZE; j++)
{
int32_t value = inputColumn1Blocks[i]->GetData()[j];
if (value > expectedResult)
{
expectedResult = value;
}
}
}
ASSERT_EQ(payloads.intpayload().intdata_size(), 1);
ASSERT_EQ(payloads.intpayload().intdata()[0], expectedResult);
}
TEST(DispatcherTests, AggregationSum)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT SUM(colInteger1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("SUM(colInteger1)");
// Get the input column
const std::vector<BlockBase<int32_t>*>& inputColumn1Blocks =
reinterpret_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get())
->GetBlocksList();
// Find min on CPU
int32_t expectedResult = 0;
for (int i = 0; i < TEST_BLOCK_COUNT; i++)
{
for (int j = 0; j < TEST_BLOCK_SIZE; j++)
{
expectedResult += inputColumn1Blocks[i]->GetData()[j];
}
}
ASSERT_EQ(payloads.intpayload().intdata_size(), 1);
ASSERT_EQ(payloads.intpayload().intdata()[0], expectedResult);
}
TEST(DispatcherTests, AggregationAvg)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT AVG(colInteger1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("AVG(colInteger1)");
// Get the input column
const std::vector<BlockBase<int32_t>*>& inputColumn1Blocks =
reinterpret_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get())
->GetBlocksList();
// Find min on CPU
int32_t expectedResult = 0; // TODO float, also in disptacher fields float
int64_t count = 0;
for (int i = 0; i < TEST_BLOCK_COUNT; i++)
{
for (int j = 0; j < TEST_BLOCK_SIZE; j++)
{
expectedResult += inputColumn1Blocks[i]->GetData()[j];
++count;
}
}
expectedResult /= count;
ASSERT_EQ(payloads.intpayload().intdata_size(), 1);
ASSERT_EQ(payloads.intpayload().intdata()[0], expectedResult);
}
TEST(DispatcherTests, AggregationCount)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colInteger1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(colInteger1)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTests, AggregationCountString)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colString1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(colString1)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTests, AggregationCountPolygon)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(colPolygon1) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(colPolygon1)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTests, Alias)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT (t.colInteger1 - 10) AS col1, t.colFloat1 AS col2, "
"colInteger1*2 AS colInteger1 FROM "
"TableA as t WHERE t.colInteger1 > 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
std::vector<int32_t> expectedResultsIntMul;
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k] - 10);
expectedResultsIntMul.push_back(blockInt->GetData()[k] * 2);
expectedResultsFloat.push_back(blockFloat->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("col1");
auto& payloadsIntMul = result->payloads().at("colInteger1");
auto& payloadsFloat = result->payloads().at("col2");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
ASSERT_EQ(payloadsIntMul.intpayload().intdata_size(), expectedResultsIntMul.size());
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsIntMul.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsIntMul[i], payloadsIntMul.intpayload().intdata()[i]);
}
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, LimitOffset)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 20 LIMIT 10 "
"OFFSET 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto limit = 10;
auto offset = 10;
auto first = expectedResultsInt.begin() + offset;
auto last = expectedResultsInt.begin() + offset + limit;
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LimitNoClauses)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA LIMIT 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
auto limit = 10;
auto first = expectedResultsInt.begin();
auto last = expectedResultsInt.begin() + limit;
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LimitOffsetNoClauses)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA LIMIT 10 OFFSET 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
auto limit = 10;
auto offset = 10;
auto first = expectedResultsInt.begin() + offset;
auto last = expectedResultsInt.begin() + offset + limit;
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LimitOffsetNoClausesBlockEdge)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA LIMIT 20 OFFSET 2040;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
auto limit = 20;
auto offset = 2040;
auto first = expectedResultsInt.begin() + offset;
auto last = expectedResultsInt.begin() + offset + limit;
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LimitOffsetNoClausesOutOfBoundsOffset)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA LIMIT 20 OFFSET 20000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, LimitOffsetNoClausesOutOfBoundsLimit)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA LIMIT 20000 OFFSET 2040;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
auto offset = 2040;
auto first = expectedResultsInt.begin() + offset;
auto last = expectedResultsInt.end();
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LimitOffsetAsteriskNoClauses)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT * FROM TableA LIMIT 10 OFFSET 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
}
TEST(DispatcherTests, Limit)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 20 LIMIT 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto limit = 10;
auto first = expectedResultsInt.begin();
auto last = expectedResultsInt.begin() + limit;
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, Offset)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 20 OFFSET 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto offset = 10;
auto first = expectedResultsInt.begin() + offset;
auto last = expectedResultsInt.end();
std::vector<int32_t> trimmedExpectedResultsInt(first, last);
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), trimmedExpectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(trimmedExpectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LargeOffset)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 20 OFFSET "
"10000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), 0);
}
TEST(DispatcherTests, LargeLimit)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 > 20 LIMIT "
"10000000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseOrColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 | 20) > 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] | 20) > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseAndColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 & 20) > 10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] & 20) > 10)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseXorColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 ^ 20) > 100;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] ^ 20) > 100)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseLeftShiftColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 << 2) > 100;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] << 2) > 100)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseRightShiftColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 >> 2) > 100;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] >> 2) > 100)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseOrColColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 | colInteger2) > "
"500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnInt2 = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger2")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockInt2 = columnInt2->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] | blockInt2->GetData()[k]) > 500)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseAndColColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 & colInteger2) > "
"10;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnInt2 = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger2")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockInt2 = columnInt2->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] & blockInt2->GetData()[k]) > 10)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, BitwiseXorColColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE (colInteger1 ^ colInteger2) > "
"500;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnInt2 = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger2")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockInt2 = columnInt2->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ((blockInt->GetData()[k] ^ blockInt2->GetData()[k]) > 500)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, NotEqualsAlternativeOperator)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE colInteger1 <> 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] != 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, MinusColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE -colInteger1 = 3;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, AbsColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE ABS(colInteger1) = 3;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (abs(blockInt->GetData()[k]) == 3)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SinColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SIN(colInteger1) > 0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (sin(blockInt->GetData()[k]) > 0.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, CosColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE COS(colInteger1) > 0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (cos(blockInt->GetData()[k]) > 0.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, TanColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE TAN(colInteger1) > 2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (tan(blockInt->GetData()[k]) > 2)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SinColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SIN(colFloat1) > 0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInteger = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInteger = columnInteger->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (sin(blockFloat->GetData()[k]) > 0.5)
{
expectedResultsInt.push_back(blockInteger->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, CosColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE COS(colFloat1) > 0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInteger = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInteger = columnInteger->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (cos(blockFloat->GetData()[k]) > 0.5)
{
expectedResultsInt.push_back(blockInteger->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, TanColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE TAN(colFloat1) > 2;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInteger = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInteger = columnInteger->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (tan(blockFloat->GetData()[k]) > 2)
{
expectedResultsInt.push_back(blockInteger->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SinPiColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SIN(colFloat1 + PI()) > 0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInteger = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInteger = columnInteger->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (sin(blockFloat->GetData()[k] + pi()) > 0.5f)
{
expectedResultsInt.push_back(blockInteger->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, ArcSinColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE ASIN(colInteger1 / 1024.0) > "
"0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (asin(blockInt->GetData()[k] / 1024.0f) > 0.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, ArcCosColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE ACOS(colInteger1 / 1024.0) > "
"0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (acos(blockInt->GetData()[k] / 1024.0f) > 0.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, ArcTanColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE ATAN(colInteger1) > 0.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (atan(blockInt->GetData()[k]) > 0.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, Logarithm10ColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE LOG10(colInteger1) > 1.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (log10f(blockInt->GetData()[k]) > 1.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LogarithmNaturalColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE LOG(colInteger1) > 1.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (logf(blockInt->GetData()[k]) > 1.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, LogarithmColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE LOG(colInteger1, 3.0) > 1.5;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (logf(blockInt->GetData()[k]) / logf(3) > 1.5)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, ExponentialColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE EXP(colInteger1) > 2000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (exp(blockInt->GetData()[k]) > 2000)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, PowerColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE POW(colInteger1, 2) > 2000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (pow(blockInt->GetData()[k], 2) > 2000)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SqrtColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SQRT(colInteger1) > 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (sqrtf(blockInt->GetData()[k]) > 20)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SquareColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SQUARE(colInteger1) > 2000;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (powf(blockInt->GetData()[k], 2) > 2000)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SignPositiveColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SIGN(colInteger1) = 1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] > 0)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SignNegativeColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SIGN(colInteger1) = -1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] < 0)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, SignZeroColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE SIGN(colInteger1) = 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] == 0)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, RootColConstInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE ROOT(colInteger1, 2) > 0;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (powf(blockInt->GetData()[k], 0.5f) > 0)
{
expectedResultsInt.push_back(blockInt->GetData()[k]);
}
}
}
std::cout << "Expected result size: " << expectedResultsInt.size() << std::endl;
auto& payloadsInt = result->payloads().at("TableA.colInteger1");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, RoundColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT ROUND(colFloat1) FROM TableA WHERE colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
expectedResultsFloat.push_back(round(blockFloat->GetData()[k]));
}
}
}
auto& payloadsFloat = result->payloads().at("ROUND(colFloat1)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, FloorColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT FLOOR(colFloat1) FROM TableA WHERE colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
expectedResultsFloat.push_back(floor(blockFloat->GetData()[k]));
}
}
}
auto& payloadsFloat = result->payloads().at("FLOOR(colFloat1)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, CeilColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT CEIL(colFloat1) FROM TableA WHERE colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
expectedResultsFloat.push_back(ceil(blockFloat->GetData()[k]));
}
}
}
auto& payloadsFloat = result->payloads().at("CEIL(colFloat1)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, RoundColInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT ROUND(colInteger1) FROM TableA WHERE colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
expectedResultsFloat.push_back(round(blockInt->GetData()[k]));
}
}
}
auto& payloadsFloat = result->payloads().at("ROUND(colInteger1)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, CotColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COT(colFloat1) FROM TableA WHERE colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
expectedResultsFloat.push_back(1.0f / tanf(blockFloat->GetData()[k]));
}
}
}
auto& payloadsFloat = result->payloads().at("COT(colFloat1)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, Atan2ColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT ATAN2(colFloat1, colFloat1 + 1) FROM TableA WHERE "
"colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
expectedResultsFloat.push_back(atan2f(blockFloat->GetData()[k], blockFloat->GetData()[k] + 1));
}
}
}
auto& payloadsFloat = result->payloads().at("ATAN2(colFloat1,colFloat1+1)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, RoundDecimalColFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT ROUND(colFloat1, 2) FROM TableA WHERE "
"colInteger1 >= 20;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] >= 20)
{
const float multiplier = powf(10.0, 2);
expectedResultsFloat.push_back(roundf(blockFloat->GetData()[k] * multiplier) / multiplier);
}
}
}
auto& payloadsFloat = result->payloads().at("ROUND(colFloat1,2)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
//== STRING FUNCTIONS ==
/// Assert equality of returned string column and expected values
void AssertEqStringCol(QikkDB::NetworkClient::Message::QueryResponsePayload payloads,
std::vector<std::string> expected)
{
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expected.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expected[i], payloads.stringpayload().stringdata()[i]) << " at row " << i;
}
}
/// Run query SELECT <col> <fromWhere>;
QikkDB::NetworkClient::Message::QueryResponsePayload RunQuery(std::string col, std::string fromWhere)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT " + col + " " + fromWhere + ";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
return result->payloads().at(col);
}
/// Run query SELECT function(column) FROM table; and return result payload
QikkDB::NetworkClient::Message::QueryResponsePayload
RunFunctionQuery(std::string function, std::string column, std::string table)
{
std::string retFunCol = function + "(" + column + ")";
return RunQuery(retFunCol, "FROM " + table);
}
/// Run query SELECT function(column) FROM table; and return result payload
QikkDB::NetworkClient::Message::QueryResponsePayload
RunFunctionColConstQuery(std::string function, std::string column, std::string cnst, std::string table)
{
std::string retFunCol = function + "(" + column + "," + cnst + ")";
return RunQuery(retFunCol, "FROM " + table);
}
TEST(DispatcherTests, StringLower)
{
const std::string col = "colString1";
const std::string table = "TableA";
auto payloads = RunFunctionQuery("LOWER", col, table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::string edited;
for (char c : block->GetData()[k])
{
edited += tolower(c);
}
expectedResultsStrings.push_back(edited);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLowerConst)
{
const std::string text = "\"ABCDabcdzZ [{|}]_#90\"";
auto payloads = RunFunctionQuery("LOWER", text, "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
std::string edited;
for (char c : text.substr(1, text.length() - 2))
{
edited += tolower(c);
}
expectedResultsStrings.push_back(edited);
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringUpper)
{
const std::string col = "colString1";
const std::string table = "TableA";
auto payloads = RunFunctionQuery("UPPER", col, table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::string edited;
for (char c : block->GetData()[k])
{
edited += toupper(c);
}
expectedResultsStrings.push_back(edited);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringUpperConst)
{
const std::string text = "\"ABCDabcdzZ [{|}]_#90\"";
auto payloads = RunFunctionQuery("UPPER", text, "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
std::string edited;
for (char c : text.substr(1, text.length() - 2))
{
edited += toupper(c);
}
expectedResultsStrings.push_back(edited);
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringReverse)
{
const std::string col = "colString1";
const std::string table = "TableA";
auto payloads = RunFunctionQuery("REVERSE", col, table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::string edited(block->GetData()[k]);
std::reverse(edited.begin(), edited.end());
expectedResultsStrings.push_back(edited);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringReverseConst)
{
const std::string text = "\"ABCDabcdzZ [{|}]_#90\"";
auto payloads = RunFunctionQuery("REVERSE", text, "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
std::string edited(text.substr(1, text.length() - 2));
std::reverse(edited.begin(), edited.end());
expectedResultsStrings.push_back(edited);
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLtrim)
{
const std::string col = "colString1";
const std::string table = "TableA";
auto payloads = RunFunctionQuery("LTRIM", col, table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::string rowString(block->GetData()[k]);
size_t index = rowString.find_first_not_of(' ');
std::string trimmed;
if (index < rowString.length())
{
trimmed = rowString.substr(index, rowString.length() - index);
}
expectedResultsStrings.push_back(trimmed);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLtrimConst)
{
const std::string text = "\" ABCDabcdzZ [{|}]_#90 \"";
auto payloads = RunFunctionQuery("LTRIM", text, "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
std::string edited(text.substr(1, text.length() - 2));
size_t index = edited.find_first_not_of(' ');
std::string trimmed;
if (index < edited.length())
{
trimmed = edited.substr(index, edited.length() - index);
}
expectedResultsStrings.push_back(trimmed);
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringRtrim)
{
const std::string col = "colString1";
const std::string table = "TableA";
auto payloads = RunFunctionQuery("RTRIM", col, table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
std::string rowString(block->GetData()[k]);
size_t index = rowString.find_last_not_of(' ');
std::string trimmed = rowString.substr(0, index + 1);
expectedResultsStrings.push_back(trimmed);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringRtrimConst)
{
const std::string text = "\" ABCDabcdzZ [{|}]_#90 \"";
auto payloads = RunFunctionQuery("RTRIM", text, "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
std::string edited(text.substr(1, text.length() - 2));
;
size_t index = edited.find_last_not_of(' ');
std::string trimmed = edited.substr(0, index + 1);
expectedResultsStrings.push_back(trimmed);
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLen)
{
const std::string col = "colString1";
const std::string table = "TableA";
auto payloads = RunFunctionQuery("LEN", col, table);
std::vector<int32_t> expectedResults;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResults.push_back(block->GetData()[k].length());
}
}
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResults.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResults[i], payloads.intpayload().intdata()[i]) << " at row " << i;
}
}
TEST(DispatcherTests, StringLenConst)
{
const std::string text = "\" ABCDabcdzZ [{|}]_#90 \"";
auto payloads = RunFunctionQuery("LEN", text, "TableA LIMIT 1");
ASSERT_EQ(payloads.intpayload().intdata_size(), 1);
ASSERT_EQ(payloads.intpayload().intdata()[0], text.length() - 2); // - 2 because of two quotes ""
}
TEST(DispatcherTests, StringLeftColCol)
{
const std::string colStrName = "colString1";
const std::string colIntName = "colInteger1";
const std::string table = "TableA";
const int32_t testLen = 2;
auto payloads = RunFunctionColConstQuery("LEFT", colStrName, "ABS(" + colIntName + ")", table);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colIntName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k].substr(0, abs(blockInt->GetData()[k])));
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLeftColConst)
{
const std::string col = "colString1";
const std::string table = "TableA";
const int32_t testLen = 2;
auto payloads = RunFunctionColConstQuery("LEFT", col, std::to_string(testLen), table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k].substr(0, testLen));
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLeftConstCol)
{
const std::string text = " ABCDabcdzZ [{|}]_#90 ";
const std::string colIntName = "colInteger1";
const std::string table = "TableA";
auto payloads = RunFunctionColConstQuery("LEFT", "\"" + text + "\"", "ABS(" + colIntName + ")", table);
std::vector<std::string> expectedResultsStrings;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colIntName).get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(text.substr(0, abs(blockInt->GetData()[k])));
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringLeftConstConst)
{
const std::string text = " ABCDabcdzZ [{|}]_#90 ";
const int32_t testLen = 2;
auto payloads = RunFunctionColConstQuery("LEFT", "\"" + text + "\"", std::to_string(testLen), "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
expectedResultsStrings.push_back(text.substr(0, testLen));
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringRightColCol)
{
const std::string colStrName = "colString1";
const std::string colIntName = "colInteger1";
const std::string table = "TableA";
auto payloads = RunFunctionColConstQuery("RIGHT", colStrName, "ABS(" + colIntName + ")", table);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colIntName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
int32_t cutLen = abs(blockInt->GetData()[k]);
size_t origLen = block->GetData()[k].size();
expectedResultsStrings.push_back(block->GetData()[k].substr(origLen < cutLen ? 0 : origLen - cutLen));
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringRightColConst)
{
const std::string col = "colString1";
const std::string table = "TableA";
const int32_t testLen = 3;
auto payloads = RunFunctionColConstQuery("RIGHT", col, std::to_string(testLen), table);
std::vector<std::string> expectedResultsStrings;
auto column = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(col).get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
size_t len = block->GetData()[k].size();
expectedResultsStrings.push_back(block->GetData()[k].substr(len < testLen ? 0 : len - testLen));
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringRightConstCol)
{
const std::string text = " ABCDabcdzZ [{|}]_#90 ";
const std::string colIntName = "colInteger1";
const std::string table = "TableA";
auto payloads = RunFunctionColConstQuery("RIGHT", "\"" + text + "\"", "ABS(" + colIntName + ")", table);
std::vector<std::string> expectedResultsStrings;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colIntName).get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
int32_t cutLen = abs(blockInt->GetData()[k]);
size_t origLen = text.size();
expectedResultsStrings.push_back(text.substr(origLen < cutLen ? 0 : origLen - cutLen));
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringRightConstConst)
{
const std::string text = " ABCDabcdzZ [{|}]_#90 ";
const int32_t testLen = 2;
auto payloads = RunFunctionColConstQuery("RIGHT", "\"" + text + "\"", std::to_string(testLen), "TableA LIMIT 1");
std::vector<std::string> expectedResultsStrings;
size_t origLen = text.size();
expectedResultsStrings.push_back(text.substr(origLen < testLen ? 0 : origLen - testLen));
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringConcatColCol)
{
const std::string colStrName = "colString1";
const std::string table = "TableA";
const int32_t testLen = 2;
auto payloads = RunQuery("CONCAT(" + table + "." + colStrName + "," + table + "." + colStrName + ")",
"FROM " + table);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k] + block->GetData()[k]);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringConcatColConst)
{
const std::string colStrName = "colString1";
const std::string text = "az#7";
const std::string table = "TableA";
const int32_t testLen = 2;
auto payloads = RunQuery("CONCAT(" + table + "." + colStrName + ",\"" + text + "\")", "FROM " + table);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k] + text);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringConcatConstCol)
{
const std::string text = "az#7";
const std::string colStrName = "colString1";
const std::string table = "TableA";
const int32_t testLen = 2;
auto payloads = RunQuery("CONCAT(\"" + text + "\"," + table + "." + colStrName + ")", "FROM " + table);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(text + block->GetData()[k]);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringConcatConstConst)
{
const std::string text1 = "abcd";
const std::string text2 = "XYZ_2";
const std::string table = "TableA";
auto payloads = RunQuery("CONCAT(\"" + text1 + "\",\"" + text2 + "\")", "FROM " + table + " LIMIT 1");
std::vector<std::string> expectedResultsStrings;
expectedResultsStrings.push_back(text1 + text2);
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringEqColConst)
{
const std::string text = "Word0";
const std::string colStrName = "colString1";
const std::string table = "TableA";
auto payloads = RunQuery(table + "." + colStrName,
"FROM " + table + " WHERE " + colStrName + " = \"" + text + "\"");
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (block->GetData()[k] == text)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringNotEqColConst)
{
const std::string text = "Word0";
const std::string colStrName = "colString1";
const std::string table = "TableA";
auto payloads = RunQuery(table + "." + colStrName,
"FROM " + table + " WHERE " + colStrName + " != \"" + text + "\"");
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (block->GetData()[k] != text)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringEqConstCol)
{
const std::string text = "Word0";
const std::string colStrName = "colString1";
const std::string table = "TableA";
auto payloads = RunQuery(table + "." + colStrName,
"FROM " + table + " WHERE " + "\"" + text + "\"" + " = " + colStrName);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (block->GetData()[k] == text)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringNotEqConstCol)
{
const std::string text = "Word0";
const std::string colStrName = "colString1";
const std::string table = "TableA";
auto payloads = RunQuery(table + "." + colStrName,
"FROM " + table + " WHERE " + "\"" + text + "\"" + " != " + colStrName);
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (block->GetData()[k] != text)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringEqConstConst)
{
const std::string text = "Word0";
const std::string colStrName = "colString1";
const std::string table = "TableA";
auto payloads = RunQuery(table + "." + colStrName,
"FROM " + table + " WHERE " + "\"" + text + "\"" + " = \"" + text + "\"");
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
TEST(DispatcherTests, StringNotEqConstConst)
{
const std::string text = "Word0";
const std::string colStrName = "colString1";
const std::string table = "TableA";
auto payloads = RunQuery(table + "." + colStrName, "FROM " + table + " WHERE " + "\"" + text +
"diff" + "\"" + " != \"" + text + "\"");
std::vector<std::string> expectedResultsStrings;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(
DispatcherObjs::GetInstance().database->GetTables().at(table).GetColumns().at(colStrName).get());
for (int i = 0; i < 2; i++)
{
auto block = columnString->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsStrings.push_back(block->GetData()[k]);
}
}
AssertEqStringCol(payloads, expectedResultsStrings);
}
// Polygon clipping tests
/*
TEST(DispatcherTests, PolygonClippingAndContains)
{
// TODO: fix zero allocation, finish polygon clippin and add asserts
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA WHERE "
"GEO_CONTAINS(GEO_INTERSECT(colPolygon1, colPolygon2), colPoint1);");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::string> expectedResultsPoints;
}
*/
TEST(DispatcherTests, CreateDropDatabase)
{
Context::getInstance();
GpuSqlCustomParser parser(nullptr, "CREATE DATABASE createdDb;");
auto resultPtr = parser.Parse();
ASSERT_TRUE(Database::Exists("createdDb"));
GpuSqlCustomParser parser2(nullptr, "DROP DATABASE createdDb;");
resultPtr = parser2.Parse();
ASSERT_TRUE(!Database::Exists("createdDb"));
}
TEST(DispatcherTests, CreateDropDatabaseWithDelimitedIdentifiers)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"CREATE DATABASE [createdDb%^&*()-+];");
auto resultPtr = parser.Parse();
ASSERT_TRUE(Database::Exists("createdDb%^&*()-+"));
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"DROP DATABASE [createdDb%^&*()-+];");
resultPtr = parser2.Parse();
ASSERT_TRUE(!Database::Exists("createdDb%^&*()-+"));
}
TEST(DispatcherTests, CreateDatabaseDelimitedIdentifiersIllegalCharacter)
{
Context::getInstance();
GpuSqlCustomParser parser(nullptr, "CREATE DATABASE [createdDb%^&*()-+@];");
ASSERT_THROW(parser.Parse(), IdentifierException);
}
TEST(DispatcherTests, CreateAlterDropTable)
{
Context::getInstance();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") ==
DispatcherObjs::GetInstance().database->GetTables().end());
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"CREATE TABLE tblA (colA int, colB float, INDEX ind (colA, colB));");
auto resultPtr = parser.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") !=
DispatcherObjs::GetInstance().database->GetTables().end());
std::vector<std::string> expectedSortingColumns = {"colA", "colB"};
std::vector<std::string> resultSortingColumns =
DispatcherObjs::GetInstance().database->GetTables().at("tblA").GetSortingColumns();
ASSERT_TRUE(expectedSortingColumns.size() == resultSortingColumns.size());
for (int i = 0; i < expectedSortingColumns.size(); i++)
{
ASSERT_TRUE(expectedSortingColumns[i] == resultSortingColumns[i]);
}
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"INSERT INTO tblA (colA, colB) VALUES (1, 2.0);");
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parser2.Parse();
}
GpuSqlCustomParser parser3(DispatcherObjs::GetInstance().database,
"SELECT colA, colB from tblA;");
resultPtr = parser3.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsColA;
std::vector<float> expectedResultsColB;
for (int k = 0; k < 5; k++)
{
expectedResultsColA.push_back(1);
expectedResultsColB.push_back(2.0);
}
auto& payloadsColA = result->payloads().at("tblA.colA");
auto& payloadsColB = result->payloads().at("tblA.colB");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), expectedResultsColA.size());
for (int i = 0; i < payloadsColA.intpayload().intdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColA[i], payloadsColA.intpayload().intdata()[i]);
}
ASSERT_EQ(payloadsColB.floatpayload().floatdata_size(), expectedResultsColB.size());
for (int i = 0; i < payloadsColB.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColB[i], payloadsColB.floatpayload().floatdata()[i]);
}
GpuSqlCustomParser parser4(DispatcherObjs::GetInstance().database,
"ALTER TABLE tblA DROP COLUMN colA, ADD colC float;");
resultPtr = parser4.Parse();
ASSERT_TRUE(
DispatcherObjs::GetInstance().database->GetTables().at("tblA").GetColumns().find("colA") ==
DispatcherObjs::GetInstance().database->GetTables().at("tblA").GetColumns().end());
GpuSqlCustomParser parser5(DispatcherObjs::GetInstance().database,
"SELECT colB, colC from tblA;");
resultPtr = parser5.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColB2 = result->payloads().at("tblA.colB");
auto& payloadsColC = result->payloads().at("tblA.colC");
ASSERT_EQ(payloadsColB2.floatpayload().floatdata_size(), expectedResultsColB.size());
for (int i = 0; i < payloadsColB2.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColB[i], payloadsColB2.floatpayload().floatdata()[i]);
}
ASSERT_EQ(payloadsColC.floatpayload().floatdata_size(), 5);
for (int i = 0; i < payloadsColC.floatpayload().floatdata_size(); i++)
{
ASSERT_TRUE(std::isnan(payloadsColC.floatpayload().floatdata()[i]));
}
GpuSqlCustomParser parser6(DispatcherObjs::GetInstance().database, "DROP TABLE tblA;");
resultPtr = parser6.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") ==
DispatcherObjs::GetInstance().database->GetTables().end());
}
TEST(DispatcherTests, CreateAlterNotNullConstraintsDropTable)
{
Context::getInstance();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") ==
DispatcherObjs::GetInstance().database->GetTables().end());
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"CREATE TABLE tblA (colA int, colB float);");
auto resultPtr = parser.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") !=
DispatcherObjs::GetInstance().database->GetTables().end());
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"INSERT INTO tblA (colA, colB) VALUES (1, 2.0);");
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parser2.Parse();
}
GpuSqlCustomParser parser3(DispatcherObjs::GetInstance().database,
"SELECT colA, colB from tblA;");
resultPtr = parser3.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsColA;
std::vector<float> expectedResultsColB;
for (int k = 0; k < 5; k++)
{
expectedResultsColA.push_back(1);
expectedResultsColB.push_back(2.0);
}
auto& payloadsColA = result->payloads().at("tblA.colA");
auto& payloadsColB = result->payloads().at("tblA.colB");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), expectedResultsColA.size());
for (int i = 0; i < payloadsColA.intpayload().intdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColA[i], payloadsColA.intpayload().intdata()[i]);
}
ASSERT_EQ(payloadsColB.floatpayload().floatdata_size(), expectedResultsColB.size());
for (int i = 0; i < payloadsColB.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColB[i], payloadsColB.floatpayload().floatdata()[i]);
}
GpuSqlCustomParser parser4(DispatcherObjs::GetInstance().database,
"ALTER TABLE tblA ADD NOT NULL notNullAB (colA, colB);");
resultPtr = parser4.Parse();
ASSERT_FALSE(
DispatcherObjs::GetInstance().database->GetTables().at("tblA").GetColumns().at("colA")->GetIsNullable());
ASSERT_FALSE(
DispatcherObjs::GetInstance().database->GetTables().at("tblA").GetColumns().at("colB")->GetIsNullable());
GpuSqlCustomParser parser6(DispatcherObjs::GetInstance().database, "DROP TABLE tblA;");
resultPtr = parser6.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") ==
DispatcherObjs::GetInstance().database->GetTables().end());
}
TEST(DispatcherTests, CreateInsertTableEquivalentTypeNotation)
{
Context::getInstance();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") ==
DispatcherObjs::GetInstance().database->GetTables().end());
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"CREATE TABLE tblA (colA integer, colB int32, colC int64, colD "
"datetime, colE bool);");
auto resultPtr = parser.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") !=
DispatcherObjs::GetInstance().database->GetTables().end());
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"INSERT INTO tblA (colA, colB, colC, colD, colE) VALUES (1, 2, 3, "
"'2019-09-11 08:00:00', True);");
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parser2.Parse();
}
GpuSqlCustomParser parser3(DispatcherObjs::GetInstance().database,
"SELECT colA, colB, colC, YEAR(colD), colE from tblA;");
resultPtr = parser3.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsColA;
std::vector<int32_t> expectedResultsColB;
std::vector<int64_t> expectedResultsColC;
std::vector<int32_t> expectedResultsColD;
std::vector<int8_t> expectedResultsColE;
for (int k = 0; k < 5; k++)
{
expectedResultsColA.push_back(1);
expectedResultsColB.push_back(2);
expectedResultsColC.push_back(3);
expectedResultsColD.push_back(2019);
expectedResultsColE.push_back(1);
}
auto& payloadsColA = result->payloads().at("tblA.colA");
auto& payloadsColB = result->payloads().at("tblA.colB");
auto& payloadsColC = result->payloads().at("tblA.colC");
auto& payloadsColD = result->payloads().at("YEAR(colD)");
auto& payloadsColE = result->payloads().at("tblA.colE");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), expectedResultsColA.size());
for (int i = 0; i < payloadsColA.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsColA[i], payloadsColA.intpayload().intdata()[i]);
}
ASSERT_EQ(payloadsColB.intpayload().intdata_size(), expectedResultsColB.size());
for (int i = 0; i < payloadsColB.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsColB[i], payloadsColB.intpayload().intdata()[i]);
}
ASSERT_EQ(payloadsColC.int64payload().int64data_size(), expectedResultsColC.size());
for (int i = 0; i < payloadsColC.int64payload().int64data_size(); i++)
{
ASSERT_EQ(expectedResultsColC[i], payloadsColC.int64payload().int64data()[i]);
}
ASSERT_EQ(payloadsColD.intpayload().intdata_size(), expectedResultsColD.size());
for (int i = 0; i < payloadsColD.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsColD[i], payloadsColD.intpayload().intdata()[i]);
}
ASSERT_EQ(payloadsColE.intpayload().intdata_size(), expectedResultsColE.size());
for (int i = 0; i < payloadsColE.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsColE[i], payloadsColE.intpayload().intdata()[i]);
}
GpuSqlCustomParser parser4(DispatcherObjs::GetInstance().database, "DROP TABLE tblA;");
resultPtr = parser4.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA") ==
DispatcherObjs::GetInstance().database->GetTables().end());
}
TEST(DispatcherTests, IsNull)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colInteger1 IS NULL;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(), 0);
}
TEST(DispatcherTests, IsNotNull)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE colInteger1 IS NOT NULL;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto column = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto block = column->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsFloat.push_back(block->GetData()[k]);
}
}
auto& payload = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payload.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payload.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payload.floatpayload().floatdata()[i]);
}
}
// TEST(DispatcherTests, WhereEvaluation)
//{
// GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database_, "SELECT colInteger1 FROM TableA
// WHERE ((colInteger2 != 500) AND (colInteger2 > 1000000)) OR ((colInteger1 >= 150) AND (colInteger1 < -1000000));");
// auto resultPtr = parser.Parse();
// auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
//
// FAIL();
//}
//
// TEST(DispatcherTests, WhereEvaluationColColPropagation)
//{
// GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database_, "SELECT colInteger1 FROM TableA
// WHERE ((colInteger2 > colInteger1) AND (colInteger2 > 1000000)) OR ((colInteger1 >= 150) AND (colInteger1 < -1000000));");
// auto resultPtr = parser.Parse();
// auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
//
// FAIL();
//}
std::string GetInsertIntoValuesString(const std::vector<std::vector<int32_t>>& data, int32_t index)
{
std::string values;
for (const auto& vctr : data)
{
values += (std::to_string(vctr[index]) + ", ");
}
return values.substr(0, values.length() - 2);
}
TEST(DispatcherTests, WhereEvaluationAdvanced)
{
GpuSqlCustomParser parserCreateDatabase(nullptr, "CREATE DATABASE WhereEvalDatabase 10;");
auto resultPtr = parserCreateDatabase.Parse();
GpuSqlCustomParser parserCreateTable(Database::GetDatabaseByName("WhereEvalDatabase"),
"CREATE TABLE TableA (ColA INT, ColB INT, ColC INT, ColD "
"INT, INDEX IndA(ColA, ColB, ColC));");
resultPtr = parserCreateTable.Parse();
std::vector<int32_t> dataIntA(
{1, 2, 3, 4, 5, 12, 17, 16, 19, 20, 1, 5, 3, 4, 2, 40, 150, 59, 110, 70});
std::vector<int32_t> dataIntB({4, 10, 1, 2, 3, 1, 3, 2, 3, 2, 7, 1, 1, 2, 10, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntC({6, 8, 1, 2, 1, 1, 3, 1, 4, 1, 7, 3, 2, 1, 6, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntD(
{1, 4, 5, 8, 10, 20, 40, 30, 50, 1, 2, 9, 6, 7, 3, 2, 6, 3, 5, 4});
for (int32_t i = 0; i < dataIntA.size(); i++)
{
GpuSqlCustomParser parserInsertInto(
Database::GetDatabaseByName("WhereEvalDatabase"),
"INSERT INTO TableA (ColA, ColB, ColC, ColD) VALUES (" +
GetInsertIntoValuesString({dataIntA, dataIntB, dataIntC, dataIntD}, i) + ");");
resultPtr = parserInsertInto.Parse();
}
std::vector<int32_t> dataIntASorted(
{1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 12, 16, 17, 19, 20, 40, 59, 70, 110, 150});
std::vector<int32_t> dataIntBSorted(
{4, 7, 10, 10, 1, 1, 2, 2, 1, 3, 1, 2, 3, 3, 2, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntCSorted(
{6, 7, 6, 8, 1, 2, 1, 2, 3, 1, 1, 1, 3, 4, 1, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntDSorted(
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 1, 2, 3, 4, 5, 6});
std::shared_ptr<Database> database = Database::GetDatabaseByName("WhereEvalDatabase");
auto& table = database->GetTables().at("TableA");
// ColA testing for correct sort
auto& blocksColA =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColA").get())->GetBlocksList();
std::vector<int32_t> dataColA;
for (int i = 0; i < blocksColA.size(); i++)
{
for (int j = 0; j < blocksColA[i]->GetSize(); j++)
{
dataColA.push_back(blocksColA[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntASorted.size(), dataColA.size());
for (int i = 0; i < dataColA.size(); i++)
{
ASSERT_EQ(dataIntASorted[i], dataColA[i]);
}
// ColB testing for correct sort
auto& blocksColB =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColB").get())->GetBlocksList();
std::vector<int32_t> dataColB;
ASSERT_EQ(blocksColB.size(), 4);
for (int i = 0; i < blocksColB.size(); i++)
{
ASSERT_EQ(blocksColB[i]->GetSize(), 5);
for (int j = 0; j < blocksColB[i]->GetSize(); j++)
{
dataColB.push_back(blocksColB[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntBSorted.size(), dataColB.size());
for (int i = 0; i < dataColB.size(); i++)
{
ASSERT_EQ(dataIntBSorted[i], dataColB[i]);
}
// ColC testing for correct sort
auto& blocksColC =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColC").get())->GetBlocksList();
std::vector<int32_t> dataColC;
for (int i = 0; i < blocksColC.size(); i++)
{
for (int j = 0; j < blocksColC[i]->GetSize(); j++)
{
dataColC.push_back(blocksColC[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntCSorted.size(), dataColC.size());
for (int i = 0; i < dataColC.size(); i++)
{
ASSERT_EQ(dataIntCSorted[i], dataColC[i]);
}
// ColD testing for correct sort
auto& blocksColD =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColD").get())->GetBlocksList();
std::vector<int32_t> dataColD;
for (int i = 0; i < blocksColD.size(); i++)
{
for (int j = 0; j < blocksColD[i]->GetSize(); j++)
{
dataColD.push_back(blocksColD[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntDSorted.size(), dataColD.size());
for (int i = 0; i < dataColD.size(); i++)
{
ASSERT_EQ(dataIntDSorted[i], dataColD[i]);
}
GpuSqlCustomParser parser(Database::GetDatabaseByName("WhereEvalDatabase"),
"SELECT ColA FROM TableA WHERE (ColA >= 10 AND ColA < 50) AND ((5 < "
"(ColB + ColC)) AND SIN(ColD));");
resultPtr = parser.Parse();
LoadColHelper& loadColHelper = LoadColHelper::getInstance();
ASSERT_EQ(loadColHelper.countSkippedBlocks,
Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 2 : 0);
GpuSqlCustomParser parserDropDatabase(nullptr, "DROP DATABASE WhereEvalDatabase;");
resultPtr = parserDropDatabase.Parse();
}
TEST(DispatcherTests, WhereEvaluationAdvanced_FourTimesAnd)
{
GpuSqlCustomParser parserCreateDatabase(nullptr, "CREATE DATABASE WhereEvalDatabase 10;");
auto resultPtr = parserCreateDatabase.Parse();
GpuSqlCustomParser parserCreateTable(Database::GetDatabaseByName("WhereEvalDatabase"),
"CREATE TABLE TableA (ColA INT, ColB INT, ColC INT, ColD "
"INT, INDEX IndA(ColA, ColB, ColC));");
resultPtr = parserCreateTable.Parse();
std::vector<int32_t> dataIntA(
{1, 2, 3, 4, 5, 12, 17, 16, 19, 20, 1, 5, 3, 4, 2, 40, 150, 59, 110, 70});
std::vector<int32_t> dataIntB({4, 10, 1, 2, 3, 1, 3, 2, 3, 2, 7, 1, 1, 2, 10, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntC({6, 8, 1, 2, 1, 1, 3, 1, 4, 1, 7, 3, 2, 1, 6, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntD(
{1, 4, 5, 8, 10, 20, 40, 30, 50, 1, 2, 9, 6, 7, 3, 2, 6, 3, 5, 4});
for (int32_t i = 0; i < dataIntA.size(); i++)
{
GpuSqlCustomParser parserInsertInto(
Database::GetDatabaseByName("WhereEvalDatabase"),
"INSERT INTO TableA (ColA, ColB, ColC, ColD) VALUES (" +
GetInsertIntoValuesString({dataIntA, dataIntB, dataIntC, dataIntD}, i) + ");");
resultPtr = parserInsertInto.Parse();
}
std::vector<int32_t> dataIntASorted(
{1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 12, 16, 17, 19, 20, 40, 59, 70, 110, 150});
std::vector<int32_t> dataIntBSorted(
{4, 7, 10, 10, 1, 1, 2, 2, 1, 3, 1, 2, 3, 3, 2, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntCSorted(
{6, 7, 6, 8, 1, 2, 1, 2, 3, 1, 1, 1, 3, 4, 1, 1, 1, 1, 1, 1});
std::vector<int32_t> dataIntDSorted(
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 1, 2, 3, 4, 5, 6});
std::shared_ptr<Database> database = Database::GetDatabaseByName("WhereEvalDatabase");
auto& table = database->GetTables().at("TableA");
// ColA testing for correct sort
auto& blocksColA =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColA").get())->GetBlocksList();
std::vector<int32_t> dataColA;
for (int i = 0; i < blocksColA.size(); i++)
{
for (int j = 0; j < blocksColA[i]->GetSize(); j++)
{
dataColA.push_back(blocksColA[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntASorted.size(), dataColA.size());
for (int i = 0; i < dataColA.size(); i++)
{
ASSERT_EQ(dataIntASorted[i], dataColA[i]);
}
// ColB testing for correct sort
auto& blocksColB =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColB").get())->GetBlocksList();
std::vector<int32_t> dataColB;
ASSERT_EQ(blocksColB.size(), 4);
for (int i = 0; i < blocksColB.size(); i++)
{
ASSERT_EQ(blocksColB[i]->GetSize(), 5);
for (int j = 0; j < blocksColB[i]->GetSize(); j++)
{
dataColB.push_back(blocksColB[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntBSorted.size(), dataColB.size());
for (int i = 0; i < dataColB.size(); i++)
{
ASSERT_EQ(dataIntBSorted[i], dataColB[i]);
}
// ColC testing for correct sort
auto& blocksColC =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColC").get())->GetBlocksList();
std::vector<int32_t> dataColC;
for (int i = 0; i < blocksColC.size(); i++)
{
for (int j = 0; j < blocksColC[i]->GetSize(); j++)
{
dataColC.push_back(blocksColC[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntCSorted.size(), dataColC.size());
for (int i = 0; i < dataColC.size(); i++)
{
ASSERT_EQ(dataIntCSorted[i], dataColC[i]);
}
// ColD testing for correct sort
auto& blocksColD =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColD").get())->GetBlocksList();
std::vector<int32_t> dataColD;
for (int i = 0; i < blocksColD.size(); i++)
{
for (int j = 0; j < blocksColD[i]->GetSize(); j++)
{
dataColD.push_back(blocksColD[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntDSorted.size(), dataColD.size());
for (int i = 0; i < dataColD.size(); i++)
{
ASSERT_EQ(dataIntDSorted[i], dataColD[i]);
}
GpuSqlCustomParser parser(Database::GetDatabaseByName("WhereEvalDatabase"),
"SELECT COUNT(ColA) FROM TableA WHERE ColB >= 2 AND ColB <=3 AND "
"ColC>=4 AND ColC <= 8 GROUP BY(ColA);");
resultPtr = parser.Parse();
LoadColHelper& loadColHelper = LoadColHelper::getInstance();
ASSERT_EQ(loadColHelper.countSkippedBlocks,
Configuration::GetInstance().IsUsingWhereEvaluationSpeedup() ? 2 : 0);
GpuSqlCustomParser parserDropDatabase(nullptr, "DROP DATABASE WhereEvalDatabase;");
resultPtr = parserDropDatabase.Parse();
}
TEST(DispatcherTests, WhereEvaluationAdvanced_FilterColCol)
{
GpuSqlCustomParser parserCreateDatabase(nullptr, "CREATE DATABASE WhereEvalDatabase 10;");
auto resultPtr = parserCreateDatabase.Parse();
GpuSqlCustomParser parserCreateTable(Database::GetDatabaseByName("WhereEvalDatabase"),
"CREATE TABLE TableA (ColA INT, ColB INT, INDEX "
"IndA(ColA, ColB));");
resultPtr = parserCreateTable.Parse();
std::vector<int32_t> dataIntA({2, 3, 13});
std::vector<int32_t> dataIntB({1, 5, 10});
for (int32_t i = 0; i < dataIntA.size(); i++)
{
GpuSqlCustomParser parserInsertInto(Database::GetDatabaseByName("WhereEvalDatabase"),
"INSERT INTO TableA (ColA, ColB) VALUES (" +
GetInsertIntoValuesString({dataIntA, dataIntB}, i) + ");");
resultPtr = parserInsertInto.Parse();
}
std::shared_ptr<Database> database = Database::GetDatabaseByName("WhereEvalDatabase");
auto& table = database->GetTables().at("TableA");
// ColA testing for correct sort
auto& blocksColA =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColA").get())->GetBlocksList();
std::vector<int32_t> dataColA;
for (int i = 0; i < blocksColA.size(); i++)
{
for (int j = 0; j < blocksColA[i]->GetSize(); j++)
{
dataColA.push_back(blocksColA[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntA.size(), dataColA.size());
for (int i = 0; i < dataColA.size(); i++)
{
ASSERT_EQ(dataIntA[i], dataColA[i]);
}
// ColB testing for correct sort
auto& blocksColB =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("ColB").get())->GetBlocksList();
std::vector<int32_t> dataColB;
for (int i = 0; i < blocksColB.size(); i++)
{
for (int j = 0; j < blocksColB[i]->GetSize(); j++)
{
dataColB.push_back(blocksColB[i]->GetData()[j]);
}
}
ASSERT_EQ(dataIntB.size(), dataColB.size());
for (int i = 0; i < dataColB.size(); i++)
{
ASSERT_EQ(dataIntB[i], dataColB[i]);
}
GpuSqlCustomParser parser(Database::GetDatabaseByName("WhereEvalDatabase"),
"SELECT ColA FROM TableA WHERE ColA <= ColB;");
resultPtr = parser.Parse();
LoadColHelper& loadColHelper = LoadColHelper::getInstance();
ASSERT_EQ(loadColHelper.countSkippedBlocks, 0);
GpuSqlCustomParser parserDropDatabase(nullptr, "DROP DATABASE WhereEvalDatabase;");
resultPtr = parserDropDatabase.Parse();
}
template <typename T>
struct IdxKeyPair
{
int32_t index;
T key;
};
template <typename T>
struct Asc
{
inline bool operator()(const IdxKeyPair<T>& struct1, const IdxKeyPair<T>& struct2)
{
return (struct1.key < struct2.key);
}
};
template <typename T>
struct Desc
{
inline bool operator()(const IdxKeyPair<T>& struct1, const IdxKeyPair<T>& struct2)
{
return (struct1.key > struct2.key);
}
};
TEST(DispatcherTests, OrderByTestSimple)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA ORDER BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int32_t i = 0; i < result->payloads().at("TableA.colInteger1").intpayload().intdata_size(); i++)
expectedResultsInt.push_back(result->payloads().at("TableA.colInteger1").intpayload().intdata()[i]);
std::vector<IdxKeyPair<int32_t>> v(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
for (int i = 0, k = 0; i < TEST_BLOCK_COUNT; i++)
for (int j = 0; j < TEST_BLOCK_SIZE; j++, k++)
v[k] = {0, columnInt->GetBlocksList()[i]->GetData()[j]};
stable_sort(v.begin(), v.end(), Asc<int32_t>());
for (int i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
{
ASSERT_EQ(expectedResultsInt[i], v[i].key) << i;
}
}
TEST(DispatcherTests, OrderByLimitOffsetTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA ORDER BY colInteger1 LIMIT 20 OFFSET "
"2040;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int32_t i = 0; i < result->payloads().at("TableA.colInteger1").intpayload().intdata_size(); i++)
{
expectedResultsInt.push_back(result->payloads().at("TableA.colInteger1").intpayload().intdata()[i]);
}
std::vector<IdxKeyPair<int32_t>> v(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
for (int i = 0, k = 0; i < TEST_BLOCK_COUNT; i++)
{
for (int j = 0; j < TEST_BLOCK_SIZE; j++, k++)
{
v[k] = {0, columnInt->GetBlocksList()[i]->GetData()[j]};
}
}
auto limit = 20;
auto offset = 2040;
stable_sort(v.begin(), v.end(), Asc<int32_t>());
auto first = v.begin() + offset;
auto last = v.begin() + offset + limit;
std::vector<IdxKeyPair<int32_t>> trimmedResultsInt(first, last);
for (int i = 0; i < expectedResultsInt.size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], trimmedResultsInt[i].key) << i;
}
}
TEST(DispatcherTests, OrderByTestMulticolumnMultitype)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, colDouble1 FROM TableA ORDER BY colInteger1 "
"ASC, colLong1 DESC, colFloat1 ASC, colDouble1 DESC;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto dataIn1 = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get())
->GetBlocksList();
auto dataIn2 = dynamic_cast<ColumnBase<int64_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colLong1")
.get())
->GetBlocksList();
auto dataIn3 = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get())
->GetBlocksList();
auto dataIn4 = dynamic_cast<ColumnBase<double>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colDouble1")
.get())
->GetBlocksList();
// Get the expected results
std::vector<int32_t> expectedResultsInt;
std::vector<double> expectedResultsDouble;
for (int32_t i = 0; i < result->payloads().at("TableA.colInteger1").intpayload().intdata_size(); i++)
expectedResultsInt.push_back(result->payloads().at("TableA.colInteger1").intpayload().intdata()[i]);
for (int32_t i = 0; i < result->payloads().at("TableA.colDouble1").doublepayload().doubledata_size(); i++)
expectedResultsDouble.push_back(
result->payloads().at("TableA.colDouble1").doublepayload().doubledata()[i]);
// Temp buffers for sort on the CPU
std::vector<int32_t> data1(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<int64_t> data2(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<float> data3(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<double> data4(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<int32_t>> v1(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<int64_t>> v2(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<float>> v3(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<double>> v4(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<int32_t> indices(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = i;
// Sort 4th col
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
data4[i] = dataIn4[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v4[i] = {indices[i], data4[i]};
stable_sort(v4.begin(), v4.end(), Desc<double>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v4[i].index;
// Sort 3th col
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
data3[i] = dataIn3[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v3[i] = {indices[i], data3[i]};
stable_sort(v3.begin(), v3.end(), Asc<float>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v3[i].index;
// Sort 2th col
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
data2[i] = dataIn2[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v2[i] = {indices[i], data2[i]};
stable_sort(v2.begin(), v2.end(), Desc<int64_t>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v2[i].index;
// Sort 1th col
for (int32_t i = 0; i < TEST_BLOCK_COUNT * TEST_BLOCK_SIZE; i++)
data1[i] = dataIn1[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v1[i] = {indices[i], data1[i]};
stable_sort(v1.begin(), v1.end(), Asc<int32_t>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v1[i].index;
// Reorder the output data
std::vector<int32_t> resultsInt(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<double> resultsDouble(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
{
resultsInt[i] = dataIn1[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
resultsDouble[i] = dataIn4[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
}
// Compare the results with the parser results
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
{
ASSERT_EQ(resultsInt[i], expectedResultsInt[i]);
ASSERT_FLOAT_EQ(resultsDouble[i], expectedResultsDouble[i]);
}
}
TEST(DispatcherTests, OrderByAliasTestMulticolumnMultitype)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, colDouble1 FROM TableA ORDER BY 1 "
"ASC, colLong1 DESC, colFloat1 ASC, 2 DESC;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto dataIn1 = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get())
->GetBlocksList();
auto dataIn2 = dynamic_cast<ColumnBase<int64_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colLong1")
.get())
->GetBlocksList();
auto dataIn3 = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get())
->GetBlocksList();
auto dataIn4 = dynamic_cast<ColumnBase<double>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colDouble1")
.get())
->GetBlocksList();
// Get the expected results
std::vector<int32_t> expectedResultsInt;
std::vector<double> expectedResultsDouble;
for (int32_t i = 0; i < result->payloads().at("TableA.colInteger1").intpayload().intdata_size(); i++)
expectedResultsInt.push_back(result->payloads().at("TableA.colInteger1").intpayload().intdata()[i]);
for (int32_t i = 0; i < result->payloads().at("TableA.colDouble1").doublepayload().doubledata_size(); i++)
expectedResultsDouble.push_back(
result->payloads().at("TableA.colDouble1").doublepayload().doubledata()[i]);
// Temp buffers for sort on the CPU
std::vector<int32_t> data1(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<int64_t> data2(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<float> data3(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<double> data4(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<int32_t>> v1(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<int64_t>> v2(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<float>> v3(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<IdxKeyPair<double>> v4(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<int32_t> indices(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = i;
// Sort 4th col
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
data4[i] = dataIn4[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v4[i] = {indices[i], data4[i]};
stable_sort(v4.begin(), v4.end(), Desc<double>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v4[i].index;
// Sort 3th col
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
data3[i] = dataIn3[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v3[i] = {indices[i], data3[i]};
stable_sort(v3.begin(), v3.end(), Asc<float>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v3[i].index;
// Sort 2th col
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
data2[i] = dataIn2[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v2[i] = {indices[i], data2[i]};
stable_sort(v2.begin(), v2.end(), Desc<int64_t>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v2[i].index;
// Sort 1th col
for (int32_t i = 0; i < TEST_BLOCK_COUNT * TEST_BLOCK_SIZE; i++)
data1[i] = dataIn1[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
v1[i] = {indices[i], data1[i]};
stable_sort(v1.begin(), v1.end(), Asc<int32_t>());
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
indices[i] = v1[i].index;
// Reorder the output data
std::vector<int32_t> resultsInt(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
std::vector<double> resultsDouble(TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
{
resultsInt[i] = dataIn1[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
resultsDouble[i] = dataIn4[indices[i] / TEST_BLOCK_SIZE]->GetData()[indices[i] % TEST_BLOCK_SIZE];
}
// Compare the results with the parser results
for (int32_t i = 0; i < (TEST_BLOCK_COUNT * TEST_BLOCK_SIZE); i++)
{
ASSERT_EQ(resultsInt[i], expectedResultsInt[i]);
ASSERT_FLOAT_EQ(resultsDouble[i], expectedResultsDouble[i]);
}
}
TEST(DispatcherTests, JoinSimpleTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA JOIN TableB ON colInteger1 = "
"colInteger3;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::cout
<< "Result size: " << result->payloads().at("TableA.colInteger1").intpayload().intdata().size()
<< std::endl;
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
std::vector<int32_t> expectedResults;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx])
{
expectedResults.push_back(leftBlock->GetData()[leftRowIdx]);
}
}
}
}
}
auto payloads = result->payloads().at("TableA.colInteger1");
std::vector<int32_t> payloadVector(payloads.intpayload().intdata().begin(),
payloads.intpayload().intdata().end());
std::sort(expectedResults.begin(), expectedResults.end());
std::sort(payloadVector.begin(), payloadVector.end());
ASSERT_EQ(payloads.intpayload().intdata().size(), expectedResults.size());
for (int32_t i = 0; i < expectedResults.size(); i++)
{
ASSERT_EQ(expectedResults[i], payloadVector[i]);
}
}
TEST(DispatcherTests, JoinWhereTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 FROM TableA JOIN TableB ON colInteger1 = "
"colInteger3 WHERE colFloat1 < 200;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::cout
<< "Result size: " << result->payloads().at("TableA.colInteger1").intpayload().intdata().size()
<< std::endl;
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto leftColFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
std::vector<int32_t> expectedResults;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
auto leftBlockFloat = leftColFloat->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlockFloat->GetData()[leftRowIdx] < 200 &&
leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx])
{
expectedResults.push_back(leftBlock->GetData()[leftRowIdx]);
}
}
}
}
}
auto payloads = result->payloads().at("TableA.colInteger1");
std::vector<int32_t> payloadVector(payloads.intpayload().intdata().begin(),
payloads.intpayload().intdata().end());
std::sort(expectedResults.begin(), expectedResults.end());
std::sort(payloadVector.begin(), payloadVector.end());
ASSERT_EQ(payloads.intpayload().intdata().size(), expectedResults.size());
for (int32_t i = 0; i < expectedResults.size(); i++)
{
ASSERT_EQ(expectedResults[i], payloadVector[i]);
}
}
TEST(DispatcherTests, JoinGroupByTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, COUNT(colInteger1) FROM TableA JOIN TableB ON "
"colInteger1 = colInteger3 GROUP BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::cout
<< "Result size: " << result->payloads().at("TableA.colInteger1").intpayload().intdata().size()
<< std::endl;
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto leftColFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
std::unordered_map<int32_t, int32_t> expectedResults;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx])
{
if (expectedResults.find(leftBlock->GetData()[leftRowIdx]) ==
expectedResults.end())
{
expectedResults.insert({leftBlock->GetData()[leftRowIdx], 1});
}
else
{
expectedResults.at(leftBlock->GetData()[leftRowIdx])++;
}
}
}
}
}
}
auto payloadsKeys = result->payloads().at("TableA.colInteger1");
auto payloadsValues = result->payloads().at("COUNT(colInteger1)");
ASSERT_EQ(payloadsKeys.intpayload().intdata().size(), expectedResults.size());
ASSERT_EQ(payloadsValues.int64payload().int64data().size(), expectedResults.size());
for (int32_t i = 0; i < payloadsKeys.intpayload().intdata().size(); i++)
{
ASSERT_TRUE(expectedResults.find(payloadsKeys.intpayload().intdata()[i]) != expectedResults.end());
ASSERT_EQ(expectedResults.at(payloadsKeys.intpayload().intdata()[i]),
payloadsValues.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, JoinGroupByWhereTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, COUNT(colInteger1) FROM TableA JOIN TableB ON "
"colInteger1 = colInteger3 WHERE colFloat1 < 200 GROUP BY "
"colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::cout
<< "Result size: " << result->payloads().at("TableA.colInteger1").intpayload().intdata().size()
<< std::endl;
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto leftColFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
std::unordered_map<int32_t, int32_t> expectedResults;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
auto leftBlockFloat = leftColFloat->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlockFloat->GetData()[leftRowIdx] < 200 &&
leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx])
{
if (expectedResults.find(leftBlock->GetData()[leftRowIdx]) ==
expectedResults.end())
{
expectedResults.insert({leftBlock->GetData()[leftRowIdx], 1});
}
else
{
expectedResults.at(leftBlock->GetData()[leftRowIdx])++;
}
}
}
}
}
}
auto payloadsKeys = result->payloads().at("TableA.colInteger1");
auto payloadsValues = result->payloads().at("COUNT(colInteger1)");
ASSERT_EQ(payloadsKeys.intpayload().intdata().size(), expectedResults.size());
ASSERT_EQ(payloadsValues.int64payload().int64data().size(), expectedResults.size());
for (int32_t i = 0; i < payloadsKeys.intpayload().intdata().size(); i++)
{
ASSERT_TRUE(expectedResults.find(payloadsKeys.intpayload().intdata()[i]) != expectedResults.end());
ASSERT_EQ(expectedResults.at(payloadsKeys.intpayload().intdata()[i]),
payloadsValues.int64payload().int64data()[i]);
}
}
TEST(DispatcherTests, JoinWhereStringTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colString1 FROM TableA JOIN TableB ON colInteger1 = "
"colInteger3 WHERE colFloat1 < 200;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::cout << "Result size: "
<< result->payloads().at("TableA.colString1").stringpayload().stringdata().size()
<< std::endl;
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto leftColFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
auto leftColString = dynamic_cast<ColumnBase<std::string>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colString1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
std::vector<std::string> expectedResults;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
auto leftBlockFloat = leftColFloat->GetBlocksList()[leftBlockIdx];
auto leftBlockString = leftColString->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlockFloat->GetData()[leftRowIdx] < 200 &&
leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx])
{
expectedResults.push_back(leftBlockString->GetData()[leftRowIdx]);
}
}
}
}
}
auto payloads = result->payloads().at("TableA.colString1");
std::vector<std::string> payloadVector(payloads.stringpayload().stringdata().begin(),
payloads.stringpayload().stringdata().end());
std::sort(expectedResults.begin(), expectedResults.end());
std::sort(payloadVector.begin(), payloadVector.end());
ASSERT_EQ(payloads.stringpayload().stringdata().size(), expectedResults.size());
for (int32_t i = 0; i < expectedResults.size(); i++)
{
ASSERT_EQ(expectedResults[i], payloadVector[i]);
}
}
TEST(DispatcherTests, CreateAlterDropTableWithDelimitedIdentifiers)
{
Context::getInstance();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA%^&*()-+") ==
DispatcherObjs::GetInstance().database->GetTables().end());
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"CREATE TABLE [tblA%^&*()-+] ([colA%^&*()-+] int, [colB%^&*()-+] "
"float, INDEX [ind%^&*()-+] ([colA%^&*()-+], [colB%^&*()-+]));");
auto resultPtr = parser.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA%^&*()-+") !=
DispatcherObjs::GetInstance().database->GetTables().end());
std::vector<std::string> expectedSortingColumns = {"colA%^&*()-+", "colB%^&*()-+"};
std::vector<std::string> resultSortingColumns =
DispatcherObjs::GetInstance().database->GetTables().at("tblA%^&*()-+").GetSortingColumns();
ASSERT_TRUE(expectedSortingColumns.size() == resultSortingColumns.size());
for (int i = 0; i < expectedSortingColumns.size(); i++)
{
ASSERT_TRUE(expectedSortingColumns[i] == resultSortingColumns[i]);
}
GpuSqlCustomParser parser2(DispatcherObjs::GetInstance().database,
"INSERT INTO [tblA%^&*()-+] ([colA%^&*()-+], [colB%^&*()-+]) VALUES "
"(1, 2.0);");
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parser2.Parse();
}
GpuSqlCustomParser parser3(DispatcherObjs::GetInstance().database,
"SELECT [colA%^&*()-+], [colB%^&*()-+] from [tblA%^&*()-+];");
resultPtr = parser3.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsColA;
std::vector<float> expectedResultsColB;
for (int k = 0; k < 5; k++)
{
expectedResultsColA.push_back(1);
expectedResultsColB.push_back(2.0);
}
auto& payloadsColA = result->payloads().at("tblA%^&*()-+.colA%^&*()-+");
auto& payloadsColB = result->payloads().at("tblA%^&*()-+.colB%^&*()-+");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), expectedResultsColA.size());
for (int i = 0; i < payloadsColA.intpayload().intdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColA[i], payloadsColA.intpayload().intdata()[i]);
}
ASSERT_EQ(payloadsColB.floatpayload().floatdata_size(), expectedResultsColB.size());
for (int i = 0; i < payloadsColB.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColB[i], payloadsColB.floatpayload().floatdata()[i]);
}
GpuSqlCustomParser parser4(DispatcherObjs::GetInstance().database,
"ALTER TABLE [tblA%^&*()-+] DROP COLUMN [colA%^&*()-+], ADD "
"[colC%^&*()-+] float;");
resultPtr = parser4.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().at("tblA%^&*()-+").GetColumns().find("colA%^&*()-+") ==
DispatcherObjs::GetInstance().database->GetTables().at("tblA%^&*()-+").GetColumns().end());
GpuSqlCustomParser parser5(DispatcherObjs::GetInstance().database,
"SELECT [colB%^&*()-+], [colC%^&*()-+] from [tblA%^&*()-+];");
resultPtr = parser5.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsColC;
for (int k = 0; k < 5; k++)
{
expectedResultsColC.push_back(0.0);
}
auto& payloadsColB2 = result->payloads().at("tblA%^&*()-+.colB%^&*()-+");
auto& payloadsColC = result->payloads().at("tblA%^&*()-+.colC%^&*()-+");
ASSERT_EQ(payloadsColB2.floatpayload().floatdata_size(), expectedResultsColB.size());
for (int i = 0; i < payloadsColB2.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsColB[i], payloadsColB2.floatpayload().floatdata()[i]);
}
ASSERT_EQ(payloadsColC.floatpayload().floatdata_size(), expectedResultsColC.size());
for (int i = 0; i < payloadsColC.floatpayload().floatdata_size(); i++)
{
ASSERT_TRUE(std::isnan(payloadsColC.floatpayload().floatdata()[i]));
}
GpuSqlCustomParser parser6(DispatcherObjs::GetInstance().database,
"DROP TABLE [tblA%^&*()-+];");
resultPtr = parser6.Parse();
ASSERT_TRUE(DispatcherObjs::GetInstance().database->GetTables().find("tblA%^&*()-+") ==
DispatcherObjs::GetInstance().database->GetTables().end());
}
//== Cast Tests ==
TEST(DispatcherTests, CastFloatColToInt)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT CAST(colFloat1 AS INT) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsInt.push_back(static_cast<int32_t>(blockFloat->GetData()[k]));
}
}
auto& payloadsInt = result->payloads().at("CAST(colFloat1ASINT)");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsInt[i], payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, CastIntColToFloat)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT CAST(colInteger1 AS FLOAT) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsFloat.push_back(static_cast<float>(blockInt->GetData()[k]));
}
}
auto& payloadsFloat = result->payloads().at("CAST(colInteger1ASFLOAT)");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(payloadsFloat.floatpayload().floatdata()[i], expectedResultsFloat[i]);
}
}
TEST(DispatcherTests, AliasWhereSimpleTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1 - 100 AS result FROM TableA WHERE result > 300;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<int32_t> expectedResultsInt;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockInt->GetData()[k] - 100 > 300)
{
expectedResultsInt.push_back(blockInt->GetData()[k] - 100);
}
}
}
auto& payloadsInt = result->payloads().at("result");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedResultsInt.size());
for (int i = 0; i < payloadsInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(payloadsInt.intpayload().intdata()[i], expectedResultsInt[i]);
}
}
TEST(DispatcherTests, AllColumnsWithDuplicatesTest)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT *, colInteger1, colFloat1, * FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
ASSERT_EQ(result->payloads().size(),
DispatcherObjs::GetInstance().database->GetTables().at("TableA").GetColumns().size());
for (auto& column : DispatcherObjs::GetInstance().database->GetTables().at("TableA").GetColumns())
{
std::string columnName = column.first;
switch (column.second->GetColumnType())
{
case COLUMN_INT:
{
auto col = dynamic_cast<ColumnBase<int32_t>*>(column.second.get());
std::vector<int32_t> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(block->GetData()[k]);
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.intpayload().intdata_size(), expectedResults.size());
for (int i = 0; i < payloads.intpayload().intdata_size(); i++)
{
ASSERT_EQ(payloads.intpayload().intdata()[i], expectedResults[i]);
}
}
break;
case COLUMN_LONG:
{
auto col = dynamic_cast<ColumnBase<int64_t>*>(column.second.get());
std::vector<int64_t> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(block->GetData()[k]);
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.int64payload().int64data_size(), expectedResults.size());
for (int i = 0; i < payloads.int64payload().int64data_size(); i++)
{
ASSERT_EQ(payloads.int64payload().int64data()[i], expectedResults[i]);
}
}
break;
case COLUMN_FLOAT:
{
auto col = dynamic_cast<ColumnBase<float>*>(column.second.get());
std::vector<float> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(block->GetData()[k]);
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.floatpayload().floatdata_size(), expectedResults.size());
for (int i = 0; i < payloads.floatpayload().floatdata_size(); i++)
{
ASSERT_EQ(payloads.floatpayload().floatdata()[i], expectedResults[i]);
}
}
break;
case COLUMN_DOUBLE:
{
auto col = dynamic_cast<ColumnBase<double>*>(column.second.get());
std::vector<double> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(block->GetData()[k]);
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.doublepayload().doubledata_size(), expectedResults.size());
for (int i = 0; i < payloads.doublepayload().doubledata_size(); i++)
{
ASSERT_EQ(payloads.doublepayload().doubledata()[i], expectedResults[i]);
}
}
break;
case COLUMN_POINT:
{
auto col = dynamic_cast<ColumnBase<QikkDB::Types::Point>*>(column.second.get());
std::vector<std::string> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(PointFactory::WktFromPoint(block->GetData()[k], true));
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResults.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(payloads.stringpayload().stringdata()[i], expectedResults[i]);
}
}
break;
case COLUMN_POLYGON:
{
auto col = dynamic_cast<ColumnBase<QikkDB::Types::ComplexPolygon>*>(column.second.get());
std::vector<std::string> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(ComplexPolygonFactory::WktFromPolygon(block->GetData()[k], true));
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResults.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(payloads.stringpayload().stringdata()[i], expectedResults[i]);
}
}
break;
case COLUMN_STRING:
{
auto col = dynamic_cast<ColumnBase<std::string>*>(column.second.get());
std::vector<std::string> expectedResults;
for (int i = 0; i < col->GetBlockCount(); i++)
{
auto block = col->GetBlocksList()[i];
for (int k = 0; k < block->GetSize(); k++)
{
expectedResults.push_back(block->GetData()[k]);
}
}
auto& payloads = result->payloads().at("TableA." + columnName);
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResults.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(payloads.stringpayload().stringdata()[i], expectedResults[i]);
}
}
break;
default:
break;
}
}
}
//== String Where Evaluation ==
TEST(DispatcherTests, StringLeftWhereColConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE LEFT(colString1, 4) = \"Word\";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colString1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockString = columnString->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if (blockString->GetData()[k].substr(0, 4) == "Word")
{
expectedResultsFloat.push_back(blockFloat->GetData()[k]);
}
}
}
auto& payloadsFloat = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, StringConcatLeftWhereColConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colFloat1 FROM TableA WHERE CONCAT(\"Concat\", "
"LEFT(colString1, 4)) = \"ConcatWord\";");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<float> expectedResultsFloat;
auto columnString = dynamic_cast<ColumnBase<std::string>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colString1")
.get());
auto columnFloat = dynamic_cast<ColumnBase<float>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colFloat1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockString = columnString->GetBlocksList()[i];
auto blockFloat = columnFloat->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
if ("Concat" + blockString->GetData()[k].substr(0, 4) == "ConcatWord")
{
expectedResultsFloat.push_back(blockFloat->GetData()[k]);
}
}
}
auto& payloadsFloat = result->payloads().at("TableA.colFloat1");
ASSERT_EQ(payloadsFloat.floatpayload().floatdata_size(), expectedResultsFloat.size());
for (int i = 0; i < payloadsFloat.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsFloat[i], payloadsFloat.floatpayload().floatdata()[i]);
}
}
TEST(DispatcherTests, RetConst)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database, "SELECT 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
const int32_t expectedSize = 2 * (1 << 11);
auto& payloadsInt = result->payloads().at("5");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedSize);
for (int i = 0; i < expectedSize; i++)
{
ASSERT_EQ(5, payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, RetConstWithFilter)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT 5 FROM TableA WHERE 500 < colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
int32_t expectedSize = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (1 << 11); j++)
{
if (j % 2)
{
if (500 < j % 1024)
{
++expectedSize;
}
}
else
{
if (500 < (j % 1024) * -1)
{
++expectedSize;
}
}
}
}
auto& payloadsInt = result->payloads().at("5");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedSize);
for (int i = 0; i < expectedSize; i++)
{
ASSERT_EQ(5, payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, RetConstWithColumn)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colInteger1, 5 FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
const int32_t expectedSize = 2 * (1 << 11);
auto& payloadsInt = result->payloads().at("5");
ASSERT_EQ(payloadsInt.intpayload().intdata_size(), expectedSize);
for (int i = 0; i < expectedSize; i++)
{
ASSERT_EQ(5, payloadsInt.intpayload().intdata()[i]);
}
}
TEST(DispatcherTests, RetConstString)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT \"test\" FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
const int32_t expectedSize = 2 * (1 << 11);
auto& payloadsStr = result->payloads().at("\"test\"");
ASSERT_EQ(payloadsStr.stringpayload().stringdata_size(), expectedSize);
for (int i = 0; i < expectedSize; i++)
{
ASSERT_EQ("test", payloadsStr.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, RetConstJoin)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT 5 FROM TableA JOIN TableB ON colInteger1 = "
"colInteger3;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
int32_t expectedResultCount = 0;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx])
{
expectedResultCount++;
}
}
}
}
}
auto payloads = result->payloads().at("5");
ASSERT_EQ(payloads.intpayload().intdata().size(), expectedResultCount);
for (int32_t i = 0; i < expectedResultCount; i++)
{
ASSERT_EQ(payloads.intpayload().intdata()[i], 5);
}
}
TEST(DispatcherTests, ReorderStringOrderBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colString1 FROM TableA ORDER BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto columnString = dynamic_cast<ColumnBase<std::string>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colString1")
.get());
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
std::vector<std::pair<std::string, std::int32_t>> intStringPairs;
for (int i = 0; i < 2; i++)
{
auto blockString = columnString->GetBlocksList()[i];
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
intStringPairs.push_back({blockString->GetData()[k], blockInt->GetData()[k]});
}
}
std::stable_sort(intStringPairs.begin(), intStringPairs.end(),
[](const std::pair<std::string, std::int32_t>& a,
const std::pair<std::string, std::int32_t>& b) -> bool {
return a.second < b.second;
});
auto& payloadsString = result->payloads().at("TableA.colString1");
ASSERT_EQ(payloadsString.stringpayload().stringdata_size(), intStringPairs.size());
for (int i = 0; i < payloadsString.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(intStringPairs[i].first, payloadsString.stringpayload().stringdata()[i]);
}
}
TEST(DispatcherTests, ReorderPolygonOrderBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colPolygon1 FROM TableA ORDER BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::pair<std::string, int32_t>> expectedResultsPolygons;
auto columnPolygon =
dynamic_cast<ColumnBase<QikkDB::Types::ComplexPolygon>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colPolygon1")
.get());
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockPolygon = columnPolygon->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsPolygons.push_back(
{ComplexPolygonFactory::WktFromPolygon(blockPolygon->GetData()[k], true),
blockInt->GetData()[k]});
}
}
std::stable_sort(expectedResultsPolygons.begin(), expectedResultsPolygons.end(),
[](const std::pair<std::string, std::int32_t>& a,
const std::pair<std::string, std::int32_t>& b) -> bool {
return a.second < b.second;
});
auto& payloads = result->payloads().at("TableA.colPolygon1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPolygons.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPolygons[i].first, payloads.stringpayload().stringdata()[i]) << i;
}
}
TEST(DispatcherTests, ReorderPointOrderBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT colPoint1 FROM TableA ORDER BY colInteger1;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
std::vector<std::pair<std::string, int32_t>> expectedResultsPoints;
auto columnPoint = dynamic_cast<ColumnBase<QikkDB::Types::Point>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colPoint1")
.get());
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < 2; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
auto blockPoint = columnPoint->GetBlocksList()[i];
for (int k = 0; k < (1 << 11); k++)
{
expectedResultsPoints.push_back(
{PointFactory::WktFromPoint(blockPoint->GetData()[k], true), blockInt->GetData()[k]});
}
}
std::stable_sort(expectedResultsPoints.begin(), expectedResultsPoints.end(),
[](const std::pair<std::string, std::int32_t>& a,
const std::pair<std::string, std::int32_t>& b) -> bool {
return a.second < b.second;
});
auto& payloads = result->payloads().at("TableA.colPoint1");
ASSERT_EQ(payloads.stringpayload().stringdata_size(), expectedResultsPoints.size());
for (int i = 0; i < payloads.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsPoints[i].first, payloads.stringpayload().stringdata()[i]) << i;
}
}
TEST(DispatcherTests, AggregationCountAsteriskNoGroupBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(*) FROM TableA;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(*)");
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], TEST_BLOCK_COUNT * TEST_BLOCK_SIZE);
}
TEST(DispatcherTests, AggregationCountAsteriskWhereNoGroupBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(*) FROM TableA WHERE colInteger1 > 512;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloads = result->payloads().at("COUNT(*)");
int64_t outSize = 0;
auto columnInt = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
for (int i = 0; i < TEST_BLOCK_COUNT; i++)
{
auto blockInt = columnInt->GetBlocksList()[i];
for (int k = 0; k < blockInt->GetSize(); k++)
{
if (blockInt->GetData()[k] > 512)
{
outSize++;
}
}
}
ASSERT_EQ(payloads.int64payload().int64data_size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], outSize);
}
TEST(DispatcherTests, AggregationCountAsterisJoinWhereNoGroupBy)
{
Context::getInstance();
GpuSqlCustomParser parser(DispatcherObjs::GetInstance().database,
"SELECT COUNT(*) FROM TableA JOIN TableB ON colInteger1 = "
"colInteger3 WHERE colInteger1 > 512;");
auto resultPtr = parser.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto leftCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableA")
.GetColumns()
.at("colInteger1")
.get());
auto rightCol = dynamic_cast<ColumnBase<int32_t>*>(DispatcherObjs::GetInstance()
.database->GetTables()
.at("TableB")
.GetColumns()
.at("colInteger3")
.get());
int32_t expectedResultCount = 0;
for (int32_t leftBlockIdx = 0; leftBlockIdx < leftCol->GetBlockCount(); leftBlockIdx++)
{
auto leftBlock = leftCol->GetBlocksList()[leftBlockIdx];
for (int32_t leftRowIdx = 0; leftRowIdx < leftBlock->GetSize(); leftRowIdx++)
{
for (int32_t rightBlockIdx = 0; rightBlockIdx < rightCol->GetBlockCount(); rightBlockIdx++)
{
auto rightBlock = rightCol->GetBlocksList()[rightBlockIdx];
for (int32_t rightRowIdx = 0; rightRowIdx < rightBlock->GetSize(); rightRowIdx++)
{
if (leftBlock->GetData()[leftRowIdx] == rightBlock->GetData()[rightRowIdx] &&
leftBlock->GetData()[leftRowIdx] > 512)
{
expectedResultCount++;
}
}
}
}
}
auto payloads = result->payloads().at("COUNT(*)");
ASSERT_EQ(payloads.int64payload().int64data().size(), 1);
ASSERT_EQ(payloads.int64payload().int64data()[0], expectedResultCount);
}
TEST(DispatcherTests, AlterTableAlterColumnIntToFloat)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterIntToFloat 10;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterIntToFloat");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (col int);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (col) VALUES (1);");
std::vector<float> expectedResultsCol;
for (int32_t i = 0; i < 22; i++)
{
resultPtr = parser2.Parse();
expectedResultsCol.push_back(static_cast<float>(1));
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN col float;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_FLOAT);
GpuSqlCustomParser parser4(database, "SELECT col from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.col");
ASSERT_EQ(payloadsCol.floatpayload().floatdata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.floatpayload().floatdata_size(); i++)
{
ASSERT_FLOAT_EQ(expectedResultsCol[i], payloadsCol.floatpayload().floatdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterIntToFloat;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnPointToString)
{
GpuSqlCustomParser createDatabase(nullptr,
"CREATE DATABASE TestDatabaseAlterPointToString 10;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterPointToString");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (col geo_point);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_POINT);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (col) VALUES (POINT(10.11 11.1));");
std::vector<std::string> expectedResultsCol;
for (int32_t i = 0; i < 22; i++)
{
resultPtr = parser2.Parse();
expectedResultsCol.push_back("POINT(10.11 11.1)");
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN col string;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser4(database, "SELECT col from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.col");
ASSERT_EQ(payloadsCol.stringpayload().stringdata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsCol[i], payloadsCol.stringpayload().stringdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterPointToString;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnPolygonToString)
{
GpuSqlCustomParser createDatabase(nullptr,
"CREATE DATABASE TestDatabaseAlterPolygonToString 10;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterPolygonToString");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (col geo_polygon);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_POLYGON);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (col) VALUES (POLYGON((10 11, "
"11.11 12.13, 10 11),(21 30, 35.55 36, 30.11 20.26, 21 "
"30),(61 80.11,90 89.15,112.12 110, 61 80.11)));");
std::vector<std::string> expectedResultsCol;
for (int32_t i = 0; i < 22; i++)
{
resultPtr = parser2.Parse();
expectedResultsCol.push_back("POLYGON((10 11, 11.11 12.13, 10 11), (21 30, 35.55 36, 30.11 "
"20.26, 21 30), (61 80.11, 90 89.15, 112.12 110, 61 80.11))");
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN col string;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser4(database, "SELECT col from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.col");
ASSERT_EQ(payloadsCol.stringpayload().stringdata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsCol[i], payloadsCol.stringpayload().stringdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterPolygonToString;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnStringToPolygon)
{
GpuSqlCustomParser createDatabase(nullptr,
"CREATE DATABASE TestDatabaseAlterStringToPolygon 3;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterStringToPolygon");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colP string, colS string);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser2(database,
"INSERT INTO testTable (colP, colS) VALUES (\"POLYGON((10 11, 11.11 "
"12.13, 10 11),(21 30, 35.55 36, 30.11 20.26, 21 30),(61 80.11,90 "
"89.15,112.12 110, 61 80.11))\", \"randomString\");");
std::vector<std::string> expectedResultsCol;
std::vector<std::string> expectedResultsColString;
for (int32_t i = 0; i < 7; i++)
{
resultPtr = parser2.Parse();
QikkDB::Types::ComplexPolygon polygon = ComplexPolygonFactory::FromWkt(
"POLYGON((10 11, 11.11 12.13, 10 11), (21 30, 35.55 36, 30.11 20.26, 21 30), (61 "
"80.11, 90 89.15, 112.12 110, 61 80.11))");
QikkDB::Types::ComplexPolygon emptyPolygon =
ComplexPolygonFactory::FromWkt(ColumnBase<QikkDB::Types::ComplexPolygon>::POLYGON_DEFAULT_VALUE);
expectedResultsCol.push_back(ComplexPolygonFactory::WktFromPolygon(polygon, true));
expectedResultsColString.push_back(ComplexPolygonFactory::WktFromPolygon(emptyPolygon, true));
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN colP geo_polygon;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_POLYGON);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser4(database, "SELECT colP from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.colP");
ASSERT_EQ(payloadsCol.stringpayload().stringdata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsCol[i], payloadsCol.stringpayload().stringdata()[i]);
}
///////
GpuSqlCustomParser parser5(database, "ALTER TABLE testTable ALTER COLUMN colS geo_polygon;");
resultPtr = parser5.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_POLYGON);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_POLYGON);
GpuSqlCustomParser parser6(database, "SELECT colS from testTable;");
resultPtr = parser6.Parse();
auto resultString =
dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColString = resultString->payloads().at("testTable.colS");
ASSERT_EQ(payloadsColString.stringpayload().stringdata_size(), expectedResultsColString.size());
for (int i = 0; i < payloadsColString.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsColString[i], payloadsColString.stringpayload().stringdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterStringToPolygon;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnStringToPoint)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterStringToPoint 3;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterStringToPoint");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colP string, colS string);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colP, colS) VALUES (\"POINT(11.5 "
"1.3)\", \"randomString\");");
std::vector<std::string> expectedResultsCol;
std::vector<std::string> expectedResultsColString;
for (int32_t i = 0; i < 7; i++)
{
resultPtr = parser2.Parse();
QikkDB::Types::Point point = PointFactory::FromWkt("POINT(11.5 1.3)");
QikkDB::Types::Point emptyPoint = QikkDB::Types::Point();
expectedResultsCol.push_back(PointFactory::WktFromPoint(point, true));
expectedResultsColString.push_back(PointFactory::WktFromPoint(emptyPoint, true));
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN colP geo_point;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_POINT);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser4(database, "SELECT colP from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.colP");
ASSERT_EQ(payloadsCol.stringpayload().stringdata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsCol[i], payloadsCol.stringpayload().stringdata()[i]);
}
///////
GpuSqlCustomParser parser5(database, "ALTER TABLE testTable ALTER COLUMN colS geo_point;");
resultPtr = parser5.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_POINT);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_POINT);
GpuSqlCustomParser parser6(database, "SELECT colS from testTable;");
resultPtr = parser6.Parse();
auto resultString =
dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColString = resultString->payloads().at("testTable.colS");
ASSERT_EQ(payloadsColString.stringpayload().stringdata_size(), expectedResultsColString.size());
for (int i = 0; i < payloadsColString.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultsColString[i], payloadsColString.stringpayload().stringdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterStringToPoint;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnStringToDouble)
{
GpuSqlCustomParser createDatabase(nullptr,
"CREATE DATABASE TestDatabaseAlterStringToDouble 3;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterStringToDouble");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colP string, colS string);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colP, colS) VALUES (\"2.5\", "
"\"randomString\");");
std::vector<double> expectedResultsCol;
// std::vector<double> expectedResultsColString;
for (int32_t i = 0; i < 7; i++)
{
resultPtr = parser2.Parse();
expectedResultsCol.push_back(2.5);
// expectedResultsColString.push_back(std::numeric_limits<double>::quiet_NaN());
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN colP double;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_DOUBLE);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser4(database, "SELECT colP from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.colP");
ASSERT_EQ(payloadsCol.doublepayload().doubledata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.doublepayload().doubledata_size(); i++)
{
ASSERT_EQ(expectedResultsCol[i], payloadsCol.doublepayload().doubledata()[i]);
}
///////
GpuSqlCustomParser parser5(database, "ALTER TABLE testTable ALTER COLUMN colS double;");
resultPtr = parser5.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_DOUBLE);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_DOUBLE);
GpuSqlCustomParser parser6(database, "SELECT colS from testTable;");
resultPtr = parser6.Parse();
auto resultString =
dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColString = resultString->payloads().at("testTable.colS");
for (int i = 0; i < payloadsColString.doublepayload().doubledata_size(); i++)
{
ASSERT_TRUE(std::isnan(payloadsColString.doublepayload().doubledata()[i]));
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterStringToDouble;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnStringToInt)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterStringToInt 3;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterStringToInt");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colP string, colS string);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colP, colS) VALUES (\"2\", "
"\"randomString\");");
std::vector<int32_t> expectedResultsCol;
std::vector<int32_t> expectedResultsColString;
for (int32_t i = 0; i < 7; i++)
{
resultPtr = parser2.Parse();
expectedResultsCol.push_back(2);
expectedResultsColString.push_back(std::numeric_limits<int32_t>::min());
}
GpuSqlCustomParser parser3(database, "ALTER TABLE testTable ALTER COLUMN colP int;");
resultPtr = parser3.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parser4(database, "SELECT colP from testTable;");
resultPtr = parser4.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.colP");
ASSERT_EQ(payloadsCol.intpayload().intdata_size(), expectedResultsCol.size());
for (int i = 0; i < payloadsCol.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsCol[i], payloadsCol.intpayload().intdata()[i]);
}
///////
GpuSqlCustomParser parser5(database, "ALTER TABLE testTable ALTER COLUMN colS int;");
resultPtr = parser5.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
type = table.GetColumns().at("colS")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
GpuSqlCustomParser parser6(database, "SELECT colS from testTable;");
resultPtr = parser6.Parse();
auto resultString =
dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColString = resultString->payloads().at("testTable.colS");
ASSERT_EQ(payloadsColString.intpayload().intdata_size(), expectedResultsColString.size());
for (int i = 0; i < payloadsColString.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultsColString[i], payloadsColString.intpayload().intdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterStringToInt;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnStringToBool)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterStringToBool 7;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterStringToBool");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colP string);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
std::vector<std::string> data = {"1", "0", "TRUE", "trUe", "FAlSE", "false",
"5", "ffaallsssee", "25", "-101", "3.6"};
std::vector<int8_t> convertedData = {1, 0, 1, 1, 0, 0, 1, std::numeric_limits<int8_t>::min(),
1, 1, 1};
for (int32_t i = 0; i < data.size(); i++)
{
GpuSqlCustomParser parserInsert(database, "INSERT INTO testTable (colP) VALUES (\"" + data[i] + "\");");
parserInsert.Parse();
}
GpuSqlCustomParser parserAlter(database, "ALTER TABLE testTable ALTER COLUMN colP BOOL;");
resultPtr = parserAlter.Parse();
type = table.GetColumns().at("colP")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT8_T);
GpuSqlCustomParser parserSelect(database, "SELECT colP from testTable;");
resultPtr = parserSelect.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsCol = result->payloads().at("testTable.colP");
ASSERT_EQ(payloadsCol.intpayload().intdata_size(), data.size());
for (int i = 0; i < payloadsCol.intpayload().intdata_size(); i++)
{
ASSERT_EQ(convertedData[i], payloadsCol.intpayload().intdata()[i]);
}
ASSERT_EQ(table.GetColumns().at("colP").get()->GetBlockCount(), 2);
ASSERT_EQ(table.GetColumns().at("colP").get()->GetNullBitMaskForBlock(0)[0], 0);
ASSERT_EQ(table.GetColumns().at("colP").get()->GetNullBitMaskForBlock(1)[0], 1);
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterStringToBool;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnBitmaskCopy)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterBitmaskCopy 10;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterBitmaskCopy");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (col int);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (col) VALUES (1);");
GpuSqlCustomParser parser3(database, "INSERT INTO testTable (col) VALUES (NULL);");
for (int32_t i = 0; i < 11; i++)
{
resultPtr = parser2.Parse();
resultPtr = parser3.Parse();
}
GpuSqlCustomParser parserSelect(database, "SELECT col from testTable;");
resultPtr = parserSelect.Parse();
auto resultInt =
dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColInt = resultInt->payloads().at("testTable.col");
ASSERT_EQ(payloadsColInt.intpayload().intdata_size(), 22);
for (int i = 0; i < 11; i += 2)
{
ASSERT_EQ(1, payloadsColInt.intpayload().intdata()[i]);
}
auto blocksBeforeCast =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("col").get())->GetBlocksList();
std::vector<std::unique_ptr<int64_t[]>> oldBitmasks;
for (int32_t i = 0; i < blocksBeforeCast.size(); i++)
{
size_t bitmaskSize = blocksBeforeCast[i]->GetNullBitmaskSize();
std::unique_ptr<int64_t[]> bitmask = std::make_unique<int64_t[]>(bitmaskSize);
std::copy(blocksBeforeCast[i]->GetNullBitmask(),
blocksBeforeCast[i]->GetNullBitmask() + bitmaskSize, bitmask.get());
oldBitmasks.push_back(std::move(bitmask));
}
GpuSqlCustomParser parser4(database, "ALTER TABLE testTable ALTER COLUMN col float;");
resultPtr = parser4.Parse();
type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_FLOAT);
auto blocksAfterCast =
dynamic_cast<ColumnBase<float>*>(table.GetColumns().at("col").get())->GetBlocksList();
for (int32_t i = 0; i < blocksAfterCast.size(); i++)
{
for (int32_t j = 0; j < blocksAfterCast[i]->GetSize(); j++)
{
int bitMaskIdx = NullValues::GetBitMaskIdx(j);
int shiftIdx = NullValues::GetShiftMaskIdx(j);
ASSERT_EQ((oldBitmasks[i][bitMaskIdx] >> shiftIdx) & 1,
(blocksAfterCast[i]->GetNullBitmask()[bitMaskIdx] >> shiftIdx) & 1);
}
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterBitmaskCopy;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAlterColumnBitmaskCopyWithInsertNull)
{
GpuSqlCustomParser createDatabase(nullptr,
"CREATE DATABASE TestDatabaseAlterBitmaskCopyNull 10;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterBitmaskCopyNull");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (col string);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
GpuSqlCustomParser parserValue(database, "INSERT INTO testTable (col) VALUES (\"1\");");
GpuSqlCustomParser parserNull(database, "INSERT INTO testTable (col) VALUES (NULL);");
GpuSqlCustomParser parserWrongValue(database,
"INSERT INTO testTable (col) VALUES (\"randomString\");");
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parserValue.Parse();
resultPtr = parserNull.Parse();
resultPtr = parserWrongValue.Parse();
}
GpuSqlCustomParser parserSelect(database, "SELECT col from testTable;");
resultPtr = parserSelect.Parse();
auto resultInt =
dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto blocksBeforeCast =
dynamic_cast<ColumnBase<std::string>*>(table.GetColumns().at("col").get())->GetBlocksList();
std::vector<nullmask_t> oldBitmasks;
for (int32_t i = 0; i < 5; i++)
{
oldBitmasks.push_back(0);
oldBitmasks.push_back(1);
oldBitmasks.push_back(1);
}
GpuSqlCustomParser parser4(database, "ALTER TABLE testTable ALTER COLUMN col int;");
resultPtr = parser4.Parse();
type = table.GetColumns().at("col")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
auto blocksAfterCast =
dynamic_cast<ColumnBase<int32_t>*>(table.GetColumns().at("col").get())->GetBlocksList();
std::vector<nullmask_t> newBitmasks;
for (int32_t i = 0; i < blocksAfterCast.size(); i++)
{
for (int32_t j = 0; j < blocksAfterCast[i]->GetSize(); j++)
{
newBitmasks.push_back(
NullValues::GetConcreteBitFromBitmask(blocksAfterCast[i]->GetNullBitmask(), j));
}
}
ASSERT_EQ(oldBitmasks.size(), newBitmasks.size());
for (int32_t i = 0; i < oldBitmasks.size(); i++)
{
ASSERT_EQ(oldBitmasks[i], newBitmasks[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterBitmaskCopyNull;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, ClusteredIndexPoint)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabasePoint 8;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabasePoint");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colA int, colB geo_point, INDEX "
"ind (colA));");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colA")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
type = table.GetColumns().at("colB")->GetColumnType();
ASSERT_EQ(type, COLUMN_POINT);
GpuSqlCustomParser parser2(database,
"INSERT INTO testTable (colA, colB) VALUES (1, POINT(2.5 3.23));");
std::vector<int32_t> expectedResultInt;
std::vector<std::string> expectedResultPoint;
for (int32_t i = 0; i < 7; i++)
{
resultPtr = parser2.Parse();
expectedResultInt.push_back(1);
QikkDB::Types::Point point = PointFactory::FromWkt("POINT(2.5 3.23)");
expectedResultPoint.push_back(PointFactory::WktFromPoint(point, true));
}
// SELECT COL INT
GpuSqlCustomParser parserSelectFromA(database, "SELECT colA from testTable;");
resultPtr = parserSelectFromA.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColInt = result->payloads().at("testTable.colA");
ASSERT_EQ(payloadsColInt.intpayload().intdata_size(), expectedResultInt.size());
for (int i = 0; i < payloadsColInt.intpayload().intdata_size(); i++)
{
ASSERT_EQ(expectedResultInt[i], payloadsColInt.intpayload().intdata()[i]);
}
// SELECT COL POINT
GpuSqlCustomParser parserSelectFromB(database, "SELECT colB from testTable;");
resultPtr = parserSelectFromB.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColPoint = result->payloads().at("testTable.colB");
ASSERT_EQ(payloadsColPoint.stringpayload().stringdata_size(), expectedResultPoint.size());
for (int i = 0; i < payloadsColPoint.stringpayload().stringdata_size(); i++)
{
ASSERT_EQ(expectedResultPoint[i], payloadsColPoint.stringpayload().stringdata()[i]);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabasePoint;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, ClusteredIndexPolygon)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabasePolygon 4;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabasePolygon");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colA int, colB geo_polygon, INDEX "
"ind (colA));");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colA")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
type = table.GetColumns().at("colB")->GetColumnType();
ASSERT_EQ(type, COLUMN_POLYGON);
std::vector<int32_t> expectedResultInt;
std::vector<std::string> expectedResultPolygon;
QikkDB::Types::ComplexPolygon polygon =
ComplexPolygonFactory::FromWkt("POLYGON((10 11, 11.11 "
"12.13, 10 11),(21 30, 35.55 36, 30.11 20.26, 21 "
"30),(61 80.11,90 "
"89.15,112.12 110, 61 80.11))");
for (int32_t i = 0; i < 7; i++)
{
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colA, colB) VALUES (" + std::to_string(i) +
", POLYGON((10 11, 11.11 "
"12.13, 10 11),(21 30, 35.55 36, 30.11 20.26, 21 "
"30),(61 80.11,90 "
"89.15,112.12 110, 61 80.11)));");
resultPtr = parser2.Parse();
expectedResultInt.push_back(i);
expectedResultPolygon.push_back(ComplexPolygonFactory::WktFromPolygon(polygon, true));
}
// SELECT COL INT
GpuSqlCustomParser parserSelectFromA(database, "SELECT colA from testTable;");
resultPtr = parserSelectFromA.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColInt = result->payloads().at("testTable.colA");
ASSERT_EQ(payloadsColInt.intpayload().intdata_size(), expectedResultInt.size());
auto& columnIntA = table.GetColumns().at("colA");
auto& blocksA = dynamic_cast<ColumnBase<int32_t>*>(columnIntA.get())->GetBlocksList();
ASSERT_EQ(blocksA[0]->GetData()[0], expectedResultInt[0]);
ASSERT_EQ(blocksA[0]->GetData()[1], expectedResultInt[1]);
ASSERT_EQ(blocksA[1]->GetData()[0], expectedResultInt[2]);
ASSERT_EQ(blocksA[1]->GetData()[1], expectedResultInt[3]);
ASSERT_EQ(blocksA[2]->GetData()[0], expectedResultInt[4]);
ASSERT_EQ(blocksA[2]->GetData()[1], expectedResultInt[5]);
ASSERT_EQ(blocksA[2]->GetData()[2], expectedResultInt[6]);
// SELECT COL POLYGON
GpuSqlCustomParser parserSelectFromB(database, "SELECT colB from testTable;");
resultPtr = parserSelectFromB.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColPolygon = result->payloads().at("testTable.colB");
ASSERT_EQ(payloadsColPolygon.stringpayload().stringdata_size(), expectedResultPolygon.size());
auto& columnIntB = table.GetColumns().at("colB");
auto& blocksB =
dynamic_cast<ColumnBase<QikkDB::Types::ComplexPolygon>*>(columnIntB.get())->GetBlocksList();
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[0]->GetData()[0], true), expectedResultPolygon[0]);
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[0]->GetData()[1], true), expectedResultPolygon[1]);
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[1]->GetData()[0], true), expectedResultPolygon[2]);
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[1]->GetData()[1], true), expectedResultPolygon[3]);
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[2]->GetData()[0], true), expectedResultPolygon[4]);
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[2]->GetData()[1], true), expectedResultPolygon[5]);
ASSERT_EQ(ComplexPolygonFactory::WktFromPolygon(blocksB[2]->GetData()[2], true), expectedResultPolygon[6]);
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabasePolygon;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, ClusteredIndexString)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseString 4;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseString");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colA int, colB string, INDEX "
"ind (colA));");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
auto& table = database->GetTables().at("testTable");
auto type = table.GetColumns().at("colA")->GetColumnType();
ASSERT_EQ(type, COLUMN_INT);
type = table.GetColumns().at("colB")->GetColumnType();
ASSERT_EQ(type, COLUMN_STRING);
std::vector<int32_t> expectedResultInt;
std::vector<std::string> expectedResultString;
for (int32_t i = 0; i < 7; i++)
{
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colA, colB) VALUES (" +
std::to_string(i) + ", \"abc" + std::to_string(i) + "\");");
resultPtr = parser2.Parse();
expectedResultInt.push_back(i);
expectedResultString.push_back("abc" + std::to_string(i));
}
// SELECT COL INT
GpuSqlCustomParser parserSelectFromA(database, "SELECT colA from testTable;");
resultPtr = parserSelectFromA.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColInt = result->payloads().at("testTable.colA");
ASSERT_EQ(payloadsColInt.intpayload().intdata_size(), expectedResultInt.size());
auto& columnIntA = table.GetColumns().at("colA");
auto& blocksA = dynamic_cast<ColumnBase<int32_t>*>(columnIntA.get())->GetBlocksList();
ASSERT_EQ(blocksA[0]->GetData()[0], expectedResultInt[0]);
ASSERT_EQ(blocksA[0]->GetData()[1], expectedResultInt[1]);
ASSERT_EQ(blocksA[1]->GetData()[0], expectedResultInt[2]);
ASSERT_EQ(blocksA[1]->GetData()[1], expectedResultInt[3]);
ASSERT_EQ(blocksA[2]->GetData()[0], expectedResultInt[4]);
ASSERT_EQ(blocksA[2]->GetData()[1], expectedResultInt[5]);
ASSERT_EQ(blocksA[2]->GetData()[2], expectedResultInt[6]);
// SELECT COL STRING
GpuSqlCustomParser parserSelectFromB(database, "SELECT colB from testTable;");
resultPtr = parserSelectFromB.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto& payloadsColString = result->payloads().at("testTable.colB");
ASSERT_EQ(payloadsColString.stringpayload().stringdata_size(), expectedResultString.size());
auto& columnIntB = table.GetColumns().at("colB");
auto& blocksB = dynamic_cast<ColumnBase<std::string>*>(columnIntB.get())->GetBlocksList();
ASSERT_EQ(blocksB[0]->GetData()[0], expectedResultString[0]);
ASSERT_EQ(blocksB[0]->GetData()[1], expectedResultString[1]);
ASSERT_EQ(blocksB[1]->GetData()[0], expectedResultString[2]);
ASSERT_EQ(blocksB[1]->GetData()[1], expectedResultString[3]);
ASSERT_EQ(blocksB[2]->GetData()[0], expectedResultString[4]);
ASSERT_EQ(blocksB[2]->GetData()[1], expectedResultString[5]);
ASSERT_EQ(blocksB[2]->GetData()[2], expectedResultString[6]);
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseString;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAddColumnWithIndex)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterAddWI 8;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterAddWI");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colA int, colB int, INDEX "
"ind(colA, colB));");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
for (int32_t i = 0; i < 15; i++)
{
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colA, colB) VALUES (" +
std::to_string(i) + ", " + std::to_string(i % 5) + ");");
resultPtr = parser2.Parse();
}
auto& table = database->GetTables().at("testTable");
auto& columnIntA = table.GetColumns().at("colA");
auto& blocksA = dynamic_cast<ColumnBase<int32_t>*>(columnIntA.get())->GetBlocksList();
auto& columnIntB = table.GetColumns().at("colB");
auto& blocksB = dynamic_cast<ColumnBase<int32_t>*>(columnIntB.get())->GetBlocksList();
ASSERT_EQ(blocksA[0]->GetSize(), 4);
ASSERT_EQ(blocksA[0]->GetSize(), blocksB[0]->GetSize());
ASSERT_EQ(blocksA[1]->GetSize(), 4);
ASSERT_EQ(blocksA[1]->GetSize(), blocksB[1]->GetSize());
ASSERT_EQ(blocksA[2]->GetSize(), 7);
ASSERT_EQ(blocksA[2]->GetSize(), blocksB[2]->GetSize());
GpuSqlCustomParser parserAlter(database, "ALTER TABLE testTable ADD colC int;");
resultPtr = parserAlter.Parse();
auto& columnIntC = table.GetColumns().at("colC");
auto& blocksC = dynamic_cast<ColumnBase<int32_t>*>(columnIntC.get())->GetBlocksList();
ASSERT_EQ(blocksC[0]->GetSize(), 4);
ASSERT_EQ(blocksC[0]->GetNullBitmask()[0], 15);
ASSERT_EQ(blocksC[1]->GetSize(), 4);
ASSERT_EQ(blocksC[1]->GetNullBitmask()[0], 15);
ASSERT_EQ(blocksC[2]->GetSize(), 7);
ASSERT_EQ(blocksC[2]->GetNullBitmask()[0], 127);
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterAddWI;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, AlterTableAddColumn)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE TestDatabaseAlterAdd 15;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("TestDatabaseAlterAdd");
ASSERT_TRUE(database->GetTables().find("testTable") == database->GetTables().end());
GpuSqlCustomParser parser(database, "CREATE TABLE testTable (colA int, colB int);");
resultPtr = parser.Parse();
ASSERT_TRUE(database->GetTables().find("testTable") != database->GetTables().end());
for (int32_t i = 0; i < 17; i++)
{
GpuSqlCustomParser parser2(database, "INSERT INTO testTable (colA, colB) VALUES (" +
std::to_string(i) + ", " + std::to_string(i % 5) + ");");
resultPtr = parser2.Parse();
}
auto& table = database->GetTables().at("testTable");
auto& columnIntA = table.GetColumns().at("colA");
auto& blocksA = dynamic_cast<ColumnBase<int32_t>*>(columnIntA.get())->GetBlocksList();
auto& columnIntB = table.GetColumns().at("colB");
auto& blocksB = dynamic_cast<ColumnBase<int32_t>*>(columnIntB.get())->GetBlocksList();
ASSERT_EQ(blocksA[0]->GetSize(), 15);
ASSERT_EQ(blocksA[0]->GetSize(), blocksB[0]->GetSize());
ASSERT_EQ(blocksA[1]->GetSize(), 2);
ASSERT_EQ(blocksA[1]->GetSize(), blocksB[1]->GetSize());
GpuSqlCustomParser parserAlter(database, "ALTER TABLE testTable ADD colC int;");
resultPtr = parserAlter.Parse();
auto& columnIntC = table.GetColumns().at("colC");
auto& blocksC = dynamic_cast<ColumnBase<int32_t>*>(columnIntC.get())->GetBlocksList();
ASSERT_EQ(blocksC[0]->GetSize(), 15);
ASSERT_EQ(blocksC[0]->GetNullBitmask()[0], 32767);
ASSERT_EQ(blocksC[1]->GetSize(), 2);
ASSERT_EQ(blocksC[1]->GetNullBitmask()[0], 3);
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE TestDatabaseAlterAdd;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, InsertInto)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE InsertIntoDb 30;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("InsertIntoDb");
GpuSqlCustomParser parserCreate(database,
"CREATE TABLE testTable (colA int, colB int, Aa int);");
resultPtr = parserCreate.Parse();
auto& table = database->GetTables().at("testTable");
// Insert values into two of three columns
GpuSqlCustomParser parserInsert(database, "insert into testTable (colA, colB) values (1, 2);");
resultPtr = parserInsert.Parse();
// Select right after inserting one row of data - insert into two of three columns
GpuSqlCustomParser parserSelect(database, "SELECT colA, colB, Aa from testTable;");
resultPtr = parserSelect.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto payloadsColA = result->payloads().at("testTable.colA");
auto payloadsColB = result->payloads().at("testTable.colB");
auto payloadsColAa = result->payloads().at("testTable.Aa");
ASSERT_EQ(payloadsColA.intpayload().intdata()[0], 1);
ASSERT_EQ(payloadsColB.intpayload().intdata()[0], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[0], -2147483648);
auto& columnIntA = table.GetColumns().at("colA");
auto& blocksA = dynamic_cast<ColumnBase<int32_t>*>(columnIntA.get())->GetBlocksList();
auto& columnIntB = table.GetColumns().at("colB");
auto& blocksB = dynamic_cast<ColumnBase<int32_t>*>(columnIntB.get())->GetBlocksList();
auto& columnIntAa = table.GetColumns().at("Aa");
auto& blocksAa = dynamic_cast<ColumnBase<int32_t>*>(columnIntAa.get())->GetBlocksList();
ASSERT_EQ(blocksA.size(), 1);
ASSERT_EQ(blocksB.size(), 1);
ASSERT_EQ(blocksAa.size(), 1);
ASSERT_EQ(blocksA[0]->GetSize(), 1);
ASSERT_EQ(blocksB[0]->GetSize(), 1);
ASSERT_EQ(blocksAa[0]->GetSize(), 1);
ASSERT_EQ(blocksA[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksB[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksAa[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksA[0]->GetData()[0], 1);
ASSERT_EQ(blocksB[0]->GetData()[0], 2);
ASSERT_EQ(blocksAa[0]->GetData()[0], -2147483648);
ASSERT_EQ(blocksA[0]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksB[0]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksAa[0]->GetNullBitmask()[0], 1);
//---------------------------------------------------------
// Insert 5 more times same values into two of three columns
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parserInsert.Parse();
}
GpuSqlCustomParser parserSelect3(database, "SELECT colA, colB, Aa from testTable;");
resultPtr = parserSelect3.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
payloadsColAa = result->payloads().at("testTable.Aa");
ASSERT_EQ(blocksA.size(), 1);
ASSERT_EQ(blocksB.size(), 1);
ASSERT_EQ(blocksAa.size(), 1);
ASSERT_EQ(blocksA[0]->GetSize(), 6);
ASSERT_EQ(blocksB[0]->GetSize(), 6);
ASSERT_EQ(blocksAa[0]->GetSize(), 6);
ASSERT_EQ(blocksA[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksB[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksAa[0]->GetNullBitmaskSize(), 1);
for (int32_t i = 0; i < 6; i++)
{
ASSERT_EQ(blocksA[0]->GetData()[i], 1);
ASSERT_EQ(blocksB[0]->GetData()[i], 2);
ASSERT_EQ(blocksAa[0]->GetData()[i], -2147483648);
ASSERT_EQ(payloadsColA.intpayload().intdata()[i], 1) << "Iteration: " << i;
ASSERT_EQ(payloadsColB.intpayload().intdata()[i], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i], -2147483648);
}
ASSERT_EQ(blocksA[0]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksB[0]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksAa[0]->GetNullBitmask()[0], 63);
//---------------------------------------------------------
// Insert 5 times into third column, which was empty - filled with null values till now
GpuSqlCustomParser parserInsert2(database, "insert into testTable (Aa) values (3);");
for (int32_t i = 0; i < 5; i++)
{
resultPtr = parserInsert2.Parse();
}
GpuSqlCustomParser parserSelect4(database, "SELECT colA, colB, Aa from testTable;");
resultPtr = parserSelect4.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
payloadsColAa = result->payloads().at("testTable.Aa");
ASSERT_EQ(blocksA.size(), 1);
ASSERT_EQ(blocksB.size(), 1);
ASSERT_EQ(blocksAa.size(), 1);
ASSERT_EQ(blocksA[0]->GetSize(), 11);
ASSERT_EQ(blocksB[0]->GetSize(), 11);
ASSERT_EQ(blocksAa[0]->GetSize(), 11);
ASSERT_EQ(blocksA[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksB[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksAa[0]->GetNullBitmaskSize(), 1);
for (int32_t i = 0; i < 6; i++)
{
ASSERT_EQ(blocksA[0]->GetData()[i], 1);
ASSERT_EQ(blocksB[0]->GetData()[i], 2);
ASSERT_EQ(blocksAa[0]->GetData()[i], -2147483648);
ASSERT_EQ(payloadsColA.intpayload().intdata()[i], 1);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i], -2147483648);
}
for (int32_t i = 0; i < 5; i++)
{
ASSERT_EQ(blocksA[0]->GetData()[i + 6], -2147483648);
ASSERT_EQ(blocksB[0]->GetData()[i + 6], -2147483648);
ASSERT_EQ(blocksAa[0]->GetData()[i + 6], 3);
ASSERT_EQ(payloadsColA.intpayload().intdata()[i + 6], -2147483648);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i + 6], -2147483648);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i + 6], 3);
}
ASSERT_EQ(blocksA[0]->GetNullBitmask()[0], 1984);
ASSERT_EQ(blocksB[0]->GetNullBitmask()[0], 1984);
ASSERT_EQ(blocksAa[0]->GetNullBitmask()[0], 63);
//---------------------------------------------------------
// Alter table to add one string column - it should be filled with null values
GpuSqlCustomParser parserAlter(database, "alter table testTable add colString string;");
resultPtr = parserAlter.Parse();
GpuSqlCustomParser parserSelect5(database, "SELECT colA, colB, Aa, colString from testTable;");
resultPtr = parserSelect5.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
payloadsColAa = result->payloads().at("testTable.Aa");
auto payloadsColString = result->payloads().at("testTable.colString");
auto& columnString = table.GetColumns().at("colString");
auto& blocksString = dynamic_cast<ColumnBase<std::string>*>(columnString.get())->GetBlocksList();
ASSERT_EQ(blocksA.size(), 1);
ASSERT_EQ(blocksB.size(), 1);
ASSERT_EQ(blocksAa.size(), 1);
ASSERT_EQ(blocksString.size(), 1);
ASSERT_EQ(blocksA[0]->GetSize(), 11);
ASSERT_EQ(blocksB[0]->GetSize(), 11);
ASSERT_EQ(blocksAa[0]->GetSize(), 11);
ASSERT_EQ(blocksString[0]->GetSize(), 11);
ASSERT_EQ(blocksA[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksB[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksAa[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksString[0]->GetNullBitmaskSize(), 1);
for (int32_t i = 0; i < 6; i++)
{
ASSERT_EQ(blocksA[0]->GetData()[i], 1);
ASSERT_EQ(blocksB[0]->GetData()[i], 2);
ASSERT_EQ(blocksAa[0]->GetData()[i], -2147483648);
ASSERT_EQ(blocksString[0]->GetData()[i], " ");
ASSERT_EQ(payloadsColA.intpayload().intdata()[i], 1);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i], -2147483648);
ASSERT_EQ(payloadsColString.stringpayload().stringdata()[i], " ");
}
for (int32_t i = 0; i < 5; i++)
{
ASSERT_EQ(blocksA[0]->GetData()[i + 6], -2147483648);
ASSERT_EQ(blocksB[0]->GetData()[i + 6], -2147483648);
ASSERT_EQ(blocksAa[0]->GetData()[i + 6], 3);
ASSERT_EQ(blocksString[0]->GetData()[i + 6], " ");
ASSERT_EQ(payloadsColA.intpayload().intdata()[i + 6], -2147483648);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i + 6], -2147483648);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i + 6], 3);
ASSERT_EQ(payloadsColString.stringpayload().stringdata()[i + 6], " ");
}
ASSERT_EQ(blocksA[0]->GetNullBitmask()[0], 1984);
ASSERT_EQ(blocksB[0]->GetNullBitmask()[0], 1984);
ASSERT_EQ(blocksAa[0]->GetNullBitmask()[0], 63);
ASSERT_EQ(blocksString[0]->GetNullBitmask()[0], 2047);
//---------------------------------------------------------
// Insert into new column "colString", other columns should be filled with null values
GpuSqlCustomParser parserInsert3(database,
"insert into testTable (colString) values (\"abc\");");
for (int32_t i = 0; i < 3; i++)
{
resultPtr = parserInsert3.Parse();
}
GpuSqlCustomParser parserSelect6(database, "SELECT colA, colB, Aa, colString from testTable;");
resultPtr = parserSelect6.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
payloadsColAa = result->payloads().at("testTable.Aa");
payloadsColString = result->payloads().at("testTable.colString");
for (int32_t i = 0; i < 6; i++)
{
ASSERT_EQ(payloadsColA.intpayload().intdata()[i], 1);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i], -2147483648);
ASSERT_EQ(payloadsColString.stringpayload().stringdata()[i], " ");
}
for (int32_t i = 0; i < 5; i++)
{
ASSERT_EQ(payloadsColA.intpayload().intdata()[i + 6], -2147483648);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i + 6], -2147483648);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i + 6], 3);
ASSERT_EQ(payloadsColString.stringpayload().stringdata()[i + 6], " ");
}
for (int32_t i = 0; i < 3; i++)
{
ASSERT_EQ(blocksA[0]->GetData()[i + 11], -2147483648);
ASSERT_EQ(blocksB[0]->GetData()[i + 11], -2147483648);
ASSERT_EQ(blocksAa[0]->GetData()[i + 11], -2147483648);
ASSERT_EQ(blocksString[0]->GetData()[i + 11], "abc");
ASSERT_EQ(payloadsColA.intpayload().intdata()[i + 11], -2147483648);
ASSERT_EQ(payloadsColB.intpayload().intdata()[i + 11], -2147483648);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[i + 11], -2147483648);
ASSERT_EQ(payloadsColString.stringpayload().stringdata()[i + 11], "abc");
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE InsertIntoDb;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, InsertIntoWithIndex)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE InsertIntoDb 4;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("InsertIntoDb");
GpuSqlCustomParser parserCreate(database, "CREATE TABLE testTable (colA int, colB int, Aa int, "
"INDEX idx(colA, colB, Aa));");
resultPtr = parserCreate.Parse();
auto& table = database->GetTables().at("testTable");
// Insert values into two of three columns
GpuSqlCustomParser parserInsert(database, "insert into testTable (colA, colB) values (1, 2);");
for (int32_t i = 0; i < 4; i++)
{
resultPtr = parserInsert.Parse();
}
// Select right after inserting one row of data - insert into two of three columns
GpuSqlCustomParser parserSelect(database, "SELECT colA, colB, Aa from testTable;");
resultPtr = parserSelect.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto payloadsColA = result->payloads().at("testTable.colA");
auto payloadsColB = result->payloads().at("testTable.colB");
auto payloadsColAa = result->payloads().at("testTable.Aa");
for (int32_t i = 0; i < 4; i++)
{
ASSERT_EQ(payloadsColA.intpayload().intdata()[0], 1);
ASSERT_EQ(payloadsColB.intpayload().intdata()[0], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[0], -2147483648);
}
auto& columnIntA = table.GetColumns().at("colA");
auto& blocksA = dynamic_cast<ColumnBase<int32_t>*>(columnIntA.get())->GetBlocksList();
auto& columnIntB = table.GetColumns().at("colB");
auto& blocksB = dynamic_cast<ColumnBase<int32_t>*>(columnIntB.get())->GetBlocksList();
auto& columnIntAa = table.GetColumns().at("Aa");
auto& blocksAa = dynamic_cast<ColumnBase<int32_t>*>(columnIntAa.get())->GetBlocksList();
ASSERT_EQ(blocksA.size(), 2);
ASSERT_EQ(blocksB.size(), 2);
ASSERT_EQ(blocksAa.size(), 2);
ASSERT_EQ(blocksA[0]->GetSize(), 2);
ASSERT_EQ(blocksB[0]->GetSize(), 2);
ASSERT_EQ(blocksAa[0]->GetSize(), 2);
ASSERT_EQ(blocksA[1]->GetSize(), 2);
ASSERT_EQ(blocksB[1]->GetSize(), 2);
ASSERT_EQ(blocksAa[1]->GetSize(), 2);
ASSERT_EQ(blocksA[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksB[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksAa[0]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksA[1]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksB[1]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksAa[1]->GetNullBitmaskSize(), 1);
ASSERT_EQ(blocksA[0]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksB[0]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksAa[0]->GetNullBitmask()[0], 3);
ASSERT_EQ(blocksA[1]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksB[1]->GetNullBitmask()[0], 0);
ASSERT_EQ(blocksAa[1]->GetNullBitmask()[0], 3);
ASSERT_EQ(blocksA[0]->GetData()[0], 1);
ASSERT_EQ(blocksB[0]->GetData()[0], 2);
ASSERT_EQ(blocksAa[0]->GetData()[0], -2147483648);
ASSERT_EQ(blocksA[0]->GetData()[1], 1);
ASSERT_EQ(blocksB[0]->GetData()[1], 2);
ASSERT_EQ(blocksAa[0]->GetData()[1], -2147483648);
ASSERT_EQ(blocksA[1]->GetData()[0], 1);
ASSERT_EQ(blocksB[1]->GetData()[0], 2);
ASSERT_EQ(blocksAa[1]->GetData()[0], -2147483648);
ASSERT_EQ(blocksA[1]->GetData()[1], 1);
ASSERT_EQ(blocksB[1]->GetData()[1], 2);
ASSERT_EQ(blocksAa[1]->GetData()[1], -2147483648);
// Insert values into two of three columns
GpuSqlCustomParser parserInsert2(database, "insert into testTable (colA, colB) values (1, 2);");
for (int32_t i = 0; i < 4; i++)
{
resultPtr = parserInsert2.Parse();
}
// Select right after inserting one row of data - insert into two of three columns
GpuSqlCustomParser parserSelect2(database, "SELECT colA, colB, Aa from testTable;");
resultPtr = parserSelect2.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
payloadsColAa = result->payloads().at("testTable.Aa");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), 8);
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), payloadsColB.intpayload().intdata_size());
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), payloadsColAa.intpayload().intdata_size());
for (int32_t i = 0; i < payloadsColA.intpayload().intdata_size(); i++)
{
ASSERT_EQ(payloadsColA.intpayload().intdata()[0], 1);
ASSERT_EQ(payloadsColB.intpayload().intdata()[0], 2);
ASSERT_EQ(payloadsColAa.intpayload().intdata()[0], -2147483648);
}
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE InsertIntoDb;");
resultPtr = parserDropDb.Parse();
}
TEST(DispatcherTests, WhereEvaluationWithString)
{
GpuSqlCustomParser createDatabase(nullptr, "CREATE DATABASE WhereEvalString 16;");
auto resultPtr = createDatabase.Parse();
auto database = Database::GetDatabaseByName("WhereEvalString");
GpuSqlCustomParser parserCreate(database, "CREATE TABLE testTable (colA int, colB string);");
resultPtr = parserCreate.Parse();
auto& table = database->GetTables().at("testTable");
GpuSqlCustomParser parserInsert1(database,
"insert into testTable (colA, colB) values (1, \"Peto\");");
GpuSqlCustomParser parserInsert2(database,
"insert into testTable (colA, colB) values (2, \"AAA\");");
GpuSqlCustomParser parserInsert3(database,
"insert into testTable (colA, colB) values (3, \"BBB\");");
GpuSqlCustomParser parserInsert4(database,
"insert into testTable (colA, colB) values (4, \"CCC\");");
resultPtr = parserInsert1.Parse();
resultPtr = parserInsert2.Parse();
resultPtr = parserInsert3.Parse();
resultPtr = parserInsert4.Parse();
GpuSqlCustomParser parserSelect(database, "SELECT colB FROM testTable WHERE colB = \"Peto\";");
resultPtr = parserSelect.Parse();
auto result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto payloadsColB = result->payloads().at("testTable.colB");
ASSERT_EQ(payloadsColB.stringpayload().stringdata_size(), 1);
ASSERT_EQ(payloadsColB.stringpayload().stringdata()[0], "Peto");
GpuSqlCustomParser parserSelect1(database, "SELECT colA FROM testTable WHERE colB = \"Peto\";");
resultPtr = parserSelect1.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
auto payloadsColA = result->payloads().at("testTable.colA");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), 1);
ASSERT_EQ(payloadsColA.intpayload().intdata()[0], 1);
GpuSqlCustomParser parserSelect2(database,
"SELECT colA, colB FROM testTable WHERE colB = \"Peto\";");
resultPtr = parserSelect2.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), 1);
ASSERT_EQ(payloadsColB.stringpayload().stringdata_size(), 1);
ASSERT_EQ(payloadsColA.intpayload().intdata()[0], 1);
ASSERT_EQ(payloadsColB.stringpayload().stringdata()[0], "Peto");
GpuSqlCustomParser parserSelect3(database, "SELECT * FROM testTable WHERE colB = \"Peto\";");
resultPtr = parserSelect3.Parse();
result = dynamic_cast<QikkDB::NetworkClient::Message::QueryResponseMessage*>(resultPtr.get());
payloadsColA = result->payloads().at("testTable.colA");
payloadsColB = result->payloads().at("testTable.colB");
ASSERT_EQ(payloadsColA.intpayload().intdata_size(), 1);
ASSERT_EQ(payloadsColB.stringpayload().stringdata_size(), 1);
ASSERT_EQ(payloadsColA.intpayload().intdata()[0], 1);
ASSERT_EQ(payloadsColB.stringpayload().stringdata()[0], "Peto");
GpuSqlCustomParser parserDropDb(database, "DROP DATABASE WhereEvalString;");
resultPtr = parserDropDb.Parse();
} | 37.47436 | 164 | 0.567701 | veselyja |
caf84f1ea36850ff8756ba02aea824c4d16905d1 | 1,420 | hpp | C++ | doc/quickbook/oalplus/quickref/buffer.hpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | null | null | null | doc/quickbook/oalplus/quickref/buffer.hpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | null | null | null | doc/quickbook/oalplus/quickref/buffer.hpp | Extrunder/oglplus | c7c8266a1571d0b4c8b02d9c8ca6a7b6a6f51791 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright 2014-2015 Matus Chochlik. 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)
*/
//[oalplus_buffer_common_1
template <>
class __ObjectOps<__tag_DirectState, __tag_Buffer>
: public __BufferName
{
public:
void Data(
__DataFormat format,
const ALvoid* data,
ALsizei size,
ALsizei frequency
); /*<
Specifies the buffer audio sample data.
See [alfunc BufferData].
>*/
ALsizei Frequency(void) const; /*<
Returns the sampling frequency (in Hz) of the data stored in this buffer.
See [alfunc GetBuffer], [alconst FREQUENCY].
>*/
ALsizei Size(void) const; /*<
Returns the size (in bytes) of the data stored in this buffer.
>*/
ALsizei Bits(void) const; /*<
Returns the number of bits per sample of the data stored in this buffer.
See [alfunc GetBuffer], [alconst BITS].
>*/
ALsizei Channels(void) const; /*<
Returns the number of channels of the data stored in this buffer.
See [alfunc GetBuffer], [alconst CHANNELS].
>*/
ALfloat Duration(void) const; /*<
Returns the duration (in seconds) of the sound stored in this buffer.
See [alfunc GetBuffer], [alconst SIZE], [alconst FREQUENCY],
[alconst CHANNELS], [alconst CHANNELS].
>*/
};
//]
//[oalplus_buffer_def
typedef ObjectOps<__tag_DirectState, __tag_Buffer>
BufferOps;
typedef __Object<BufferOps> Buffer;
//]
| 24.067797 | 74 | 0.722535 | Extrunder |
caffeabd0600cf0fd0d24d17dcc4b37ab9dd7c32 | 1,202 | hpp | C++ | NWNXLib/API/Globals.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | NWNXLib/API/Globals.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | NWNXLib/API/Globals.hpp | Qowyn/unified | 149d0b7670a9d156e64555fe0bd7715423db4c2a | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include "API/Version.hpp"
namespace NWNXLib {
namespace API {
#ifdef _WIN32
static_assert(false, "Windows is not suported.");
#endif
struct CExoBase;
struct CExoResMan;
struct CVirtualMachine;
struct CScriptCompiler;
struct CAppManager;
struct CTlkTable;
struct CNWRules;
struct CExoString;
namespace Globals {
constexpr uintptr_t g_exoBaseAddr = 0x005F2CEC; NWNX_EXPECT_VERSION(8186);
constexpr uintptr_t g_exoResManAddr = 0x005F2CE8; NWNX_EXPECT_VERSION(8186);
constexpr uintptr_t g_virtualMachineAddr = 0x005F2CE4; NWNX_EXPECT_VERSION(8186);
constexpr uintptr_t g_scriptCompilerAddr = 0x005F2CE0; NWNX_EXPECT_VERSION(8186);
constexpr uintptr_t g_appManagerAddr = 0x005F2CDC; NWNX_EXPECT_VERSION(8186);
constexpr uintptr_t g_tlkTableAddr = 0x005F2CD8; NWNX_EXPECT_VERSION(8186);
constexpr uintptr_t g_nwRulesAddr = 0x005F2CD4; NWNX_EXPECT_VERSION(8186);
extern CExoBase* ExoBase();
extern CExoResMan* ExoResMan();
extern CVirtualMachine* VirtualMachine();
extern CScriptCompiler* ScriptCompiler();
extern CAppManager* AppManager();
extern CTlkTable* TlkTable();
extern CNWRules* Rules();
}
}
}
| 26.130435 | 81 | 0.772879 | Qowyn |
1b01f82b0f9d45e6339d2c7494871c60f07491ac | 2,716 | cpp | C++ | old-sybil/XApp1/D2DInputContrtol.cpp | sugarontop/UWPFRM | ab93099b7e15c525f782cfaa225faaf4bd239686 | [
"MIT"
] | null | null | null | old-sybil/XApp1/D2DInputContrtol.cpp | sugarontop/UWPFRM | ab93099b7e15c525f782cfaa225faaf4bd239686 | [
"MIT"
] | null | null | null | old-sybil/XApp1/D2DInputContrtol.cpp | sugarontop/UWPFRM | ab93099b7e15c525f782cfaa225faaf4bd239686 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "D2DUniversalControlBase.h"
#include "D2DInputControl.h"
using namespace V4;
using namespace V4_XAPP1;
void D2DInputTextbox::Create(D2DControls* pacontrol, const FRectFBoxModel& rc, int stat, std::vector<InputRow>& rows, Init& init)
{
InnerCreateWindow(pacontrol,rc,stat, L"noname", -1);
D2DContext* cxt = parent_->cxt();
int i = 0;
rows_.resize(rows.size());
ComPTR<IDWriteTextFormat> tf, vf;
cxt->wfactory->CreateTextFormat( init.fontnm, nullptr,
DWRITE_FONT_WEIGHT_BOLD,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
init.title_font_height,
DEFAULTLOCALE,
&tf );
cxt->wfactory->CreateTextFormat( init.fontnm, nullptr,
DWRITE_FONT_WEIGHT_REGULAR,
DWRITE_FONT_STYLE_NORMAL,
DWRITE_FONT_STRETCH_NORMAL,
init.title_font_height,
DEFAULTLOCALE,
&vf );
for(auto& it : rows)
{
ComPTR<IDWriteTextLayout> tl, val;
cxt->wfactory->CreateTextLayout( it.title, wcslen(it.title), tf, 100,1000, &tl );
cxt->wfactory->CreateTextLayout( L"***", 3, vf, 100,1000, &val );
Row r;
r.row = i;
r.typ = it.typ;
r.title = tl;
r.value = val;
r.height = it.height;
rows_[i++] = r;
}
tx_ = init.textbox;
cell_width_.resize(init.width_cnt);
for(i = 0; i < init.width_cnt; i++ )
{
cell_width_[i] = init.width[i];
}
FRectF txbox_rc;
txbox_rc.SetPoint( cell_width_[0], 0 );
txbox_rc.SetSize( cell_width_[1], rows[0].height );
txbox_rc.Offset( rc_.left, rc_.top );
tx_->SetRect( txbox_rc );
static WParameter wp;
wp.sender = this;
wp.target = tx_;
wp.prm = (LPVOID)L"this is test.";
//tx_->WndProc( win, WM_D2D_TEXTBOX_SETTEXT, (INT_PTR)&wp, nullptr );
parent_->PostMessage(WM_D2D_TEXTBOX_SETTEXT, (INT_PTR)&wp, nullptr );
}
int D2DInputTextbox::WndProc(D2DWindow* d, int message, INT_PTR wp, Windows::UI::Core::ICoreWindowEventArgs^ lp)
{
if ( IsHide() )
return 0;
int ret = 0;
switch( message )
{
case WM_PAINT:
{
auto& cxt = *(d->cxt());
D2DMatrix mat(cxt);
mat_ = mat.PushTransform();
mat.Offset(rc_.left, rc_.top);
OnPaint(cxt);
mat.PopTransform();
}
break;
case WM_D2D_TEXTBOX_CHANGED :
{
WParameter* wwp = (WParameter*)wp;
if ( wwp->sender == tx_ )
{
std::wstring s = (LPCWSTR)wwp->prm;
auto rc = tx_->GetRect();
rc.Offset(0,40);
tx_->SetRect( rc );
d->redraw();
ret = 1;
}
}
break;
}
return ret;
}
void D2DInputTextbox::OnPaint(D2DContext& cxt)
{
FPointF pt(0,0);
for(auto& it : rows_)
{
pt.x = 0;
cxt.cxt->DrawTextLayout( pt, it.title, cxt.black );
pt.x += cell_width_[0];
pt.x += cell_width_[1];
cxt.cxt->DrawTextLayout( pt, it.value, cxt.black );
pt.y += it.height;
}
} | 17.986755 | 129 | 0.654271 | sugarontop |
1b0214f710df47cf6b30b5d6fb051460c1944082 | 6,225 | cpp | C++ | libfairygui/Classes/GProgressBar.cpp | cui-shinan0812/FairyGUI-cocos2dx | dbb7a5e45b8a34791c80be882a2e9607acd96e5e | [
"MIT"
] | null | null | null | libfairygui/Classes/GProgressBar.cpp | cui-shinan0812/FairyGUI-cocos2dx | dbb7a5e45b8a34791c80be882a2e9607acd96e5e | [
"MIT"
] | null | null | null | libfairygui/Classes/GProgressBar.cpp | cui-shinan0812/FairyGUI-cocos2dx | dbb7a5e45b8a34791c80be882a2e9607acd96e5e | [
"MIT"
] | null | null | null | #include "GProgressBar.h"
#include "PackageItem.h"
#include "utils/ByteBuffer.h"
#include "tween/GTween.h"
NS_FGUI_BEGIN
USING_NS_CC;
GProgressBar::GProgressBar() :
_max(100),
_value(0),
_titleType(ProgressTitleType::PERCENT),
_titleObject(nullptr),
_barObjectH(nullptr),
_barObjectV(nullptr),
_barMaxWidth(0),
_barMaxHeight(0),
_barMaxWidthDelta(0),
_barMaxHeightDelta(0),
_barStartX(0),
_barStartY(0),
_tweening(false)
{
}
GProgressBar::~GProgressBar()
{
if (_tweening)
GTween::kill(this);
}
void GProgressBar::setTitleType(ProgressTitleType value)
{
if (_titleType != value)
{
_titleType = value;
update(_value);
}
}
void GProgressBar::setMax(double value)
{
if (_max != value)
{
_max = value;
update(_value);
}
}
void GProgressBar::setValue(double value)
{
if (_tweening)
{
GTween::kill(this, TweenPropType::Progress, true);
_tweening = false;
}
if (_value != value)
{
_value = value;
update(_value);
}
}
void GProgressBar::tweenValue(double value, float duration)
{
double oldValule = _value;
_value = value;
if (_tweening)
GTween::kill(this, TweenPropType::Progress, false);
_tweening = true;
GTween::toDouble(oldValule, _value, duration)
->setEase(EaseType::Linear)
->setTarget(this, TweenPropType::Progress)
->onComplete([this]() { _tweening = false; });
}
void GProgressBar::update(double newValue)
{
float percent = _max != 0 ? MIN(newValue / _max, 1) : 0;
if (_titleObject != nullptr)
{
std::ostringstream oss;
switch (_titleType)
{
case ProgressTitleType::PERCENT:
oss << round(percent * 100) << "%";
break;
case ProgressTitleType::VALUE_MAX:
oss << round(newValue) << "/" << round(_max);
break;
case ProgressTitleType::VALUE:
oss << newValue;
break;
case ProgressTitleType::MAX:
oss << _max;
break;
}
_titleObject->setText(oss.str());
}
float fullWidth = this->getWidth() - _barMaxWidthDelta;
float fullHeight = this->getHeight() - _barMaxHeightDelta;
if (!_reverse)
{
if (_barObjectH != nullptr)
{
/*if (dynamic_cast<GImage*>(_barObjectH) && ((GImage *)_barObjectH)->getFillMethod() != FillMethod::None)
((GImage *)_barObjectH).fillAmount = percent;
else if (dynamic_cast<GLoader*>(_barObjectH) && ((GLoader*)_barObjectH)->getFillMethod() != FillMethod::None)
((GLoader *)_barObjectH).fillAmount = percent;
else*/
_barObjectH->setWidth(round(fullWidth * percent));
}
if (_barObjectV != nullptr)
{
/*if (dynamic_cast<GImage*>(_barObjectV) && ((GImage *)_barObjectV)->getFillMethod() != FillMethod::None)
((GImage *)_barObjectV).fillAmount = percent;
else if (dynamic_cast<GLoader*>(_barObjectV) && ((GLoader*)_barObjectV)->getFillMethod() != FillMethod::None)
((GLoader *)_barObjectV).fillAmount = percent;
else*/
_barObjectV->setHeight(round(fullHeight * percent));
}
}
else
{
if (_barObjectH != nullptr)
{
/*if (dynamic_cast<GImage*>(_barObjectH) && ((GImage *)_barObjectH)->getFillMethod() != FillMethod::None)
((GImage *)_barObjectH).fillAmount = 1 - percent;
else if (dynamic_cast<GLoader*>(_barObjectH) && ((GLoader*)_barObjectH)->getFillMethod() != FillMethod::None)
((GLoader *)_barObjectH).fillAmount = 1 - percent;
else*/
{
_barObjectH->setWidth(round(fullWidth * percent));
_barObjectH->setX(_barStartX + (fullWidth - _barObjectH->getWidth()));
}
}
if (_barObjectV != nullptr)
{
/*if (dynamic_cast<GImage*>(_barObjectV) && ((GImage *)_barObjectV)->getFillMethod() != FillMethod::None)
((GImage *)_barObjectV).fillAmount = 1 - percent;
else if (dynamic_cast<GLoader*>(_barObjectV) && ((GLoader*)_barObjectV)->getFillMethod() != FillMethod::None)
((GLoader *)_barObjectV).fillAmount = 1 - percent;
else*/
{
_barObjectV->setHeight(round(fullHeight * percent));
_barObjectV->setY(_barStartY + (fullHeight - _barObjectV->getHeight()));
}
}
}
}
void GProgressBar::handleSizeChanged()
{
GComponent::handleSizeChanged();
if (_barObjectH != nullptr)
_barMaxWidth = getWidth() - _barMaxWidthDelta;
if (_barObjectV != nullptr)
_barMaxHeight = getHeight() - _barMaxHeightDelta;
if (!_underConstruct)
update(_value);
}
void GProgressBar::constructExtension(ByteBuffer* buffer)
{
buffer->Seek(0, 6);
_titleType = (ProgressTitleType)buffer->ReadByte();
_reverse = buffer->ReadBool();
_titleObject = getChild("title");
_barObjectH = getChild("bar");
_barObjectV = getChild("bar_v");
if (_barObjectH != nullptr)
{
_barMaxWidth = _barObjectH->getWidth();
_barMaxWidthDelta = getWidth() - _barMaxWidth;
_barStartX = _barObjectH->getX();
}
if (_barObjectV != nullptr)
{
_barMaxHeight = _barObjectV->getHeight();
_barMaxHeightDelta = getHeight() - _barMaxHeight;
_barStartY = _barObjectV->getY();
}
}
void GProgressBar::setup_afterAdd(ByteBuffer* buffer, int beginPos)
{
GComponent::setup_afterAdd(buffer, beginPos);
if (!buffer->Seek(beginPos, 6))
{
update(_value);
return;
}
if ((ObjectType)buffer->ReadByte() != _packageItem->objectType)
{
update(_value);
return;
}
_value = buffer->ReadInt();
_max = buffer->ReadInt();
update(_value);
}
NS_FGUI_END | 28.424658 | 122 | 0.56996 | cui-shinan0812 |
1b03916b03c3ce4bdc6592f6d01c13fca3a94902 | 7,944 | cpp | C++ | doc/CSBwin-src/Code13ea4.cpp | Tehel/dmjs | 641e83246012ce8fdc24fafed7315e6d474f4d16 | [
"MIT"
] | 1 | 2017-07-27T23:46:11.000Z | 2017-07-27T23:46:11.000Z | doc/CSBwin-src/Code13ea4.cpp | Tehel/dmjs | 641e83246012ce8fdc24fafed7315e6d474f4d16 | [
"MIT"
] | null | null | null | doc/CSBwin-src/Code13ea4.cpp | Tehel/dmjs | 641e83246012ce8fdc24fafed7315e6d474f4d16 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "UI.h"
#include <stdio.h>
//#include "Objects.h"
#include "Dispatch.h"
#include "CSB.h"
#include "Data.h"
bool IsPlayFileOpen(void);
bool PlayFile_Play(MouseQueueEnt *MQ);
void RecordFile_Record(MouseQueueEnt *MQ);
// TAG013ea4
RESTARTABLE _ReIncarnate(CHARDESC *pChar)
{ //void
static dReg D0, D4, D5, D6, D7;
static aReg A2;
static i16 w_40;
static i8 b_30[8];
static i16 w_22;
//static i16 w_20;
//static i16 w_18 = 0x7ddd;
static i16 w_16;
static i16 w_14;
static RectPos rect_12;
static i16 w_4;
static i16 w_2;
RESTARTMAP
RESTART(1)
RESTART(2)
END_RESTARTMAP
D5L = 0xccccc;
//;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
keyboardMode = 2;
rect_12.w.y1 = 3;
rect_12.w.y2 = 8;
rect_12.w.x1 = 3;
rect_12.w.x2 = sw(rect_12.w.x1 + 167);
FillRectangle(d.pViewportBMP, &rect_12, 12, 112);
BLT2Viewport(GetBasicGraphicAddress(27),
&d.wRectPos926,
72,
4);
TextToViewport(177, 58, COLOR_13, "_______", false);//Seven of them
TextToViewport(105, 76, COLOR_13, "___________________", false);// Nineteen
STHideCursor(HC12);
MarkViewportUpdated(0);
SetCursorShape(0); // Arrow
STShowCursor(HC12);
D7W = 0;
pChar->name[0] = 0;
pChar->title[0] = 0;
D6W = 1;
A2 = (aReg)pChar->name;
w_2 = 177;
w_4 = 91;
//w_20 = (I16)(d.MouseSwitches & 2);
for (;;)
{
SET(D0B, D6W==2);
if (D0B != 0)
{
SET(D0B, D7W==19);
};
D4W = (I16)(D0W&1);
if (D4W == 0)
{
STHideCursor(HC13);
TextOut_OneLine(d.LogicalScreenBase,
160,
w_2,
w_4,
9,
12,
(char *)d.Byte1414,
999,
false); //Highlight the active character position
STShowCursor(HC13);
};
while (IsPlayFileOpen() || UI_CONSTAT() == 0)
{
if (IsPlayFileOpen())
{
MouseQueueEnt MQ;
PlayFile_Play(&MQ);
if (MQ.num != 0x4444)
{
RETURN;
};
if (MQ.x != 0)
{
D5W = MQ.x;
break;
};
RecordFile_Record(&MQ);
keyboardMode = 1;
RETURN;
};
WAITFORMESSAGE(_2_);
if (!mouseQueueIsEmpty())
//w_18 = (I16)(d.MouseSwitches & 2);
//if ((w_18!=0) && (w_20==0))
{
bool unClick;
{
//MouseQueueEnt MQ;
//MQ.num = 0x4445;
//MQ.x = d.NewMouseX;
//MQ.y = d.NewMouseY;
//RecordFile.Record(&MQ);
};
w_14 = pMouseQueue[d.MouseQStart].x; //w_14 = d.NewMouseX;
w_16 = pMouseQueue[d.MouseQStart].y; //w_16 = d.NewMouseY;
unClick = pMouseQueue[d.MouseQStart].num == 0x0add;
d.MouseQStart = (ui16)((d.MouseQStart + 1) % MOUSEQLEN);
if (unClick)
{
continue;
};
//
if ( ((D6W==2)||(D7W>0))
&& (w_14>=197)
&& (w_14<=215)
&& (w_16>=147)
&& (w_16<=155) ) //Name non-blank and pressed 'OK'
{
w_22 = D7W;
StrCpy((char *)b_30, pChar->name);
D7W = StrLen(pChar->name);
while (pChar->name[--D7W]==' ')
{
pChar->name[D7W] = 0;
};
for (D7W = 0;
D7W < d.NumCharacter-1;
D7W++)
{
D0W = StrCmp(d.CH16482[D7W].name, pChar->name);
if (D0W==0) goto tag014088;
}; // for D7W
{
MouseQueueEnt MQ;
MQ.num = 0x4444;
MQ.x = 0;
MQ.y = 0xffff;
RecordFile_Record(&MQ);
}
keyboardMode=1;
RETURN;
tag014088:
if (D6W == 2)
{
A2 = (aReg)pChar->title;
};
StrCpy(pChar->name, (char *)b_30);
D7W = w_22;
}
else
{
if ( (w_14>=107)
&& (w_14<=175)
&& (w_16>=147)
&& (w_16<=155) ) // Backspace button
{
D5W = 8;
break;
};
if ( (w_14>=107)
&& (w_14<=215)
&& (w_16>=116)
&& (w_16<=144 ) ) // Letters, punctuation, carriage-return
{
D0W = (I16)((w_14+4) % 10); //pixel within column
//
//
//
if ( (D0W!=0) //not on vertical line and not on horizontal line
&& ( (((w_16+5)%10)!=0)
|| ((w_14>=207)&&(w_16==135)) ) )
{
w_40 = sw(11 * ((w_16-116)/10)); // starting index in row
D5W = sw(w_40 + 'A'); //starting letter in row
D5W = sw(D5W + (w_14-107)/10); //letter
//
if ( (D5W==86) || (D5W==97) ) //if carriage-return
{
D5W = 13;
break;
};
if (D5W >= 87)
{
D5W--; //adjust for carriage-return
};
if (D5W > 90)
{
D0W = sw(D5W - 90);
D5W = d.SpecialChars[D0W-1]; // comma, period, semi-colon, colon, space
};
break;
};
};
};
};
//w_20 = w_18;
wvbl(_1_);
}; // while waiting for input.
if (!IsPlayFileOpen())
{
//ASSERT(w_18 != 0x7ddd,"w_18");
//w_20 = w_18;
D0W = sw(UI_CONSTAT());
if (D0W != 0)
{
D5W = sw(UI_DIRECT_CONIN());
};
};
ASSERT(D5L != 0xccccc,"D5L");
{
MouseQueueEnt MQ;
MQ.num = 0x4444;
MQ.x = D5W;
MQ.y = 0xffff;
RecordFile_Record(&MQ);
};
if ( (D5W>='a') && (D5W <='z') )
{
D5W -= 32; // Convert to uppercase
};
//
if ( ((D5W>='A')&&(D5W<='Z'))
|| (D5W=='.')
|| (D5W==44)
|| (D5W==59)
|| (D5W==58)
|| (D5W==' ') )
{
if (D5W==' ')
{
if (D7W == 0) continue;
};
if (D4W != 0) continue;
d.Byte1416[0] = D5B;
STHideCursor(HC14);
TextOut_OneLine(d.LogicalScreenBase,
160,
w_2,
w_4,
13,
12,
(char *)d.Byte1416,
999,
false);
STShowCursor(HC14);
A2[D7W++] = D5B;
A2[D7W] = 0;
w_2 += 6;
if (D6W != 1) continue;
if (D7W != 7) continue;
goto tag0142c2;
}
else
{
if (D5W != 13) goto tag0142de;
if (D6W != 1) continue;
if (D7W <= 0) continue;
STHideCursor(HC15);
TextOut_OneLine(d.LogicalScreenBase,
160,
w_2,
w_4,
13,
12,
(char *)d.Byte1414,
999,
false);
STShowCursor(HC15);
tag0142c2:
D6W = 2;
A2 = (aReg)pChar->title;
w_2 = 105;
w_4 = 109;
D7W = 0;
continue;
};
tag0142de:
if (D5W != 8) continue;
if ( (D6W==1) && (D7W==0) ) continue;
if (D4W == 0)
{
STHideCursor(HC16);
TextOut_OneLine(d.LogicalScreenBase,
160,
w_2,
w_4,
13,
12,
(char *)d.Byte1414,
999,
false);
STShowCursor(HC16);
};
if (D7W == 0)
{
A2 = (aReg)pChar->name;
D0W = StrLen((char *)A2);
D7W = sw(D0W - 1);
D6W = 1;
w_2 = sw(177 + 6*D7W);
w_4 = 91;
}
else
{
D7W--;
w_2 -= 6;
};
A2[D7W] = 0;
};
//RETURN;
}
| 24.145897 | 87 | 0.408736 | Tehel |
1b05b3433b46db9b649ec3bb4bba8f6721587a9a | 645 | cpp | C++ | TeaFiles/header/sections/ContentSectionFormatter.cpp | fced42/TeaFiles.Cpp | 6702a2056d025da9d18d0112ba294ac47269e861 | [
"MIT"
] | 47 | 2015-01-01T14:37:36.000Z | 2021-04-25T07:38:07.000Z | TeaFiles/header/sections/ContentSectionFormatter.cpp | fced42/TeaFiles.Cpp | 6702a2056d025da9d18d0112ba294ac47269e861 | [
"MIT"
] | 6 | 2016-01-11T05:20:05.000Z | 2021-02-06T11:37:24.000Z | TeaFiles/header/sections/ContentSectionFormatter.cpp | fced42/TeaFiles.Cpp | 6702a2056d025da9d18d0112ba294ac47269e861 | [
"MIT"
] | 17 | 2015-01-05T15:10:43.000Z | 2021-06-22T04:59:16.000Z | #include "ContentSectionFormatter.h"
#include "../ReadContext.h"
#include "../WriteContext.h"
#include "../../file/FormattedReader.h"
#include "../../file/FormattedWriter.h"
#include "../../description/ItemDescriptionInternals.h"
#include "../../description/TeaFileDescription.h"
namespace teatime {
void ContentSectionFormatter::Read(ReadContext *rc)
{
auto r = rc->Reader();
string s = r->ReadText();
rc->Description()->Content(s);
}
void ContentSectionFormatter::Write(WriteContext *wc)
{
auto w = wc->Writer();
string s = wc->Description()->Content();
if(s.length() == 0) return;
w->WriteText(s);
}
} // namespace teatime
| 23.888889 | 55 | 0.686822 | fced42 |
db4c6c61222bddfc531f8380f28b2f443119892a | 3,650 | cpp | C++ | Codechef/Cook/nov12_2.cpp | TiwariAnil/Algorithmic_Puzzles | 13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774 | [
"MIT"
] | null | null | null | Codechef/Cook/nov12_2.cpp | TiwariAnil/Algorithmic_Puzzles | 13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774 | [
"MIT"
] | null | null | null | Codechef/Cook/nov12_2.cpp | TiwariAnil/Algorithmic_Puzzles | 13a6b2ed8e8fd0176b9b58c073b2e9847e7ba774 | [
"MIT"
] | null | null | null | //Data Structure includes
#include<vector>
#include<stack>
#include<set>
#include<map>
#include<queue>
#include<deque>
#include<string>
//Other Includes
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<cmath>
//some common functionn
#define maX(a,b) ( (a) > (b) ? (a) : (b))
#define miN(a,b) ( (a) < (b) ? (a) : (b))
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define FORs(i,a,b) for(int i=a;i>=b;i--)
#define fill(a,v) memset(a,v,sizeof a)
#define abS(x) ((x)<0?-(x):(x))
#define mP make_pair
#define pB push_back
#define error(x) cout << #x << " : " << (x) << endl
// Input macros
#define s(n) scanf("%d",&n)
#define sc(n) scanf("%c",&n)
#define sl(n) scanf("%lld",&n)
#define sf(n) scanf("%lf",&n)
#define ss(n) scanf("%s",n)
// Output macros
#define p(n) printf("%d",n)
#define pc(n) printf("%c",n)
#define pl(n) printf("%lld",n)
#define pf(n) printf("%lf",n)
#define ps(n) printf("%s",n)
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
typedef pair<LL,LL> PLL;
typedef pair<int,PII> TRI;
typedef vector<int> VI;
typedef vector<LL> VL;
typedef vector<PII> VII;
typedef vector<PLL> VLL;
typedef vector<TRI> VT;
typedef vector<VI> VVI;
typedef vector<VL> VVL;
typedef vector<VII> VVII;
typedef vector<VLL> VVLL;
typedef vector<VT> VVT;
using namespace std;
void chekarre(int * arr,int n)
{
cout<<"[";
for(int i=0;i<n;i++)
cout<<arr[i]<<" ";
cout<<"]"<<endl;
}
//////////////
#include<stdio.h>
#define size 100010
int gcd(int a,int b)
{
if(a==0)
return b;
return gcd(b%a,a);
}
int main()
{
int t,n,i,a[size],count,min,bool;
scanf("%d",&t);
while(t--)
{
min=100000000;bool=1;
scanf("%d",&n);
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
if(min>a[i])
min=a[i];
}
count=a[0];
for(i=1;i<n;i++)
count=gcd(count,a[i]);
if(count>1)
for(i=2;i*i<=count;i++)
if(count%i==0)
{
printf("%d\n",i);
bool=0;
break;
}
if(bool && count>1)
printf("%d\n",count);
else
if(bool)
printf("-1\n");
}
return 0;
}
/////////////////////
int n, m ;
int a[1000000],mins=0;
int gcd(int a, int b)
{
if(b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}
}
int solve()
{
FOR(i,0,n)
{
FOR(j,i,n)
{
if(gcd(a[i],a[j])==1 )
{
cout<<"-1";
cout<<endl;
return 1;
}
}
}
int i=2;
while(i<=mins)
{
if(mins%i==0)
{
cout<<i;
cout<<endl;
return 0;
}
}
return 1;
}
bool input()
{
s(n);
mins=1000000;//,even=0;
FOR(i,0,n)
{
s(a[i]);
if(mins>a[i])
mins=a[i];
}
return true;
}
int main()
{
int T=1;
s(T);
for(int testnum=1;testnum<=T;testnum++)
{
if(!input()) break;
solve();
//printf("\n");
}
return 0;
}
| 19.836957 | 66 | 0.419726 | TiwariAnil |
db4f2fc92ae221fce2e7fd34a768a9a55e8134ce | 663 | hh | C++ | include/ten/task/rendez.hh | toffaletti/libten | 00c6dcc91c8d769c74ed9063277b1120c9084427 | [
"Apache-2.0"
] | 23 | 2015-02-28T12:51:54.000Z | 2021-07-21T10:34:20.000Z | include/ten/task/rendez.hh | toffaletti/libten | 00c6dcc91c8d769c74ed9063277b1120c9084427 | [
"Apache-2.0"
] | 1 | 2015-04-26T05:44:18.000Z | 2015-04-26T05:44:18.000Z | include/ten/task/rendez.hh | toffaletti/libten | 00c6dcc91c8d769c74ed9063277b1120c9084427 | [
"Apache-2.0"
] | 8 | 2015-05-04T08:04:11.000Z | 2020-09-07T11:30:56.000Z | #ifndef LIBTEN_TASK_RENDEZ_HH
#define LIBTEN_TASK_RENDEZ_HH
#include "ten/task/qutex.hh"
namespace ten {
//! task aware condition rendezvous point
class rendez {
private:
std::mutex _m;
std::deque<ptr<task::impl>> _waiting;
public:
rendez() {}
rendez(const rendez &) = delete;
rendez &operator =(const rendez &) = delete;
~rendez();
void sleep(std::unique_lock<qutex> &lk);
template <typename Predicate>
void sleep(std::unique_lock<qutex> &lk, Predicate pred) {
while (!pred()) {
sleep(lk);
}
}
void wakeup();
void wakeupall();
};
} // namespace
#endif // LIBTEN_TASK_RENDEZ_HH
| 18.416667 | 61 | 0.631976 | toffaletti |
db5222a0ebfcfb4b8e0711e54a025d153a9ed701 | 1,024 | cpp | C++ | BasicTools/BasicToolsMain.cpp | daniel-anavaino/tinkercell | 7896a7f809a0373ab3c848d25e3691d10a648437 | [
"BSD-3-Clause"
] | 1 | 2021-01-07T13:12:51.000Z | 2021-01-07T13:12:51.000Z | BasicTools/BasicToolsMain.cpp | whipplelabs/tinkercell | 8528c46c2ea04bbb93d9f3a84156c67d8fbaa589 | [
"BSD-3-Clause"
] | 7 | 2020-04-12T22:25:46.000Z | 2020-04-13T07:50:40.000Z | BasicTools/BasicToolsMain.cpp | daniel-anavaino/tinkercell | 7896a7f809a0373ab3c848d25e3691d10a648437 | [
"BSD-3-Clause"
] | 2 | 2020-04-12T21:57:01.000Z | 2020-04-12T21:59:29.000Z | /****************************************************************************
Copyright (c) 2008 Deepak Chandran
Contact: Deepak Chandran (dchandran1@gmail.com)
See COPYRIGHT.TXT
Function that loads dll into main window
****************************************************************************/
#include "BasicToolsMain.h"
/*
extern "C" TINKERCELLEXPORT void loadTCTool(Tinkercell::MainWindow * main)
{
if (!main) return;
main->addTool(new Tinkercell::CollisionDetection);
main->addTool(new Tinkercell::ConnectionInsertion);
main->addTool(new Tinkercell::NodeInsertion);
main->addTool(new Tinkercell::NodeSelection);
main->addTool(new Tinkercell::ConnectionSelection);
main->addTool(new Tinkercell::TinkercellAboutBox);
main->addTool(new Tinkercell::GraphicsReplaceTool);
main->addTool(new Tinkercell::GraphicsTransformTool);
main->addTool(new Tinkercell::GroupHandlerTool);
main->addTool(new Tinkercell::NameFamilyDialog);
main->addTool(new Tinkercell::ConnectionMaker);
}
*/
| 35.310345 | 78 | 0.646484 | daniel-anavaino |
db55e0193f93b6748d2231af7d76463093d8a5c9 | 4,715 | inl | C++ | c++/Ail/ComString.inl | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | c++/Ail/ComString.inl | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | c++/Ail/ComString.inl | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////
//......................................................................................
// This is a part of AI Library [Arthur's Interfaces Library]. .
// 1998-2001 Arthur Amshukov .
//......................................................................................
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND .
// DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE .
//......................................................................................
////////////////////////////////////////////////////////////////////////////////////////
#ifndef __COMSTRING_INL__
#define __COMSTRING_INL__
#pragma once
__BEGIN_NAMESPACE__
////////////////////////////////////////////////////////////////////////////////////////
// class ComString
// ----- ---------
__INLINE__ const ComString& ComString::operator = (const ComString& other)
{
if(this != &other)
{
if(Str != null)
{
::SysFreeString(Str);
}
Str = other.Copy();
}
return *this;
}
__INLINE__ const ComString& ComString::operator = (const wchar* _str)
{
if(Str != null)
{
::SysFreeString(Str);
}
Str = ::SysAllocString(_str);
return *this;
}
__INLINE__ ComString::operator BSTR() const
{
return Str;
}
__INLINE__ bool ComString::operator ! () const
{
return Str == null;
}
__INLINE__ BSTR* ComString::operator & ()
{
return &Str;
}
__INLINE__ ComString& ComString::operator += (const ComString& other)
{
AppendBSTR(other.Str);
return *this;
}
__INLINE__ bool ComString::operator < (BSTR _str) const
{
if(_str == null && Str == NULL)
{
return false;
}
if(_str != null && Str != null)
{
return wcscmp(Str, _str) < 0;
}
return Str == null;
}
__INLINE__ bool ComString::operator == (BSTR _str) const
{
if(_str == null && Str == null)
{
return true;
}
if(_str != null && Str != null)
{
return wcscmp(Str, _str) == 0;
}
return false;
}
__INLINE__ bool ComString::operator < (const char* _str)
{
if(_str == null && Str == null)
{
return false;
}
if(_str != null && Str != null)
{
AutoPtrArray<wchar> p = _A2W(_str);
return wcscmp(Str, p) < 0;
}
return Str == null;
}
__INLINE__ bool ComString::operator == (const char* _str)
{
if(_str == null && Str == null)
{
return true;
}
if(_str != null && Str != null)
{
AutoPtrArray<wchar> p = _A2W(_str);
return wcscmp(Str, p) == 0;
}
return false;
}
__INLINE__ bool ComString::IsEmpty() const
{
return Str == null;
}
__INLINE__ char* ComString::GetAsText()
{
if(Str != null)
{
return _W2A(Str);
}
return null;
}
__INLINE__ BSTR ComString::GetStr() const
{
return Str;
}
__INLINE__ uint ComString::GetCount() const
{
return (Str == null) ? 0 : ::SysStringLen(Str);
}
__INLINE__ BSTR ComString::Copy() const
{
return ::SysAllocStringLen(Str, ::SysStringLen(Str));
}
__INLINE__ HRESULT ComString::CopyTo(BSTR* _str)
{
if(_str == null)
{
return E_POINTER;
}
*_str = ::SysAllocStringLen(Str, ::SysStringLen(Str));
if(*_str == null)
{
return E_OUTOFMEMORY;
}
return S_OK;
}
__INLINE__ void ComString::Attach(BSTR _str)
{
if(Str == null)
{
Str = _str;
}
}
__INLINE__ BSTR ComString::Detach()
{
BSTR str = Str;
Str = null;
return str;
}
__INLINE__ void ComString::Empty()
{
if(Str != null)
{
::SysFreeString(Str), Str = null;
}
}
__INLINE__ HRESULT ComString::Append(const wchar* _str)
{
return Append(_str, wcslen(_str));
}
__INLINE__ HRESULT ComString::Append(const wchar* _str, uint _count)
{
int count = GetCount();
BSTR str = ::SysAllocStringLen(NULL, count+_count);
if(_str == NULL)
{
return E_OUTOFMEMORY;
}
memcpy(str, Str, count*sizeof(wchar));
memcpy(str+count, _str, _count*sizeof(wchar));
str[count+_count] = null;
::SysFreeString(Str);
Str = str;
return S_OK;
}
__INLINE__ HRESULT ComString::Append(const ComString& other)
{
return Append(other.Str, ::SysStringLen(other.Str));
}
__INLINE__ HRESULT ComString::AppendBSTR(BSTR _str)
{
return Append(_str, ::SysStringLen(_str));
}
////////////////////////////////////////////////////////////////////////////////////////
__END_NAMESPACE__
#endif // __COMSTRING_INL__
| 19.564315 | 88 | 0.502439 | aamshukov |
db593c520c989c27d2ec2cbd4ddc81099fa6aba0 | 2,843 | cpp | C++ | android-30/android/widget/GridLayout_LayoutParams.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-30/android/widget/GridLayout_LayoutParams.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/widget/GridLayout_LayoutParams.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../content/Context.hpp"
#include "../content/res/TypedArray.hpp"
#include "../view/ViewGroup_LayoutParams.hpp"
#include "../view/ViewGroup_MarginLayoutParams.hpp"
#include "./GridLayout_Spec.hpp"
#include "../../JObject.hpp"
#include "./GridLayout_LayoutParams.hpp"
namespace android::widget
{
// Fields
android::widget::GridLayout_Spec GridLayout_LayoutParams::columnSpec()
{
return getObjectField(
"columnSpec",
"Landroid/widget/GridLayout$Spec;"
);
}
android::widget::GridLayout_Spec GridLayout_LayoutParams::rowSpec()
{
return getObjectField(
"rowSpec",
"Landroid/widget/GridLayout$Spec;"
);
}
// QJniObject forward
GridLayout_LayoutParams::GridLayout_LayoutParams(QJniObject obj) : android::view::ViewGroup_MarginLayoutParams(obj) {}
// Constructors
GridLayout_LayoutParams::GridLayout_LayoutParams()
: android::view::ViewGroup_MarginLayoutParams(
"android.widget.GridLayout$LayoutParams",
"()V"
) {}
GridLayout_LayoutParams::GridLayout_LayoutParams(android::view::ViewGroup_LayoutParams arg0)
: android::view::ViewGroup_MarginLayoutParams(
"android.widget.GridLayout$LayoutParams",
"(Landroid/view/ViewGroup$LayoutParams;)V",
arg0.object()
) {}
GridLayout_LayoutParams::GridLayout_LayoutParams(android::view::ViewGroup_MarginLayoutParams arg0)
: android::view::ViewGroup_MarginLayoutParams(
"android.widget.GridLayout$LayoutParams",
"(Landroid/view/ViewGroup$MarginLayoutParams;)V",
arg0.object()
) {}
GridLayout_LayoutParams::GridLayout_LayoutParams(android::widget::GridLayout_LayoutParams &arg0)
: android::view::ViewGroup_MarginLayoutParams(
"android.widget.GridLayout$LayoutParams",
"(Landroid/widget/GridLayout$LayoutParams;)V",
arg0.object()
) {}
GridLayout_LayoutParams::GridLayout_LayoutParams(android::content::Context arg0, JObject arg1)
: android::view::ViewGroup_MarginLayoutParams(
"android.widget.GridLayout$LayoutParams",
"(Landroid/content/Context;Landroid/util/AttributeSet;)V",
arg0.object(),
arg1.object()
) {}
GridLayout_LayoutParams::GridLayout_LayoutParams(android::widget::GridLayout_Spec arg0, android::widget::GridLayout_Spec arg1)
: android::view::ViewGroup_MarginLayoutParams(
"android.widget.GridLayout$LayoutParams",
"(Landroid/widget/GridLayout$Spec;Landroid/widget/GridLayout$Spec;)V",
arg0.object(),
arg1.object()
) {}
// Methods
jboolean GridLayout_LayoutParams::equals(JObject arg0) const
{
return callMethod<jboolean>(
"equals",
"(Ljava/lang/Object;)Z",
arg0.object<jobject>()
);
}
jint GridLayout_LayoutParams::hashCode() const
{
return callMethod<jint>(
"hashCode",
"()I"
);
}
void GridLayout_LayoutParams::setGravity(jint arg0) const
{
callMethod<void>(
"setGravity",
"(I)V",
arg0
);
}
} // namespace android::widget
| 29.926316 | 127 | 0.744636 | YJBeetle |
db5e6868fb6e3a7e465cb9417a7fbc4cfd3abbd0 | 2,259 | cpp | C++ | labs/6/Practice_03 - The big 4/Solutions/Marta'sProject/MartenitsaGenerator.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 19 | 2020-02-21T16:46:50.000Z | 2022-01-26T19:59:49.000Z | labs/6/Practice_03 - The big 4/Solutions/Marta'sProject/MartenitsaGenerator.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 1 | 2020-03-14T08:09:45.000Z | 2020-03-14T08:09:45.000Z | labs/6/Practice_03 - The big 4/Solutions/Marta'sProject/MartenitsaGenerator.cpp | triffon/oop-2019-20 | db199631d59ddefdcc0c8eb3d689de0095618f92 | [
"MIT"
] | 11 | 2020-02-23T12:29:58.000Z | 2021-04-11T08:30:12.000Z | //
// Created by yasen on 3/8/20.
//
#include <time.h>
#include <stdlib.h>
#include "MartenitsaGenerator.h"
const size_t countNames = 8;
const char* names[countNames] = {"Yasen", "Gosho", "Victor", "Niki", "Gabi", "Victoria", "Tedi", "Andi"};
const size_t countWishes = 5;
const char* wishes[countWishes] = {"Zdrave", "Mnogo shtastie", "Mnogo 6ci", "Zavurshvane na FMI", "Lubov"};
MartenitsaGenerator::MartenitsaGenerator(size_t length, size_t countBeads)
: defaultLength(length)
, defaultCountBeads(countBeads) {
srand(time(NULL));
if(length == 0) {
defaultLength = rand() % 20 + 10;
}
if(countBeads == 0) {
defaultCountBeads = rand() % 20 + 10;
}
}
Martenitsa MartenitsaGenerator::generate() {
return Martenitsa(names[rand()%countNames], wishes[rand()%countWishes],defaultLength, defaultCountBeads);
}
Martenitsa MartenitsaGenerator::generateByName(const char* name) {
return Martenitsa(name, wishes[rand()%countWishes], defaultLength, defaultCountBeads);
}
Martenitsa MartenitsaGenerator::generateByWish(const char* wish) {
return Martenitsa(names[rand()%countNames], wish, defaultLength, defaultCountBeads);
}
Martenitsa MartenitsaGenerator::generateByNameAndWish(const char* name, const char* wish) {
return Martenitsa(name, wish, defaultLength, defaultCountBeads);
}
void MartenitsaGenerator::generateList(size_t count) {
if( count < list.getCapacity() ){
for (int i = 0; i < count; ++i) {
list.add(this->generate());
}
}
}
void MartenitsaGenerator::generateListByName(const char *name, size_t count) {
if( count < list.getCapacity() ){
for (int i = 0; i < count; ++i) {
list.add(this->generateByName(name));
}
}
}
void MartenitsaGenerator::generateListByWish(const char *wish, size_t count) {
if( count < list.getCapacity() ){
for (int i = 0; i < count; ++i) {
list.add(this->generateByWish(wish));
}
}
}
void MartenitsaGenerator::generateListByNameAndWish(const char *name, const char *wish, size_t count) {
if( count < list.getCapacity() ){
for (int i = 0; i < count; ++i) {
list.add(this->generateByNameAndWish(name, wish));
}
}
}
| 29.723684 | 109 | 0.655157 | triffon |
db5e784623c086f1a1d751192a36a422f297bed4 | 869 | cpp | C++ | cpp/0200-0299/206. Reverse Linked List/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | cpp/0200-0299/206. Reverse Linked List/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | cpp/0200-0299/206. Reverse Linked List/solution.cpp | RapDoodle/LeetCode-Solutions | 6f14b7621bc6db12303be7f85508f3a5b2c2c30a | [
"MIT"
] | null | null | null | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = nullptr, *next;
while (head) {
// Step 1: Register the next node
next = head->next;
// Step 2: Modify the reference to the next to
// the current node.
head->next = prev;
// Step 3: Register the previous node with the
// current node
prev = head;
// Step 4: Move on to the next node
head = next;
}
return prev;
}
}; | 27.15625 | 62 | 0.484465 | RapDoodle |
db68041d6e994c3c66b299fa5ef76e9ace82150c | 3,627 | cpp | C++ | dev/test/so_5/environment/stop_guards/parallel_remove_50k/main.cpp | ZaMaZaN4iK/sobjectizer | afe9fc4d9fac6157860ec4459ac7a129223be87c | [
"BSD-3-Clause"
] | 272 | 2019-05-16T11:45:54.000Z | 2022-03-28T09:32:14.000Z | dev/test/so_5/environment/stop_guards/parallel_remove_50k/main.cpp | ZaMaZaN4iK/sobjectizer | afe9fc4d9fac6157860ec4459ac7a129223be87c | [
"BSD-3-Clause"
] | 40 | 2019-10-29T18:19:18.000Z | 2022-03-30T09:02:49.000Z | dev/test/so_5/environment/stop_guards/parallel_remove_50k/main.cpp | ZaMaZaN4iK/sobjectizer | afe9fc4d9fac6157860ec4459ac7a129223be87c | [
"BSD-3-Clause"
] | 29 | 2019-05-16T12:05:32.000Z | 2022-03-19T12:28:33.000Z | /*
* A test for parallel remove of 5K stop_guards.
*
* NOTE: count of agents is reduced to 5K because it takes
* to much time inside virtual machines.
*/
#include <so_5/all.hpp>
#include <test/3rd_party/various_helpers/time_limited_execution.hpp>
#include <test/3rd_party/various_helpers/ensure.hpp>
#include <test/3rd_party/utest_helper/helper.hpp>
#include <random>
using namespace std;
int
random( int l, int r )
{
std::default_random_engine engine;
return std::uniform_int_distribution<int>( l, r )( engine );
}
struct shutdown_started final : public so_5::signal_t {};
class second_stop_guard_t final
: public so_5::stop_guard_t
, public std::enable_shared_from_this<second_stop_guard_t>
{
public :
struct remove_me final : public so_5::signal_t {};
second_stop_guard_t( so_5::mbox_t owner )
: m_owner( std::move(owner) )
{}
virtual void
stop() noexcept override
{
so_5::send< remove_me >( m_owner );
}
private :
const so_5::mbox_t m_owner;
};
const std::size_t N = 50000u;
class first_worker_t final : public so_5::agent_t
{
public :
struct worker_started final : public so_5::signal_t {};
first_worker_t( context_t ctx )
: so_5::agent_t( std::move(ctx) )
{
so_subscribe_self()
.event( &first_worker_t::on_worker_started );
}
virtual void
so_evt_finish() override
{
const auto finish_at = std::chrono::steady_clock::now();
std::cout << "stop completed in: "
<< std::chrono::duration_cast<
std::chrono::milliseconds >( finish_at - m_started_at ).count()
<< "ms" << std::endl;
}
private :
std::size_t m_active_workers = 0;
std::chrono::steady_clock::time_point m_started_at;
void
on_worker_started( mhood_t< worker_started > )
{
++m_active_workers;
if( m_active_workers >= N )
{
m_started_at = std::chrono::steady_clock::now();
so_environment().stop();
}
}
};
class second_worker_t final : public so_5::agent_t
{
struct do_init final : public so_5::signal_t {};
public :
second_worker_t(
context_t ctx,
so_5::mbox_t manager_mbox )
: so_5::agent_t( std::move(ctx) )
, m_manager_mbox( std::move(manager_mbox) )
{
so_subscribe_self()
.event( &second_worker_t::on_do_init )
.event( &second_worker_t::on_remove_me );
}
virtual void
so_evt_start() override
{
so_5::send_delayed< do_init >( *this,
std::chrono::milliseconds( random( 1, 50 ) ) );
}
private :
const so_5::mbox_t m_manager_mbox;
std::shared_ptr< second_stop_guard_t > m_guard;
void
on_do_init( mhood_t<do_init> )
{
m_guard = std::make_shared< second_stop_guard_t >( so_direct_mbox() );
so_environment().setup_stop_guard( m_guard );
so_5::send< first_worker_t::worker_started >( m_manager_mbox );
}
void
on_remove_me( mhood_t<second_stop_guard_t::remove_me> )
{
so_environment().remove_stop_guard( m_guard );
}
};
void make_stuff( so_5::environment_t & env )
{
namespace tpdisp = so_5::disp::thread_pool;
auto notify_mbox = env.create_mbox();
env.introduce_coop(
tpdisp::make_dispatcher( env ).binder(
tpdisp::bind_params_t().fifo( tpdisp::fifo_t::individual ) ),
[&]( so_5::coop_t & coop ) {
auto first = coop.make_agent< first_worker_t >();
for( std::size_t i = 0; i != N; ++i )
coop.make_agent< second_worker_t >( first->so_direct_mbox() );
} );
}
int
main()
{
try
{
run_with_time_limit(
[]() {
so_5::launch(
[&](so_5::environment_t & env) {
make_stuff( env );
},
[](so_5::environment_params_t & params) {
(void)params;
} );
},
600 );
}
catch(const exception & ex)
{
cerr << "Error: " << ex.what() << endl;
return 1;
}
return 0;
}
| 20.844828 | 72 | 0.682658 | ZaMaZaN4iK |
db6f03e9ba812e5765e04eeb77e91d0ff7fa5c7f | 8,899 | cc | C++ | aku/PhnReader.cc | phsmit/AaltoASR | 33cb58b288cc01bcdff0d6709a296d0dfcc7f74a | [
"BSD-3-Clause"
] | 78 | 2015-01-07T14:33:47.000Z | 2022-03-15T09:01:30.000Z | aku/PhnReader.cc | phsmit/AaltoASR | 33cb58b288cc01bcdff0d6709a296d0dfcc7f74a | [
"BSD-3-Clause"
] | 4 | 2015-05-19T13:00:34.000Z | 2016-07-26T12:29:32.000Z | aku/PhnReader.cc | phsmit/AaltoASR | 33cb58b288cc01bcdff0d6709a296d0dfcc7f74a | [
"BSD-3-Clause"
] | 32 | 2015-01-16T08:16:24.000Z | 2021-04-02T21:26:22.000Z | #include <ctype.h>
#include <vector>
#include <string>
#include <errno.h>
#include <string.h>
#include <sstream>
#include <cstdlib>
#include <assert.h>
#include "PhnReader.hh"
#include "str.hh"
namespace aku {
PhnReader::Phn::Phn()
: start(0), end(0)
{
}
PhnReader::PhnReader(HmmSet *model)
: m_file(NULL), m_model(model),
m_state_num_labels(false), m_relative_sample_numbers(false)
{
set_frame_rate(125); // Default frame rate
// Initialize the current state and its probability
m_cur_pdf.insert(IndexProbMap::value_type(-1, 1.0));
}
PhnReader::~PhnReader()
{
close();
}
void
PhnReader::open(std::string filename)
{
m_current_line = 0;
m_first_line = 0;
m_last_line = 0;
m_first_frame = 0;
m_last_frame = 0;
m_current_frame = -1;
m_eof_flag = false;
close();
m_file = fopen(filename.c_str(), "r");
if (!m_file) {
fprintf(stderr, "PhnReader::open(): could not open %s\n",
filename.c_str());
perror("error");
exit(1);
}
}
void
PhnReader::close()
{
if (m_file)
fclose(m_file);
m_file = NULL;
}
void
PhnReader::reset(void)
{
assert( m_file != NULL );
fseek(m_file, 0, SEEK_SET);
m_current_line = 0;
m_current_frame = -1;
m_eof_flag = false;
if (m_first_frame > 0)
set_frame_limits(m_first_frame, m_last_frame);
if (m_first_line > 0)
set_line_limits(m_first_line, m_last_line, NULL);
}
void
PhnReader::set_line_limits(int first_line, int last_line,
int *first_frame)
{
Phn phn;
m_first_line = first_line;
m_last_line = last_line;
while (m_current_line < m_first_line)
next_phn_line(phn);
if (first_frame != NULL)
{
*first_frame = phn.start;
if (m_relative_sample_numbers)
(*first_frame) += m_first_frame;
}
}
void
PhnReader::set_frame_limits(int first_frame, int last_frame)
{
Phn phn;
m_first_frame = first_frame;
m_last_frame = last_frame;
if (!m_relative_sample_numbers)
{
long oldpos = ftell(m_file);
long curpos = oldpos;
while (next_phn_line(phn)) {
oldpos = curpos;
curpos = ftell(m_file);
if (phn.end < 0 || phn.end > m_first_frame)
{
fseek(m_file, oldpos, SEEK_SET);
m_current_line--;
return;
}
}
}
}
bool
PhnReader::init_utterance_segmentation(void)
{
m_eof_flag = false;
if (!next_phn_line(m_cur_phn))
m_eof_flag = true;
return !m_eof_flag;
}
bool
PhnReader::next_frame(void)
{
int cur_state_index = -1;
assert( m_model != NULL );
if (m_eof_flag)
return false;
// Segmentator object must reset the model cache during next_frame()
m_model->reset_cache();
if (m_current_frame == -1)
{
// Initialize the current frame to the beginning of the file
m_current_frame = m_cur_phn.start;
assert( m_cur_phn.end >= m_current_frame );
}
else
{
m_current_frame++;
}
assert( m_current_frame >= m_cur_phn.start );
assert( m_current_frame <= m_cur_phn.end );
if (m_state_num_labels)
{
cur_state_index = m_cur_phn.state;
}
else
{
if (m_cur_phn.state < 0)
throw std::string("PhnReader::next_frame(): A state segmented phn file is required");
Hmm &hmm = m_model->hmm(m_model->hmm_index(m_cur_phn.label[0]));
cur_state_index = hmm.state(m_cur_phn.state);
}
m_cur_pdf.clear();
m_cur_pdf.insert(IndexProbMap::value_type(
m_model->emission_pdf_index(cur_state_index), 1.0));
if (m_cur_phn.label.size() > 0)
{
m_cur_label = m_cur_phn.label[0];
if (m_cur_phn.label.size() > 1)
{
for (int i = 1 ; i < (int)m_cur_phn.label.size(); i++)
{
m_cur_label += ",";
m_cur_label += m_cur_phn.label[i];
}
}
}
else
m_cur_label = str::fmt(16, "%d", m_cur_phn.state);
if (m_cur_phn.label.size() > 0)
{
m_cur_label = m_cur_phn.label[0];
if (m_cur_phn.label.size() > 1)
{
for (int i = 1 ; i < (int)m_cur_phn.label.size(); i++)
{
m_cur_label += ",";
m_cur_label += m_cur_phn.label[i];
}
}
}
else
m_cur_label = str::fmt(16, "%d", m_cur_phn.state);
bool new_phn_loaded = false;
Phn prev_phn = m_cur_phn;
// Do we need to load more phn lines?
while (m_current_frame+1 >= m_cur_phn.end)
{
if (!next_phn_line(m_cur_phn))
{
m_eof_flag = true; // For the next call
break;
}
new_phn_loaded = true;
}
if (m_collect_transitions)
{
m_transition_info.clear();
if (!m_eof_flag) // Not the last frame
{
std::vector<int> &tr_index=m_model->state(cur_state_index).transitions();
int transition_index = -1;
if (new_phn_loaded)
{
// Out transition
if (m_state_num_labels)
{
// We don't have information which transition it is, select the first
// out transition
for (int i = 0; i < (int)tr_index.size(); i++)
if (m_model->transition(tr_index[i]).target_offset != 0)
{
transition_index = tr_index[i];
break;
}
}
else
{
int cur_state = prev_phn.state;
Hmm &cur_hmm = m_model->hmm(m_model->hmm_index(prev_phn.label[0]));
// Find the correct transition
for (int i = 0; i < (int)tr_index.size(); i++)
{
int next_state =
m_model->transition(tr_index[i]).target_offset+cur_state;
if ((next_state >= cur_hmm.num_states() &&
m_cur_phn.state == 0) ||
(m_model->transition(tr_index[i]).target_offset != 0 &&
next_state == m_cur_phn.state))
{
transition_index = tr_index[i];
break;
}
}
}
}
else
{
// Self transition
for (int i = 0; i < (int)tr_index.size(); i++)
if (m_model->transition(tr_index[i]).target_offset == 0)
{
transition_index = tr_index[i];
break;
}
}
if (transition_index == -1)
{
throw std::string("PhnReader::next_frame(): Correct transition was not found");
}
if (transition_index != -1)
{
m_transition_info.insert(IndexProbMap::value_type(
transition_index, 1.0));
}
}
}
return true;
}
bool
PhnReader::next_phn_line(Phn &phn)
{
if (m_last_line > 0 && m_current_line >= m_last_line)
return false;
do {
// Read line at time
if (!str::read_line(&m_line, m_file)) {
if (ferror(m_file)) {
throw str::fmt(1024,
"PhnReader::next_phn_line(): read error on line %d: %s\n",
m_current_line, strerror(errno));
}
if (feof(m_file))
return false;
assert(false);
}
str::chomp(&m_line);
} while (m_line.size() == 0);
// Parse the line in fields.
std::vector<std::string> fields;
phn.state = -1; // state default value !
// If the first char is digit, we have start and end fields.
if (isdigit(m_line[0])) {
str::split(&m_line, " \t", true, &fields, 4);
bool ok = true;
if (fields.size() > 2) {
// read start & end
phn.start = (int)(str::str2long(&fields[0], &ok)/m_samples_per_frame);
phn.end = (int)(str::str2long(&fields[1], &ok)/m_samples_per_frame);
// read state
if (strchr(fields[2].c_str(), '.') != NULL){
phn.state = atoi( (const char*)(strchr(fields[2].c_str(), '.') + 1) );
fields[2].erase(fields[2].find('.', 0), 2);
}
}
else
ok = false;
if (!ok || phn.start > phn.end) {
throw str::fmt(
1024,
"PhnReader::next_phn_line(): invalid start or end time on line %d:\n"
"%s\n", m_current_line, m_line.c_str());
}
fields.erase(fields.begin(), fields.begin() + 2);
}
// Otherwise we have just label and comments.
else {
str::split(&m_line, " \t", true, &fields, 2);
phn.start = -1;
phn.end = -1;
}
if (m_relative_sample_numbers && phn.start >= 0)
{
phn.start += m_first_frame;
phn.end += m_first_frame;
}
// Is the current starting time out of requested range?
if (m_last_frame > 0)
{
if (phn.start >= m_last_frame)
return false;
if (phn.end >= m_last_frame)
phn.end = m_last_frame;
}
if (m_first_frame > 0 && phn.start < m_first_frame && phn.start >= 0)
{
phn.start = m_first_frame;
assert( phn.start > phn.end );
}
// Read label and comments
phn.label.clear();
if (m_state_num_labels)
{
phn.state = atoi(fields[0].c_str()); // State number instead of label
}
else
{
str::split(&fields[0], ",", false, &phn.label);
}
if ((int)fields.size() > 1)
phn.comment = fields[1];
else
phn.comment = "";
m_current_line++;
return true;
}
}
| 22.136816 | 91 | 0.581189 | phsmit |
db6fe3e7f621bdbed417d65e1bfb824d40d5cdb3 | 2,027 | cpp | C++ | YorozuyaGSLib/source/__respond_checkDetail.cpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | YorozuyaGSLib/source/__respond_checkDetail.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | YorozuyaGSLib/source/__respond_checkDetail.cpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | #include <__respond_checkDetail.hpp>
#include <common/ATFCore.hpp>
START_ATF_NAMESPACE
namespace Detail
{
Info::__respond_checkctor___respond_check2_ptr __respond_checkctor___respond_check2_next(nullptr);
Info::__respond_checkctor___respond_check2_clbk __respond_checkctor___respond_check2_user(nullptr);
Info::__respond_checkdtor___respond_check6_ptr __respond_checkdtor___respond_check6_next(nullptr);
Info::__respond_checkdtor___respond_check6_clbk __respond_checkdtor___respond_check6_user(nullptr);
void __respond_checkctor___respond_check2_wrapper(struct __respond_check* _this)
{
__respond_checkctor___respond_check2_user(_this, __respond_checkctor___respond_check2_next);
};
void __respond_checkdtor___respond_check6_wrapper(struct __respond_check* _this)
{
__respond_checkdtor___respond_check6_user(_this, __respond_checkdtor___respond_check6_next);
};
::std::array<hook_record, 2> __respond_check_functions =
{
_hook_record {
(LPVOID)0x14027a5a0L,
(LPVOID *)&__respond_checkctor___respond_check2_user,
(LPVOID *)&__respond_checkctor___respond_check2_next,
(LPVOID)cast_pointer_function(__respond_checkctor___respond_check2_wrapper),
(LPVOID)cast_pointer_function((void(__respond_check::*)())&__respond_check::ctor___respond_check)
},
_hook_record {
(LPVOID)0x140273060L,
(LPVOID *)&__respond_checkdtor___respond_check6_user,
(LPVOID *)&__respond_checkdtor___respond_check6_next,
(LPVOID)cast_pointer_function(__respond_checkdtor___respond_check6_wrapper),
(LPVOID)cast_pointer_function((void(__respond_check::*)())&__respond_check::dtor___respond_check)
},
};
}; // end namespace Detail
END_ATF_NAMESPACE
| 44.065217 | 113 | 0.696596 | lemkova |
db71e1a9090351940a94603b210a7731ca9206aa | 2,511 | cpp | C++ | src/index_buffer.cpp | Arnyxa/Pepper | 1da7b68badff9fcd04724cdac0c3434c5c0b5448 | [
"MIT"
] | 1 | 2021-11-28T00:40:51.000Z | 2021-11-28T00:40:51.000Z | src/index_buffer.cpp | Arnyxa/Pepper | 1da7b68badff9fcd04724cdac0c3434c5c0b5448 | [
"MIT"
] | null | null | null | src/index_buffer.cpp | Arnyxa/Pepper | 1da7b68badff9fcd04724cdac0c3434c5c0b5448 | [
"MIT"
] | 1 | 2021-12-08T21:44:01.000Z | 2021-12-08T21:44:01.000Z | #include "index_buffer.hpp"
namespace ppr
{
index_buffer::index_buffer(const vk::Device& a_device)
: m_device(a_device)
, m_buffer(a_device)
, m_indices({0, 1, 2, 2, 3, 0})
{}
void index_buffer::create(const vk::PhysicalDevice& a_physical_device,
const vk::CommandPool& a_command_pool,
const vk::Queue& a_graphics_queue)
{
const vk::DeviceSize buffer_size = sizeof(m_indices[0]) * m_indices.size();
buffer staging_buffer(m_device);
auto staging_buffer_info = buffer::create_info(a_physical_device,
vk::MemoryPropertyFlagBits::eHostVisible
| vk::MemoryPropertyFlagBits::eHostCoherent,
vk::BufferUsageFlagBits::eTransferSrc,
buffer_size);
staging_buffer.create(staging_buffer_info);
auto memory_map = m_device.mapMemory(staging_buffer.memory(), 0, staging_buffer_info.data.size);
memcpy(memory_map, m_indices.data(), staging_buffer_info.data.size);
m_device.unmapMemory(staging_buffer.memory());
auto index_buffer_info = buffer::create_info(a_physical_device,
vk::MemoryPropertyFlagBits::eDeviceLocal,
vk::BufferUsageFlagBits::eTransferDst
| vk::BufferUsageFlagBits::eIndexBuffer,
buffer_size);
m_buffer.create(index_buffer_info);
auto buffer_copy_data = buffer::copy_data(m_buffer,
nullptr,
buffer_size,
a_command_pool,
a_graphics_queue);
staging_buffer.copy(buffer_copy_data);
staging_buffer.destroy();
}
void index_buffer::destroy() const
{
m_buffer.destroy();
}
const vk::Buffer& index_buffer::get() const
{
return m_buffer.get();
}
vk::Buffer& index_buffer::get_mut()
{
return m_buffer.get_mut();
}
const std::vector<uint16_t>& index_buffer::indices() const
{
return m_indices;
}
} | 38.630769 | 104 | 0.503783 | Arnyxa |
db75794d0cbfb91de8c5672a4b4dd5460cac6d32 | 879 | cpp | C++ | Alpha/src/Alpha/Renderer/Texture.cpp | TygoB-B5/AlphaEngine | f197ce8a9bd66b17bc9170cb3b0a9bbd3918991e | [
"Apache-2.0"
] | null | null | null | Alpha/src/Alpha/Renderer/Texture.cpp | TygoB-B5/AlphaEngine | f197ce8a9bd66b17bc9170cb3b0a9bbd3918991e | [
"Apache-2.0"
] | null | null | null | Alpha/src/Alpha/Renderer/Texture.cpp | TygoB-B5/AlphaEngine | f197ce8a9bd66b17bc9170cb3b0a9bbd3918991e | [
"Apache-2.0"
] | null | null | null | #include "appch.h"
#include "Texture.h"
#include "Renderer.h"
#include "Alpha/Platform/OpenGL/OpenGLTexture2D.h"
namespace Alpha
{
Ref<Texture2D> Texture2D::Create(const std::string& filepath)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: AP_CORE_ASSERT(false, "RenderAPI: \"None\" is not supported") return nullptr;
case RendererAPI::API::OpenGL: return std::make_shared<OpenGLTexture2D>(filepath);
}
AP_CORE_ASSERT(false, "Unknown RendererAPI");
return nullptr;
}
Ref<Texture2D> Texture2D::Create(uint32_t width, uint32_t height)
{
switch (Renderer::GetAPI())
{
case RendererAPI::API::None: AP_CORE_ASSERT(false, "RenderAPI: \"None\" is not supported") return nullptr;
case RendererAPI::API::OpenGL: return std::make_shared<OpenGLTexture2D>(width, height);
}
AP_CORE_ASSERT(false, "Unknown RendererAPI");
return nullptr;
}
} | 28.354839 | 108 | 0.730375 | TygoB-B5 |
db760f38d4973a1ba947d5ec530da9be1e8b5d4f | 1,317 | hpp | C++ | libs/PhiCore/include/phi/type_traits/underlying_type.hpp | AMS21/Phi | d62d7235dc5307dd18607ade0f95432ae3a73dfd | [
"MIT"
] | 3 | 2020-12-21T13:47:35.000Z | 2022-03-16T23:53:21.000Z | libs/PhiCore/include/phi/type_traits/underlying_type.hpp | AMS21/Phi | d62d7235dc5307dd18607ade0f95432ae3a73dfd | [
"MIT"
] | 53 | 2020-08-07T07:46:57.000Z | 2022-02-12T11:07:08.000Z | libs/PhiCore/include/phi/type_traits/underlying_type.hpp | AMS21/Phi | d62d7235dc5307dd18607ade0f95432ae3a73dfd | [
"MIT"
] | 1 | 2020-08-19T15:50:02.000Z | 2020-08-19T15:50:02.000Z | #ifndef INCG_PHI_CORE_TYPE_TRAITS_UNDERLYING_TYPE_HPP
#define INCG_PHI_CORE_TYPE_TRAITS_UNDERLYING_TYPE_HPP
#include "phi/phi_config.hpp"
#if PHI_HAS_EXTENSION_PRAGMA_ONCE()
# pragma once
#endif
#include "phi/compiler_support/intrinsics/underlying_type.hpp"
#include "phi/type_traits/false_t.hpp"
#include "phi/type_traits/integral_constant.hpp"
#include "phi/type_traits/is_enum.hpp"
DETAIL_PHI_BEGIN_NAMESPACE()
#if PHI_SUPPORTS_UNDERLYING_TYPE()
namespace detail
{
template <typename TypeT, bool = is_enum<TypeT>::value>
struct underlying_type_impl;
template <typename TypeT>
struct underlying_type_impl<TypeT, false>
{};
template <typename TypeT>
struct underlying_type_impl<TypeT, true>
{
using type = PHI_UNDERLYING_TYPE(TypeT);
};
} // namespace detail
template <typename TypeT>
struct underlying_type : public detail::underlying_type_impl<TypeT, is_enum<TypeT>::value>
{};
#else
template <typename TypeT>
struct underlying_type
{
static_assert(false_t<TypeT>,
"phi::underlying_type requires compiler support for intrinsic underlying_type");
};
#endif
template <typename TypeT>
using underlying_type_t = typename underlying_type<TypeT>::type;
DETAIL_PHI_END_NAMESPACE()
#endif // INCG_PHI_CORE_TYPE_TRAITS_UNDERLYING_TYPE_HPP
| 23.517857 | 98 | 0.77221 | AMS21 |
db77a349faf98742cd8e99278a578fe25e3e908e | 2,898 | tpp | C++ | STEM4U/src.tpp/Finantial_en-us.tpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | 8 | 2021-02-28T12:07:43.000Z | 2021-11-14T19:40:45.000Z | STEM4U/src.tpp/Finantial_en-us.tpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | 8 | 2021-03-20T10:46:58.000Z | 2022-01-27T19:50:32.000Z | STEM4U/src.tpp/Finantial_en-us.tpp | XOULID/Anboto | 2743b066f23bf2db9cc062d3adedfd044bc69ec1 | [
"Apache-2.0"
] | 1 | 2021-08-20T09:15:18.000Z | 2021-08-20T09:15:18.000Z | topic "Finantial functions";
[H6;0 $$1,0#05600065144404261032431302351956:begin]
[i448;a25;kKO9;2 $$2,0#37138531426314131252341829483370:codeitem]
[l288;2 $$3,0#27521748481378242620020725143825:desc]
[0 $$4,0#96390100711032703541132217272105:end]
[i448;a25;kKO9; $$5,0#37138531426314131252341829483380:structitem]
[ $$0,0#00000000000000000000000000000000:Default]
[{_}%EN-US
[ {{10000@3 [s0; [*@7;4 Financial functions]]}}&]
[s1;%- &]
[s0;%- &]
[s0; [2 Some financial functions.]&]
[s0;2 &]
[s4; &]
[s1;%- &]
[s2;:Upp`:`:NetPresentValue`(double`,const Upp`:`:Vector`<double`>`&`):%- [@(0.0.255) d
ouble]_[* NetPresentValue]([@(0.0.255) double]_[*@3 discountRate],
[@(0.0.255) const]_[_^Upp`:`:Vector^ Vector]<[@(0.0.255) double]>_`&[*@3 cf])&]
[s3; Calculates the [^https`:`/`/en`.wikipedia`.org`/wiki`/Net`_present`_value^ Net
present value].with [%-*@3 discountRate] discount rate, and [%-*@3 cf]
cash flow.&]
[s4; &]
[s1;%- &]
[s2;:Upp`:`:InternalRateOfReturn`(const Upp`:`:Vector`<double`>`&`,double`,double`,int`,double`):%- [_^Upp`:`:Vector^ V
ector]<[@(0.0.255) double]>_[* InternalRateOfReturn]([@(0.0.255) const]_[_^Upp`:`:Vector^ V
ector]<[@(0.0.255) double]>_`&[*@3 cf], [@(0.0.255) double]_[*@3 lowRate],
[@(0.0.255) double]_[*@3 highRate], [@(0.0.255) int]_[*@3 maxIteration],
[@(0.0.255) double]_[*@3 precisionReq])&]
[s3; Calculates the [^https`:`/`/en`.wikipedia`.org`/wiki`/Internal`_rate`_of`_return^ I
nternal rate of return] of an investment. The arguments are:&]
[s3;i150;O0; [%-*@3 cf] is the cash flow.&]
[s3;i150;O0; [%-*@3 lowRate] is the initial rate with which we compute
the NPV.&]
[s3;i150;O0; [%-*@3 highRate] is the highest rate up to which we should
consider for computing NPV.&]
[s3;i150;O0; [%-*@3 maxIteration]: There is always a possibility of
not able to arrive at the rate for certain cash flows. This variable
acts as a stopper for the number of iterations the code should
check for NPV so as to ensure that the program does not go for
an infinite loop&]
[s3;i150;O0; [%-*@3 precisionReq] : NPV value will not normally hit
zero. We can find the NPV value with a precision upto certain
value. When the computed NPV is below this value, the calculation
stop and the rate used will be the IRR.&]
[s4; &]
[s1;%- &]
[s2;:Upp`:`:PMT`(double`,double`,double`): [%-@(0.0.255) double][%- _][%-* PMT][%- (][%-@(0.0.255) d
ouble][%- _][%-*@3 rate][%- , ][%-@(0.0.255) double][%- _][%-*@3 nper][%- ,
][%-@(0.0.255) double][%- _][%-*@3 pv][%- )].&]
[s3; Calculates the payment for a loan based on constant payments
and a constant interest rate. The arguments are:&]
[s3;i150;O0; [%-*@3 rate] is the interest rate for the loan.&]
[s3;i150;O0; [%-*@3 nper] is the total number of payments for the loan.&]
[s3;i150;O0; [%-*@3 pv] is the present value, or the total amount that
a series of future payments is worth now; also known as the principal.&]
[s4; ]] | 51.75 | 119 | 0.657695 | XOULID |
db7df66895646f2e3ae4cf663adf93d907f2da17 | 2,353 | hpp | C++ | src/Enki/Signals/Connection.hpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | 2 | 2021-01-20T11:31:44.000Z | 2022-01-11T01:38:01.000Z | src/Enki/Signals/Connection.hpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | null | null | null | src/Enki/Signals/Connection.hpp | Zephilinox/Enki | 5f405fec9ae0f3c3344a99fbee590d76ed4dbe55 | [
"MIT"
] | null | null | null | #pragma once
//STD
#include <functional>
#include <memory>
namespace enki
{
template <typename... Args>
class Signal;
class Disconnector;
/*
Connection is returned by signal.connect()
you use it to control disconnecting your function from the signal
*/
class Connection
{
public:
Connection() noexcept = default;
Connection(const Connection& c) = default;
//Not Required?
//Connection(Connection&& c) = default;
virtual ~Connection() noexcept = default;
//Not Required?
//Connection& operator=(const Connection& c) = default;
//Required
Connection& operator=(Connection&& c) noexcept = default;
//Check to see if the Connection is still valid
operator bool() const noexcept;
//Ensures both Connections are connected to the same Signal and referring to the same function
//Might return false if both connections are invalid, depending on what made them invalid.
friend bool operator==(const Connection& lhs, const Connection& rhs) noexcept
{
return lhs.slot_id == rhs.slot_id && lhs.dc.lock().get() == rhs.dc.lock().get();
}
//Returns true if disconnection was successful
//False if it was not, or if it's already disconnected
bool disconnect();
private:
//Signal needs to be able to create Connection with specific params
//Clients should not be able to, as it means they can do random shit to a signal
//Note: this means that a Signal<int> is a friend of Connection<bool>
//But this shouldn't be a problem, since it's created based on the Signal <Args...>
template <typename...>
friend class Signal;
//Only meant to be accessed by Signal
Connection(std::weak_ptr<Disconnector> dc, unsigned id) noexcept;
std::weak_ptr<Disconnector> dc;
unsigned slot_id = 0;
};
/*
Just a wrapper around Connection
Automatically disconnects on destruction
RAII
*/
class ManagedConnection : public Connection
{
public:
ManagedConnection() noexcept = default;
ManagedConnection(const Connection& c);
//Possibly useful
ManagedConnection(const ManagedConnection&) = default;
//Not Required?
//ManagedConnection(ManagedConnection&& c) noexcept = default;
~ManagedConnection() noexcept final;
//Not Required?
//ManagedConnection& operator=(const ManagedConnection& c) = default;
//Required, hides connection operator=? important?
ManagedConnection& operator=(ManagedConnection&& c) noexcept;
};
} // namespace enki | 26.438202 | 95 | 0.746706 | Zephilinox |
db89d4f0f8239dfd0efc249a800784cbfd936185 | 8,715 | cpp | C++ | src/etp/ClientSessionLaunchers.cpp | F2I-Consulting/fetpapi | fcb0d911bb7b49aabef8383ec916808cdb53b6b1 | [
"Apache-2.0"
] | 1 | 2021-04-20T06:56:43.000Z | 2021-04-20T06:56:43.000Z | src/etp/ClientSessionLaunchers.cpp | F2I-Consulting/fetpapi | fcb0d911bb7b49aabef8383ec916808cdb53b6b1 | [
"Apache-2.0"
] | null | null | null | src/etp/ClientSessionLaunchers.cpp | F2I-Consulting/fetpapi | fcb0d911bb7b49aabef8383ec916808cdb53b6b1 | [
"Apache-2.0"
] | 1 | 2021-04-20T08:17:14.000Z | 2021-04-20T08:17:14.000Z | /*-----------------------------------------------------------------------
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"; you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-----------------------------------------------------------------------*/
#include "ClientSessionLaunchers.h"
#include <sstream>
#include "HttpClientSession.h"
namespace
{
std::vector<Energistics::Etp::v12::Datatypes::SupportedProtocol> getRequestedProtocols() {
Energistics::Etp::v12::Datatypes::Version protocolVersion;
protocolVersion.major = 1;
protocolVersion.minor = 2;
protocolVersion.patch = 0;
protocolVersion.revision = 0;
std::vector<Energistics::Etp::v12::Datatypes::SupportedProtocol> requestedProtocols;
Energistics::Etp::v12::Datatypes::SupportedProtocol protocol;
protocol.protocol = static_cast<int32_t>(Energistics::Etp::v12::Datatypes::Protocol::Core);
protocol.protocolVersion = protocolVersion;
protocol.role = "server";
requestedProtocols.push_back(protocol);
protocol.protocol = static_cast<int32_t>(Energistics::Etp::v12::Datatypes::Protocol::Discovery);
protocol.protocolVersion = protocolVersion;
protocol.role = "store";
requestedProtocols.push_back(protocol);
protocol.protocol = static_cast<int32_t>(Energistics::Etp::v12::Datatypes::Protocol::Store);
protocol.protocolVersion = protocolVersion;
protocol.role = "store";
requestedProtocols.push_back(protocol);
protocol.protocol = static_cast<int32_t>(Energistics::Etp::v12::Datatypes::Protocol::DataArray);
protocol.protocolVersion = protocolVersion;
protocol.role = "store";
requestedProtocols.push_back(protocol);
protocol.protocol = static_cast<int32_t>(Energistics::Etp::v12::Datatypes::Protocol::StoreNotification);
protocol.protocolVersion = protocolVersion;
protocol.role = "store";
requestedProtocols.push_back(protocol);
return requestedProtocols;
}
std::vector<Energistics::Etp::v12::Datatypes::SupportedDataObject> getSupportedDataObjects() {
std::vector<Energistics::Etp::v12::Datatypes::SupportedDataObject> result;
Energistics::Etp::v12::Datatypes::SupportedDataObject supportedDataObject;
supportedDataObject.qualifiedType = "resqml20.*";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "resqml22.*";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml20.EpcExternalPartReference";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml21.PropertyKind";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml23.Activity";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml23.ActivityTemplate";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml23.GraphicalInformationSet";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml23.PropertyKind";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml23.TimeSeries";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "eml23.EpcExternalPartReference";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.Channel";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.Trajectory";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.Well";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.Wellbore";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.WellboreCompletion";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.WellboreGeometry";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "witsml20.WellCompletion";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "prodml21.FluidCharacterization";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "prodml21.FluidSystem";
result.push_back(supportedDataObject);
supportedDataObject.qualifiedType = "prodml21.TimeSeriesData";
result.push_back(supportedDataObject);
return result;
}
std::size_t getNegotiatedMaxWebSocketFramePayloadSize(const std::string & responseBody, std::size_t preferredMaxFrameSize) {
const auto maxWebSocketFramePayloadSizePos = responseBody.find("MaxWebSocketFramePayloadSize");
if (maxWebSocketFramePayloadSizePos != std::string::npos) {
std::istringstream iss(responseBody);
iss.seekg(maxWebSocketFramePayloadSizePos);
std::string temp;
std::size_t serverMaxWebSocketFramePayloadSize;
while (!iss.eof()) {
/* extracting word by word from stream */
iss >> temp;
/* Checking the given word is integer or not */
if (std::istringstream(temp) >> serverMaxWebSocketFramePayloadSize) {
return std::min(serverMaxWebSocketFramePayloadSize, preferredMaxFrameSize);
}
}
}
return preferredMaxFrameSize;
}
}
std::shared_ptr<ETP_NS::PlainClientSession> ETP_NS::ClientSessionLaunchers::createWsClientSession(InitializationParameters* initializationParams, const std::string & target, const std::string & authorization,
std::size_t preferredMaxFrameSize)
{
boost::asio::io_context ioc;
auto httpClientSession = std::make_shared<HttpClientSession>(ioc);
std::string etpServerCapTarget = target.empty() ? "/" : target;
if (etpServerCapTarget[etpServerCapTarget.size() - 1] != '/') {
etpServerCapTarget += '/';
}
etpServerCapTarget += ".well-known/etp-server-capabilities?GetVersion=etp12.energistics.org";
httpClientSession->run(initializationParams->getHost().c_str(), initializationParams->getPort(), etpServerCapTarget.c_str(), 11, authorization);
// Run the I/O service. The call will return when the get operation is complete.
ioc.run();
preferredMaxFrameSize = getNegotiatedMaxWebSocketFramePayloadSize(httpClientSession->getResponse().body(), preferredMaxFrameSize);
auto result = std::make_shared<PlainClientSession>(initializationParams, target.empty() ? "/" : target, authorization, preferredMaxFrameSize);
initializationParams->postSessionCreationOperation(result.get());
return result;
}
#ifdef WITH_ETP_SSL
#include "ssl/HttpsClientSession.h"
namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
std::shared_ptr<ETP_NS::SslClientSession> ETP_NS::ClientSessionLaunchers::createWssClientSession(InitializationParameters* initializationParams, const std::string & target, const std::string & authorization,
std::size_t preferredMaxFrameSize, const std::string & additionalCertificates)
{
// The SSL context is required, and holds certificates
ssl::context ctx{ ssl::context::sslv23_client };
if (!additionalCertificates.empty()) {
boost::system::error_code ec;
ctx.add_certificate_authority(
boost::asio::buffer(additionalCertificates.data(), additionalCertificates.size()), ec);
if (ec) {
std::cerr << "Cannot add certificates : " << additionalCertificates << std::endl;
return nullptr;
}
}
boost::asio::io_context ioc;
auto httpsClientSession = std::make_shared<HttpsClientSession>(ioc, ctx);
std::string etpServerCapTarget = target.empty() ? "/" : target;
if (etpServerCapTarget[etpServerCapTarget.size() - 1] != '/') {
etpServerCapTarget += '/';
}
etpServerCapTarget += ".well-known/etp-server-capabilities?GetVersion=etp12.energistics.org";
httpsClientSession->run(initializationParams->getHost().c_str(), initializationParams->getPort(), etpServerCapTarget.c_str(), 11, authorization);
// Run the I/O service. The call will return when the get operation is complete.
ioc.run();
preferredMaxFrameSize = getNegotiatedMaxWebSocketFramePayloadSize(httpsClientSession->getResponse().body(), preferredMaxFrameSize);
auto result = std::make_shared<SslClientSession>(ctx, initializationParams, target.empty() ? "/" : target, authorization, preferredMaxFrameSize);
initializationParams->postSessionCreationOperation(result.get());
return result;
}
#endif
| 43.358209 | 208 | 0.771199 | F2I-Consulting |
db8b626c8af92f1c61f97b46710390ea26815ac2 | 1,411 | cpp | C++ | number_theory/primes_and_factorization/prime_factors_seive.cpp | Zim95/cpp_proj | b73781be17e818fc778320a7498dc4d021b92ffa | [
"MIT"
] | 2 | 2019-04-22T11:04:59.000Z | 2021-03-01T18:32:25.000Z | number_theory/primes_and_factorization/prime_factors_seive.cpp | Zim95/cpp_proj | b73781be17e818fc778320a7498dc4d021b92ffa | [
"MIT"
] | null | null | null | number_theory/primes_and_factorization/prime_factors_seive.cpp | Zim95/cpp_proj | b73781be17e818fc778320a7498dc4d021b92ffa | [
"MIT"
] | 1 | 2019-04-18T14:04:38.000Z | 2019-04-18T14:04:38.000Z | /*
Getting prime factors by using sieve of eratosthenes.
-----------------------------------------------------
1. Calculate primes vector by using sieve method.
2. Divide by all primes less than the square root of n.
Computing seive = O(NloglogN)
Getting prime_factors = O(logN)
Total time complexity = O(NloglogN) + O(logN)
*/
#include<iostream>
#include<vector>
#include<cmath>
#define ll long long
using namespace std;
void sieve(int *p, vector<int> &primes) {
p[2] = 1;
primes.push_back(2);
for(int i=3; i<=1000000; i+=2) {
p[i] = 1;
}
for(ll i=3; i<=1000000; i+=2) {
if(p[i]==1) {
primes.push_back(i);
for(ll j=i*i; j<=1000000; j=j+i) {
p[j] = 0;
}
}
}
}
vector<int> prime_factors(int n, vector<int> &primes) {
vector<int> factors;
for(int i=0; primes[i]<sqrt(n); i++) {
if(n % primes[i] == 0) {
factors.push_back(primes[i]);
while(n%primes[i]==0) {
n = n/primes[i];
}
}
}
if(n!=1) {
factors.push_back(n);
}
return factors;
}
int main() {
int p[1000005] = {0};
vector<int> primes;
sieve(p, primes);
int n = 12;
vector<int> factors = prime_factors(n, primes);
for(int x: factors) {
cout << x << " ";
}
cout << endl;
return 0;
} | 23.131148 | 59 | 0.496102 | Zim95 |
db8b6b7e8decd23f9920569d99336604c87b033e | 1,127 | hpp | C++ | include/freedom/exponential_bucketizer.hpp | strikles/poker-mcts | 6bd1443a7b497cf64fafd4b25e8d3bb64219e18c | [
"MIT"
] | 9 | 2019-08-22T06:25:12.000Z | 2021-02-17T16:27:27.000Z | include/freedom/exponential_bucketizer.hpp | strikles/poker-mcts | 6bd1443a7b497cf64fafd4b25e8d3bb64219e18c | [
"MIT"
] | null | null | null | include/freedom/exponential_bucketizer.hpp | strikles/poker-mcts | 6bd1443a7b497cf64fafd4b25e8d3bb64219e18c | [
"MIT"
] | 4 | 2019-09-04T14:20:05.000Z | 2022-02-09T06:32:14.000Z | #ifndef EXPONENTIAL_BUCKETIZER_H
#define EXPONENTIAL_BUCKETIZER_H
#include "bucket_collection.hpp"
namespace freedom {
// ----------------------------------------------------------------------
/// @brief maps hands according to a exponential distribution
// ----------------------------------------------------------------------
class ExponentialBucketizer {
public:
// ----------------------------------------------------------------------
/// @brief maps a number of hands to a number of buckets according
/// to an balances distribution (same nb of hands in each bucket)
/// Strong hands are in low index buckets, bad hand in big index
/// buckets.
/// example: AA is in bucket 0, 72o is in bucket n
///
/// @param nb_buckets number of buckets to create
/// @param hands_ hands to map
///
/// @return mapped hands in a bucketcollection
// ----------------------------------------------------------------------
virtual BucketCollection map_hands(const unsigned &nb_buckets,
const vector<BucketHand> &hands_) const;
};
}
#endif
| 36.354839 | 77 | 0.496007 | strikles |
db8beebb82ec78f325016432f4541ab150d793b8 | 526 | cpp | C++ | FPSGame/src/Entity.cpp | brizzbrett/ObjectiveBasedFPS | d29eb3885a4399f0e20556b0571a1bb7a55c3476 | [
"MIT"
] | null | null | null | FPSGame/src/Entity.cpp | brizzbrett/ObjectiveBasedFPS | d29eb3885a4399f0e20556b0571a1bb7a55c3476 | [
"MIT"
] | null | null | null | FPSGame/src/Entity.cpp | brizzbrett/ObjectiveBasedFPS | d29eb3885a4399f0e20556b0571a1bb7a55c3476 | [
"MIT"
] | null | null | null | #include "Entity.hpp"
Entity::Entity(Model* m, glm::vec3 pos, int t) :
model(m), position(pos), type(t)
{
modelMatrix = glm::translate(glm::mat4(1.0f), this->position);
}
Entity::~Entity()
{
}
void Entity::Update()
{
//slog("Updating Entities...");
modelMatrix = glm::translate(glm::mat4(1.0f), this->position);
}
void Entity::Render(Shader* s)
{
GLuint MmatrixID = glGetUniformLocation(s->getProgram(), "Model");
glUniformMatrix4fv(MmatrixID, 1, GL_FALSE, &modelMatrix[0][0]);
if(model)
{
model->Render(s);
}
} | 19.481481 | 67 | 0.665399 | brizzbrett |
db930a33ca0d0471bd172283b18af4a3423f95f1 | 587 | cpp | C++ | euler2.cpp | akkiind4/Codechef | 83821c0b6056e3d631ad1d3273b41727074537bb | [
"MIT"
] | null | null | null | euler2.cpp | akkiind4/Codechef | 83821c0b6056e3d631ad1d3273b41727074537bb | [
"MIT"
] | null | null | null | euler2.cpp | akkiind4/Codechef | 83821c0b6056e3d631ad1d3273b41727074537bb | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
#define fo(i,a,b) for(int i=a;i<b;i++)
#define enter(a,n) fo(i,0,n)cin>>a[i]
#define nl cout<<'/n'
#define spc cout<<" "
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
long a=0,b=2,s=2;
long long c;
if(n<=2)
{
cout<<0<<endl;
continue;
}
while(1)
{
c = 4*b+a;
if(c>n)
break;
s+=c;
a=b;
b=c;
}
cout<<s<<endl;
}
return 0;
}
| 13.97619 | 40 | 0.502555 | akkiind4 |
db94220f8a54cb6681983126c6862c88ee14009b | 120 | cpp | C++ | CppUnitTest/Source/CppUnitTest/MyFunctionalTestActor.cpp | sharpwind612/UnrealCookbook | e55d2814f30c990d676e103996a592f2e6c05fcc | [
"MIT"
] | null | null | null | CppUnitTest/Source/CppUnitTest/MyFunctionalTestActor.cpp | sharpwind612/UnrealCookbook | e55d2814f30c990d676e103996a592f2e6c05fcc | [
"MIT"
] | null | null | null | CppUnitTest/Source/CppUnitTest/MyFunctionalTestActor.cpp | sharpwind612/UnrealCookbook | e55d2814f30c990d676e103996a592f2e6c05fcc | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "MyFunctionalTestActor.h"
| 24 | 79 | 0.766667 | sharpwind612 |
db99adbd43f0bfcb4468dac1722935685702f902 | 6,057 | cpp | C++ | src/widgets/source/ui/SequenceTableWidget.cpp | ahmedskhalil/SmartPeak | 3e0b137f2fec119d8c11e5450c80156576c36f3e | [
"MIT"
] | 13 | 2020-12-09T14:40:15.000Z | 2022-01-14T17:56:57.000Z | src/widgets/source/ui/SequenceTableWidget.cpp | ahmedskhalil/SmartPeak | 3e0b137f2fec119d8c11e5450c80156576c36f3e | [
"MIT"
] | 106 | 2020-12-02T20:50:58.000Z | 2022-03-26T10:45:57.000Z | src/widgets/source/ui/SequenceTableWidget.cpp | ahmedskhalil/SmartPeak | 3e0b137f2fec119d8c11e5450c80156576c36f3e | [
"MIT"
] | 8 | 2020-12-03T10:54:42.000Z | 2022-01-17T11:21:06.000Z | // --------------------------------------------------------------------------
// SmartPeak -- Fast and Accurate CE-, GC- and LC-MS(/MS) Data Processing
// --------------------------------------------------------------------------
// Copyright The SmartPeak Team -- Novo Nordisk Foundation
// Center for Biosustainability, Technical University of Denmark 2018-2021.
//
// 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 ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS 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.
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Ahmed Khalil, Bertrand Boudaud $
// $Authors: Douglas McCloskey $
// --------------------------------------------------------------------------
#include <SmartPeak/ui/SequenceTableWidget.h>
#include <misc/cpp/imgui_stdlib.h>
namespace SmartPeak
{
static const size_t sample_group_col = 2;
static const size_t sequence_segment_col = 3;
static const size_t replicate_group_name_col = 4;
static const size_t sample_type_col = 5;
bool SequenceTableWidget::isEditable(const size_t row, const size_t col) const
{
return ((col == sequence_segment_col) ||
(col == sample_group_col) ||
(col == replicate_group_name_col) ||
(col == sample_type_col));
}
void SequenceTableWidget::onEdit()
{
if (selected_cells_.empty())
return;
// we get one selected cell to display the default value and the edited column
auto one_selected_cell = selected_cells_.back();
size_t row = std::get<0>(one_selected_cell);
size_t col = std::get<1>(one_selected_cell);
auto injection = getInjectionFromTable(row, col);
if (!injection)
{
LOGE << "Cannot edit cell (" << row << ", " << col << ")";
return;
}
if (col == sequence_segment_col)
{
sequence_segment_editor_.open(getSequenceGroups(sequence_segment_col), injection->getMetaData().getSequenceSegmentName(),
[this](const std::string& sequence_segment_name)
{
for (const auto selected_cell : selected_cells_)
{
auto injection = getInjectionFromTable(std::get<0>(selected_cell), std::get<1>(selected_cell));
injection->getMetaData().setSequenceSegmentName(sequence_segment_name);
}
sequence_handler_->notifySequenceUpdated();
});
}
else if (col == sample_group_col)
{
sample_group_editor_.open(getSequenceGroups(sample_group_col), injection->getMetaData().getSampleGroupName(),
[this](const std::string& sample_group_name)
{
for (const auto selected_cell : selected_cells_)
{
auto injection = getInjectionFromTable(std::get<0>(selected_cell), std::get<1>(selected_cell));
injection->getMetaData().setSampleGroupName(sample_group_name);
}
sequence_handler_->notifySequenceUpdated();
});
}
else if (col == replicate_group_name_col)
{
replicate_group_name_editor_.open(getSequenceGroups(replicate_group_name_col), injection->getMetaData().getReplicateGroupName(),
[this](const std::string& replicate_group_name)
{
for (const auto selected_cell : selected_cells_)
{
auto injection = getInjectionFromTable(std::get<0>(selected_cell), std::get<1>(selected_cell));
injection->getMetaData().setReplicateGroupName(replicate_group_name);
}
sequence_handler_->notifySequenceUpdated();
});
}
else if (col == sample_type_col)
{
sample_type_editor_.open(injection->getMetaData().getSampleTypeAsString(),
[this](const std::string& sample_type_name)
{
if (stringToSampleType.find(sample_type_name) != stringToSampleType.end())
{
const auto sample_type = stringToSampleType.at(sample_type_name);
for (const auto selected_cell : selected_cells_)
{
auto injection = getInjectionFromTable(std::get<0>(selected_cell), std::get<1>(selected_cell));
injection->getMetaData().setSampleType(sample_type);
}
sequence_handler_->notifySequenceUpdated();
}
});
}
}
void SequenceTableWidget::drawPopups()
{
sequence_segment_editor_.draw();
sample_group_editor_.draw();
replicate_group_name_editor_.draw();
sample_type_editor_.draw();
}
std::set<std::string> SequenceTableWidget::getSequenceGroups(const size_t col)
{
std::set<std::string> groups;
for (size_t row = 0; row < table_data_.body_.dimension(0); ++row) {
if (checked_rows_.size() <= 0 || (checked_rows_.size() > 0 && checked_rows_(row))) {
std::string group = table_data_.body_(row, col);
groups.insert(group);
}
}
return groups;
}
InjectionHandler* SequenceTableWidget::getInjectionFromTable(const size_t row, const size_t col)
{
InjectionHandler* injection = nullptr;
std::string sample_name = table_data_.body_(row, 1);
auto find_it = std::find_if(sequence_handler_->getSequence().begin(),
sequence_handler_->getSequence().end(),
[&](const auto& injection_handler) { return injection_handler.getMetaData().getSampleName() == sample_name; });
if (find_it != sequence_handler_->getSequence().end())
{
injection = &(*find_it);
}
return injection;
}
}
| 39.848684 | 134 | 0.647515 | ahmedskhalil |
db99ff39baf58a8b31c0258871341eec5d8c4b07 | 7,066 | cc | C++ | DEM/Src/nebula2/src/gfx2/nd3d9server_main.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | 2 | 2017-04-30T20:24:29.000Z | 2019-02-12T08:36:26.000Z | DEM/Src/nebula2/src/gfx2/nd3d9server_main.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | DEM/Src/nebula2/src/gfx2/nd3d9server_main.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// nd3d9server_main.cc
// (C) 2003 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "gfx2/nd3d9server.h"
#include <Data/DataServer.h>
#include "gfx2/nd3d9texture.h"
#include <Events/EventManager.h>
#include <Gfx/Events/DisplayInput.h>
nD3D9Server* nD3D9Server::Singleton = 0;
nD3D9Server::nD3D9Server():
deviceBehaviourFlags(0),
pD3DXSprite(NULL),
pD3DFont(NULL),
pD3D9(0),
pD3D9Device(0),
depthStencilSurface(0),
backBufferSurface(0),
captureSurface(0),
effectPool(0),
featureSet(InvalidFeatureSet),
textElements(64, 64),
#if __NEBULA_STATS__
timeStamp(0.0),
queryResourceManager(0),
statsFrameCount(0),
statsNumTextureChanges(0),
statsNumRenderStateChanges(0),
statsNumDrawCalls(0),
statsNumPrimitives(0),
#endif
d3dxLine(0)
{
n_assert(!Singleton);
Singleton = this;
//WATCHER_INIT(watchNumPrimitives, "watchGfxNumPrimitives", DATA_TYPE(int));
//WATCHER_INIT(watchFPS, "watchGfxFPS", DATA_TYPE(float));
//WATCHER_INIT(watchNumDrawCalls, "watchGfxDrawCalls", DATA_TYPE(int));
//WATCHER_INIT(watchNumRenderStateChanges, "watchGfxRSChanges", DATA_TYPE(int));
memset(&devCaps, 0, sizeof(devCaps));
memset(&presentParams, 0, sizeof(presentParams));
memset(&shapeMeshes, 0, sizeof(shapeMeshes));
D3dOpen();
InitDeviceIdentifier();
}
//---------------------------------------------------------------------
nD3D9Server::~nD3D9Server()
{
if (displayOpen) CloseDisplay();
D3dClose();
n_assert(Singleton);
Singleton = NULL;
}
//---------------------------------------------------------------------
void nD3D9Server::D3dOpen()
{
n_assert(!pD3D9);
pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
n_assert2(pD3D9, "nD3D9Server: could not initialize Direct3D!\n");
UpdateFeatureSet();
}
//---------------------------------------------------------------------
void nD3D9Server::D3dClose()
{
n_assert(pD3D9 && !pD3D9Device);
int refCount = pD3D9->Release();
if (refCount > 0) n_printf("WARNING: Direct3D9 interface was still referenced (count = %d)\n", refCount);
pD3D9 = NULL;
}
//---------------------------------------------------------------------
bool nD3D9Server::OpenDisplay()
{
n_assert(!displayOpen);
SUBSCRIBE_PEVENT(OnDisplaySetCursor, nD3D9Server, OnSetCursor);
SUBSCRIBE_PEVENT(OnDisplayPaint, nD3D9Server, OnPaint);
SUBSCRIBE_PEVENT(OnDisplayToggleFullscreen, nD3D9Server, OnToggleFullscreenWindowed);
SUBSCRIBE_NEVENT(DisplayInput, nD3D9Server, OnDisplayInput);
// Don't do this in the constructor because the window's name and icon won't have been set at that time.
if (!Display.IsWindowOpen()) Display.OpenWindow();
if (!DeviceOpen()) FAIL;
nGfxServer2::OpenDisplay();
// Clear display
if (BeginFrame())
{
if (BeginScene())
{
Clear(AllBuffers, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0);
EndScene();
PresentScene();
}
EndFrame();
}
OK;
}
//---------------------------------------------------------------------
void nD3D9Server::CloseDisplay()
{
n_assert(displayOpen);
UNSUBSCRIBE_EVENT(OnDisplaySetCursor);
UNSUBSCRIBE_EVENT(OnDisplayPaint);
UNSUBSCRIBE_EVENT(OnDisplayToggleFullscreen);
UNSUBSCRIBE_EVENT(DisplayInput);
DeviceClose();
if (Display.IsWindowOpen()) Display.CloseWindow();
nGfxServer2::CloseDisplay();
}
//---------------------------------------------------------------------
// Implements the Windows message pump. Must be called once a frame OUTSIDE of BeginScene() / EndScene().
void nD3D9Server::Trigger()
{
Display.ProcessWindowMessages();
}
//---------------------------------------------------------------------
bool nD3D9Server::SaveScreenshot(const char* fileName, nTexture2::FileFormat fileFormat)
{
n_assert(fileName);
n_assert(pD3D9Device);
n_assert(SUCCEEDED(pD3D9Device->GetRenderTargetData(backBufferSurface, captureSurface)));
nString mangledPath = DataSrv->ManglePath(fileName);
D3DXIMAGE_FILEFORMAT d3dxFormat = nD3D9Texture::FileFormatToD3DX(fileFormat);
n_assert(SUCCEEDED(D3DXSaveSurfaceToFile(mangledPath.Get(), d3dxFormat, captureSurface, NULL, NULL)));
OK;
}
//---------------------------------------------------------------------
void nD3D9Server::EnterDialogBoxMode()
{
n_assert(pD3D9Device);
HRESULT hr;
nGfxServer2::EnterDialogBoxMode();
// reset the device with lockable backbuffer flag
OnDeviceCleanup(false);
D3DPRESENT_PARAMETERS p = presentParams;
p.MultiSampleType = D3DMULTISAMPLE_NONE;
p.Flags |= D3DPRESENTFLAG_LOCKABLE_BACKBUFFER;
hr = pD3D9Device->Reset(&p);
InitDeviceState();
OnDeviceInit(false);
pD3D9Device->SetDialogBoxMode(TRUE);
}
//---------------------------------------------------------------------
void nD3D9Server::LeaveDialogBoxMode()
{
n_assert(pD3D9Device);
nGfxServer2::LeaveDialogBoxMode();
pD3D9Device->SetDialogBoxMode(FALSE);
// only reset the device if it is currently valid
if (SUCCEEDED(pD3D9Device->TestCooperativeLevel()))
{
OnDeviceCleanup(false);
pD3D9Device->Reset(&presentParams);
InitDeviceState();
OnDeviceInit(false);
}
}
//---------------------------------------------------------------------
bool nD3D9Server::AreVertexShadersEmulated()
{
n_assert(pD3D9Device);
#if N_D3D9_FORCEMIXEDVERTEXPROCESSING
OK;
#else
if (DX7 == GetFeatureSet()) OK;
return !(deviceBehaviourFlags & D3DCREATE_HARDWARE_VERTEXPROCESSING);
#endif
}
//---------------------------------------------------------------------
bool nD3D9Server::OnSetCursor(const Events::CEventBase& Event)
{
if (!pD3D9Device) FAIL;
switch (cursorVisibility)
{
case nGfxServer2::None:
case nGfxServer2::Gui:
SetCursor(NULL);
pD3D9Device->ShowCursor(FALSE);
OK;
case nGfxServer2::System:
pD3D9Device->ShowCursor(FALSE);
FAIL;
case nGfxServer2::Custom:
SetCursor(NULL);
pD3D9Device->ShowCursor(TRUE);
OK;
}
FAIL;
}
//---------------------------------------------------------------------
bool nD3D9Server::OnPaint(const Events::CEventBase& Event)
{
if (Display.Fullscreen && pD3D9Device && !inDialogBoxMode)
pD3D9Device->Present(0, 0, 0, 0);
OK;
}
//---------------------------------------------------------------------
bool nD3D9Server::OnToggleFullscreenWindowed(const Events::CEventBase& Event)
{
Display.Fullscreen = !Display.Fullscreen;
CloseDisplay();
OpenDisplay();
OK;
}
//---------------------------------------------------------------------
// In full-screen mode, update the cursor position myself
bool nD3D9Server::OnDisplayInput(const Events::CEventBase& Event)
{
const Event::DisplayInput& Ev = (const Event::DisplayInput&)Event;
if (Display.Fullscreen && Ev.Type == Event::DisplayInput::MouseMove)
pD3D9Device->SetCursorPosition(Ev.MouseInfo.x, Ev.MouseInfo.y, 0);
OK;
}
//---------------------------------------------------------------------
| 28.723577 | 107 | 0.596235 | moltenguy1 |
db9c228d47929ec5a347bc18df963fdc5ac24abe | 16,291 | cpp | C++ | app/entities/Structure.cpp | isonil/survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2017-05-12T10:12:41.000Z | 2017-05-12T10:12:41.000Z | app/entities/Structure.cpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | null | null | null | app/entities/Structure.cpp | isonil/Survival | ecb59af9fcbb35b9c28fd4fe29a4628f046165c8 | [
"MIT"
] | 1 | 2019-01-09T04:05:36.000Z | 2019-01-09T04:05:36.000Z | #include "Structure.hpp"
#include "engine/app3D/sceneNodes/Model.hpp"
#include "engine/app3D/physics/RigidBody.hpp"
#include "engine/app3D/managers/SceneManager.hpp"
#include "engine/app3D/managers/PhysicsManager.hpp"
#include "engine/app3D/Device.hpp"
#include "engine/GUI/GUIManager.hpp"
#include "engine/GUI/IGUIRenderer.hpp"
#include "../defs/DefsCache.hpp"
#include "../defs/StructureDef.hpp"
#include "../defs/ItemDef.hpp"
#include "../defs/CachedCollisionShapeDef.hpp"
#include "../itemContainers/MultiSlotItemContainer.hpp"
#include "../world/World.hpp"
#include "../world/WorldPart.hpp"
#include "../world/ElectricitySystem.hpp"
#include "../world/Effect.hpp"
#include "../thisPlayer/ThisPlayer.hpp"
#include "../Global.hpp"
#include "../Core.hpp"
#include "../Snapper.hpp"
#include "../SoundPool.hpp"
#include "../EffectsPool.hpp"
#include "components/TurretComponent.hpp"
#include "components/ElectricityComponent.hpp"
#include "character/CharacterStatsOrSkillsRelatedFormulas.hpp"
#include "Character.hpp"
#include "Item.hpp"
namespace app
{
Structure::Structure(int entityID, const std::shared_ptr <StructureDef> &def)
: Entity{entityID},
m_def{def},
m_ownerEntityID{-1},
m_HP{},
m_shouldExplodeWhenRemovedFromWorld{}
{
TRACK;
if(!m_def)
throw engine::Exception{"Structure def is nullptr."};
m_HP = m_def->getMaxHP();
if(m_def->getTurretInfo().isTurret())
m_turretComponent = std::make_unique <TurretComponent> (*this);
if(m_def->usesElectricity())
m_electricityComponent = std::make_unique <ElectricityComponent> (*this);
if(m_def->hasSearchableItemContainer())
m_searchableItemContainer = std::make_shared <MultiSlotItemContainer> (k_searchableItemContainerSize);
}
bool Structure::wantsEverInWorldUpdate() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
return m_def->hasMass() || m_def->getTurretInfo().isTurret();
}
void Structure::setInWorldPosition(const engine::FloatVec3 &pos)
{
base::setInWorldPosition(pos);
if(m_model)
m_model->setPosition(pos);
if(m_rigidBody)
m_rigidBody->setPosition(pos);
if(m_effect) {
E_DASSERT(m_def, "Structure def is nullptr.");
m_effect->setPosition(pos + rotateAsMe(m_def->getEffectOffset()));
}
turret_setInWorldPosition(pos);
}
void Structure::setInWorldRotation(const engine::FloatVec3 &rot)
{
base::setInWorldRotation(rot);
if(m_model)
m_model->setRotation(rot);
if(m_rigidBody)
m_rigidBody->setRotation(rot);
if(m_effect) {
E_DASSERT(m_def, "Structure def is nullptr.");
m_effect->setRotation(rot);
}
turret_setInWorldRotation(rot);
}
bool Structure::canBuildOnTopOfIt() const
{
return true;
}
bool Structure::wantsToBeRemovedFromWorld() const
{
return isKilled();
}
std::vector <std::pair <engine::FloatVec3, engine::FloatVec3>> Structure::trySnapToMe(const StructureDef &structureDef, const engine::FloatVec3 &designatedPos) const
{
TRACK;
E_DASSERT(m_def, "Structure def is nullptr.");
if(!m_def->getCanSnapToOtherStructures() || !structureDef.getCanSnapToOtherStructures())
return {};
return Snapper::trySnap(*this, structureDef, designatedPos);
}
bool Structure::canBeDeconstructed(const Character &doer) const
{
return &getFactionDef() == &doer.getFactionDef();
}
bool Structure::isKilled() const
{
return m_HP <= 0;
}
engine::FloatVec3 Structure::getAIAimPosition() const
{
return getCenterPosition();
}
int Structure::getAIPotentialTargetPriority() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
return m_def->getTurretInfo().isTurret() ? 2 : 1;
}
std::shared_ptr <EffectDef> Structure::getOnHitEffectDefPtr() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
return m_def->getOnHitEffectDefPtr();
}
bool Structure::hasSearchableItemContainer() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
return m_def->hasSearchableItemContainer();
}
std::shared_ptr <MultiSlotItemContainer> Structure::getSearchableItemContainer() const
{
if(!m_searchableItemContainer)
throw engine::Exception{"This structure does not have any searchable item container. This should have been checked before."};
return m_searchableItemContainer;
}
std::string Structure::getName() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
return m_def->getCapitalizedLabel();
}
void Structure::onInWorldUpdate()
{
TRACK;
E_DASSERT(m_def, "Structure def is nullptr.");
E_DASSERT(m_model, "Model is nullptr.");
E_DASSERT(m_rigidBody, "Rigid body is nullptr.");
// update entitiy position and model position with physical body position
const auto &pos = m_rigidBody->getPosition();
const auto &rot = m_rigidBody->getRotation();
base::setInWorldPosition(pos);
base::setInWorldRotation(rot);
m_model->setPosition(pos);
m_model->setRotation(rot);
if(m_effect) {
E_DASSERT(m_def, "Structure def is nullptr.");
m_effect->setPosition(pos + rotateAsMe(m_def->getEffectOffset()));
m_effect->setRotation(rot);
}
if(m_def->hasMass())
m_rigidBody->affectByWater(WorldPart::k_waterHeight);
turret_onInWorldUpdate(pos, rot);
}
void Structure::onSpawnedInWorld()
{
TRACK;
base::onSpawnedInWorld();
auto &device = Global::getCore().getDevice();
const auto &pos = getInWorldPosition();
const auto &rot = getInWorldRotation();
E_DASSERT(m_def, "Structure def is nullptr.");
m_model = device.getSceneManager().addModel(m_def->getModelDefPtr());
m_model->setPosition(pos);
m_model->setRotation(rot);
const auto &cachedCollisionShapeDef = m_def->getCachedCollisionShapeDef();
const auto &shape = cachedCollisionShapeDef.getCollisionShapePtr();
const auto &posOffset = cachedCollisionShapeDef.getPosOffset();
m_rigidBody = device.getPhysicsManager().addRigidBody(shape, m_def->getMass(), getEntityID(), posOffset);
m_rigidBody->setPosition(pos);
m_rigidBody->setRotation(rot);
if(m_def->hasEffectDef())
m_effect = std::make_unique <Effect> (m_def->getEffectDefPtr(), pos + rotateAsMe(m_def->getEffectOffset()), rot);
m_shouldExplodeWhenRemovedFromWorld = false;
turret_onSpawnedInWorld(pos, rot);
}
void Structure::onRemovedFromWorld()
{
base::onRemovedFromWorld();
E_DASSERT(m_def, "Mineable def is nullptr.");
auto &core = Global::getCore();
const auto &cachedCollisionShapeDef = m_def->getCachedCollisionShapeDef();
auto &defsCache = core.getDefsCache();
if(m_shouldExplodeWhenRemovedFromWorld) {
auto &effectsPool = core.getEffectsPool();
const auto &turretInfo = m_def->getTurretInfo();
engine::FloatVec3 offset;
if(turretInfo.isTurret())
offset = {0.f, turretInfo.getDistanceToHead(), 0.f};
else
offset = cachedCollisionShapeDef.getPosOffset();
effectsPool.add(defsCache.Effect_Explosion, getInWorldPosition() + offset, getInWorldRotation());
}
else {
cachedCollisionShapeDef.addPoofEffect(getInWorldPosition(), getInWorldRotation());
auto &soundPool = core.getSoundPool();
soundPool.play(defsCache.Sound_Poof, getInWorldPosition());
}
m_model.reset();
m_rigidBody.reset();
m_effect.reset();
turret_onRemovedFromWorld();
}
void Structure::onPointedByPlayer()
{
if(m_model)
m_model->highlightNextFrame();
if(m_electricityComponent && m_electricityComponent->isInAnyElectricitySystem())
m_electricityComponent->getElectricitySystem().setOverlay(ElectricitySystem::Overlay::NormalSymbolsAndLines);
}
void Structure::onDraw2DInfoWhenPointed()
{
auto &core = Global::getCore();
auto &device = core.getDevice();
const auto &screenCenter = device.getScreenSize() / 2;
const auto &GUIRenderer = device.getGUIManager().getRenderer();
const auto &thisPlayerCharacter = core.getThisPlayer().getCharacter();
auto pos = screenCenter.moved(35, -20);
E_DASSERT(m_def, "Structure def is nullptr.");
GUIRenderer.drawText(m_def->getCapitalizedLabel(), pos, {0.5f, 0.5f, 0.5f, 0.8f}, engine::GUI::IGUIRenderer::FontSize::Big);
pos.y += GUIRenderer.getTextSize(m_def->getCapitalizedLabel(), engine::GUI::IGUIRenderer::FontSize::Big).y;
const auto &hpStr = std::to_string(m_HP) + " / " + std::to_string(m_def->getMaxHP());
GUIRenderer.drawText(hpStr, pos, {0.7f, 0.2f, 0.2f, 0.8f}, engine::GUI::IGUIRenderer::FontSize::Medium);
pos.y += GUIRenderer.getTextSize(hpStr, engine::GUI::IGUIRenderer::FontSize::Medium).y;
if(m_electricityComponent && m_electricityComponent->isInAnyElectricitySystem()) {
engine::Color color{0.2f, 0.8f, 0.2f, 0.8f};
if(!m_electricityComponent->isWorking())
color = {0.8f, 0.2f, 0.2f, 0.8f};
const auto &electricitySystem = m_electricityComponent->getElectricitySystem();
const auto &requiredPowerStr = "Total required power: " + std::to_string(electricitySystem.getRequiredPower());
const auto &generatedPowerStr = "Total generated power: " + std::to_string(electricitySystem.getGeneratedPower());
GUIRenderer.drawText(requiredPowerStr, pos, color, engine::GUI::IGUIRenderer::FontSize::Medium);
pos.y += GUIRenderer.getTextSize(requiredPowerStr, engine::GUI::IGUIRenderer::FontSize::Medium).y;
GUIRenderer.drawText(generatedPowerStr, pos, color, engine::GUI::IGUIRenderer::FontSize::Medium);
pos.y += GUIRenderer.getTextSize(generatedPowerStr, engine::GUI::IGUIRenderer::FontSize::Medium).y;
}
if(m_def->isWorkbench()) {
std::string text = "Press E to use this workbench.";
GUIRenderer.drawText(text, pos, {0.5f, 0.5f, 0.5f, 0.8f}, engine::GUI::IGUIRenderer::FontSize::Medium);
pos.y += GUIRenderer.getTextSize(text, engine::GUI::IGUIRenderer::FontSize::Medium).y;
}
if(hasSearchableItemContainer()) {
std::string text = "Press E to search.";
GUIRenderer.drawText(text, pos, {0.5f, 0.5f, 0.5f, 0.8f}, engine::GUI::IGUIRenderer::FontSize::Medium);
pos.y += GUIRenderer.getTextSize(text, engine::GUI::IGUIRenderer::FontSize::Medium).y;
}
if(canBeDeconstructed(thisPlayerCharacter))
GUIRenderer.drawText("Hold X to deconstruct.", pos, {0.5f, 0.5f, 0.5f, 0.8f}, engine::GUI::IGUIRenderer::FontSize::Medium);
}
void Structure::onItemUsedOnMe(Entity &doer, const Item &item)
{
if(isKilled())
return;
m_HP -= CharacterStatsOrSkillsRelatedFormulas::getDamage(doer, *this, item);
if(m_HP <= 0) {
m_HP = 0;
E_DASSERT(m_def, "Structure def is nullptr.");
if(m_def->shouldExplodeWhenDestroyed())
m_shouldExplodeWhenRemovedFromWorld = true;
}
}
void Structure::onDeconstructed(Character &doer)
{
TRACK;
E_DASSERT(m_def, "Structure def is nullptr.");
auto &inv = doer.getInventory().getMultiSlotItemContainer();
auto &world = Global::getCore().getWorld();
for(const auto &elem : m_def->getItemsWhenDeconstructed().getItems()) {
const auto &item = std::make_shared <Item> (world.getUniqueEntityID(), elem.getItemDefPtr(), elem.getStack());
inv.tryAddItem(item);
}
}
void Structure::onCharacterStepOnIt(Character &character)
{
E_DASSERT(m_def, "Structure def is nullptr.");
if(m_def->hasStepSound())
Global::getCore().getSoundPool().play(m_def->getStepSoundDefPtr(), character.getInWorldPosition());
}
engine::FloatVec3 Structure::getCenterPosition() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
// if we add pos offset to our current position we will get the center of physical body shape
return getInWorldPosition() + rotateAsMe(m_def->getCachedCollisionShapeDef().getPosOffset());
}
const engine::FloatVec3 &Structure::getTurretHeadRotation() const
{
return m_turretHeadRot;
}
void Structure::setTurretHeadRotation(const engine::FloatVec3 &turretHeadRot)
{
m_turretHeadRot = turretHeadRot;
if(m_turretHeadModel)
m_turretHeadModel->setRotation(m_turretHeadRot);
if(m_turretHeadRigidBody)
m_turretHeadRigidBody->setRotation(m_turretHeadRot);
}
ElectricityComponent &Structure::getElectricityComponent() const
{
if(!m_electricityComponent)
throw engine::Exception{"Electricity component is nullptr."};
return *m_electricityComponent;
}
StructureDef &Structure::getDef() const
{
E_DASSERT(m_def, "Structure def is nullptr.");
return *m_def;
}
void Structure::setOwner(const Character &character)
{
m_ownerEntityID = character.getEntityID();
}
bool Structure::hasOwner() const
{
auto &world = Global::getCore().getWorld();
return m_ownerEntityID >= 0 && world.entityExists(m_ownerEntityID) && !world.getEntity(m_ownerEntityID).isKilled();
}
Character &Structure::getOwner() const
{
if(m_ownerEntityID < 0)
throw engine::Exception{"Tried to get nullptr owner."};
auto &ownerCharacter = Global::getCore().getWorld().getEntityAndCast <Character> (m_ownerEntityID);
return ownerCharacter;
}
bool Structure::rayTest_notTurretHead(const engine::FloatVec3 &start, const engine::FloatVec3 &end, engine::app3D::CollisionFilter withWhatCollide, engine::FloatVec3 &outPos, int &outHitBodyUserIndex) const
{
TRACK;
auto &physicsManager = Global::getCore().getDevice().getPhysicsManager();
return physicsManager.rayTest_notMe(start, end, m_turretHeadRigidBody, withWhatCollide, outPos, outHitBodyUserIndex);
}
Structure::~Structure() = default;
void Structure::turret_setInWorldPosition(const engine::FloatVec3 &pos)
{
E_DASSERT(m_def, "Structure def is nullptr.");
float offset{m_def->getTurretInfo().getDistanceToHead()};
if(m_turretHeadModel)
m_turretHeadModel->setPosition(pos.movedY(offset));
if(m_turretHeadRigidBody)
m_turretHeadRigidBody->setPosition(pos.movedY(offset));
}
void Structure::turret_setInWorldRotation(const engine::FloatVec3 &rot)
{
}
void Structure::turret_onInWorldUpdate(const engine::FloatVec3 &rigidBodyPos, const engine::FloatVec3 &rigidBodyRot)
{
float offset{m_def->getTurretInfo().getDistanceToHead()};
if(m_turretHeadModel)
m_turretHeadModel->setPosition(rigidBodyPos.movedY(offset));
if(m_turretHeadRigidBody)
m_turretHeadRigidBody->setPosition(rigidBodyPos.movedY(offset));
if(m_turretComponent)
m_turretComponent->onInWorldUpdate();
}
void Structure::turret_onSpawnedInWorld(const engine::FloatVec3 &inWorldPos, const engine::FloatVec3 &inWorldRot)
{
E_DASSERT(m_def, "Structure def is nullptr.");
m_turretHeadRot = inWorldRot;
const auto &turretInfo = m_def->getTurretInfo();
if(!turretInfo.isTurret())
return;
auto &device = Global::getCore().getDevice();
float offset{m_def->getTurretInfo().getDistanceToHead()};
m_turretHeadModel = device.getSceneManager().addModel(turretInfo.getHeadModelDefPtr());
m_turretHeadModel->setPosition(inWorldPos.movedY(offset));
m_turretHeadModel->setRotation(m_turretHeadRot);
const auto &cachedCollisionShapeDef = turretInfo.getHeadCachedCollisionShapeDef();
const auto &shape = cachedCollisionShapeDef.getCollisionShapePtr();
const auto &posOffset = cachedCollisionShapeDef.getPosOffset();
m_turretHeadRigidBody = device.getPhysicsManager().addRigidBody(shape, 0.f, getEntityID(), posOffset);
m_turretHeadRigidBody->setPosition(inWorldPos.movedY(offset));
m_turretHeadRigidBody->setRotation(m_turretHeadRot);
}
void Structure::turret_onRemovedFromWorld()
{
if(m_turretHeadRigidBody && !m_shouldExplodeWhenRemovedFromWorld) {
E_DASSERT(m_def, "Mineable def is nullptr.");
const auto &turretInfo = m_def->getTurretInfo();
const auto &cachedCollisionShapeDef = turretInfo.getHeadCachedCollisionShapeDef();
cachedCollisionShapeDef.addPoofEffect(getInWorldPosition().movedY(turretInfo.getDistanceToHead()), getTurretHeadRotation());
}
m_turretHeadModel.reset();
m_turretHeadRigidBody.reset();
}
const engine::IntVec2 Structure::k_searchableItemContainerSize{6, 6};
} // namespace app
| 31.208812 | 206 | 0.714505 | isonil |
db9cfe7c2f51b1515718f9a510f6383a2d51a00c | 4,187 | hpp | C++ | Framework/[Droid]/OpenGLEngine.hpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 3 | 2019-10-10T19:25:42.000Z | 2019-12-17T10:51:23.000Z | Framework/[Droid]/OpenGLEngine.hpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | null | null | null | Framework/[Droid]/OpenGLEngine.hpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 1 | 2021-11-16T15:29:40.000Z | 2021-11-16T15:29:40.000Z | //
// OpenGLEngine.hpp
// Crazy Darts 2 iOS
//
// Created by Nicholas Raptis on 3/8/19.
// Copyright © 2019 Froggy Studios. All rights reserved.
//
#ifndef OpenGLEngine_hpp
#define OpenGLEngine_hpp
#include "ShaderProgram.hpp"
#include "ShaderProgramSprite.hpp"
#include "ShaderProgramSpriteWhite.hpp"
#include "ShaderProgramShape3D.hpp"
#include "ShaderProgramShapeNode.hpp"
#include "ShaderProgramSpriteNode.hpp"
#include "ShaderProgramSimpleModel.hpp"
#include "ShaderProgramSimpleModelIndexed.hpp"
#include "ShaderProgramModelIndexed.hpp"
#include "ShaderProgramModelIndexedLightedAmbient.hpp"
#include "ShaderProgramModelIndexedLightedDiffuse.hpp"
#include "ShaderProgramModelIndexedLightedPhong.hpp"
#include "ShaderProgramModelIndexedLightedSimpleSpotlight.hpp"
class OpenGLEngine {
public:
OpenGLEngine();
~OpenGLEngine();
void SetUp();
void TearDown();
void BuildPrograms();
void Prerender();
void Postrender();
bool IsReady();
bool mIsReady;
void UseProgram(ShaderProgram *pProgram);
void UseProgramShape2D();
void UseProgramShape3D();
void UseProgramSprite();
void UseProgramSpriteWhite();
void UseProgramShapeNode();
void UseProgramSimpleModel();
void UseProgramSimpleModelIndexed();
void UseProgramModelIndexed();
void UseProgramModelIndexedAmbient();
void UseProgramModelIndexedDiffuse();
void UseProgramModelIndexedPhong();
void UseProgramModelIndexedPhongOverlay();
void UseProgramModelIndexedSimpleSpotlight();
ShaderProgram *mShaderProgramShape2D;
ShaderProgramShape3D *mShaderProgramShape3D;
ShaderProgramSprite *mShaderProgramSprite;
ShaderProgramSpriteWhite *mShaderProgramSpriteWhite;
ShaderProgramShapeNode *mShaderProgramShapeNode;//ShaderProgramShapeNode
ShaderProgramSpriteNode *mShaderProgramSpriteNode;//ShaderProgramSpriteNode
ShaderProgramSimpleModel *mShaderProgramSimpleModel;//ShaderProgramSimpleModel
ShaderProgramSimpleModelIndexed *mShaderProgramSimpleModelIndexed;
ShaderProgramModelIndexed *mShaderProgramModelIndexed;
ShaderProgramModelIndexedLightedAmbient *mShaderProgramModelIndexedLightedAmbient;
ShaderProgramModelIndexedLightedDiffuse *mShaderProgramModelIndexedLightedDiffuse;
ShaderProgramModelIndexedLightedPhong *mShaderProgramModelIndexedLightedPhong;
ShaderProgramModelIndexedLightedPhong *mShaderProgramModelIndexedLightedPhongOverlay;
ShaderProgramModelIndexedLightedSimpleSpotlight *mShaderProgramModelIndexedLightedSimpleSpotlight;
//model_lighted_phong_vertex_shader.glsl
//model_lighted_phong_vertex_shader.glsl
//model_lighted_ambient_diffuse_fragment_shader.glsl
//model_lighted_ambient_diffuse_vertex_shader.glsl
//model_lighted_phong_fragment_shader.glsl
};
extern OpenGLEngine *gOpenGLEngine;
#endif /* OpenGLEngine_hpp */
| 38.063636 | 105 | 0.557679 | nraptis |
db9d4051c8ae61bf3816985b2d71e4430d7b8888 | 925 | cpp | C++ | examples/linkedlist-sort.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | examples/linkedlist-sort.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | examples/linkedlist-sort.cpp | davidwed/sqlrelay_rudiments | 6ccffdfc5fa29f8c0226f3edc2aa888aa1008347 | [
"BSD-2-Clause-NetBSD"
] | null | null | null | #include <rudiments/linkedlist.h>
#include <rudiments/randomnumber.h>
#include <rudiments/stdio.h>
int main(int argc, const char **argv) {
linkedlist<uint32_t> llis;
linkedlist<uint32_t> llhs;
// generate random numbers and append them to the lists
randomnumber rr;
rr.setSeed(randomnumber::getSeed());
stdoutput.printf("generating numbers...\n");
for (uint16_t i=0; i<20000; i++) {
uint32_t num;
rr.generateNumber(&num);
llis.append(num);
llhs.append(num);
}
// sort one list using insertion sort
stdoutput.printf("sorting using insertion sort...\n");
llis.insertionSort();
// sort one list using heap sort
stdoutput.printf("sorting using heap sort...\n");
llhs.heapSort();
// print the lists
stdoutput.printf("insertion sorted list\n");
llis.print(5);
stdoutput.write("...\n\n");
// print the list
stdoutput.printf("heap sorted list\n");
llhs.print(5);
stdoutput.write("...\n\n");
}
| 22.02381 | 56 | 0.697297 | davidwed |
dba4982185a28dbd6c3be7bd967163092eb29808 | 7,067 | cpp | C++ | src/common/swldap/search.cpp | arpa2/steamworks | 149d1bf7d44c27791564fd8a3ccb1a9b2f5a4692 | [
"OML",
"BSD-2-Clause"
] | null | null | null | src/common/swldap/search.cpp | arpa2/steamworks | 149d1bf7d44c27791564fd8a3ccb1a9b2f5a4692 | [
"OML",
"BSD-2-Clause"
] | 7 | 2018-01-05T12:29:09.000Z | 2019-02-19T12:18:16.000Z | src/common/swldap/search.cpp | arpa2/steamworks | 149d1bf7d44c27791564fd8a3ccb1a9b2f5a4692 | [
"OML",
"BSD-2-Clause"
] | null | null | null | /*
Copyright (c) 2014, 2015 InternetWide.org and the ARPA2.net project
All rights reserved. See file LICENSE for exact terms (2-clause BSD license).
Adriaan de Groot <groot@kde.org>
*/
#include "search.h"
#include "private.h"
#include "picojson.h"
/**
* Internals of a search. A search holds a base dn for the search
* and a filter expression. When executed, it returns an array
* of objects found.
*/
class SteamWorks::LDAP::Search::Private
{
private:
std::string m_base, m_filter;
LDAPScope m_scope;
public:
Private(const std::string& base, const std::string& filter, LDAPScope scope) :
m_base(base),
m_filter(filter),
m_scope(scope)
{
}
const std::string& base() const { return m_base; }
const std::string& filter() const { return m_filter; }
LDAPScope scope() const { return m_scope; }
} ;
SteamWorks::LDAP::Search::Search(const std::string& base, const std::string& filter, LDAPScope scope) :
Action(true),
d(new Private(base, filter, scope))
{
}
SteamWorks::LDAP::Search::~Search()
{
}
void SteamWorks::LDAP::Search::execute(Connection& conn, Result results)
{
::LDAP* ldaphandle = handle(conn);
SteamWorks::Logging::Logger& log = SteamWorks::Logging::getLogger("steamworks.ldap");
// TODO: settings for timeouts?
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
LDAPMessage* res;
int r = ldap_search_ext_s(ldaphandle,
d->base().c_str(),
d->scope(),
d->filter().c_str(),
nullptr, // attrs
0,
server_controls(conn),
client_controls(conn),
&tv,
1024*1024,
&res);
if (r)
{
log.errorStream() << "Search result " << r << " " << ldap_err2string(r);
ldap_msgfree(res); // Should be freed regardless of the return value
return;
}
copy_search_result(ldaphandle, res, results, log);
ldap_msgfree(res);
}
/**
* Internals of an update.
*/
class SteamWorks::LDAP::Update::Private
{
private:
std::string m_dn;
SteamWorks::LDAP::Update::Attributes m_map;
public:
Private(const std::string& dn) :
m_dn(dn)
{
};
void update(const SteamWorks::LDAP::Update::Attributes& attrs)
{
m_map.insert(attrs.cbegin(), attrs.cend());
}
void update(const std::string& name, const std::string& value)
{
m_map.emplace<>(name, value);
}
void remove(const std::string& name)
{
m_map.erase(name);
}
size_t size() const
{
return m_map.size();
}
const std::string& name() const
{
return m_dn;
}
SteamWorks::LDAP::Update::Attributes::const_iterator begin() const
{
return m_map.begin();
}
SteamWorks::LDAP::Update::Attributes::const_iterator end() const
{
return m_map.end();
}
} ;
class LDAPMods
{
private:
::ldapmod** m_mods;
size_t m_size;
unsigned int m_count;
public:
LDAPMods(size_t n) :
m_mods((::ldapmod**)calloc(n+1, sizeof(::ldapmod*))),
m_size(n),
m_count(0)
{
}
~LDAPMods()
{
for (unsigned int i=0; i<m_count; i++)
{
free(m_mods[i]->mod_vals.modv_strvals);
free(m_mods[i]);
}
free(m_mods);
m_mods = nullptr;
}
void replace(const std::string& attr, const std::string& val)
{
::ldapmod* mod;
if (m_count < m_size)
{
// TODO: check for allocation failures
mod = m_mods[m_count++] = (::ldapmod*)malloc(sizeof(::ldapmod));
mod->mod_op = LDAP_MOD_REPLACE;
mod->mod_type = const_cast<char *>(attr.c_str());
mod->mod_vals.modv_strvals = (char**)calloc(2, sizeof(char *));
mod->mod_vals.modv_strvals[0] = const_cast<char *>(val.c_str());
mod->mod_vals.modv_strvals[1] = nullptr;
}
}
::ldapmod** c_ptr() const
{
return m_mods;
}
} ;
SteamWorks::LDAP::Update::Update(const std::string& dn) :
Action(false),
d(new Private(dn))
{
}
SteamWorks::LDAP::Update::Update(const std::string& dn, const SteamWorks::LDAP::Update::Attributes& attr) :
Action(attr.size() > 0),
d(new Private(dn))
{
d->update(attr);
}
SteamWorks::LDAP::Update::Update(const picojson::value& json) :
Action(false), // For now
d(nullptr)
{
if (!json.is<picojson::value::object>())
{
return;
}
std::string dn = json.get("dn").to_str();
if (!dn.empty())
{
d.reset(new Private(dn));
}
else
{
return; // no dn? remain invalid
}
const picojson::object& o = json.get<picojson::object>();
if (o.size() > 1) // "dn" plus one more
{
for (auto i: o)
{
if (i.first != "dn")
{
d->update(i.first, i.second.to_str());
}
}
m_valid = true;
}
}
SteamWorks::LDAP::Update::~Update()
{
}
void SteamWorks::LDAP::Update::execute(Connection& conn, Result result)
{
// TODO: actually do an update
SteamWorks::Logging::Logger& log = SteamWorks::Logging::getLogger("steamworks.ldap");
if (!m_valid)
{
log.warnStream() << "Can't execute invalid update.";
return;
}
log.debugStream() << "Update execute:" << d->name() << " #changes:" << d->size();
// TODO: here we assume each JSON-change maps to one LDAP modification
LDAPMods mods(d->size());
for (auto i = d->begin(); i != d->end(); ++i)
{
log.debugStream() << " A=" << i->first << " V=" << i->second;
mods.replace(i->first, i->second);
}
int r = ldap_modify_ext_s(
handle(conn),
d->name().c_str(),
mods.c_ptr(),
server_controls(conn),
client_controls(conn)
);
log.debugStream() << "Result " << r << " " << (r ? ldap_err2string(r) : "OK");
}
/**
* Addition as a variation on updates.
*/
SteamWorks::LDAP::Addition::Addition(const picojson::value& v): Update(v)
{
}
void SteamWorks::LDAP::Addition::execute(Connection& conn, Result result)
{
// TODO: actually do an update
SteamWorks::Logging::Logger& log = SteamWorks::Logging::getLogger("steamworks.ldap");
if (!m_valid)
{
log.warnStream() << "Can't execute invalid addition.";
return;
}
log.debugStream() << "Addition execute:" << d->name() << " #changes:" << d->size();
// TODO: here we assume each JSON-change maps to one LDAP modification
LDAPMods mods(d->size());
for (auto i = d->begin(); i != d->end(); ++i)
{
log.debugStream() << " A=" << i->first << " V=" << i->second;
mods.replace(i->first, i->second);
}
int r = ldap_add_ext_s(
handle(conn),
d->name().c_str(),
mods.c_ptr(),
server_controls(conn),
client_controls(conn)
);
log.debugStream() << "Result " << r << " " << (r ? ldap_err2string(r) : "OK");
}
/** Internals of a Remove (delete) action.
*/
class SteamWorks::LDAP::Remove::Private
{
private:
std::string m_dn;
public:
Private(const std::string& dn) :
m_dn(dn)
{
};
const std::string& name() const
{
return m_dn;
}
} ;
SteamWorks::LDAP::Remove::Remove(const std::string& dn) :
Action(!dn.empty()),
d(new Private(dn))
{
}
SteamWorks::LDAP::Remove::~Remove()
{
}
void SteamWorks::LDAP::Remove::execute(Connection& conn, Result result)
{
SteamWorks::Logging::Logger& log = SteamWorks::Logging::getLogger("steamworks.ldap");
if (!is_valid())
{
log.warnStream() << "Can't execute invalid removal.";
return;
}
log.debugStream() << "Removal execute:" << d->name();
int r = ldap_delete_ext_s(
handle(conn),
d->name().c_str(),
server_controls(conn),
client_controls(conn)
);
log.debugStream() << "Result " << r << " " << (r ? ldap_err2string(r) : "OK");
}
| 20.076705 | 107 | 0.642989 | arpa2 |
dba53fe9a518204c2bcefacaf529bcd342c65a10 | 9,400 | cpp | C++ | src/repetition.cpp | isourou/gdstk | 3b436230dba1e2f86f3863693d3d80ecd5eaf40d | [
"BSL-1.0"
] | null | null | null | src/repetition.cpp | isourou/gdstk | 3b436230dba1e2f86f3863693d3d80ecd5eaf40d | [
"BSL-1.0"
] | null | null | null | src/repetition.cpp | isourou/gdstk | 3b436230dba1e2f86f3863693d3d80ecd5eaf40d | [
"BSL-1.0"
] | 1 | 2021-02-18T09:33:58.000Z | 2021-02-18T09:33:58.000Z | /*
Copyright 2020 Lucas Heitzmann Gabrielli.
This file is part of gdstk, distributed under the terms of the
Boost Software License - Version 1.0. See the accompanying
LICENSE file or <http://www.boost.org/LICENSE_1_0.txt>
*/
#define _USE_MATH_DEFINES
#include "repetition.h"
#include <cstdint>
#include <cstdio>
#include "array.h"
#include "vec.h"
namespace gdstk {
void Repetition::print() const {
const uint8_t n = 12;
switch (type) {
case RepetitionType::Rectangular:
printf("Rectangular repetition <%p>, %" PRIu64 " columns, %" PRIu64
" rows, spacing (%lg, %lg)\n",
this, columns, rows, spacing.x, spacing.y);
break;
case RepetitionType::Regular:
printf("Regular repetition <%p>, %" PRIu64 " x %" PRIu64
" elements along (%lg, %lg) and (%lg, %lg)\n",
this, columns, rows, v1.x, v1.y, v2.x, v2.y);
break;
case RepetitionType::Explicit:
printf("Explicit repetition <%p>: ", this);
offsets.print(true);
break;
case RepetitionType::ExplicitX:
case RepetitionType::ExplicitY:
printf("Explicit %c repetition <%p>:", type == RepetitionType::ExplicitX ? 'X' : 'Y',
this);
for (uint64_t i = 0; i < coords.size; i += n) {
for (uint64_t j = 0; j < n && i + j < coords.size; j++) {
printf(" %lg", coords[i + j]);
}
putchar('\n');
}
break;
case RepetitionType::None:
return;
}
}
void Repetition::clear() {
if (type == RepetitionType::Explicit) {
offsets.clear();
} else if (type == RepetitionType::ExplicitX || type == RepetitionType::ExplicitY) {
coords.clear();
}
memset(this, 0, sizeof(Repetition));
}
void Repetition::copy_from(const Repetition repetition) {
type = repetition.type;
switch (type) {
case RepetitionType::Rectangular:
columns = repetition.columns;
rows = repetition.rows;
spacing = repetition.spacing;
break;
case RepetitionType::Regular:
columns = repetition.columns;
rows = repetition.rows;
v1 = repetition.v1;
v2 = repetition.v2;
break;
case RepetitionType::Explicit:
offsets.copy_from(repetition.offsets);
break;
case RepetitionType::ExplicitX:
case RepetitionType::ExplicitY:
coords.copy_from(repetition.coords);
break;
case RepetitionType::None:
return;
}
}
uint64_t Repetition::get_size() const {
switch (type) {
case RepetitionType::Rectangular:
case RepetitionType::Regular:
return columns * rows;
case RepetitionType::Explicit:
return offsets.size + 1; // Assume (0, 0) is not included.
case RepetitionType::ExplicitX:
case RepetitionType::ExplicitY:
return coords.size + 1; // Assume 0 is not included.
case RepetitionType::None:
return 0;
}
return 0;
}
void Repetition::get_offsets(Array<Vec2>& result) const {
if (type == RepetitionType::None) return;
uint64_t size = get_size();
result.ensure_slots(size);
double* c_item;
double* c = (double*)(result.items + result.size);
switch (type) {
case RepetitionType::Rectangular:
for (uint64_t i = 0; i < columns; i++) {
double cx = i * spacing.x;
for (uint64_t j = 0; j < rows; j++) {
*c++ = cx;
*c++ = j * spacing.y;
}
}
result.size += size;
break;
case RepetitionType::Regular:
for (uint64_t i = 0; i < columns; i++) {
Vec2 vi = (double)i * v1;
for (uint64_t j = 0; j < rows; j++) {
*c++ = vi.x + j * v2.x;
*c++ = vi.y + j * v2.y;
}
}
result.size += size;
break;
case RepetitionType::ExplicitX:
*c++ = 0;
*c++ = 0;
c_item = coords.items;
for (uint64_t j = 1; j < size; j++) {
*c++ = *c_item++;
*c++ = 0;
}
result.size += size;
break;
case RepetitionType::ExplicitY:
*c++ = 0;
*c++ = 0;
c_item = coords.items;
for (uint64_t j = 1; j < size; j++) {
*c++ = 0;
*c++ = *c_item++;
}
result.size += size;
break;
case RepetitionType::Explicit:
result.append_unsafe(Vec2{0, 0});
result.extend(offsets);
break;
case RepetitionType::None:
return;
}
}
void Repetition::transform(double magnification, bool x_reflection, double rotation) {
if (type == RepetitionType::None) return;
switch (type) {
case RepetitionType::Rectangular: {
if (magnification != 1) spacing *= magnification;
if (x_reflection || rotation != 0) {
Vec2 v = spacing;
if (x_reflection) v.y = -v.y;
double ca = cos(rotation);
double sa = sin(rotation);
type = RepetitionType::Regular;
v1.x = v.x * ca;
v1.y = v.x * sa;
v2.x = -v.y * sa;
v2.y = v.y * ca;
}
} break;
case RepetitionType::Regular: {
if (magnification != 1) {
v1 *= magnification;
v2 *= magnification;
}
if (x_reflection) {
v1.y = -v1.y;
v2.y = -v2.y;
}
if (rotation != 0) {
Vec2 r = {cos(rotation), sin(rotation)};
v1 = cplx_mul(v1, r);
v2 = cplx_mul(v2, r);
}
} break;
case RepetitionType::ExplicitX: {
if (rotation != 0) {
double ca = magnification * cos(rotation);
double sa = magnification * sin(rotation);
Array<Vec2> temp = {0};
temp.ensure_slots(coords.size);
temp.size = coords.size;
Vec2* v = temp.items;
double* c = coords.items;
for (uint64_t i = coords.size; i > 0; i--, c++, v++) {
v->x = *c * ca;
v->y = *c * sa;
}
coords.clear();
type = RepetitionType::Explicit;
offsets = temp;
} else if (magnification != 1) {
double* c = coords.items;
for (uint64_t i = coords.size; i > 0; i--) {
*c++ *= magnification;
}
}
} break;
case RepetitionType::ExplicitY: {
if (rotation != 0) {
double ca = magnification * cos(rotation);
double sa = -magnification * sin(rotation);
if (x_reflection) {
ca = -ca;
sa = -sa;
}
Array<Vec2> temp = {0};
temp.ensure_slots(coords.size);
temp.size = coords.size;
Vec2* v = temp.items;
double* c = coords.items;
for (uint64_t i = coords.size; i > 0; i--, c++, v++) {
v->x = *c * sa;
v->y = *c * ca;
}
coords.clear();
type = RepetitionType::Explicit;
offsets = temp;
} else if (x_reflection || magnification != 1) {
if (x_reflection) magnification = -magnification;
double* c = coords.items;
for (uint64_t i = coords.size; i > 0; i--) {
*c++ *= magnification;
}
}
} break;
case RepetitionType::Explicit: {
Vec2* v = offsets.items;
if (rotation != 0) {
Vec2 r = {magnification * cos(rotation), magnification * sin(rotation)};
if (x_reflection) {
for (uint64_t i = offsets.size; i > 0; i--, v++) {
*v = cplx_mul(cplx_conj(*v), r);
}
} else {
for (uint64_t i = offsets.size; i > 0; i--, v++) {
*v = cplx_mul(*v, r);
}
}
} else if (x_reflection && magnification != 1) {
for (uint64_t i = offsets.size; i > 0; i--, v++) {
v->x *= magnification;
v->y *= -magnification;
}
} else if (x_reflection) {
for (uint64_t i = offsets.size; i > 0; i--, v++) {
v->y = -v->y;
}
} else if (magnification != 1) {
for (uint64_t i = offsets.size; i > 0; i--, v++) {
*v *= magnification;
}
}
} break;
default:
return;
}
}
} // namespace gdstk
| 33.935018 | 97 | 0.449149 | isourou |
dba79ba5f407e65ee15a846f1d23a58879adc897 | 3,811 | cpp | C++ | src/audio_file_decoder.cpp | jomael/AudioMixer | cfdd19b0d56418f9bf37164429a248f075a0751a | [
"MIT"
] | 151 | 2018-06-05T14:06:42.000Z | 2022-03-29T09:56:35.000Z | src/audio_file_decoder.cpp | JchKrnt/AudioMixer | b2327fb2b1c5c215e199d95812e7a5dc17d106b7 | [
"MIT"
] | 7 | 2019-05-16T11:39:28.000Z | 2021-11-22T02:45:16.000Z | src/audio_file_decoder.cpp | JchKrnt/AudioMixer | b2327fb2b1c5c215e199d95812e7a5dc17d106b7 | [
"MIT"
] | 51 | 2018-06-06T02:29:15.000Z | 2022-01-29T02:41:28.000Z | //
// Created by Piasy on 08/11/2017.
//
#include <algorithm>
#include <rtc_base/checks.h>
#include <modules/audio_mixer/audio_mixer_impl.h>
#include "audio_file_decoder.h"
namespace audio_mixer {
AudioFileDecoder::AudioFileDecoder(const std::string& filepath) : packet_consumed_(true) {
frame_.reset(av_frame_alloc());
RTC_CHECK(frame_.get()) << "av_frame_alloc fail";
packet_.reset(av_packet_alloc());
RTC_CHECK(packet_.get()) << "av_packet_alloc fail";
av_init_packet(packet_.get());
{
AVFormatContext* format_context = nullptr;
int32_t error = avformat_open_input(&format_context, filepath.c_str(), nullptr, nullptr);
RTC_CHECK(error >= 0) << av_err2str(error);
format_context_.reset(format_context);
}
AVCodec* codec;
int32_t error = avformat_find_stream_info(format_context_.get(), nullptr);
RTC_CHECK(error >= 0) << av_err2str(error);
stream_no_ = av_find_best_stream(format_context_.get(), AVMEDIA_TYPE_AUDIO, -1, -1, &codec, 0);
RTC_CHECK(stream_no_ >= 0) << av_err2str(stream_no_);
if (!(codec = avcodec_find_decoder(format_context_->streams[stream_no_]->codecpar->codec_id))) {
RTC_CHECK(false) << "avcodec_find_decoder fail";
}
codec_context_.reset(avcodec_alloc_context3(codec));
RTC_CHECK(codec_context_.get()) << "avcodec_alloc_context3 fail";
error = avcodec_parameters_to_context(codec_context_.get(),
format_context_->streams[stream_no_]->codecpar);
RTC_CHECK(error >= 0) << av_err2str(error);
error = avcodec_open2(codec_context_.get(), codec, nullptr);
RTC_CHECK(error >= 0) << av_err2str(error);
fifo_capacity_ = 10 * codec_context_->sample_rate
/ (1000 / webrtc::AudioMixerImpl::kFrameDurationInMs);
fifo_.reset(av_audio_fifo_alloc(codec_context_->sample_fmt, codec_context_->channels,
fifo_capacity_));
RTC_CHECK(fifo_.get()) << "av_audio_fifo_alloc fail";
FillDecoder();
}
AudioFileDecoder::~AudioFileDecoder() {
}
AVSampleFormat AudioFileDecoder::sample_format() {
return codec_context_->sample_fmt;
}
int32_t AudioFileDecoder::sample_rate() {
return codec_context_->sample_rate;
}
int32_t AudioFileDecoder::channel_num() {
return codec_context_->channels;
}
int32_t AudioFileDecoder::Consume(void** buffer, int32_t samples) {
FillDecoder();
FillFifo();
int32_t target_samples = std::min(av_audio_fifo_size(fifo_.get()), samples);
int32_t actual_samples = av_audio_fifo_read(fifo_.get(), buffer, target_samples);
return actual_samples * 2 * codec_context_->channels;
}
void AudioFileDecoder::FillDecoder() {
while (true) {
if (packet_consumed_) {
if (av_read_frame(format_context_.get(), packet_.get()) != 0) {
break;
}
if (packet_->stream_index != stream_no_) {
av_packet_unref(packet_.get());
continue;
}
packet_consumed_ = false;
}
int32_t error = avcodec_send_packet(codec_context_.get(), packet_.get());
if (error == 0) {
av_packet_unref(packet_.get());
packet_consumed_ = true;
continue;
}
if (error == AVERROR(EAGAIN) || error == AVERROR_EOF) {
break;
}
RTC_CHECK(false) << av_err2str(error);
}
}
void AudioFileDecoder::FillFifo() {
while (av_audio_fifo_size(fifo_.get()) < fifo_capacity_
&& avcodec_receive_frame(codec_context_.get(), frame_.get()) == 0) {
av_audio_fifo_write(fifo_.get(), reinterpret_cast<void**>(frame_->extended_data),
frame_->nb_samples);
av_frame_unref(frame_.get());
}
}
}
| 32.29661 | 100 | 0.649961 | jomael |
dba89882741639ec24ae5cf5712e88a7bce1b9d8 | 195 | cpp | C++ | src/Common/Constants.cpp | HorphGerbInc/gametest | 8c91a0823bcc84a0a75f8a70aed6040a92d28027 | [
"MIT"
] | null | null | null | src/Common/Constants.cpp | HorphGerbInc/gametest | 8c91a0823bcc84a0a75f8a70aed6040a92d28027 | [
"MIT"
] | null | null | null | src/Common/Constants.cpp | HorphGerbInc/gametest | 8c91a0823bcc84a0a75f8a70aed6040a92d28027 | [
"MIT"
] | null | null | null |
#include <Common/Constants.hpp>
namespace jerobins {
namespace common {
// Game engine version.
const Version version(0, 1, 0);
} // namespace common
} // namespace jerobins | 21.666667 | 36 | 0.65641 | HorphGerbInc |
dbafa205602cf9a271fa8153f234ad62f35541d7 | 1,703 | cpp | C++ | testsuite/select_in_t.cpp | RaftLib/RaftLib | d7a5520b8c239e9c78ca4a7fdb4fed845c6dda74 | [
"Apache-2.0"
] | 759 | 2016-05-23T22:40:00.000Z | 2022-03-25T09:05:41.000Z | testsuite/select_in_t.cpp | RaftLib/RaftLib | d7a5520b8c239e9c78ca4a7fdb4fed845c6dda74 | [
"Apache-2.0"
] | 111 | 2016-05-24T02:30:14.000Z | 2021-08-16T15:11:53.000Z | testsuite/select_in_t.cpp | RaftLib/RaftLib | d7a5520b8c239e9c78ca4a7fdb4fed845c6dda74 | [
"Apache-2.0"
] | 116 | 2016-05-31T08:03:05.000Z | 2022-03-01T00:54:31.000Z | /**
* @author: Jonathan Beard
* @version: Mon Mar 2 14:00:14 2015
*
* Copyright 2015 Jonathan Beard
*
* 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 <raft>
#include <cstdint>
#include <iostream>
#include <raftio>
#include "generate.tcc"
using type_t = std::int32_t;
class dummy : public raft::kernel
{
public:
dummy() : raft::kernel()
{
input.addPort< type_t >( "x_1", "x_2", "x_3" );
output.addPort< type_t >( "y_1" );
}
/**
* simple test case to select_in
*/
virtual raft::kstatus run() override
{
auto ret_val = raft::select::in( input, "x_1", "x_2", "x_3" );
if( ret_val.first > 0 )
{
type_t x;
ret_val.second.get().pop( x );
output[ "y_1" ].push( x );
}
return( raft::proceed );
}
};
int
main()
{
using gen = raft::test::generate< type_t >;
using print = raft::print< type_t , '\n' >;
gen a1;
gen a2;
gen a3;
dummy d;
print p;
raft::map m;
m += a1 >> d[ "x_1" ];
m += a2 >> d[ "x_2" ];
m += a3 >> d[ "x_3" ];
m += d >> p;
m.exe();
return( EXIT_SUCCESS );
}
| 22.116883 | 75 | 0.576042 | RaftLib |
dbb271dd5a0d86c3584e41145880662547439854 | 488 | hpp | C++ | regAlloc.hpp | InbarGera/236360_Compilation_03 | 16e966da0db31de525647c4995528997b3e58da6 | [
"Unlicense"
] | null | null | null | regAlloc.hpp | InbarGera/236360_Compilation_03 | 16e966da0db31de525647c4995528997b3e58da6 | [
"Unlicense"
] | null | null | null | regAlloc.hpp | InbarGera/236360_Compilation_03 | 16e966da0db31de525647c4995528997b3e58da6 | [
"Unlicense"
] | null | null | null | #ifndef COMPILATION_03_REGALLOC_HPP
#define COMPILATION_03_REGALLOC_HPP
#include <cassert>
#include <vector>
#include "utills.hpp"
class regClass{
int myIndex;
public:
regClass() : myIndex(-1) {};
regClass(int i);
std::string toString();
bool isFree();
int index();
};
regClass regAlloc();
void regFree(regClass toFree);
void assertAllRegistersAreFree();
std::vector<regClass> getAllUsedRegisters();
#endif //COMPILATION_03_REGALLOC_HPP
| 20.333333 | 45 | 0.694672 | InbarGera |
dbb4b39c07c0fa015c129f294316d47042ffbaed | 1,420 | cpp | C++ | Configuration.cpp | jscrane/Twilight-ESP | a00a8f631432b7a6f837bbfb321f1e20e64b9b37 | [
"Apache-2.0"
] | 1 | 2019-11-24T00:37:00.000Z | 2019-11-24T00:37:00.000Z | Configuration.cpp | jscrane/Twilight-ESP | a00a8f631432b7a6f837bbfb321f1e20e64b9b37 | [
"Apache-2.0"
] | 13 | 2018-02-16T09:32:31.000Z | 2020-01-24T14:54:30.000Z | Configuration.cpp | jscrane/Twilight-ESP | a00a8f631432b7a6f837bbfb321f1e20e64b9b37 | [
"Apache-2.0"
] | null | null | null | #include <LittleFS.h>
#include <ArduinoJson.h>
#include "Configuration.h"
bool Configuration::read_file(const char *filename) {
File f = LittleFS.open(filename, "r");
if (!f) {
Serial.println("failed to open config file");
return false;
}
DynamicJsonDocument doc(JSON_OBJECT_SIZE(19) + 600);
auto error = deserializeJson(doc, f);
f.close();
if (error) {
Serial.print("json read failed: ");
Serial.println(error.c_str());
return false;
}
configure(doc);
return true;
}
void config::configure(JsonDocument &o) {
strlcpy(ssid, o[F("ssid")] | "", sizeof(ssid));
strlcpy(password, o[F("password")] | "", sizeof(password));
strlcpy(hostname, o[F("hostname")] | "", sizeof(hostname));
strlcpy(mqtt_server, o[F("mqtt_server")] | "", sizeof(mqtt_server));
interval_time = 1000 * (long)o[F("interval_time")];
inactive_time = 1000 * (long)o[F("inactive_time")];
threshold = o[F("threshold")];
switch_idx = o[F("switch_idx")];
pir_idx = o[F("pir_idx")];
on_delay = o[F("on_delay")];
off_delay = o[F("off_delay")];
on_bright = o[F("on_bright")] | 1023;
off_bright = o[F("off_bright")] | 0;
strlcpy(stat_topic, o[F("stat_topic")] | "", sizeof(stat_topic));
strlcpy(cmnd_topic, o[F("cmnd_topic")] | "", sizeof(cmnd_topic));
strlcpy(to_domoticz, o[F("to_domoticz")] | "", sizeof(to_domoticz));
strlcpy(from_domoticz, o[F("from_domoticz")] | "", sizeof(from_domoticz));
debug = o[F("debug")];
}
| 31.555556 | 75 | 0.664085 | jscrane |
dbb7f21f378880ca0e48e3b583530c1337f578df | 567 | cpp | C++ | leetcode/medium/238. Product of Array Except Self.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | 7 | 2019-08-05T14:49:41.000Z | 2022-03-13T07:10:51.000Z | leetcode/medium/238. Product of Array Except Self.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | null | null | null | leetcode/medium/238. Product of Array Except Self.cpp | Jeongseo21/Algorithm-1 | 1bce4f3d2328c3b3e24b9d7772fca43090a285e1 | [
"MIT"
] | 4 | 2021-01-04T03:45:22.000Z | 2021-10-06T06:11:00.000Z | /**
* problem : https://leetcode.com/problems/product-of-array-except-self/
* time complexity : O(N)
* algorithm : subsum
*/
class Solution {
public:
vector<int> productExceptSelf(vector<int>& nums) {
int n = nums.size();
vector<int> ans(n, 1);
for(int i=1;i<n;i++) ans[i] = ans[i-1] * nums[i-1]; // nums[0, i) multiple
for(int i=n-2;i>=0;i--) nums[i] = nums[i+1] * nums[i]; // nums[i, n) multiple
for(int i=0; i<n-1;i++) ans[i] = ans[i] * nums[i+1]; // nums[0, i) * nums[i+1, n) multiple
return ans;
}
};
| 31.5 | 98 | 0.54321 | Jeongseo21 |
dbbf0d4aea108f517ad94670350a01d4060ee336 | 29,591 | cpp | C++ | mainwindow.cpp | hackingotter/LC3-Simulator | dbb58929922149b29c0f0cf630d46261ed7cb01f | [
"MIT"
] | null | null | null | mainwindow.cpp | hackingotter/LC3-Simulator | dbb58929922149b29c0f0cf630d46261ed7cb01f | [
"MIT"
] | null | null | null | mainwindow.cpp | hackingotter/LC3-Simulator | dbb58929922149b29c0f0cf630d46261ed7cb01f | [
"MIT"
] | 1 | 2018-09-22T23:01:40.000Z | 2018-09-22T23:01:40.000Z | #include "QScreen"
#include "UndoStackMasker.h"
#include <QInputDialog>
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QStandardItemModel>
#include <QDebug>
#include <QScrollArea>
#include "BetterScrollbar.h"
#include "RegisterModel.h"
//#include "Simulator.h"
#include "QProgressDialog"
#include "ModelDelegate.h"
#include "Util.h"
#include "MemWindow.h"
#include "stdio.h"
#include "hope.h"
#include "QErrorMessage"
#include <QColorDialog>
#include <QtConcurrent/QtConcurrentRun>
#include <QStatusBar>
#include <QProgressBar>
#include <QVBoxLayout>
#include <QThread>
#include "RegisterModel.h"
#include "status.h"
#include "modeler.h"
#include "Bridge.h"
#include <QFuture>
#include "StackModeler.h"
#include "DoUndo.h"
#include "FileHandler.h"
#include "UndoStackView.h"
#include <QSettings>
#include <QMessageBox>
#include <QFileDialog>
#include "HelpMenu.h"
#include "MemTable.h"
#include <QDataStream>
#include "Assembler.h"
#include <QUndoView>
#include <QItemSelectionModel>
#include <map>
#include <QFile>
#include "KBRDModel.h"
#include <QProcess>
#include "Console.h"
#include "Saver.h"
#include <QCoreApplication>
#define REGISTERVIEWNUMCOLUMN 2
#define SCROLLTO(VIEW,INPUT)\
{\
(VIEW)->scrollTo((VIEW)->model()->index(INPUT,0),QAbstractItemView::PositionAtTop);\
}
#define MEMVIEWSETUPPERCENT 20
#define HEX_COLUMN_WIDTH 60
#define MEM_VIEW_BP_COL 0
#define MEM_VIEW_ADR_COL 1
#define MEM_VIEW_NAME_COL 2
#define MEM_VIEW_VAL_COL 3
#define MEM_VIEW_MNEM_COL 4
#define MEM_VIEW_COMMENT_COL 5
#define STACK_VIEW_ADR_COL 0
#define STACK_VIEW_OFFSET_COL 1
#define STACK_VIEW_NAME_COL 2
#define STACK_VIEW_VAL_COL 3
#define STACK_VIEW_MNEM_COL 4
#define STACK_VIEW_COMMENT_COL 5
#define UPDATEVIEW(TABLEVIEW) TABLEVIEW->hide();TABLEVIEW->show();
#define SETUPDISPLAY(UI,THIS)\
qDebug("Setting up the display");
#define FINISHING_TOUCHES(DISP,MODEL)\
disp->update();
#define UPDATE_REGISTER_DISPLAY(UI,REGISTER)\
UI->RegisterView->item((int)REGISTER,REGISTERVIEWNUMCOLUMN)->setText(QString().setNum(getRegister(REGISTER)));
#define UPDATE_COND_DISPLAY(UI)\
switch(getProgramStatus())\
{\
case cond_n:UI->RegisterView->item((int)PSR,REGISTERVIEWNUMCOLUMN)->setText("N");break;\
case cond_z:UI->RegisterView->item((int)PSR,REGISTERVIEWNUMCOLUMN)->setText("Z");break;\
case cond_p:UI->RegisterView->item((int)PSR,REGISTERVIEWNUMCOLUMN)->setText("P");break;\
case cond_none:UI->RegisterView->item((int)PSR,REGISTERVIEWNUMCOLUMN)->setText("ERR");break;\
default:UI->RegisterView->item((int)PSR,REGISTERVIEWNUMCOLUMN)->setText("P");\
}
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
setWindowTitle("LC-3 Sim");
// Computer::getDefault()->lowerBoundTimes();
// std::cout<<Computer::getDefault()->proposedNewAddress(8,5,10,-2)<<std::endl;
// Saver::savePortable();
// std::cout<<Computer::getDefault()->proposedNewAddress(9,5,10,-2)<<std::endl;
Computer::getDefault()->setProgramStatus(cond_z);
Utility::systemInfoDebug();//Just some fun info
Utility::Utilit::setup();
setupThreadManager();//QED
QFuture<void> f1 = QtConcurrent::run(threadTest,QString("1"));
f1.waitForFinished();
qDebug("About to setup ui");
ui->setupUi(this);//this puts everything in place
// ui->consoleTab->deleteLater();
ui->tab_3->deleteLater();
ui->actionLoad->deleteLater();
ui->actionSave_2->deleteLater();
ui->menuOptions->deleteLater();
ui->menuMore_Options->deleteLater();
setupConnections();
setupDisplay();
setupMenuBar();
setupRegisterView();
setupViews();
setupControlButtons();
setupInOut();
setupWatches();
setupUndoInterface();
setupConsoleInterface();
Bridge::doWork();
qDebug("Connecting Disp");
// QObject::connect(Computer::getDefault() ,SIGNAL(update()),disp,SLOT(update()));
QObject::connect(Computer::getDefault() ,SIGNAL(update()),this,SLOT(update()));
QObject::connect(disp,SIGNAL(mouseMoved(QString)),ui->Mouseposition,SLOT(setText(QString)));
qDebug("Connecting ");
QObject::connect(ui->actionClear,SIGNAL(triggered()),disp,SLOT(clearScreen()));
// ui->undoStackSpot->addWidget();f
// QObject::connect(ui->NextButton,SIGNAL(on_NextButton_pressed()),ui->RegisterView,SLOT(update()));
readSettings();
update();
// testSave();
if(false)
{
QString inFileName = QFileDialog::getOpenFileName();
qDebug(inFileName.toLocal8Bit());
assembleNLoadFile("LC3-Simulator/Assembler Unit Test/AND.asm");
prettySave();
inFileName = QFileDialog::getOpenFileName();
assembleNLoadFile(inFileName);
}
connect(ui->actionInfo, &QAction::triggered, this,[=](){MainWindow::importantInfo();});
// QObject::connect(ui->actionInfo,SIGNAL(triggered()),this,SLOT(()));
// ui->actionInfo
// CONNECT(ui->actionInfo,triggered(),this, this::);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::importantInfo()
{
HelpMenu* help = new HelpMenu();
help->show();
help->activateWindow();
}
//MemWindow* MainWindow::makeNConnectNewMemWindow(modeler* model)
//{
// MemWindow* Newest = new MemWindow(model,Saturn->generateBar());
// CONNECT(this,signalUpdate(),Newest,kick());
//}
void MainWindow::setupViews()
{
qDebug("Setting Up Views");
qDebug("Now will be making the model");
this->model = new modeler(this, threadRunning);
this->StackModel = new StackModeler(this,threadRunning);
QString str;
Saturn = new ScrollBarHandler();
for(int i = 0;i<3;i++)
{
MemWindow* memy = new MemWindow(model,Saturn->generateBar());
setupMemView(memy->getMemView(),false,true);
CONNECT(this,signalUpdate(),memy,kick());
ui->MemorySplitter->addWidget(memy);
};
ui->MemorySplitter->children().at(2);
setupMemView(ui->MemView3View);
// ui->MemView3->deleteLater();
setupStackView();
qDebug("Model Created");
/*
* There is an assumption that hitting enter will cause an input to be entered.
* These lines connect the three inputs for the views
*/
qDebug("Connecting View interfaces");
{
// connect(ui->MemView1Input,SIGNAL(returnPressed()),ui->MemView1GotoButton,SLOT(click()));
connect(ui->MemView3Input,SIGNAL(returnPressed()),ui->MemView3GotoButton,SLOT(click()));
// connect(ui->StackViewInput,SIGNAL(returnPressed()),ui->StackViewGotoButton,SLOT(click()));
}
qDebug("Done Connecting Views");
qDebug("Done Setting Up Views");
}
void MainWindow::setupWatches()
{
qDebug("Setting up Watch");
Clockmaker = new WatchWatcher(0,threadRunning);
setupMemView(Clockmaker->getTableViewPtr(),false,false);
ui->verticalLayout_8->addWidget(Clockmaker);
}
void MainWindow::setupMenuBar()
{
QAction* actionLoad_File = new QAction("Load File",this);
QAction* actionAssemble_File = new QAction("Assemble File",this);
QAction* actionAssemble_Load_File = new QAction("Assemble and Load File",this);
QAction* actionSave_File = new QAction("Save File",this);
QAction* actionSave_File_As= new QAction("Save File As ...",this);
QAction* actionSave_State = new QAction("Save IDE State",this);
QAction* actionLoad_State = new QAction("Load IDE State",this);
QAction* actionTestingSave = new QAction("To Save, use console",this);
QList<QAction*> fileActions;
// fileActions <<actionLoad_File;
// fileActions <<actionAssemble_File;
fileActions <<actionAssemble_Load_File;
// fileActions <<actionSave_File;
// fileActions <<actionSave_File_As;
// fileActions <<actionSave_State;
// fileActions <<actionLoad_State;
fileActions <<actionTestingSave;
actionAssemble_Load_File->setShortcut(QKeySequence(tr("Ctrl+D")));
// actionSave_File_As->setShortcut(QKeySequence(tr("Ctrl+S")));
// <<actionAssemble_File<<actionAssemble_Load_File<<actionSave_File<<actionSave_File_As<<actionSave_State<<actionLoad_State;
// fileActions << actionTestingSave;
ui->menuFile->addActions(fileActions);
CONNECT(actionSave_State,triggered(),this, storeState());
CONNECT(actionLoad_State,triggered(),this, reloadState());
CONNECT(actionLoad_File,triggered(),this,loadFile());
CONNECT(actionAssemble_Load_File,triggered(),this, assembleNLoadFile());
// qDebug("Setting up testing Save");
connect(actionTestingSave, &QAction::triggered, this,[=](){/*this->prettySave()*/;});
// this->prettySave();
// QMenu* fillMenu = new QMenu("Fill...");
// setupScreenMenuDropdown(*fillMenu);
// ui->menuScreen->addMenu(fillMenu);
}
QString getSaveValue(QString text)
{
QString out;
bool ok;
do{
out = QInputDialog::getText(nullptr, "QInputDialog::getText()",
text, QLineEdit::Normal,
QDir::home().dirName(), &ok);
}while(!ok || text.isEmpty());
return out;
}
void MainWindow::prettySave()
{
qDebug("Beginning Pretty Save");
QString fileName = QFileDialog::getSaveFileName(nullptr,"Save to *.asm",QString(),"*.asm");
if(fileName == QString())
{
qDebug("Looks like they decided not to saves");
return;
}
mem_addr_t begin = Utility::QSTRING2INTBASE(getSaveValue("Save Start"),16);
mem_addr_t end = Utility::QSTRING2INTBASE(getSaveValue("Save End"),16);
Saver::savePortable(begin,end,true,fileName);
}
void MainWindow::testSave()
{
// QFrame* pictu = new QFrame();
assembleNLoadFile("C:/Users/Jedadiah/Downloads/LC3Fill.asm");
handleConsoleIn(QString("save x3000 x3104").toLatin1().data());
exit(0);
}
void MainWindow::setupScreenMenuDropdown(QMenu & menu)
{
QAction* actionFill_White = new QAction("White",this);
QAction* actionFill_Black = new QAction("Black",this);
QAction* actionFill_Red = new QAction("Red",this);
QAction* actionFill_Green = new QAction("Green",this);
QAction* actionFill_Blue = new QAction("Blue",this);
QAction* actionFill_Puce = new QAction("Puce",this);
QList<QAction*> fillActions;
fillActions<<actionFill_White<<actionFill_Black<<actionFill_Red<<actionFill_Green<<actionFill_Blue<<actionFill_Puce;
connect(actionFill_White, &QAction::triggered, disp, [=](){ disp->fillScreen(0x7FFF);});
connect(actionFill_Black, &QAction::triggered, disp, [=](){ disp->fillScreen(0x0000);});
connect(actionFill_Red, &QAction::triggered, disp, [=](){ disp->fillScreen(0x7C00);});
connect(actionFill_Green, &QAction::triggered, disp, [=](){ disp->fillScreen(0x03C0);});
connect(actionFill_Blue, &QAction::triggered, disp, [=](){ disp->fillScreen(0x001F);});
connect(actionFill_Puce, &QAction::triggered, disp, [=](){ disp->fillScreen(0x3466);});
menu.addActions(fillActions);
}
void MainWindow::setupConsoleInterface()
{
ui->consoleOut->insertPlainText("Hello");
// QFuture<void> f1 = QtConcurrent::run(startConsole(),QString("1"));
// f1.begin();
}
void MainWindow::testingSave()
{
prettySave();
// Saver::savePortable();
}
void MainWindow::reloadState()
{
Saver::loadState();
}
void MainWindow::storeState()
{
Saver::saveState();
}
void MainWindow::setupControlButtons()
{
Computer* comp = Computer::getDefault();
connect(ui->haltButton, &QPushButton::pressed,comp, [=](){ comp->setRunning(false); });
// CONNECT(ui->haltButton,pressed(),Computer::getDefault(),);
}
void MainWindow::setupConnections()
{
qRegisterMetaType<mem_addr_t>("mem_addr_t");
qRegisterMetaType<val_t>("val_t");
// qRegisterMetaType<ProcessHandle*>("ProcessHandle*const");
}
void MainWindow::setupUndoInterface()
{
UndoStackMasker* widge = new UndoStackMasker(Computer::getDefault()->Undos);
ui->undoStackSpot->addWidget(widge);
widge->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Expanding);
}
bool MainWindow::loadFile(QString path)
{
bool success = false;
Computer::getDefault()->Undos->beginMacro("Load "+ path);
qDebug("Attempting to load a program");
if(path==QString())
{
qDebug("Looks like there was no file specified. Time for the user to choose.");
path = QFileDialog::getOpenFileName(this,"Select a file to load",QString(),"*.obj");
}
if(path!=QString())
{
qDebug("Attempting to use that choice " +path.toLocal8Bit());
try
{
Computer::getDefault()->loadProgramFile(path.toLocal8Bit().data());
success = true;
}
catch(const std::string& e)
{
std::cout<<e<<std::endl;
success = false;
}
catch(...)
{
qDebug("SOMETHING WENT WRONG WITH THE FILE!");
std::cout<<"An unexpected error has occurred"<<std::endl;
success = false;
}
}
else
{
qDebug("Seems that the user chose not to choose");
}
Computer::getDefault()->Undos->endMacro();
if(!success) Computer::getDefault()->Undos->undo();
return success;
}
QString MainWindow::assembleFile(QString path)
{
QFileDialog* fileUI = new QFileDialog();
fileUI->setNameFilter(QString("Assembly (*").append(ASSEMBLY_SUFFIX).append(")"));
fileUI->setReadOnly(true);
fileUI->setWindowTitle("Choose a file to assemble and load into memory");
Assembler embler = Assembler();
if(path==QString())
{
qDebug("Looks like there was no file specified. Time for the user to choose.");
path = fileUI->getOpenFileName();
}
QString target = path;
try
{
QString target = path;
target.replace(-3,3,OBJECT_SUFFIX);
embler.assembleFile(path.toLocal8Bit().data(),target.toLocal8Bit().data());
}
catch(const std::string& e)
{
std::cout<<e<<std::endl;
return "";
}
catch(...)
{
std::cout<<"An unforseen error has occured"<<std::endl;
return "";
}
return "Test.obj";
}
void MainWindow::indicatingAssembleNLoad(QString path)
{
}
void MainWindow::assembleNLoadFile(QString path)
{
QFileDialog* fileUI = new QFileDialog();
fileUI->setNameFilter(QString("Assembly (*").append(ASSEMBLY_SUFFIX).append(")"));
fileUI->setReadOnly(true);
fileUI->setWindowTitle("Choose a file to assemble and load into memory");
Assembler embler = Assembler();
if(path==QString())
{
qDebug("Looks like there was no file specified. Time for the user to choose.");
path = fileUI->getOpenFileName();
}
qDebug(path.toLocal8Bit());
// QString shortPath = QString(path);
// shortPath.remove(".asm");
// QString namePath = shortPath+".obj";
Computer::getDefault()->Undos->beginMacro("Assemble and Load "+path);
qDebug("assembling and loading");
qDebug("Trying " + path.toLocal8Bit());
try
{
const QByteArray qba = path.toLocal8Bit();
const char* ccpp = qba.constData();
qDebug(QString("I am attempting to assemble the file" + path + " into " + "/TemporaryFile.obj").toLocal8Bit());
// path.append("obj")
embler.assembleFile(ccpp,"/TemporaryFile.obj");
}
catch(const std::string& e)
{
// progressy->cancel();
QErrorMessage* errory = new QErrorMessage(this);
errory->showMessage(QString().fromStdString(e));
std::cout<<e<<std::endl;
Computer::getDefault()->Undos->endMacro();
Computer::getDefault()->Undos->undo();//no need in saving this
return;
}
catch(char e)
{
std::cout<<e<<std::endl;
return;
}
catch(...)
{
// progressy->cancel();
QErrorMessage* errory = new QErrorMessage(this);
errory->showMessage("An unforseen error has occured");
std::cout<<"An unforseen error has occured"<<std::endl;
Computer::getDefault()->Undos->endMacro();
Computer::getDefault()->Undos->undo();//no need in saving this
return;
}
try{
// progress= 1;
// progressy->setLabelText("Passing values over.");
embler.passLabelsToComputer(Computer::getDefault());
embler.passCommentsToComputer(Computer::getDefault());
embler.passDataTypesToComputer(Computer::getDefault());
}
catch(const std::string& e)
{
std::cout<<e<<endl;
Computer::getDefault()->Undos->endMacro();
Computer::getDefault()->Undos->undo();
return;
}
catch(...)
{
qDebug("What happened?");
return;
}
// progressy->setValue(2);
// progressy->setLabelText("Loading file.");
Computer::getDefault()->Undos->endMacro();
if(loadFile("/TemporaryFile.obj"))
{
// progressy->setLabelText("File loaded.");
// progressy->setValue(3);
qDebug("successfully loaded");
}
else
{
Computer::getDefault()->Undos->undo();
qDebug("didn't work");
QErrorMessage* errory = new QErrorMessage(this);
errory->showMessage("This file couldn't be loaded.");
// progressy->cancel();
}
// embler.assembleFile();
}
void MainWindow::handleFiles()
{
Assembler Bill;
const char* inputPath = QFileDialog::getOpenFileName().toLocal8Bit().data();
Bill.assembleFile(inputPath,"LC3Maybe.obj");
Computer::getDefault()->loadProgramFile(QString("LC3Maybe.obj").toLatin1().data());
IFNOMASK(emit update();)
}
void MainWindow::setupDisplay()
{
disp = new Hope();
QHBoxLayout* qhbl= new QHBoxLayout();
qhbl->addWidget(disp,0,Qt::AlignCenter);
ui->verticalLayout_11->addLayout(qhbl);
disp->autoFillBackground();
disp->setMinimumSize(SCREEN_WIDTH,SCREEN_HEIGHT);
disp->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Minimum);
QObject::connect(Computer::getDefault(),SIGNAL(memValueChanged(mem_addr_t)),disp,SLOT(update(mem_addr_t)));
}
void MainWindow::setupMemView(QTableView* view, bool setmodel, bool setScroll)
{
qDebug("Attaching the model to the views");
qDebug("Showing Grid");
view->showGrid();
if(setmodel)
{
qDebug("Setting Model");
view->setModel(model);
}
if(setScroll){
HighlightScrollBar* scroll = new HighlightScrollBar(Qt::Vertical,this);
Saturn->addScrollBar(scroll);
view->setVerticalScrollBar(scroll);
}
// this is inefficient and useless since we should set those in the design
//qDebug("Resizing Columns");
//qDebug("model has "+QString().setNum(model->columnCount()).toLocal8Bit());
//qDebug(QString().setNum(view->height()).toLocal8Bit());
//view->resizeColumnsToContents();
qDebug("Hiding vertical Header");
view->verticalHeader()->hide();
qDebug("setting Column width");
view->setColumnWidth(MEM_VIEW_BP_COL,30);
view->horizontalHeader()->setSectionResizeMode(MEM_VIEW_BP_COL,QHeaderView::Fixed);
view->setColumnWidth(MEM_VIEW_ADR_COL,HEX_COLUMN_WIDTH);
view->horizontalHeader()->setSectionResizeMode(MEM_VIEW_ADR_COL,QHeaderView::Fixed);
view->setColumnWidth(MEM_VIEW_NAME_COL,HEX_COLUMN_WIDTH);
view->setColumnWidth(MEM_VIEW_VAL_COL,HEX_COLUMN_WIDTH);
view->horizontalHeader()->setSectionResizeMode(MEM_VIEW_VAL_COL,QHeaderView::Fixed);
view->setSelectionMode(QAbstractItemView::SingleSelection);
view->setSelectionBehavior(QAbstractItemView::SelectRows);
// view->setContextMenuPolicy(Qt::CustomContextMenu);
// connect(view, SIGNAL(customContextMenuRequested(const QPoint &)),
// this, SLOT(showClickOptions(const QPoint &,view)));
QObject::connect(Computer::getDefault(),SIGNAL(update()),view,SLOT(update()));
}
void MainWindow::setupInOut()
{
InOutPut = new InOutSet(this);
ui->inOutHome->addWidget(InOutPut);
QMenu* InOutMenuBar = new QMenu("Text Options");
QAction* actionClearInput= new QAction("Clear Input Space",this);
CONNECT(actionClearInput,triggered(),InOutPut, clearText());
InOutMenuBar->addAction(actionClearInput);
// ui->menuBar->addMenu(InOutMenuBar);
CONNECT(this, reCheck(), InOutPut, update());
}
void MainWindow::onTableClicked(const QModelIndex & current)
{
}
void MainWindow::setupStackView()
{
qDebug("Setting up Stack View");
qDebug("Showing Grid");
MemWindow* StackWindow = new MemWindow(StackModel,Saturn->generateBar());
CONNECT(this,signalUpdate(),StackWindow,kick());
ui->StackBox->layout()->addWidget(StackWindow);
MemTable* view = StackWindow->getMemView();
StackWindow->setFlipped(true);
// view->setButtonText("SP");
// qDebug("Setting Model");
// view->hide();
// view->setModel(StackModel);
// StackModel->flip();
view->resizeColumnsToContents();
view->verticalHeader()->hide();
view->setColumnWidth(STACK_VIEW_ADR_COL,HEX_COLUMN_WIDTH);
view->horizontalHeader()->setSectionResizeMode(MEM_VIEW_ADR_COL,QHeaderView::Fixed);
view->setColumnWidth(STACK_VIEW_VAL_COL,HEX_COLUMN_WIDTH);
view->horizontalHeader()->setSectionResizeMode(MEM_VIEW_VAL_COL,QHeaderView::Fixed);
view->showGrid();
// // set row height and fix it
view->verticalHeader()->setDefaultSectionSize(20);
view->verticalHeader()->setSectionResizeMode(QHeaderView::Fixed);
view->setSelectionBehavior(QAbstractItemView::SelectRows);
// CONNECT(MainWindow::ui->actionFlip,triggered(),StackModel,flip());
// CONNECT(StackModel,flip(),this,update());
QObject::connect(Computer::getDefault(),SIGNAL(memValueChanged(mem_addr_t)),StackModel,SLOT(stackFrameListener(mem_addr_t)));
// QObject::connect(Computer::getDefault(),SIGNAL(subRoutineCalled()),StackModel,SLOT(increaseStackFrameCounter()));
//QObject::connect(Computer::getDefault(),SIGNAL(memValueChanged(mem_addr_t)),StackModel,SLOT(stackFrameListener(mem_addr_t)));
CONNECT(this,signalUpdate(),StackWindow,kick());
}
void MainWindow::setupRegisterView()
{
QTableView* view = ui->RegisterView;
qDebug("Initializing model");
regModel = new RegisterModel(this,threadRunning);
qDebug("Attaching the model to the views");
view->setModel(regModel);
qDebug("Showing Grid");
view->showGrid();
view->resizeColumnToContents(1);
view->setColumnWidth(0,10);
view->setColumnWidth(1,43);
view->resizeColumnToContents(reg_value_column);
qDebug("Setting horizantal heading options");
{
QHeaderView* hori = view->horizontalHeader();
hori->hide();
// hori->setSectionResizeMode(reg_color_column,QHeaderView::Fixed);
hori->setSectionResizeMode(reg_name_column,QHeaderView::Fixed);
hori->setDefaultAlignment(Qt::AlignRight);
}
qDebug("Setting vertical heading options");
{
QHeaderView* vert = view->verticalHeader();
vert->hide();
vert->setDefaultSectionSize(DEFAULT_TEXT_HEIGHT);
vert->setSectionResizeMode(QHeaderView::Fixed);
}
// CONNECT(ui->RegisterView,requestChange(),this,update());
}
void MainWindow::setupThreadManager()
{
manager = new ThreadManager();
CONNECT(manager,started(),this, gotoRunningMode());
CONNECT(manager,stopped(),this, gotoUserMode());
}
void MainWindow::on_continueButton_clicked()
{
disp->repaint();
}
void MainWindow::on_MemView3Input_returnPressed()
{
//This is just here so that the corressponding GotoButton can listen to it
}
void MainWindow::on_MemView3PCButton_pressed()
{
SCROLLTO(ui->MemView3View,Computer::getDefault()->getRegister(PC))
}
void MainWindow::on_MemView3GotoButton_pressed()
{
bool ok = true;
int target = Utility::unifiedInput2Val(ui->MemView3Input->text(),&ok);
if(ok)
{
SCROLLTO(ui->MemView3View,target)
}
CLEAR(ui->MemView3Input)
}
void MainWindow::on_NextButton_pressed()
{
qDebug("Executing Single instruction");
// executeSingleInstruction();
manager->activate(ThreadManager::Next);
// update();
}
void MainWindow::update()
{
emit signalUpdate();
disp->update();
UPDATEVIEW(ui->MemView3View);
// UPDATEVIEW();
UPDATEVIEW(ui->RegisterView);
UPDATEVIEW(Clockmaker->Coat);
Saturn->update();
emit reCheck();
}
void MainWindow::threadTest(QString name)
{
qDebug()<< name << QThread::currentThread();
for(int i = 0;i<1000;i++)
{
}
qDebug()<< name << QThread::currentThread();
}
void MainWindow::gotoRunningMode()
{
qDebug("Going to Running Mode");
*threadRunning = true;
ui->NextButton->setEnabled(false);
IFNOMASK(emit update();)
MASK
}
void MainWindow::gotoUserMode()
{
qDebug("Going to User Mode");
*threadRunning = false;
ui->NextButton->setEnabled(true);
UNMASK
IFNOMASK(emit update();)
}
void MainWindow::prepWork()
{
}
void MainWindow::on_info_pressed(){
HelpMenu* help = new HelpMenu();
help->show();
help->activateWindow();
}
void MainWindow::on_pushButton_4_pressed()
{
qDebug("Next");
manager->activate(ThreadManager::Next);
update();
}
void MainWindow::on_IntoButton_pressed()
{
qDebug("Step");
manager->activate(ThreadManager::Step);
}
void MainWindow::readSettings()
{
QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
settings.beginGroup("MainWindow");
qDebug("heylo");
int width = settings.value("Window Width",QVariant(DEFAULT_WINDOW_WIDTH)).toInt();
int height= settings.value("Window Height",QVariant(DEFAULT_WINDOW_HEIGHT)).toInt();
int defaultX = (getScreenWidth()-DEFAULT_WINDOW_WIDTH)/2;
int defaultY = (getScreenHeight()-DEFAULT_WINDOW_HEIGHT)/4;
int x = settings.value("Window X",QVariant(defaultX)).toInt();
int y = settings.value("Window Y",QVariant(defaultY)).toInt();
this->setGeometry(x,y,geometry().width(),geometry().height());
int MemoryBoxHeight = settings.value("Memory Box Height",QVariant(635)).toInt();
int MemoryBoxWidth = settings.value("Memory Box Width" ,QVariant(354)).toInt();
ui->MemorySplitter->restoreState(settings.value("Memory Splitter State").toByteArray());
this->resize(width,height);
ui->MemoryBox->resize(MemoryBoxWidth,MemoryBoxHeight);
setWindowState(static_cast<Qt::WindowState>(settings.value("Window State",QVariant(Qt::WindowMaximized)).toInt()));
settings.endGroup();
qDebug("theylo");
}
int MainWindow::getScreenWidth()
{
QScreen* screen = QGuiApplication::primaryScreen();
return screen->geometry().width();
}
int MainWindow::getScreenHeight()
{
QScreen* screen = QGuiApplication::primaryScreen();
return screen->geometry().height();
}
void MainWindow::saveSettings()
{
QSettings settings(QCoreApplication::organizationName(),QCoreApplication::applicationName());
settings.beginGroup("MainWindow");
settings.setValue("Window Height",this->height());
settings.setValue("Window Width",this->width());
settings.setValue("Memory Box Height", ui->MemoryBox->height());
settings.setValue("Memory Box Width",ui->MemoryBox->width());
settings.setValue("Memory Splitter State",ui->MemorySplitter->saveState());
settings.setValue("Window State",static_cast<int>(windowState()));
settings.setValue("Window X",geometry().x());
settings.setValue("Window Y",geometry().y());
settings.endGroup();
qDebug("done saving ui Settings");
}
void MainWindow::closeEvent(QCloseEvent *event)
{
// saveWorkSpace();
// Computer::getDefault()->testUndoSpeed();
saveSettings();
Saver::vanguard();
event->accept();
}
void MainWindow::saveWorkSpace()
{
// Computer::getDefault()->saveWorkSpace();
}
void MainWindow::on_undoButton_pressed()
{
Computer::getDefault()->Undos->undo();
}
void MainWindow::on_redoButton_pressed()
{
Computer::getDefault()->Undos->redo();
}
void MainWindow::on_consoleEnterButton_pressed()
{
qDebug("I want to take the input");
freopen("temp.txt","w",stdout);
handleConsoleIn(ui->lineEdit->text().toLocal8Bit().data());
std::fclose(stdout);
QFile phil("temp.txt");
phil.open(QIODevice::ReadWrite);
qDebug("handled");
QTextStream streamy(&phil);
while(!streamy.atEnd())
ui->consoleOut->insertPlainText(streamy.readLine()+"\n");
}
void MainWindow::on_continueButton_pressed()
{
manager->activate(ThreadManager::Flag);
}
void MainWindow::on_haltButton_pressed()
{
Computer::getDefault()->setRunning(false);
}
void MainWindow::on_Big_Undo_pressed()
{
}
| 31.214135 | 130 | 0.65378 | hackingotter |
dbc2ea04d835a1508fb1665cde595fedb3ba41e3 | 1,134 | cpp | C++ | _site/Competitive Programming/Hackerearth/House in Cities.cpp | anujkyadav07/anuj-k-yadav.github.io | ac5cccc8cdada000ba559538cd84921437b3c5e6 | [
"MIT"
] | 1 | 2019-06-10T04:39:49.000Z | 2019-06-10T04:39:49.000Z | _site/Competitive Programming/Hackerearth/House in Cities.cpp | anujkyadav07/anuj-k-yadav.github.io | ac5cccc8cdada000ba559538cd84921437b3c5e6 | [
"MIT"
] | 2 | 2021-09-27T23:34:07.000Z | 2022-02-26T05:54:27.000Z | _site/Competitive Programming/Hackerearth/House in Cities.cpp | anujkyadav07/anuj-k-yadav.github.io | ac5cccc8cdada000ba559538cd84921437b3c5e6 | [
"MIT"
] | 3 | 2019-06-23T14:15:08.000Z | 2019-07-09T20:40:58.000Z | #include <bits/stdc++.h>
using namespace std;
int getmid(int s, int e){
return (s + (e-s)/2);
}
int RSQ(int* st, int s, int e, int qs, int qe, int pos){
if(qs<=s && qe>=e){
return st[pos];
}
if(qe < s || e < qs){
return 0;
}
int mid = getmid(s,e);
return RSQ(st,s,mid,qs,qe,2*pos+1) + RSQ(st,mid+1,e,qs,qe,2*pos+2);
}
int Construct(int arr[], int* st, int start, int end, int pos){
if(start == end){
st[pos] = arr[start];
return arr[start];
}
int mid = getmid(start,end);
st[pos] = Construct(arr,st,start,mid,2*pos + 1) + Construct(arr,st,mid+1,end,2*pos + 2);
return st[pos];
}
int* segTree(int arr[], int n){
int x = (int)(ceil(log2(n)));
int size = 2*(int)pow(2,x) - 1;
int* st = new int[size];
Construct(arr,st,0,n-1,0);
return st;
}
int solve(int arr[], int n, int qs, int qe){
int* st = segTree(arr,n);
return RSQ(st,0,n-1,qs-1,qe-1,0);
}
int main(){
std::ios_base::sync_with_stdio(false);
int t;
cin>>t;
int n, l, r, q;
while(t--){
cin>>n;
int arr[n];
for (int i = 0; i < n; ++i)
{
cin>>arr[i];
}
cin>>q;
while(q--){
cin>>l>>r;
cout<<solve(arr,n,l,r)<<"\n";
}
}
} | 18.9 | 89 | 0.558201 | anujkyadav07 |
dbc59b65ed624319e3be2b94fe99d2b97f7aced9 | 23,656 | cc | C++ | src/fcst/source/equations/sorption_source_terms.cc | OpenFcst/OpenFcst0.2 | 770a0d9b145cd39c3a065b653a53b5082dc5d85c | [
"MIT"
] | 16 | 2015-05-08T18:19:39.000Z | 2021-05-21T17:22:47.000Z | src/fcst/source/equations/sorption_source_terms.cc | OpenFcst/OpenFcst0.2 | 770a0d9b145cd39c3a065b653a53b5082dc5d85c | [
"MIT"
] | 3 | 2016-09-05T10:17:36.000Z | 2016-12-11T18:23:06.000Z | src/fcst/source/equations/sorption_source_terms.cc | OpenFcst/OpenFcst0.2 | 770a0d9b145cd39c3a065b653a53b5082dc5d85c | [
"MIT"
] | 1 | 2021-04-15T16:45:47.000Z | 2021-04-15T16:45:47.000Z | //---------------------------------------------------------------------------
//
// FCST: Fuel Cell Simulation Toolbox
//
// Copyright (C) 2013 by Energy Systems Design Laboratory, University of Alberta
//
// This software is distributed under the MIT License.
// For more information, see the README file in /doc/LICENSE
//
// - Class: sorption_source_terms.cc
// - Description: This class is used to assemble cell matrix and cell residual
// corresponding to sorption/desorption of water inside the catalyst layer.
// - Developers: Madhur Bhaiya
// - $Id: sorption_source_terms.cc 2605 2014-08-15 03:36:44Z secanell $
//
//---------------------------------------------------------------------------
#include "equations/sorption_source_terms.h"
namespace NAME = FuelCellShop::Equation;
// --- ---
// --- Constructor ---
// --- ---
template<int dim>
NAME::SorptionSourceTerms<dim>::SorptionSourceTerms(FuelCell::SystemManagement& system_management)
:
NAME::EquationBase<dim>(system_management)
{
FcstUtilities::log << "->FuelCellShop::Equation::SorptionSourceTerms" << std::endl;
//----Initializing VariableInfo Structs------------------------------------------
//----Setting indices_exist to false --------------------------------------------
x_water.indices_exist = false;
lambda.indices_exist = false;
t_rev.indices_exist = false;
this->counter.resize(2, true);
}
// --- ---
// --- Destructor ---
// --- ---
template<int dim>
NAME::SorptionSourceTerms<dim>::~SorptionSourceTerms()
{}
// --- ---
// --- declare_parameters ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::declare_parameters(ParameterHandler& param) const
{
param.enter_subsection("Sorption Source Terms");
{
param.declare_entry("Water soption time constant [1/s]",
"10000.0",
Patterns::Double(0.0),
"Time constant for sorption isotherm. Units [1/s]");
param.declare_entry("Heat source/sink due to sorption/desorption",
"false",
Patterns::Bool(),
"Flag to include heat release/absorption due to sorption/desorption of water inside the catalyst layer.");
}
param.leave_subsection();
}
// --- ---
// --- initialize ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::initialize(ParameterHandler& param)
{
param.enter_subsection("Sorption Source Terms");
{
time_constant = param.get_double("Water soption time constant [1/s]");
flag_sorp_heat_cl = param.get_bool("Heat source/sink due to sorption/desorption");
}
param.leave_subsection();
//-------Assertion check that x_water and lambda should be the solution variables to account for sorption/desorption process --------------------
AssertThrow( this->system_management->solution_in_userlist("water_molar_fraction"),VariableNotFoundForSorption("water_molar_fraction", "sorption/desorption") );
AssertThrow( this->system_management->solution_in_userlist("membrane_water_content"), VariableNotFoundForSorption("membrane_water_content", "sorption/desorption") );
if (flag_sorp_heat_cl)
AssertThrow( this->system_management->solution_in_userlist("temperature_of_REV"), VariableNotFoundForSorption("temperature_of_REV", "heat source/sink due to sorption/desorption") );
}
// --- ---
// --- assemble_cell_matrix ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::assemble_cell_matrix(FuelCell::ApplicationCore::MatrixVector& cell_matrices,
const typename FuelCell::ApplicationCore::DoFApplication<dim>::CellInfo& cell_info,
FuelCellShop::Layer::BaseLayer<dim>* const layer)
{
if ( this->counter[0] )
{
this->make_assemblers_generic_constant_data();
this->counter[0] = false;
}
if ( this->counter[1] )
{
this->make_assemblers_cell_constant_data(cell_info);
this->counter[1] = false;
}
cell_residual_counter = false;
this->make_assemblers_cell_variable_data(cell_info, layer);
assemble_matrix_for_equation(cell_matrices, cell_info, "Ficks Transport Equation - water", cell_info.fe(x_water.fetype_index), phi_xWater_cell, 1.);
assemble_matrix_for_equation(cell_matrices, cell_info, "Membrane Water Content Transport Equation", cell_info.fe(lambda.fetype_index), phi_lambda_cell, -1.);
if (flag_sorp_heat_cl)
assemble_matrix_for_equation(cell_matrices, cell_info, "Thermal Transport Equation", cell_info.fe(t_rev.fetype_index), phi_T_cell, -1.);
}
// --- ---
// --- assemble_cell_residual ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::assemble_cell_residual(FuelCell::ApplicationCore::FEVector& cell_residual,
const typename FuelCell::ApplicationCore::DoFApplication<dim>::CellInfo& cell_info,
FuelCellShop::Layer::BaseLayer<dim>* const layer)
{
if ( this->counter[0] )
{
this->make_assemblers_generic_constant_data();
this->counter[0] = false;
}
if ( this->counter[1] )
{
this->make_assemblers_cell_constant_data(cell_info);
this->counter[1] = false;
}
cell_residual_counter = true;
this->make_assemblers_cell_variable_data(cell_info, layer);
for (unsigned int q=0; q < this->n_q_points_cell; ++q)
{
// ---- Ficks Transport Equation - water ------------------------------
for (unsigned int i=0; i < (cell_info.fe(x_water.fetype_index)).dofs_per_cell; ++i)
cell_residual.block(x_water.solution_index)(i) += ( this->JxW_cell[q] * phi_xWater_cell[q][i] * ((time_constant*rho_dry_cell)/EW_cell) *
(lambda_eq_cell[q] - (cell_info.values[last_iter_cell][lambda.solution_index][q])) );
// ---- Membrane Water Content Transport Equation ------------------------------
for (unsigned int i=0; i < (cell_info.fe(lambda.fetype_index)).dofs_per_cell; ++i)
cell_residual.block(lambda.solution_index)(i) += ( this->JxW_cell[q] * phi_lambda_cell[q][i] * ((time_constant*rho_dry_cell)/EW_cell) * (-1.0) *
(lambda_eq_cell[q] - (cell_info.values[last_iter_cell][lambda.solution_index][q])) );
// ---- Thermal Transport Equation ------------------------
if (flag_sorp_heat_cl)
for (unsigned int i=0; i < (cell_info.fe(t_rev.fetype_index)).dofs_per_cell; ++i)
cell_residual.block(t_rev.solution_index)(i) += ( this->JxW_cell[q] * phi_T_cell[q][i] * ((time_constant*rho_dry_cell)/EW_cell) * (-1.0) * h_sorp_cell[q] *
(lambda_eq_cell[q] - (cell_info.values[last_iter_cell][lambda.solution_index][q])) );
} // End Loop Over Quadrature Points
}
// --- ---
// --- adjust_internal_cell_couplings ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::adjust_internal_cell_couplings(std::vector< couplings_map >& equation_map) const
{
Assert( equation_map.size() != 0, ExcMessage("Vector size should be greater than zero in SorptionSourceTerms::adjust_internal_cell_couplings.") );
for (unsigned int i=0; i<equation_map.size(); ++i)
{
for ( couplings_map::iterator iter = equation_map[i].begin(); iter != equation_map[i].end(); ++iter )
{
if ( (iter->first == "Ficks Transport Equation - water") || (iter->first == "Membrane Water Content Transport Equation") )
{
(iter->second)["water_molar_fraction"] = DoFTools::always;
(iter->second)["membrane_water_content"] = DoFTools::always;
if (flag_sorp_heat_cl)
(iter->second)["temperature_of_REV"] = DoFTools::always;
}
else if ( iter->first == "Thermal Transport Equation" )
{
(iter->second)["temperature_of_REV"] = DoFTools::always;
if (flag_sorp_heat_cl)
{
(iter->second)["water_molar_fraction"] = DoFTools::always;
(iter->second)["membrane_water_content"] = DoFTools::always;
}
}
}
}
}
// --- ---
// --- print_equation_info ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::print_equation_info() const
{
FcstUtilities::log << std::endl;
FcstUtilities::log << "-------------------------------------------------------------------------------" << std::endl;
FcstUtilities::log << std::endl;
FcstUtilities::log << "PARAMETERS for \"Sorption Source Terms\":" << std::endl;
FcstUtilities::log << std::endl;
FcstUtilities::log << "Water soption time constant [1/s]: " << time_constant << std::endl;
FcstUtilities::log << "Heat source/sink due to sorption/desorption: " << flag_sorp_heat_cl << std::endl;
FcstUtilities::log << std::endl;
FcstUtilities::log << "-------------------------------------------------------------------------------" << std::endl;
FcstUtilities::log << std::endl;
}
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// LOCAL CG FEM BASED ASSEMBLERS - make_ FUNCTIONS //
/////////////////////////////////////////////////////
/////////////////////////////////////////////////////
// --- ---
// --- make_assemblers_generic_constant_data ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::make_assemblers_generic_constant_data()
{
//--------Block indices can't be filled here, as they depend on what equation we are in -------------------------------------------
//--------While doing cell_matrix assembly, developers need to be wary of the fact that block_indices are still not filled yet-----
//-----------Filling VariableInfo structures----------------------------------------------------------
//----------water_molar_fraction--------------------------------------------------------------
x_water.solution_index = this->system_management->solution_name_to_index("water_molar_fraction");
x_water.fetype_index = this->system_management->block_info->base_element[x_water.solution_index];
x_water.indices_exist = true;
//----------membrane_water_content--------------------------------------------------------------
lambda.solution_index = this->system_management->solution_name_to_index("membrane_water_content");
lambda.fetype_index = this->system_management->block_info->base_element[lambda.solution_index];
lambda.indices_exist = true;
if (flag_sorp_heat_cl) // It indirectly checks whether temperature_of_solid_phase is in user-defined list or not.
{
//-----------temperature_of_solid_phase-------------------------------------------------------
t_rev.solution_index = this->system_management->solution_name_to_index("temperature_of_REV");
t_rev.fetype_index = this->system_management->block_info->base_element[t_rev.solution_index];
t_rev.indices_exist = true;
}
}
// --- ---
// --- make_assemblers_cell_constant_data ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::make_assemblers_cell_constant_data(const typename FuelCell::ApplicationCore::DoFApplication<dim>::CellInfo& cell_info)
{
Assert( (x_water.indices_exist && lambda.indices_exist), ExcMessage("make_assemblers_generic_constant_data function not called before.") );
this->n_q_points_cell = (cell_info.fe(x_water.fetype_index)).n_quadrature_points;
last_iter_cell = cell_info.global_data->find_vector("Newton iterate");
//-------Allocation------------------------------------------------------------------------
// ----- All containers intialized to zero by default -------------------------------------
phi_xWater_cell.resize( this->n_q_points_cell, std::vector<double>( (cell_info.fe(x_water.fetype_index)).dofs_per_cell ) );
phi_lambda_cell.resize( this->n_q_points_cell, std::vector<double>( (cell_info.fe(lambda.fetype_index)).dofs_per_cell ) );
if (t_rev.indices_exist)
phi_T_cell.resize( this->n_q_points_cell, std::vector<double>( (cell_info.fe(t_rev.fetype_index)).dofs_per_cell ) );
//-----------------------------------------------------------------
this->JxW_cell.resize(this->n_q_points_cell);
lambda_eq_cell.resize(this->n_q_points_cell);
dlambdaEq_dxWater_cell.resize(this->n_q_points_cell);
dlambdaEq_dT_cell.resize(this->n_q_points_cell);
h_sorp_cell.resize(this->n_q_points_cell);
dhsorp_dT_cell.resize(this->n_q_points_cell);
}
// --- ---
// --- make_assemblers_cell_variable_data ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::make_assemblers_cell_variable_data(const typename FuelCell::ApplicationCore::DoFApplication<dim>::CellInfo& cell_info,
FuelCellShop::Layer::BaseLayer<dim>* const layer)
{
Assert( this->n_q_points_cell != 0, ExcMessage("make_assemblers_cell_constant_data function not called before.") );
// ----- type infos -------------
const std::type_info& CatalystLayer = typeid(FuelCellShop::Layer::CatalystLayer<dim>);
const std::type_info& base_layer = layer->get_base_type();
// ----- dynamic cast and filling the containers -----------------
try
{
if ( base_layer == CatalystLayer )
{
FuelCellShop::Layer::CatalystLayer<dim>* ptr = dynamic_cast< FuelCellShop::Layer::CatalystLayer<dim>* >(layer);
rho_dry_cell = ptr->get_electrolyte()->get_density();
EW_cell = ptr->get_electrolyte()->get_EW();
std::vector<VariableNames> deriv_flags;
ptr->get_electrolyte()->set_water_molar_fraction( FuelCellShop::SolutionVariable(&cell_info.values[last_iter_cell][x_water.solution_index],
water_molar_fraction) );
deriv_flags.push_back(water_molar_fraction);
if (t_rev.indices_exist)
{
ptr->get_electrolyte()->set_temperature( FuelCellShop::SolutionVariable(&cell_info.values[last_iter_cell][t_rev.solution_index],
temperature_of_REV) );
deriv_flags.push_back(temperature_of_REV);
}
ptr->get_electrolyte()->sorption_isotherm(lambda_eq_cell);
if (flag_sorp_heat_cl)
ptr->get_electrolyte()->sorption_enthalpy(h_sorp_cell);
if (!cell_residual_counter)
{
ptr->set_derivative_flags(deriv_flags);
std::map< VariableNames, std::vector<double> > dlambdaEq;
ptr->get_electrolyte()->sorption_isotherm_derivative(dlambdaEq);
dlambdaEq_dxWater_cell = dlambdaEq[water_molar_fraction];
if (t_rev.indices_exist)
dlambdaEq_dT_cell = dlambdaEq[temperature_of_REV];
if (flag_sorp_heat_cl)
{
std::map< VariableNames, std::vector<double> > dhsorp;
ptr->get_electrolyte()->sorption_enthalpy_derivative(dhsorp);
dhsorp_dT_cell = dhsorp[temperature_of_REV];
}
}
}
else
AssertThrow( false, ExcNotImplemented() );
}
catch(const std::bad_cast& e)
{
const std::type_info& info = typeid(*layer);
FcstUtilities::log << "Object of type " << info.name() << " not implemented" << std::endl;
FcstUtilities::log << e.what() << std::endl;
}
//---------------------------------------------------------------------------------------------------------------
//------------Looping over quadrature points in the cell --------------------------------------------------------
for (unsigned int q = 0; q < this->n_q_points_cell; ++q)
{
//-------JxW----------
this->JxW_cell[q] = (cell_info.fe(x_water.fetype_index)).JxW(q);
//------ Filling shape functions etc ----------------------------------------------------------------------
//------ This avoids recalculating shape functions etc for efficiency -------------------------------------
for (unsigned int k=0; k < (cell_info.fe(x_water.fetype_index)).dofs_per_cell; ++k)
phi_xWater_cell[q][k] = (cell_info.fe(x_water.fetype_index)).shape_value(k,q);
for (unsigned int k=0; k < (cell_info.fe(lambda.fetype_index)).dofs_per_cell; ++k)
phi_lambda_cell[q][k] = (cell_info.fe(lambda.fetype_index)).shape_value(k,q);
//------- Checking based on boolean flags for other fe elements--------------------------------------------
if (t_rev.indices_exist)
for (unsigned int k=0; k < (cell_info.fe(t_rev.fetype_index)).dofs_per_cell; ++k)
phi_T_cell[q][k] = (cell_info.fe(t_rev.fetype_index)).shape_value(k,q);
}
}
// --- ---
// --- assemble_matrix_for_equation ---
// --- ---
template<int dim>
void
NAME::SorptionSourceTerms<dim>::assemble_matrix_for_equation(FuelCell::ApplicationCore::MatrixVector& cell_matrices,
const typename FuelCell::ApplicationCore::DoFApplication<dim>::CellInfo& cell_info,
const std::string& eq_name,
const FEValuesBase<dim>& test_fe,
const std::vector< std::vector<double> >& test_shape_functions,
const double& sourceterm_factor)
{
Assert( !cell_residual_counter, ExcInternalError() );
Assert( this->n_q_points_cell != 0, ExcMessage("make_assemblers_cell_constant_data function not called before.") );
Assert( ((eq_name == "Ficks Transport Equation - water") || (eq_name == "Membrane Water Content Transport Equation") || (eq_name == "Thermal Transport Equation")), ExcNotImplemented() );
// --- Filling block indices --------------------------------------------
x_water.block_index = this->system_management->matrix_block_index(eq_name,"water_molar_fraction");
lambda.block_index = this->system_management->matrix_block_index(eq_name,"membrane_water_content");
if (t_rev.indices_exist)
t_rev.block_index = this->system_management->matrix_block_index(eq_name,"temperature_of_REV");
//-------- Looping over Quadrature points ----------------------------
for (unsigned int q = 0; q < this->n_q_points_cell; ++q)
{
//---------------LOOP over i -----------------------------------------------------------------
for (unsigned int i=0; i < test_fe.dofs_per_cell; ++i)
{
if (eq_name != "Thermal Transport Equation") // Ficks Transport Equation - water OR Membrane Water Content Transport Equation
{
//--------------LOOP(s) over j-------------------------------------------------------------
for (unsigned int j=0; j < (cell_info.fe(x_water.fetype_index)).dofs_per_cell; ++j)
cell_matrices[x_water.block_index].matrix(i,j) += ( this->JxW_cell[q] * sourceterm_factor * ((time_constant*rho_dry_cell)/EW_cell) * dlambdaEq_dxWater_cell[q] *
test_shape_functions[q][i] * phi_xWater_cell[q][j] );
for (unsigned int j=0; j < (cell_info.fe(lambda.fetype_index)).dofs_per_cell; ++j)
cell_matrices[lambda.block_index].matrix(i,j) += ( this->JxW_cell[q] * sourceterm_factor * (-1.0) * ((time_constant*rho_dry_cell)/EW_cell) *
test_shape_functions[q][i] * phi_lambda_cell[q][j] );
if (t_rev.indices_exist)
for (unsigned int j=0; j < (cell_info.fe(t_rev.fetype_index)).dofs_per_cell; ++j)
cell_matrices[t_rev.block_index].matrix(i,j) += ( this->JxW_cell[q] * sourceterm_factor * ((time_constant*rho_dry_cell)/EW_cell) * dlambdaEq_dT_cell[q] *
test_shape_functions[q][i] * phi_T_cell[q][j] );
}
else // Thermal Transport Equation
{
//--------------LOOP(s) over j-------------------------------------------------------------
for (unsigned int j=0; j < (cell_info.fe(x_water.fetype_index)).dofs_per_cell; ++j)
cell_matrices[x_water.block_index].matrix(i,j) += ( this->JxW_cell[q] * sourceterm_factor * ((time_constant*rho_dry_cell)/EW_cell) * dlambdaEq_dxWater_cell[q] * h_sorp_cell[q] *
test_shape_functions[q][i] * phi_xWater_cell[q][j] );
for (unsigned int j=0; j < (cell_info.fe(lambda.fetype_index)).dofs_per_cell; ++j)
cell_matrices[lambda.block_index].matrix(i,j) += ( this->JxW_cell[q] * sourceterm_factor * ((time_constant*rho_dry_cell)/EW_cell) *
( (-1.0) * h_sorp_cell[q]) *
test_shape_functions[q][i] * phi_lambda_cell[q][j] );
for (unsigned int j=0; j < (cell_info.fe(t_rev.fetype_index)).dofs_per_cell; ++j)
cell_matrices[t_rev.block_index].matrix(i,j) += ( this->JxW_cell[q] * sourceterm_factor * ((time_constant*rho_dry_cell)/EW_cell) *
((lambda_eq_cell[q]-cell_info.values[last_iter_cell][lambda.solution_index][q])*dhsorp_dT_cell[q] + dlambdaEq_dT_cell[q]*h_sorp_cell[q]) *
test_shape_functions[q][i] * phi_T_cell[q][j] );
}
} // End Loop over "i"
} // End Loop over "q"
}
// --- ---
// --- EXPLICIT INSTANTIATIONS ---
// --- ---
template class NAME::SorptionSourceTerms<deal_II_dimension>;
| 50.225053 | 211 | 0.536608 | OpenFcst |
3a774b9eb866cd8ced42668e5d81ff0f0d4e7ac0 | 14,826 | cpp | C++ | src/Editor/WorldEditor/CPoiMapSidebar.cpp | liakman/PrimeWorldEditor | 483184719701fbc59ad66212afcade9488956186 | [
"MIT"
] | 32 | 2018-12-17T20:22:32.000Z | 2019-06-14T06:48:25.000Z | src/Editor/WorldEditor/CPoiMapSidebar.cpp | liakman/PrimeWorldEditor | 483184719701fbc59ad66212afcade9488956186 | [
"MIT"
] | 10 | 2019-11-25T04:54:05.000Z | 2022-02-12T20:20:56.000Z | src/Editor/WorldEditor/CPoiMapSidebar.cpp | liakman/PrimeWorldEditor | 483184719701fbc59ad66212afcade9488956186 | [
"MIT"
] | 10 | 2019-11-22T09:16:00.000Z | 2021-11-21T22:55:54.000Z | #include "CPoiMapSidebar.h"
#include "ui_CPoiMapSidebar.h"
#include "CWorldEditor.h"
#include "Editor/UICommon.h"
#include <Core/Resource/Cooker/CPoiToWorldCooker.h>
#include <Core/Resource/Scan/CScan.h>
#include <Core/Resource/Script/CGameTemplate.h>
#include <Core/Resource/Script/NGameList.h>
#include <Core/ScriptExtra/CPointOfInterestExtra.h>
#include <QMouseEvent>
#include <QMessageBox>
constexpr CColor skNormalColor(0.137255f, 0.184314f, 0.776471f, 0.5f);
constexpr CColor skImportantColor(0.721569f, 0.066667f, 0.066667f, 0.5f);
constexpr CColor skHoverColor(0.047059f, 0.2f, 0.003922f, 0.5f);
CPoiMapSidebar::CPoiMapSidebar(CWorldEditor *pEditor)
: CWorldEditorSidebar(pEditor)
, ui(std::make_unique<Ui::CPoiMapSidebar>())
, mSourceModel(pEditor, this)
{
mModel.setSourceModel(&mSourceModel);
mModel.sort(0);
ui->setupUi(this);
ui->ListView->setModel(&mModel);
ui->ListView->selectionModel()->select(mModel.index(0,0), QItemSelectionModel::Select | QItemSelectionModel::Current);
SetHighlightSelected();
connect(ui->HighlightSelectedButton, &QPushButton::pressed, this, &CPoiMapSidebar::SetHighlightSelected);
connect(ui->HighlightAllButton, &QPushButton::pressed, this, &CPoiMapSidebar::SetHighlightAll);
connect(ui->HighlightNoneButton, &QPushButton::pressed, this, &CPoiMapSidebar::SetHighlightNone);
connect(ui->ListView->selectionModel(), &QItemSelectionModel::selectionChanged,
this, &CPoiMapSidebar::OnSelectionChanged);
connect(ui->ListView, &QListView::doubleClicked, this, &CPoiMapSidebar::OnItemDoubleClick);
connect(ui->MapMeshesButton, &QPushButton::clicked, this, &CPoiMapSidebar::OnPickButtonClicked);
connect(ui->UnmapMeshesButton, &QPushButton::clicked, this, &CPoiMapSidebar::OnPickButtonClicked);
connect(ui->UnmapAllButton, &QPushButton::clicked, this, &CPoiMapSidebar::OnUnmapAllPressed);
connect(ui->AddPoiFromViewportButton, &QPushButton::clicked, this, &CPoiMapSidebar::OnPickButtonClicked);
connect(ui->AddPoiFromInstanceListButton, &QPushButton::clicked, this, &CPoiMapSidebar::OnInstanceListButtonClicked);
connect(ui->RemovePoiButton, &QPushButton::clicked, this, &CPoiMapSidebar::OnRemovePoiButtonClicked);
}
CPoiMapSidebar::~CPoiMapSidebar() = default;
void CPoiMapSidebar::SidebarOpen()
{
Editor()->SetRenderingMergedWorld(false);
UpdateModelHighlights();
}
void CPoiMapSidebar::SidebarClose()
{
// Clear model highlights
if (mHighlightMode != EHighlightMode::HighlightNone)
{
EHighlightMode OldHighlightMode = mHighlightMode;
SetHighlightNone();
mHighlightMode = OldHighlightMode;
}
// Stop picking
if (mPickType != EPickType::NotPicking)
StopPicking();
// Disable unmerged world rendering
Editor()->SetRenderingMergedWorld(true);
}
void CPoiMapSidebar::HighlightPoiModels(const QModelIndex& rkIndex)
{
// Get POI and models
QModelIndex SourceIndex = mModel.mapToSource(rkIndex);
const QList<CModelNode*>& rkModels = mSourceModel.GetPoiMeshList(SourceIndex);
bool Important = IsImportant(SourceIndex);
// Highlight the meshes
for (auto& model : rkModels)
{
model->SetScanOverlayEnabled(true);
model->SetScanOverlayColor(Important ? skImportantColor : skNormalColor);
}
}
void CPoiMapSidebar::UnhighlightPoiModels(const QModelIndex& rkIndex)
{
const QModelIndex SourceIndex = mModel.mapToSource(rkIndex);
const QList<CModelNode*>& rkModels = mSourceModel.GetPoiMeshList(SourceIndex);
for (const auto& model : rkModels)
RevertModelOverlay(model);
}
void CPoiMapSidebar::HighlightModel(const QModelIndex& rkIndex, CModelNode *pNode)
{
bool Important = IsImportant(rkIndex);
pNode->SetScanOverlayEnabled(true);
pNode->SetScanOverlayColor(Important ? skImportantColor : skNormalColor);
}
void CPoiMapSidebar::UnhighlightModel(CModelNode *pNode)
{
pNode->SetScanOverlayEnabled(false);
}
void CPoiMapSidebar::RevertModelOverlay(CModelNode *pModel)
{
if (pModel)
{
if (mHighlightMode == EHighlightMode::HighlightAll)
{
// Prioritize the selected POI over others.
QModelIndex Selected = GetSelectedRow();
if (mSourceModel.IsModelMapped(Selected, pModel))
{
HighlightModel(Selected, pModel);
}
// If it's not mapped to the selected POI, then check whether it's mapped to any others.
else
{
for (int iRow = 0; iRow < mSourceModel.rowCount(QModelIndex()); iRow++)
{
QModelIndex Index = mSourceModel.index(iRow, 0);
if (mSourceModel.IsModelMapped(Index, pModel))
{
HighlightModel(Index, pModel);
return;
}
}
UnhighlightModel(pModel);
}
}
else if (mHighlightMode == EHighlightMode::HighlightSelected)
{
QModelIndex Index = GetSelectedRow();
if (mSourceModel.IsModelMapped(Index, pModel))
HighlightModel(Index, pModel);
else
UnhighlightModel(pModel);
}
else
{
UnhighlightModel(pModel);
}
}
}
CPoiMapSidebar::EPickType CPoiMapSidebar::GetRealPickType(bool AltPressed) const
{
if (!AltPressed) return mPickType;
if (mPickType == EPickType::AddMeshes) return EPickType::RemoveMeshes;
return EPickType::AddMeshes;
}
bool CPoiMapSidebar::IsImportant(const QModelIndex& rkIndex)
{
CScriptNode *pPOI = mSourceModel.PoiNodePointer(rkIndex);
bool Important = false;
TResPtr<CScan> pScan = static_cast<CPointOfInterestExtra*>(pPOI->Extra())->GetScan();
if (pScan)
Important = pScan->IsCriticalPropertyRef();
return Important;
}
QModelIndex CPoiMapSidebar::GetSelectedRow() const
{
QModelIndexList Indices = ui->ListView->selectionModel()->selectedRows();
return ( Indices.isEmpty() ? QModelIndex() : mModel.mapToSource(Indices.front()) );
}
void CPoiMapSidebar::UpdateModelHighlights()
{
const QItemSelection kSelection = ui->ListView->selectionModel()->selection();
QList<QModelIndex> SelectedIndices;
QList<QModelIndex> UnselectedIndices;
for (int iRow = 0; iRow < mModel.rowCount(QModelIndex()); iRow++)
{
QModelIndex Index = mModel.index(iRow, 0);
switch (mHighlightMode)
{
case EHighlightMode::HighlightSelected:
if (kSelection.contains(Index))
SelectedIndices.push_back(Index);
else
UnselectedIndices.push_back(Index);
break;
case EHighlightMode::HighlightAll:
SelectedIndices.push_back(Index);
break;
case EHighlightMode::HighlightNone:
UnselectedIndices.push_back(Index);
break;
}
}
for (const QModelIndex& rkIndex : UnselectedIndices)
UnhighlightPoiModels(rkIndex);
for (const QModelIndex& rkIndex : SelectedIndices)
HighlightPoiModels(rkIndex);
}
void CPoiMapSidebar::SetHighlightSelected()
{
mHighlightMode = EHighlightMode::HighlightSelected;
UpdateModelHighlights();
}
void CPoiMapSidebar::SetHighlightAll()
{
mHighlightMode = EHighlightMode::HighlightAll;
UpdateModelHighlights();
// Call HighlightPoiModels again on the selected index to prioritize it over the non-selected POIs.
if (ui->ListView->selectionModel()->hasSelection())
HighlightPoiModels(ui->ListView->selectionModel()->selectedRows().front());
}
void CPoiMapSidebar::SetHighlightNone()
{
mHighlightMode = EHighlightMode::HighlightNone;
UpdateModelHighlights();
}
void CPoiMapSidebar::OnSelectionChanged(const QItemSelection& rkSelected, const QItemSelection& rkDeselected)
{
if (mHighlightMode == EHighlightMode::HighlightSelected)
{
// Clear highlight on deselected models
QModelIndexList DeselectedIndices = rkDeselected.indexes();
for (const auto& index : DeselectedIndices)
UnhighlightPoiModels(index);
// Highlight newly selected models
const QModelIndexList SelectedIndices = rkSelected.indexes();
for (const auto& index : SelectedIndices)
HighlightPoiModels(index);
}
}
void CPoiMapSidebar::OnItemDoubleClick(QModelIndex Index)
{
QModelIndex SourceIndex = mModel.mapToSource(Index);
CScriptNode *pPOI = mSourceModel.PoiNodePointer(SourceIndex);
Editor()->ClearAndSelectNode(pPOI);
}
void CPoiMapSidebar::OnUnmapAllPressed()
{
QModelIndex Index = GetSelectedRow();
QList<CModelNode*> ModelList = mSourceModel.GetPoiMeshList(Index);
for (CModelNode *pModel : ModelList)
{
mSourceModel.RemoveMapping(Index, pModel);
RevertModelOverlay(pModel);
}
}
void CPoiMapSidebar::OnPickButtonClicked()
{
QPushButton *pButton = qobject_cast<QPushButton*>(sender());
if (pButton == ui->AddPoiFromViewportButton)
{
Editor()->EnterPickMode(ENodeType::Script, true, false, false);
connect(Editor(), &CWorldEditor::PickModeExited, this, &CPoiMapSidebar::StopPicking);
connect(Editor(), &CWorldEditor::PickModeClick, this, &CPoiMapSidebar::OnPoiPicked);
pButton->setChecked(true);
ui->MapMeshesButton->setChecked(false);
ui->UnmapMeshesButton->setChecked(false);
mPickType = EPickType::AddPOIs;
}
else
{
if (!pButton->isChecked())
{
Editor()->ExitPickMode();
}
else
{
Editor()->EnterPickMode(ENodeType::Model, false, false, true);
connect(Editor(), &CWorldEditor::PickModeExited, this, &CPoiMapSidebar::StopPicking);
connect(Editor(), &CWorldEditor::PickModeHoverChanged, this, &CPoiMapSidebar::OnModelHover);
pButton->setChecked(true);
if (pButton == ui->MapMeshesButton)
{
mPickType = EPickType::AddMeshes;
ui->UnmapMeshesButton->setChecked(false);
}
else if (pButton == ui->UnmapMeshesButton)
{
mPickType = EPickType::RemoveMeshes;
ui->MapMeshesButton->setChecked(false);
}
}
}
}
void CPoiMapSidebar::StopPicking()
{
ui->MapMeshesButton->setChecked(false);
ui->UnmapMeshesButton->setChecked(false);
ui->AddPoiFromViewportButton->setChecked(false);
mPickType = EPickType::NotPicking;
RevertModelOverlay(mpHoverModel);
mpHoverModel = nullptr;
Editor()->ExitPickMode();
disconnect(Editor(), &CWorldEditor::PickModeExited, this, nullptr);
disconnect(Editor(), &CWorldEditor::PickModeHoverChanged, this, nullptr);
disconnect(Editor(), &CWorldEditor::PickModeClick, this, nullptr);
}
void CPoiMapSidebar::OnInstanceListButtonClicked()
{
EGame Game = Editor()->CurrentGame();
CScriptTemplate *pPoiTemplate = NGameList::GetGameTemplate(Game)->TemplateByID("POIN");
CPoiListDialog Dialog(pPoiTemplate, &mSourceModel, Editor()->Scene(), this);
Dialog.exec();
const QList<CScriptNode*>& rkSelection = Dialog.Selection();
if (!rkSelection.empty())
{
for (CScriptNode *pNode : rkSelection)
mSourceModel.AddPOI(pNode);
mModel.sort(0);
}
}
void CPoiMapSidebar::OnRemovePoiButtonClicked()
{
if (ui->ListView->selectionModel()->hasSelection())
{
QModelIndex Index = ui->ListView->selectionModel()->selectedRows().front();
UnhighlightPoiModels(Index);
Index = mModel.mapToSource(Index);
mSourceModel.RemovePOI(Index);
}
}
void CPoiMapSidebar::OnPoiPicked(const SRayIntersection& rkIntersect, QMouseEvent *pEvent)
{
CScriptNode *pPOI = static_cast<CScriptNode*>(rkIntersect.pNode);
if (pPOI->Instance()->ObjectTypeID() != CFourCC("POIN").ToLong()) return;
mSourceModel.AddPOI(pPOI);
mModel.sort(0);
// Exit pick mode unless the user is holding the Ctrl key
if (!(pEvent->modifiers() & Qt::ControlModifier))
Editor()->ExitPickMode();
}
void CPoiMapSidebar::OnModelPicked(const SRayIntersection& rkRayIntersect, QMouseEvent* pEvent)
{
if (!rkRayIntersect.pNode)
return;
// Check for valid selection
const QModelIndexList Indices = ui->ListView->selectionModel()->selectedRows();
if (Indices.isEmpty())
return;
// Map selection to source model
QModelIndexList SourceIndices;
SourceIndices.reserve(Indices.size());
for (const auto& index : Indices)
SourceIndices.push_back(mModel.mapToSource(index));
// If alt is pressed, invert the pick mode
CModelNode *pModel = static_cast<CModelNode*>(rkRayIntersect.pNode);
const bool AltPressed = (pEvent->modifiers() & Qt::AltModifier) != 0;
const EPickType PickType = GetRealPickType(AltPressed);
// Add meshes
if (PickType == EPickType::AddMeshes)
{
for (const auto& index : SourceIndices)
mSourceModel.AddMapping(index, pModel);
if (mHighlightMode != EHighlightMode::HighlightNone)
HighlightModel(SourceIndices.front(), pModel);
}
// Remove meshes
else if (PickType == EPickType::RemoveMeshes)
{
for (const auto& index : SourceIndices)
mSourceModel.RemoveMapping(index, pModel);
if (mHighlightMode != EHighlightMode::HighlightNone)
RevertModelOverlay(mpHoverModel);
else
UnhighlightModel(pModel);
}
}
void CPoiMapSidebar::OnModelHover(const SRayIntersection& rkIntersect, QMouseEvent *pEvent)
{
// Restore old hover model to correct overlay color, and set new hover model
if (mpHoverModel)
RevertModelOverlay(mpHoverModel);
mpHoverModel = static_cast<CModelNode*>(rkIntersect.pNode);
// If the left mouse button is pressed, treat this as a click.
if (pEvent->buttons() & Qt::LeftButton)
{
OnModelPicked(rkIntersect, pEvent);
}
else // Otherwise, process as a mouseover
{
QModelIndex Index = GetSelectedRow();
// Process new hover model
if (mpHoverModel)
{
bool AltPressed = (pEvent->modifiers() & Qt::AltModifier) != 0;
EPickType PickType = GetRealPickType(AltPressed);
if ( ((PickType == EPickType::AddMeshes) && !mSourceModel.IsModelMapped(Index, mpHoverModel)) ||
((PickType == EPickType::RemoveMeshes) && mSourceModel.IsModelMapped(Index, mpHoverModel)) )
{
mpHoverModel->SetScanOverlayEnabled(true);
mpHoverModel->SetScanOverlayColor(skHoverColor);
}
}
}
}
| 32.728477 | 122 | 0.673007 | liakman |
3a842e2371c397c34681883af18f96006659c5a6 | 543 | hpp | C++ | src/src/CharacterEncoding.hpp | rolfwr/HuffmanCompression | c8d8501b076bcb193ce1df48ec86f7dfa4fa8331 | [
"MIT"
] | null | null | null | src/src/CharacterEncoding.hpp | rolfwr/HuffmanCompression | c8d8501b076bcb193ce1df48ec86f7dfa4fa8331 | [
"MIT"
] | null | null | null | src/src/CharacterEncoding.hpp | rolfwr/HuffmanCompression | c8d8501b076bcb193ce1df48ec86f7dfa4fa8331 | [
"MIT"
] | null | null | null | #pragma once
#define START_SIZE 2
#include <stdlib.h>
/*
================================
Represents the encoding of a character
================================
*/
class CharacterEncoding
{
public:
CharacterEncoding();
CharacterEncoding( CharacterEncoding const& original );
~CharacterEncoding();
unsigned char GetBit( size_t index ) const;
size_t GetBitSize();
void AddBit( unsigned char bit );
void RemoveBit();
private:
char* bytes;
size_t index;
size_t numBytes;
size_t bitSize;
};
| 17.516129 | 56 | 0.598527 | rolfwr |
3a8bf4db4e423319eaeba5502c9c0922e962090f | 4,444 | cpp | C++ | client/include/game/CLoadingScreen.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 97 | 2019-01-13T20:19:19.000Z | 2022-02-27T18:47:11.000Z | client/include/game/CLoadingScreen.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 92 | 2019-01-23T23:02:31.000Z | 2022-03-23T19:59:40.000Z | client/include/game/CLoadingScreen.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 69 | 2019-01-13T22:01:40.000Z | 2022-03-09T00:55:49.000Z | /*
Plugin-SDK (Grand Theft Auto San Andreas) header file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CLoadingScreen.h"
int &CLoadingScreen::m_currDisplayedSplash = *(int*)0x8D093C;
int &CLoadingScreen::m_numChunksLoaded = *(int*)0x8D0940;
int &CLoadingScreen::m_chunkBarAppeared = *(int*)0x8D0944;
char *CLoadingScreen::m_PopUpMessage = (char*)0xBAB268;
char *CLoadingScreen::m_LoadingGxtMsg2 = (char*)0xBAB278;
char *CLoadingScreen::m_LoadingGxtMsg1 = (char*)0xBAB2C8;
bool &CLoadingScreen::m_bActive = *(bool*)0xBAB318;
bool &CLoadingScreen::m_bPaused = *(bool*)0xBAB319;
bool &CLoadingScreen::m_bWantToPause = *(bool*)0xBAB31A;
bool &CLoadingScreen::m_bFading = *(bool*)0xBAB31C;
bool &CLoadingScreen::m_bLegalScreen = *(bool*)0xBAB31D;
bool &CLoadingScreen::m_bFadeInNextSplashFromBlack = *(bool*)0xBAB31E;
bool &CLoadingScreen::m_bFadeOutCurrSplashToBlack = *(bool*)0xBAB31F;
char &CLoadingScreen::m_FadeAlpha = *(char*)0xBAB320;
float &CLoadingScreen::m_StartFadeTime = *(float*)0xBAB324;
float &CLoadingScreen::m_ClockTimeOnPause = *(float*)0xBAB328;
float &CLoadingScreen::m_PauseTime = *(float*)0xBAB32C;
bool &CLoadingScreen::m_bReadyToDelete = *(bool*)0xBAB33D;
float &CLoadingScreen::m_timeSinceLastScreen = *(float*)0xBAB340;
CSprite2d *CLoadingScreen::m_aSplashes = (CSprite2d*)0xBAB35C; // CSprite2d CLoadingScreen::m_aSplashes[7]
// Converted from cdecl void CLoadingScreen::Shutdown(void) 0x58FF10
void CLoadingScreen::Shutdown() {
plugin::Call<0x58FF10>();
}
// Converted from cdecl void CLoadingScreen::RenderSplash(void) 0x58FF60
void CLoadingScreen::RenderSplash() {
plugin::Call<0x58FF60>();
}
// Converted from cdecl void CLoadingScreen::LoadSplashes(uchar bStarting,uchar bNvidia) 0x5900B0
void CLoadingScreen::LoadSplashes(unsigned char bStarting, unsigned char bNvidia) {
plugin::Call<0x5900B0, unsigned char, unsigned char>(bStarting, bNvidia);
}
// Converted from cdecl void CLoadingScreen::DisplayMessage(char const *message) 0x590220
void CLoadingScreen::DisplayMessage(char const* message) {
plugin::Call<0x590220, char const*>(message);
}
// Converted from cdecl void CLoadingScreen::SetLoadingBarMsg(char const *msg1,char const *msg2) 0x590240
void CLoadingScreen::SetLoadingBarMsg(char const* msg1, char const* msg2) {
plugin::Call<0x590240, char const*, char const*>(msg1, msg2);
}
// Converted from cdecl double CLoadingScreen::GetClockTime(bool bIgnorePauseTime) 0x590280
double CLoadingScreen::GetClockTime(bool bIgnorePauseTime) {
return plugin::CallAndReturn<double, 0x590280, bool>(bIgnorePauseTime);
}
// Converted from cdecl void CLoadingScreen::Init(bool unusedflag,bool bLoaded) 0x5902B0
void CLoadingScreen::Init(bool unusedflag, bool bLoaded) {
plugin::Call<0x5902B0, bool, bool>(unusedflag, bLoaded);
}
// Converted from cdecl void CLoadingScreen::Continue(void) 0x590320
void CLoadingScreen::Continue() {
plugin::Call<0x590320>();
}
// Converted from cdecl void CLoadingScreen::RenderLoadingBar(void) 0x590370
void CLoadingScreen::RenderLoadingBar() {
plugin::Call<0x590370>();
}
// Converted from cdecl void CLoadingScreen::DisplayNextSplash(void) 0x5904D0
void CLoadingScreen::DisplayNextSplash() {
plugin::Call<0x5904D0>();
}
// Converted from cdecl void CLoadingScreen::StartFading(void) 0x590530
void CLoadingScreen::StartFading() {
plugin::Call<0x590530>();
}
// Converted from cdecl void CLoadingScreen::DisplayPCScreen(void) 0x590570
void CLoadingScreen::DisplayPCScreen() {
plugin::Call<0x590570>();
}
// Converted from cdecl void CLoadingScreen::Update(void) 0x5905E0
void CLoadingScreen::Update() {
plugin::Call<0x5905E0>();
}
// Converted from cdecl void CLoadingScreen::DoPCTitleFadeOut(void) 0x590860
void CLoadingScreen::DoPCTitleFadeOut() {
plugin::Call<0x590860>();
}
// Converted from cdecl void CLoadingScreen::DoPCTitleFadeIn(void) 0x590990
void CLoadingScreen::DoPCTitleFadeIn() {
plugin::Call<0x590990>();
}
// Converted from cdecl void CLoadingScreen::DoPCScreenChange(uint bFinish) 0x590AC0
void CLoadingScreen::DoPCScreenChange(unsigned int bFinish) {
plugin::Call<0x590AC0, unsigned int>(bFinish);
}
// Converted from cdecl void CLoadingScreen::NewChunkLoaded(void) 0x590D00
void CLoadingScreen::NewChunkLoaded() {
plugin::Call<0x590D00>();
}
| 37.344538 | 107 | 0.764626 | MayconFelipeA |
3a9968e98377ed63aba1317272b2df7a8aae9437 | 2,105 | cpp | C++ | src/progress.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 94 | 2021-04-23T03:31:15.000Z | 2022-03-29T08:20:26.000Z | src/progress.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 64 | 2021-05-05T21:51:15.000Z | 2022-02-08T17:06:52.000Z | src/progress.cpp | GhostatSpirit/hdrview | 61596f8ba45554db23ae1b214354ab40da065638 | [
"MIT"
] | 3 | 2021-07-06T04:58:27.000Z | 2022-02-08T16:53:48.000Z | //
// Copyright (C) Wojciech Jarosz <wjarosz@gmail.com>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can
// be found in the LICENSE.txt file.
//
#include "progress.h"
#include <iostream>
AtomicProgress::AtomicProgress(bool createState, float totalPercentage) :
m_num_steps(1), m_percentage_of_parent(totalPercentage),
m_step_percent(m_num_steps == 0 ? totalPercentage : totalPercentage / m_num_steps),
m_state(createState ? std::make_shared<State>() : nullptr)
{
}
//
// AtomicProgress::AtomicProgress(AtomicPercent32 * state, float totalPercentage) :
// m_num_steps(1),
// m_percentage_of_parent(totalPercentagße),
// m_step_percent(m_num_steps == 0 ? totalPercentage : totalPercentage / m_num_steps),
// m_state(state), m_isStateOwner(false)
//{
//
//}
AtomicProgress::AtomicProgress(const AtomicProgress &parent, float percentageOfParent) :
m_num_steps(1), m_percentage_of_parent(parent.m_percentage_of_parent * percentageOfParent),
m_step_percent(m_num_steps == 0 ? m_percentage_of_parent : m_percentage_of_parent / m_num_steps),
m_state(parent.m_state)
{
}
void AtomicProgress::reset_progress(float p)
{
if (!m_state)
return;
m_state->progress = p;
}
float AtomicProgress::progress() const { return m_state ? float(m_state->progress) : -1.f; }
void AtomicProgress::set_available_percent(float available_percent)
{
m_percentage_of_parent = available_percent;
m_step_percent = m_num_steps == 0 ? available_percent : available_percent / m_num_steps;
}
void AtomicProgress::set_num_steps(int num_steps)
{
m_num_steps = num_steps;
m_step_percent = m_num_steps == 0 ? m_percentage_of_parent : m_percentage_of_parent / m_num_steps;
}
AtomicProgress &AtomicProgress::operator+=(int steps)
{
if (!m_state)
return *this;
m_state->progress += steps * m_step_percent;
return *this;
}
bool AtomicProgress::canceled() const { return m_state ? m_state->canceled : false; }
void AtomicProgress::cancel()
{
if (!m_state)
return;
m_state->canceled = true;
} | 28.835616 | 102 | 0.733017 | GhostatSpirit |
3a9d77468facd95e0c2e361bb9162b0f8aa37ac6 | 4,192 | cpp | C++ | avogadro/rendering/cartoongeometry.cpp | serk12/avogadrolibs | f2dd0fda7e0d2ca4a0586354ea253cc05242f022 | [
"BSD-3-Clause"
] | 244 | 2015-09-09T15:08:54.000Z | 2022-03-30T17:44:21.000Z | avogadro/rendering/cartoongeometry.cpp | serk12/avogadrolibs | f2dd0fda7e0d2ca4a0586354ea253cc05242f022 | [
"BSD-3-Clause"
] | 670 | 2015-05-08T18:59:38.000Z | 2022-03-29T19:47:08.000Z | avogadro/rendering/cartoongeometry.cpp | serk12/avogadrolibs | f2dd0fda7e0d2ca4a0586354ea253cc05242f022 | [
"BSD-3-Clause"
] | 129 | 2015-01-28T01:18:36.000Z | 2022-03-17T08:50:25.000Z | /******************************************************************************
This source file is part of the Avogadro project.
This source code is released under the 3-Clause BSD License, (see "LICENSE").
******************************************************************************/
#include "cartoongeometry.h"
#include <cmath>
namespace Avogadro {
namespace Rendering {
using Core::Residue;
using std::make_pair;
using std::vector;
const float Cartoon::ELIPSE_RATIO = 0.75f;
Cartoon::Cartoon()
: BSplineGeometry(false), m_minRadius(-1.0f), m_maxRadius(-1.0f)
{}
Cartoon::Cartoon(float minRadius, float maxRadius)
: BSplineGeometry(false), m_minRadius(minRadius), m_maxRadius(maxRadius)
{}
vector<ColorNormalVertex> Cartoon::computeCirclePoints(const Eigen::Affine3f& a,
const Eigen::Affine3f& b,
bool flat) const
{
unsigned int circleResolution = flat ? 2 : 20;
const float resolutionRadians =
2.0f * static_cast<float>(M_PI) / static_cast<float>(circleResolution);
vector<ColorNormalVertex> result;
float elipseA = flat ? 0.999f : ELIPSE_RATIO;
float elipseB = 1.0f - elipseA;
float e = std::sqrt(1.0f - ((elipseB * elipseB) / (elipseA * elipseA)));
float c = elipseA * e;
for (unsigned int i = 0; i < circleResolution; ++i) {
float theta = resolutionRadians * i;
float r = (elipseA * (1.0f - (e * e))) / (1.0f + e * std::cos(theta));
Vector3f elipse =
Vector3f(r * std::sin(theta), 0.0f, c + r * std::cos(theta));
ColorNormalVertex vert1;
vert1.normal = a.linear() * elipse;
vert1.vertex = a * elipse;
result.push_back(vert1);
ColorNormalVertex vert2;
vert2.normal = b.linear() * elipse;
vert2.vertex = b * elipse;
result.push_back(vert2);
}
return result;
}
float arrowFunction(float t)
{
float result;
const float maxPoint = 0.7f;
if (t < maxPoint) {
// normalize t using max point and scale it so that adding will be between
// [minimunRadius, 1]
result = t / maxPoint;
} else {
// starting with 1 and go decreassing
t = (t - maxPoint) / (1.0f - maxPoint);
result = 1.0f - t;
result = result < 0.3 ? 0.3 : result;
}
return result;
}
float Cartoon::computeScale(size_t index, float p, float radius) const
{
if (index > m_type.size())
return radius;
float t = (m_type[index].second + p) / 0.80f;
t = t > 1.0f ? 1.0f : t;
switch (m_type[index].first) {
default:
case Undefined:
return radius;
case Body:
return m_minRadius;
case Arrow:
if (m_type[index].second == 0) {
return (arrowFunction(1.0f - t) * m_maxRadius) + m_minRadius;
} else {
return 0.3 * m_maxRadius + m_minRadius;
}
case Head:
return ((1.0f - t) * (m_maxRadius - m_minRadius)) + (1.0f * m_minRadius);
case Tail:
return (t * (m_maxRadius - m_minRadius)) + (1.0f * m_minRadius);
}
}
CartoonType secondaryToCartoonType(Residue::SecondaryStructure sec)
{
switch (sec) {
case Residue::SecondaryStructure::betaSheet:
return Arrow;
case Residue::SecondaryStructure::alphaHelix:
return Tail;
default:
return Body;
}
}
void Cartoon::addPoint(const Vector3f& pos, const Vector3ub& color,
size_t group, size_t id, Residue::SecondaryStructure sec)
{
CartoonType ct = secondaryToCartoonType(sec);
size_t idCartoon = 0;
if (m_type.size() > 0) {
idCartoon = ct == m_type.back().first && m_type.size() > (SKIPPED + 1)
? m_type.back().second + 1
: 0;
if (Tail == m_type.back().first && ct == Body) {
for (size_t i = m_type.size(), j = 0;
i > 0 && j < std::ceil(m_type.back().second / 2.0f); --i, ++j) {
m_type[i - 1].first = Head;
m_type[i - 1].second = j;
}
}
if (ct == Arrow && m_type.back().first == Arrow) {
m_type.back().second = 1;
idCartoon = 0;
}
}
m_type.push_back(make_pair(ct, idCartoon));
BSplineGeometry::addPoint(pos, color, m_minRadius, group, id);
}
} // namespace Rendering
} // namespace Avogadro
| 30.158273 | 80 | 0.588025 | serk12 |
3aa24ae95ff01a62b413d389b29fbfef381cd7bf | 352 | hpp | C++ | Shared/Support/NonCopyable.hpp | bradhowes/SimplyPhaser | ca2fdd26f48dc6fb0a627e05955c81b23a9fe386 | [
"MIT"
] | 1 | 2021-07-30T17:08:04.000Z | 2021-07-30T17:08:04.000Z | Shared/Support/NonCopyable.hpp | bradhowes/SimplyPhaser | ca2fdd26f48dc6fb0a627e05955c81b23a9fe386 | [
"MIT"
] | null | null | null | Shared/Support/NonCopyable.hpp | bradhowes/SimplyPhaser | ca2fdd26f48dc6fb0a627e05955c81b23a9fe386 | [
"MIT"
] | 1 | 2022-02-24T23:19:54.000Z | 2022-02-24T23:19:54.000Z | // Copyright © 2021 Brad Howes. All rights reserved.
#pragma once
/**
Simple class for prohibiting derived classes from being copied.
*/
class NonCopyable
{
protected:
constexpr NonCopyable() = default;
~NonCopyable() = default;
private:
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator =(const NonCopyable&) = delete;
};
| 19.555556 | 64 | 0.721591 | bradhowes |
3aa2649eece3b21afbe532afc2dc88360c6c848c | 1,915 | cpp | C++ | PETCS/Intermediate/ccc03s5.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | PETCS/Intermediate/ccc03s5.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | PETCS/Intermediate/ccc03s5.cpp | dl4us/Competitive-Programming-1 | d42fab3bd68168adbe4b5f594f19ee5dfcd1389b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int MAX = 1e4 + 5;
struct Edge {
int a, b, w;
};
int C, R, D, ans = 0x3f3f3f3f, par[MAX], dist[MAX];
vector<pair<int, int>> adj[MAX]; vector<Edge> edges;
bool cmp(Edge a, Edge b) {
return a.w > b.w;
}
int Find(int x) {
if(par[x] == x) {
return x;
}
return par[x] = Find(par[x]);
}
void Union(int x, int y) {
int p = Find(x);
int q = Find(y);
par[p] = par[q];
}
void dfs(int src, int p) {
for(auto &child : adj[src]) {
if(child.second == p) {
continue;
}
dist[child.second] = min(dist[src], child.first);
cout << child.second << " ";
for(int i = 1; i < 10; i++) {
cout << dist[i] << " ";
}
cout << "\n";
dfs(child.second, src);
}
}
int main() {
cin.tie(0)->sync_with_stdio(0);
#ifndef ONLINE_JUDGE
freopen("../../input.txt", "r", stdin);
freopen("../../output.txt", "w", stdout);
#endif
cin >> C >> R >> D;
dist[1] = 0x3f3f3f3f;
for(int i = 0, x, y, w; i < R; i++) {
cin >> x >> y >> w;
edges.push_back({x, y, w});
}
sort(edges.begin(), edges.end(), cmp);
for(int i = 1; i <= C; i++) {
par[i] = i;
}
for(auto &x : edges) {
cout << x.a << " " << x.b << " " << x.w << "\n";
}
for(auto &edge : edges) {
if(Find(edge.a) != Find(edge.b)) {
cout << edge.a << " " << edge.b << " " << Find(edge.a) << " " << Find(edge.b) << "\n";
Union(edge.a, edge.b);
adj[edge.a].push_back({edge.w, edge.b});
adj[edge.b].push_back({edge.w, edge.a});
}
}
for(int i = 0; i < C; i++) {
cout << par[i] << " ";
}
cout << "\n";
dfs(1, 1);
for(int i = 0, d; i < D; i++) {
cin >> d;
ans = min(ans, dist[d]);
}
cout << ans << "\n";
return 0;
}
| 25.197368 | 98 | 0.432376 | dl4us |
3aa7054058e82e8f7a51b20a6fbf290cf3fc5c25 | 10,348 | cpp | C++ | openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateAirLoopHVACOutdoorAirSystem.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | 1 | 2017-10-13T09:23:04.000Z | 2017-10-13T09:23:04.000Z | openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateAirLoopHVACOutdoorAirSystem.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | null | null | null | openstudiocore/src/energyplus/ForwardTranslator/ForwardTranslateAirLoopHVACOutdoorAirSystem.cpp | OpenStudioThailand/OpenStudio | 4e2173955e687ef1b934904acc10939ac0bed52f | [
"MIT"
] | 1 | 2022-03-20T13:19:42.000Z | 2022-03-20T13:19:42.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. 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 any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* 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, THE UNITED STATES GOVERNMENT, OR ANY 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 "../ForwardTranslator.hpp"
#include "../../model/AirToAirComponent.hpp"
#include "../../model/AirToAirComponent_Impl.hpp"
#include "../../model/AirLoopHVACOutdoorAirSystem.hpp"
#include "../../model/AirLoopHVACOutdoorAirSystem_Impl.hpp"
#include "../../model/ControllerOutdoorAir.hpp"
#include "../../model/ControllerOutdoorAir_Impl.hpp"
#include "../../model/ControllerWaterCoil.hpp"
#include "../../model/ControllerWaterCoil_Impl.hpp"
#include "../../model/CoilCoolingWater.hpp"
#include "../../model/CoilCoolingWater_Impl.hpp"
#include "../../model/CoilHeatingWater.hpp"
#include "../../model/CoilHeatingWater_Impl.hpp"
#include "../../model/Node.hpp"
#include "../../model/Node_Impl.hpp"
#include "../../model/Schedule.hpp"
#include "../../model/Schedule_Impl.hpp"
#include "../../utilities/idf/IdfExtensibleGroup.hpp"
#include <utilities/idd/AirLoopHVAC_ControllerList_FieldEnums.hxx>
#include <utilities/idd/AirLoopHVAC_OutdoorAirSystem_FieldEnums.hxx>
#include <utilities/idd/AirLoopHVAC_SupplyPath_FieldEnums.hxx>
#include <utilities/idd/AvailabilityManagerAssignmentList_FieldEnums.hxx>
#include <utilities/idd/AvailabilityManager_Scheduled_FieldEnums.hxx>
#include <utilities/idd/Controller_OutdoorAir_FieldEnums.hxx>
#include <utilities/idd/OutdoorAir_Mixer_FieldEnums.hxx>
#include "../../utilities/idd/IddEnums.hpp"
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/IddFactory.hxx>
#include "../../utilities/core/Assert.hpp"
using namespace openstudio::model;
namespace openstudio {
namespace energyplus {
boost::optional<IdfObject> ForwardTranslator::translateAirLoopHVACOutdoorAirSystem( AirLoopHVACOutdoorAirSystem & modelObject )
{
OptionalString s;
IdfObject idfObject(IddObjectType::AirLoopHVAC_OutdoorAirSystem);
m_idfObjects.push_back(idfObject);
// Name
std::string name = modelObject.name().get();
idfObject.setString(openstudio::AirLoopHVAC_OutdoorAirSystemFields::Name,name);
// Controller List
IdfObject _controllerList(IddObjectType::AirLoopHVAC_ControllerList);
_controllerList.setName(name + " Controller List");
_controllerList.clearExtensibleGroups();
m_idfObjects.push_back(_controllerList);
ControllerOutdoorAir controllerOutdoorAir = modelObject.getControllerOutdoorAir();
boost::optional<IdfObject> _controllerOutdoorAir = translateAndMapModelObject(controllerOutdoorAir);
OS_ASSERT(_controllerOutdoorAir);
idfObject.setString(openstudio::AirLoopHVAC_OutdoorAirSystemFields::ControllerListName,_controllerList.name().get());
IdfExtensibleGroup eg = _controllerList.pushExtensibleGroup();
eg.setString(AirLoopHVAC_ControllerListExtensibleFields::ControllerObjectType,_controllerOutdoorAir->iddObject().name());
eg.setString(AirLoopHVAC_ControllerListExtensibleFields::ControllerName,_controllerOutdoorAir->name().get());
std::vector<ModelObject> controllers;
auto components = modelObject.components();
for( const auto & component : components ) {
boost::optional<ControllerWaterCoil> controller;
if( auto coil = component.optionalCast<CoilCoolingWater>() ) {
controller = coil->controllerWaterCoil();
} else if ( auto coil = component.optionalCast<CoilHeatingWater>() ) {
controller = coil->controllerWaterCoil();
}
if( controller ) {
controllers.push_back(controller.get());
}
}
for( auto & controller: controllers ) {
auto _controller = translateAndMapModelObject(controller);
if( _controller ) {
IdfExtensibleGroup eg = _controllerList.pushExtensibleGroup();
eg.setString(AirLoopHVAC_ControllerListExtensibleFields::ControllerObjectType,_controller->iddObject().name());
eg.setString(AirLoopHVAC_ControllerListExtensibleFields::ControllerName,_controller->name().get());
}
}
// Field: Availability Manager List Name //////////////////////////////////
IdfObject availabilityManagerListIdf(IddObjectType::AvailabilityManagerAssignmentList);
availabilityManagerListIdf.setName(name + " Availability Manager List");
m_idfObjects.push_back(availabilityManagerListIdf);
IdfObject availabilityManagerScheduledIdf = IdfObject(openstudio::IddObjectType::AvailabilityManager_Scheduled);
availabilityManagerScheduledIdf.setName(name + " Availability Manager");
m_idfObjects.push_back(availabilityManagerScheduledIdf);
Schedule alwaysOn = modelObject.model().alwaysOnDiscreteSchedule();
IdfObject alwaysOnIdf = translateAndMapModelObject(alwaysOn).get();
s = availabilityManagerListIdf.getString(openstudio::AvailabilityManagerAssignmentListFields::Name);
if(s)
{
idfObject.setString(openstudio::AirLoopHVAC_OutdoorAirSystemFields::AvailabilityManagerListName,*s);
}
availabilityManagerListIdf.setString(1 + openstudio::AvailabilityManagerAssignmentListExtensibleFields::AvailabilityManagerObjectType,
availabilityManagerScheduledIdf.iddObject().name());
availabilityManagerListIdf.setString(1 + openstudio::AvailabilityManagerAssignmentListExtensibleFields::AvailabilityManagerName,
availabilityManagerScheduledIdf.name().get());
availabilityManagerScheduledIdf.setString(openstudio::AvailabilityManager_ScheduledFields::ScheduleName,alwaysOnIdf.name().get());
// OA Node List
s = modelObject.outboardOANode()->name();
IdfObject oaNodeListIdf(openstudio::IddObjectType::OutdoorAir_NodeList);
if(s)
{
oaNodeListIdf.setString(0,*s);
}
m_idfObjects.push_back(oaNodeListIdf);
///////////////////////////////////////////////////////////////////////////
// Field: Outdoor Air Equipment List Name /////////////////////////////////
IdfObject equipmentListIdf(IddObjectType::AirLoopHVAC_OutdoorAirSystem_EquipmentList);
equipmentListIdf.setName(name + " Equipment List");
m_idfObjects.push_back(equipmentListIdf);
IdfObject outdoorAirMixerIdf(IddObjectType::OutdoorAir_Mixer);
outdoorAirMixerIdf.setName(name + " Outdoor Air Mixer");
m_idfObjects.push_back(outdoorAirMixerIdf);
s = modelObject.mixedAirModelObject()->name();
if(s)
{
outdoorAirMixerIdf.setString(OutdoorAir_MixerFields::MixedAirNodeName,*s);
}
s = modelObject.outdoorAirModelObject()->name();
if(s)
{
outdoorAirMixerIdf.setString(OutdoorAir_MixerFields::OutdoorAirStreamNodeName,*s);
}
s = modelObject.reliefAirModelObject()->name();
if(s)
{
outdoorAirMixerIdf.setString(OutdoorAir_MixerFields::ReliefAirStreamNodeName,*s);
}
s = modelObject.returnAirModelObject()->name();
if(s)
{
outdoorAirMixerIdf.setString(OutdoorAir_MixerFields::ReturnAirStreamNodeName,*s);
}
unsigned i = 1;
ModelObjectVector oaModelObjects = modelObject.oaComponents();
for( auto oaIt = oaModelObjects.begin();
oaIt != oaModelObjects.end();
++oaIt )
{
if( boost::optional<IdfObject> idfObject = translateAndMapModelObject(*oaIt) )
{
equipmentListIdf.setString(i,idfObject->iddObject().name());
i++;
equipmentListIdf.setString(i,idfObject->name().get());
i++;
}
}
ModelObjectVector reliefModelObjects = modelObject.reliefComponents();
for( auto reliefIt = reliefModelObjects.begin();
reliefIt != reliefModelObjects.end();
++reliefIt )
{
// Make sure this is not an AirToAirComponent,
// because those will be added to the equipment list
// from the oaComponents() side.
if( ! reliefIt->optionalCast<AirToAirComponent>() ) {
if( boost::optional<IdfObject> idfObject = translateAndMapModelObject(*reliefIt) )
{
equipmentListIdf.setString(i,idfObject->iddObject().name());
i++;
equipmentListIdf.setString(i,idfObject->name().get());
i++;
}
}
}
s = outdoorAirMixerIdf.iddObject().name();
equipmentListIdf.setString(i,*s);
++i;
s = outdoorAirMixerIdf.name();
equipmentListIdf.setString(i,*s);
s = equipmentListIdf.name();
if(s)
{
idfObject.setString(openstudio::AirLoopHVAC_OutdoorAirSystemFields::OutdoorAirEquipmentListName,*s);
}
return boost::optional<IdfObject>(idfObject);
}
} // energyplus
} // openstudio
| 42.937759 | 136 | 0.730769 | OpenStudioThailand |
3aa77e58a324d200e3ba41f8aaf7f90bae4bcfba | 1,497 | cpp | C++ | Practice/2018/2018.1.19/SNM227.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.1.19/SNM227.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.1.19/SNM227.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=100010;
const int maxM=maxN*4;
const int inf=2147483647;
int n,m;
int S1[maxN],S2[maxN];
int edgecnt=-1,Head[maxN],Next[maxM],V[maxM];
int dfncnt=0,dfn[maxN],low[maxN],Fa[maxN];
int Find(int *F,int x);
void Add_Edge(int u,int v);
void Tarjan(int u,int edge);
int main()
{
mem(Head,-1);
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) S1[i]=S2[i]=i;
for (int i=1;i<=m;i++)
{
int u,v;scanf("%d%d",&u,&v);
if (Find(S1,u)!=Find(S1,v))
{
Add_Edge(u,v);S1[Find(S1,u)]=Find(S1,v);
}
else if (Find(S2,u)!=Find(S2,v))
{
Add_Edge(u,v);S2[Find(S2,u)]=Find(S2,v);
}
}
for (int i=1;i<=n;i++) if (dfn[i]==0) Tarjan(i,edgecnt+10),Fa[i]=i;
for (int i=1;i<=n;i++) if ((dfn[i]==low[i])&&(i!=Fa[i])) printf("%d %d\n",i,Fa[i]);
return 0;
}
int Find(int *F,int x)
{
if (F[x]!=x) F[x]=Find(F,F[x]);
return F[x];
}
void Add_Edge(int u,int v)
{
edgecnt++;Next[edgecnt]=Head[u];Head[u]=edgecnt;V[edgecnt]=v;
edgecnt++;Next[edgecnt]=Head[v];Head[v]=edgecnt;V[edgecnt]=u;
return;
}
void Tarjan(int u,int edge)
{
dfn[u]=low[u]=++dfncnt;
for (int i=Head[u];i!=-1;i=Next[i])
if (i!=(edge^1))
{
if (dfn[V[i]]==0)
{
Fa[V[i]]=u;
Tarjan(V[i],i);
low[u]=min(low[u],low[V[i]]);
}
else low[u]=min(low[u],dfn[V[i]]);
}
return;
}
| 19.96 | 86 | 0.565798 | SYCstudio |
3aaa007490ecfdf79022365d626a57bd3a2b4ebf | 1,011 | hpp | C++ | include/nanikanizer/dropout_layer.hpp | planaria/nanikanizer | b1da7a434c04f78c01538572c39db373c73bfe9d | [
"BSD-3-Clause"
] | 12 | 2016-01-22T14:27:39.000Z | 2022-01-20T12:05:51.000Z | include/nanikanizer/dropout_layer.hpp | planaria/nanikanizer | b1da7a434c04f78c01538572c39db373c73bfe9d | [
"BSD-3-Clause"
] | null | null | null | include/nanikanizer/dropout_layer.hpp | planaria/nanikanizer | b1da7a434c04f78c01538572c39db373c73bfe9d | [
"BSD-3-Clause"
] | 3 | 2016-08-29T07:14:11.000Z | 2020-01-29T08:43:33.000Z | #pragma once
#include "layer_base.hpp"
namespace nnk
{
template <class T>
class dropout_layer : public layer_base
{
public:
typedef T scalar_type;
typedef std::valarray<scalar_type> tensor_type;
explicit dropout_layer(scalar_type ratio = 0.5)
: ratio_(ratio)
{
}
virtual void save(binary_writer& writer) const override
{
writer.write(ratio_);
writer.write(*train_);
}
virtual void load(binary_reader& reader) override
{
reader.read(ratio_);
reader.read(*train_);
}
virtual void enumerate_parameters(optimizer_base& /*optimizer*/) override
{
}
double ratio() const
{
return ratio_;
}
double& ratio()
{
return ratio_;
}
bool train() const
{
return *train_;
}
bool& train()
{
return *train_;
}
expression<scalar_type> forward(const expression<scalar_type>& v) const
{
return dropout(v, ratio_, train_);
}
private:
scalar_type ratio_;
std::shared_ptr<bool> train_ = std::make_shared<bool>(true);
};
}
| 14.652174 | 75 | 0.667656 | planaria |
3aaa3ca7f69686b1d86dadb07a0e1f88ebc88ca2 | 850 | cpp | C++ | init/init_turtle_test.cpp | btwooton/logo | fb55611a7e42606da7fe0fdc4a501741e1d29552 | [
"MIT"
] | 2 | 2019-04-09T03:50:37.000Z | 2019-11-17T12:37:44.000Z | init/init_turtle_test.cpp | btwooton/logo | fb55611a7e42606da7fe0fdc4a501741e1d29552 | [
"MIT"
] | 1 | 2019-04-23T21:54:36.000Z | 2019-04-23T21:54:36.000Z | init/init_turtle_test.cpp | btwooton/logo | fb55611a7e42606da7fe0fdc4a501741e1d29552 | [
"MIT"
] | 1 | 2019-04-09T03:54:20.000Z | 2019-04-09T03:54:20.000Z | #include <cassert>
#include <cstdio>
#include "init_turtle.hpp"
#define ASSERT(condition) if(!(condition)) { \
printf("Assertion failed at line %d in file %s\n", __LINE__, __FILE__); \
assert(false); }
#define SUCCESS() printf("Test %s has passed\n", __func__);
void test_init_turtle() {
// Given: You have declared the following inital values
float x = 500;
float y = 500;
float a = 180;
bool pd = true;
// When: You call init_turtle, passing in these values
init_turtle(x, y, a, pd);
// Then: The __turtle__ reference should hold the appropriate values
ASSERT(__turtle__.get_x() == 500);
ASSERT(__turtle__.get_y() == 500);
ASSERT(__turtle__.get_heading() == 180);
ASSERT(__turtle__.isdown());
SUCCESS();
}
int main(int argc, char *argv[]) {
test_init_turtle();
return 0;
}
| 25 | 77 | 0.649412 | btwooton |
3aafa4d006d074f4d1c11e117031b7b1405ad662 | 1,395 | cpp | C++ | examples/SendDataInChunks.cpp | UlloLabs/liblsl | a74e5288a797309f155abbbbc8e3f60e178496e6 | [
"MIT"
] | 2 | 2021-11-19T00:57:20.000Z | 2021-12-13T23:24:51.000Z | examples/SendDataInChunks.cpp | staticfloat/liblsl | ccdc76f80622690768707035436c8d833bb3dfd2 | [
"MIT"
] | null | null | null | examples/SendDataInChunks.cpp | staticfloat/liblsl | ccdc76f80622690768707035436c8d833bb3dfd2 | [
"MIT"
] | 1 | 2021-12-19T23:31:13.000Z | 2021-12-19T23:31:13.000Z | #include <cmath>
#include <iostream>
#include <lsl_cpp.h>
#include <thread>
// define a packed sample struct (here: a 16 bit stereo sample).
#pragma pack(1)
struct stereo_sample {
int16_t l, r;
};
int main(int argc, char **argv) {
std::string name{argc > 1 ? argv[1] : "MyAudioStream"}, type{argc > 2 ? argv[2] : "Audio"};
int samplingrate = argc > 3 ? std::stol(argv[3]) : 44100;
try {
// make a new stream_info (44.1Khz, 16bit, audio, 2 channels) and open an outlet with it
lsl::stream_info info(name, type, 2, samplingrate, lsl::cf_int16);
lsl::stream_outlet outlet(info);
std::cout << "Now sending data..." << std::endl;
auto nextsample = std::chrono::high_resolution_clock::now();
std::vector<stereo_sample> mychunk(info.nominal_srate() / 10);
int phase = 0;
for (unsigned c = 0;; c++) {
// wait a bit and generate a chunk of random data
nextsample += std::chrono::milliseconds(100);
std::this_thread::sleep_until(nextsample);
for (stereo_sample &sample : mychunk) {
sample.l = static_cast<int16_t>(100 * sin(phase / 200.));
sample.r = static_cast<int16_t>(120 * sin(phase / 400.));
phase++;
}
// send it
outlet.push_chunk_numeric_structs(mychunk);
}
} catch (std::exception& e) { std::cerr << "Got an exception: " << e.what() << std::endl; }
std::cout << "Press any key to exit. " << std::endl;
std::cin.get();
return 0;
}
| 31 | 92 | 0.649462 | UlloLabs |
3ab03d1a155f1d68a1484744f99ce8d8f51822b2 | 1,082 | cpp | C++ | src/medGui/toolboxes/medBrowserJobsToolBox.cpp | papadop/medInria-public | fd8bec14c97bb95bf4d58a60741ef3b7c159f757 | [
"BSD-4-Clause"
] | null | null | null | src/medGui/toolboxes/medBrowserJobsToolBox.cpp | papadop/medInria-public | fd8bec14c97bb95bf4d58a60741ef3b7c159f757 | [
"BSD-4-Clause"
] | null | null | null | src/medGui/toolboxes/medBrowserJobsToolBox.cpp | papadop/medInria-public | fd8bec14c97bb95bf4d58a60741ef3b7c159f757 | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include <medBrowserJobsToolBox.h>
#include <medProgressionStack.h>
#include <QtGui>
class medBrowserJobsToolBoxPrivate
{
public:
medProgressionStack *stack;
};
medBrowserJobsToolBox::medBrowserJobsToolBox(QWidget *parent) : medToolBox(parent), d(new medBrowserJobsToolBoxPrivate)
{
d->stack = new medProgressionStack(this);
connect(d->stack, SIGNAL(shown()), this, SLOT(show()));
connect(d->stack, SIGNAL(hidden()), this, SLOT(hide()));
this->setTitle("Jobs");
this->addWidget(d->stack);
}
medBrowserJobsToolBox::~medBrowserJobsToolBox(void)
{
delete d;
d = NULL;
}
medProgressionStack *medBrowserJobsToolBox::stack(void)
{
return d->stack;
}
| 22.541667 | 119 | 0.627542 | papadop |
3ab28d4c7bccd18706f32fcc8b23d32a318a242e | 3,523 | cpp | C++ | Evo/EvolutionCore/individual.cpp | pk1954/Solutions | b224522283f82cb7d73b8005e35e0c045edc2fc0 | [
"MIT"
] | null | null | null | Evo/EvolutionCore/individual.cpp | pk1954/Solutions | b224522283f82cb7d73b8005e35e0c045edc2fc0 | [
"MIT"
] | null | null | null | Evo/EvolutionCore/individual.cpp | pk1954/Solutions | b224522283f82cb7d73b8005e35e0c045edc2fc0 | [
"MIT"
] | null | null | null | // individual.cpp :
//
#include "stdafx.h"
#include "assert.h"
#include "debug.h"
#include "random.h"
#include "config.h"
#include "strategy.h"
#include "individual.h"
static DefectAlways StratD;
static CooperateAlways StratC;
static Tit4Tat StratT;
static EmptyStrategy StratNull;
ENERGY_UNITS Individual::m_stdEnergyCapacity;
ENERGY_UNITS Individual::m_initialEnergy;
const std::array< Strategy * const, Strategy::COUNT > Individual::m_apStrat =
{
&StratD, // Strategy::Id::defect,
&StratC, // Strategy::Id::cooperate,
&StratT // Strategy::Id::tit4tat,
};
void Individual::RefreshCache( )
{
m_stdEnergyCapacity = ENERGY_UNITS(Config::GetConfigValueShort( Config::tId::stdCapacity ));
m_initialEnergy = ENERGY_UNITS(Config::GetConfigValueShort( Config::tId::initialEnergy ));
}
Individual::Individual( )
{
ResetIndividual( );
}
void Individual::ResetIndividual( )
{
m_id.Set2Null( );
m_genBirth.Set2Null();
m_origin = tOrigin::undefined;
m_enStock = 0_ENERGY_UNITS;
m_enCapacity = 0_ENERGY_UNITS;
m_strategyId = Strategy::Id::empty;
m_stratData.SetMemorySize( 0 );
m_genome.InitGenome( );
};
void Individual::Create
(
IND_ID const id,
EVO_GENERATION const genBirth,
Strategy::Id const strategyId
)
{
m_genome.InitGenome( );
m_id = id;
m_genBirth = genBirth;
m_origin = tOrigin::editor;
m_enCapacity = m_stdEnergyCapacity;
m_strategyId = strategyId;
m_stratData.SetMemorySize( m_genome.GetAllele(GeneType::Id::memSize) ); // clears memory. Experience not inheritable.
SetEnergy( m_initialEnergy ); // makes IsAlive() true. Last assignment to avoid race conditions
}
// Clone - creates a mutated clone of this individual
// all member variables of new individual are initialized after this function
void Individual::Clone
(
IND_ID const id,
EVO_GENERATION const genBirth,
PERCENT const mutationRate,
Random & random,
Individual const & indParent
)
{
m_id = id;
m_genBirth = genBirth;
m_origin = tOrigin::cloning;
m_enCapacity = indParent.m_enCapacity;
m_strategyId = indParent.m_strategyId;
m_genome.Mutate( mutationRate, random );
m_stratData.SetMemorySize( m_genome.GetAllele(GeneType::Id::memSize) ); // clears memory. Experience not inheritable.
}
static Individual const & selectParent
(
Random & random,
Individual const & indParA,
Individual const & indParB
)
{
return random.NextBooleanValue( ) ? indParA : indParB;
}
// Breed - creates a child with a mix of genes of both parents
// all member variables of new individual are initialized after this function
void Individual::Breed
(
IND_ID const id,
EVO_GENERATION const genBirth,
PERCENT const mutationRate,
Random & random,
Individual const & indParentA,
Individual const & indParentB
)
{
m_id = id;
m_genBirth = genBirth;
m_origin = tOrigin::marriage;
m_enCapacity = selectParent( random, indParentA, indParentB ).m_enCapacity;
m_strategyId = selectParent( random, indParentA, indParentB ).m_strategyId;
m_genome.Recombine( indParentA.m_genome, indParentB.m_genome, random );
m_genome.Mutate( mutationRate, random );
m_stratData.SetMemorySize( m_genome.GetAllele(GeneType::Id::memSize) ); // clears memory. Experience not inheritable.
}
| 29.358333 | 122 | 0.683225 | pk1954 |
3ab2f5bb46c6e7ea5535f69b65798f4158478c40 | 6,069 | cc | C++ | windows/agora_rtc_channel_plugin.cc | outlier-collective/Agora-Flutter-SDK | 1b44bcdb534a8acac94daaf1347608b515c9a962 | [
"MIT"
] | 364 | 2019-02-11T11:57:58.000Z | 2020-12-19T08:40:51.000Z | windows/agora_rtc_channel_plugin.cc | outlier-collective/Agora-Flutter-SDK | 1b44bcdb534a8acac94daaf1347608b515c9a962 | [
"MIT"
] | 186 | 2019-02-22T08:20:55.000Z | 2020-12-18T11:39:02.000Z | windows/agora_rtc_channel_plugin.cc | outlier-collective/Agora-Flutter-SDK | 1b44bcdb534a8acac94daaf1347608b515c9a962 | [
"MIT"
] | 101 | 2019-02-12T05:08:34.000Z | 2020-12-16T19:05:53.000Z | #include "include/agora_rtc_engine/agora_rtc_channel_plugin.h"
#include "include/agora_rtc_engine/call_api_method_call_handler.h"
// This must be included before many other Windows headers.
#include <windows.h>
#include <flutter/event_channel.h>
#include <flutter/event_stream_handler_functions.h>
#include <flutter/method_channel.h>
#include <flutter/plugin_registrar_windows.h>
#include <flutter/standard_method_codec.h>
namespace
{
using namespace flutter;
using namespace agora::iris;
using namespace agora::iris::rtc;
class RtcChannelCallApiMethodCallHandler : public CallApiMethodCallHandler
{
public:
RtcChannelCallApiMethodCallHandler(agora::iris::rtc::IrisRtcEngine *engine);
int32_t CallApi(int32_t api_type, const char *params, char *result) override;
int32_t CallApi(int32_t api_type,
const char *params,
void *buffer,
char *result) override;
};
RtcChannelCallApiMethodCallHandler::RtcChannelCallApiMethodCallHandler(
agora::iris::rtc::IrisRtcEngine *engine) : CallApiMethodCallHandler(engine) {}
int32_t RtcChannelCallApiMethodCallHandler::CallApi(int32_t api_type, const char *params,
char *result)
{
return irisRtcEngine_->channel()->CallApi(
static_cast<ApiTypeChannel>(api_type), params, result);
}
int32_t RtcChannelCallApiMethodCallHandler::CallApi(int32_t api_type,
const char *params,
void *buffer,
char *result)
{
return irisRtcEngine_->channel()->CallApi(static_cast<ApiTypeChannel>(api_type),
params, buffer, result);
}
class AgoraRtcChannelPlugin : public Plugin, public IrisEventHandler
{
public:
static void RegisterWithRegistrar(PluginRegistrarWindows *registrar,
IrisRtcEngine *engine);
AgoraRtcChannelPlugin(PluginRegistrar *registrar, IrisRtcEngine *engine);
virtual ~AgoraRtcChannelPlugin();
public:
virtual void OnEvent(const char *event, const char *data) override;
virtual void OnEvent(const char *event, const char *data, const void *buffer,
unsigned int length) override;
private:
// Called when a method is called on this plugin's channel from Dart.
void HandleMethodCall(const MethodCall<EncodableValue> &method_call,
std::unique_ptr<MethodResult<EncodableValue>> result);
private:
std::unique_ptr<EventSink<EncodableValue>> event_sink_;
std::unique_ptr<CallApiMethodCallHandler> callApiMethodCallHandler_;
IrisRtcEngine *engine_;
};
// static
void AgoraRtcChannelPlugin::RegisterWithRegistrar(
PluginRegistrarWindows *registrar, IrisRtcEngine *engine)
{
auto method_channel = std::make_unique<MethodChannel<EncodableValue>>(
registrar->messenger(), "agora_rtc_channel",
&StandardMethodCodec::GetInstance());
auto event_channel = std::make_unique<EventChannel<EncodableValue>>(
registrar->messenger(), "agora_rtc_channel/events",
&StandardMethodCodec::GetInstance());
auto plugin = std::make_unique<AgoraRtcChannelPlugin>(registrar, engine);
method_channel->SetMethodCallHandler(
[plugin_pointer = plugin.get()](const auto &call, auto result)
{
plugin_pointer->HandleMethodCall(call, std::move(result));
});
auto handler = std::make_unique<StreamHandlerFunctions<EncodableValue>>(
[plugin_pointer =
plugin.get()](const EncodableValue *arguments,
std::unique_ptr<EventSink<EncodableValue>> &&events)
-> std::unique_ptr<StreamHandlerError<EncodableValue>>
{
plugin_pointer->event_sink_ = std::move(events);
return nullptr;
},
[plugin_pointer = plugin.get()](const EncodableValue *arguments)
-> std::unique_ptr<StreamHandlerError<EncodableValue>>
{
plugin_pointer->event_sink_ = nullptr;
return nullptr;
});
event_channel->SetStreamHandler(std::move(handler));
registrar->AddPlugin(std::move(plugin));
}
AgoraRtcChannelPlugin::AgoraRtcChannelPlugin(PluginRegistrar *registrar,
IrisRtcEngine *engine)
: engine_(engine)
{
engine_->channel()->SetEventHandler(this);
callApiMethodCallHandler_ = std::make_unique<RtcChannelCallApiMethodCallHandler>(engine_);
}
AgoraRtcChannelPlugin::~AgoraRtcChannelPlugin() {}
void AgoraRtcChannelPlugin::HandleMethodCall(
const MethodCall<EncodableValue> &method_call,
std::unique_ptr<MethodResult<EncodableValue>> result)
{
callApiMethodCallHandler_->HandleMethodCall(method_call, std::move(result));
}
void AgoraRtcChannelPlugin::OnEvent(const char *event, const char *data)
{
if (event_sink_)
{
EncodableMap ret = {{EncodableValue("methodName"), EncodableValue(event)},
{EncodableValue("data"), EncodableValue(data)}};
event_sink_->Success(ret);
}
}
void AgoraRtcChannelPlugin::OnEvent(const char *event, const char *data,
const void *buffer, unsigned int length)
{
if (event_sink_)
{
std::vector<uint8_t> vector(length);
if (buffer && length)
{
memcpy(&vector[0], buffer, length);
}
EncodableMap ret = {{EncodableValue("methodName"), EncodableValue(event)},
{EncodableValue("data"), EncodableValue(data)},
{EncodableValue("buffer"), EncodableValue(vector)}};
event_sink_->Success(ret);
}
}
} // namespace
void AgoraRtcChannelPluginRegisterWithRegistrar(
PluginRegistrarWindows *registrar, IrisRtcEngine *engine)
{
AgoraRtcChannelPlugin::RegisterWithRegistrar(registrar, engine);
}
| 36.781818 | 94 | 0.658099 | outlier-collective |
3ab444cc910181a925875a133e48be2251edcd12 | 1,098 | cpp | C++ | test/pre_reserch/plag_original_codes/08_076_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | 13 | 2021-01-20T19:53:16.000Z | 2021-11-14T16:30:32.000Z | test/training_data/plag_original_codes/08_076_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | test/training_data/plag_original_codes/08_076_plag.cpp | xryuseix/SA-Plag | 167f7a2b2fa81ff00fd5263772a74c2c5c61941d | [
"MIT"
] | null | null | null | // 引用元 : https://atcoder.jp/contests/abc077/submissions/5997212
// 得点 : 300
// コード長 : 920
// 実行時間 : 148
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
using ll = long long;
int main() {
int n;
cin >> n;
vector<ll> a(n);
vector<ll> b(n);
vector<ll> c(n);
for(int i=0;i<n;++i){
cin >> a[i];
}
sort(a.begin(), a.end());
for(int i=0;i<n;++i){
cin >> b[i];
}
sort(b.begin(), b.end());
for(int i=0;i<n;++i){
cin >> c[i];
}
sort(c.begin(), c.end());
vector<ll> ab(n);
vector<ll> bc(n);
vector<ll> bc_count(n, 0);
for(int i=0;i<n;++i) {
ab[i] = upper_bound(b.begin(), b.end(), a[i]) - b.begin();
++bc_count[ab[i]];
}
for(int i=1;i<n;++i) bc_count[i] += bc_count[i-1];
for(int i=0;i<n;++i) {
bc[i] = upper_bound(c.begin(), c.end(), b[i]) - c.begin();
}
ll ans = 0LL;
for(int i=0;i<n;++i) {
ans += bc_count[i] * (n-bc[i]);
}
cout << ans << endl;
}
| 20.333333 | 67 | 0.448087 | xryuseix |
3ab6c39cf34a600a32d8818938696c34d11dfcaf | 1,122 | hpp | C++ | data-structure/dynamic-union-find.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 69 | 2020-11-06T05:21:42.000Z | 2022-03-29T03:38:35.000Z | data-structure/dynamic-union-find.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 21 | 2020-07-25T04:47:12.000Z | 2022-02-01T14:39:29.000Z | data-structure/dynamic-union-find.hpp | NachiaVivias/library | 73091ddbb00bc59328509c8f6e662fea2b772994 | [
"CC0-1.0"
] | 9 | 2020-11-06T11:55:10.000Z | 2022-03-20T04:45:31.000Z | #pragma once
#include "../hashmap/hashmap.hpp"
struct DynamicUnionFind {
HashMap<int, int> m;
DynamicUnionFind() = default;
int data(int k) {
auto it = m.find(k);
return it == m.end() ? m[k] = -1 : it->second;
}
int find(int k) {
int n = data(k);
return n < 0 ? k : m[k] = find(n);
}
int unite(int x, int y) {
x = find(x), y = find(y);
if (x == y) return false;
auto itx = m.find(x), ity = m.find(y);
if (itx->second > ity->second) swap(itx, ity), swap(x, y);
itx->second += ity->second;
ity->second = x;
return true;
}
template <typename F>
int unite(int x, int y, const F& f) {
x = find(x), y = find(y);
if (x == y) return false;
auto itx = m.find(x), ity = m.find(y);
if (itx->second > ity->second) swap(itx, ity), swap(x, y);
itx->second += ity->second;
ity->second = x;
f(x, y);
return true;
}
int size(int k) { return -data(find(k)); }
int same(int x, int y) { return find(x) == find(y); }
void clear() { m.clear(); }
};
/**
* @brief 動的Union Find
* @docs docs/data-structure/dynamic-union-find.md
*/
| 22 | 62 | 0.540998 | NachiaVivias |
3ab6e000d5f10b3a66c12bcd0543b8913b8e46a6 | 6,054 | cpp | C++ | pgadmin/pgscript/objects/pgsNumber.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 111 | 2015-01-02T15:39:46.000Z | 2022-01-08T05:08:20.000Z | pgadmin/pgscript/objects/pgsNumber.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 13 | 2015-07-08T20:26:20.000Z | 2019-06-17T12:45:35.000Z | pgadmin/pgscript/objects/pgsNumber.cpp | cjayho/pgadmin3 | df5f0b83175b4fb495bfcb4d4ce175def486c9df | [
"PostgreSQL"
] | 96 | 2015-03-11T14:06:44.000Z | 2022-02-07T10:04:45.000Z | //////////////////////////////////////////////////////////////////////////
//
// pgScript - PostgreSQL Tools
//
// Copyright (C) 2002 - 2016, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
//////////////////////////////////////////////////////////////////////////
#include "pgAdmin3.h"
#include "pgscript/objects/pgsNumber.h"
#include <wx/regex.h>
#include "pgscript/objects/pgsRecord.h"
#include "pgscript/objects/pgsString.h"
#include "pgscript/exceptions/pgsArithmeticException.h"
#include "pgscript/exceptions/pgsCastException.h"
#define PGS_INTEGER_FORM_1 wxT("^[+-]?[0-9]+$")
#define PGS_REAL_FORM_1 wxT("^[+-]?[0-9]+[Ee][+-]?[0-9]+$")
#define PGS_REAL_FORM_2 wxT("^[+-]?[0-9]*[.][0-9]+([Ee][+-]?[0-9]+)?$")
#define PGS_REAL_FORM_3 wxT("^[+-]?[0-9]+[.][0-9]*([Ee][+-]?[0-9]+)?$")
pgsNumber::pgsNumber(const wxString &data, const bool &is_real) :
pgsVariable(!is_real ? pgsVariable::pgsTInt : pgsVariable::pgsTReal),
m_data(data.Strip(wxString::both))
{
wxASSERT(is_valid());
}
bool pgsNumber::is_valid() const
{
pgsTypes type = num_type(m_data);
return (type == pgsTInt) || (type == pgsTReal && is_real());
}
pgsNumber::~pgsNumber()
{
}
pgsNumber::pgsNumber(const pgsNumber &that) :
pgsVariable(that), m_data(that.m_data)
{
wxASSERT(is_valid());
}
pgsNumber &pgsNumber::operator =(const pgsNumber &that)
{
if (this != &that)
{
pgsVariable::operator=(that);
m_data = that.m_data;
}
wxASSERT(is_valid());
return (*this);
}
pgsVariable *pgsNumber::clone() const
{
return pnew pgsNumber(*this);
}
wxString pgsNumber::value() const
{
return m_data;
}
pgsOperand pgsNumber::eval(pgsVarMap &vars) const
{
return this->clone();
}
pgsVariable::pgsTypes pgsNumber::num_type(const wxString &num)
{
if (wxRegEx(PGS_INTEGER_FORM_1).Matches(num))
{
return pgsTInt;
}
else if (( wxRegEx(PGS_REAL_FORM_1).Matches(num)
|| wxRegEx(PGS_REAL_FORM_2).Matches(num)
|| wxRegEx(PGS_REAL_FORM_3).Matches(num)))
{
return pgsTReal;
}
else
{
return pgsTString;
}
}
pgsOperand pgsNumber::pgs_plus(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(pgsMapm::pgs_mapm_str(num(m_data)
+ num(rhs.value())), is_real() || rhs.is_real());
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_minus(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(pgsMapm::pgs_mapm_str(num(m_data)
- num(rhs.value())), is_real() || rhs.is_real());
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_times(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(pgsMapm::pgs_mapm_str(num(m_data)
* num(rhs.value())), is_real() || rhs.is_real());
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_over(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
if (num(rhs.value()) != 0)
{
if (is_real() || rhs.is_real())
return pnew pgsNumber(pgsMapm::pgs_mapm_str(num(m_data)
/ num(rhs.value())), is_real() || rhs.is_real());
else
return pnew pgsNumber(pgsMapm::pgs_mapm_str(num(m_data)
.div(num(rhs.value()))), is_real() || rhs.is_real());
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_modulo(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
if (num(rhs.value()) != 0)
{
return pnew pgsNumber(pgsMapm::pgs_mapm_str(num(m_data)
% num(rhs.value())), is_real() || rhs.is_real());
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_equal(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(num(m_data) == num(rhs.value())
? wxT("1") : wxT("0"));
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_different(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(num(m_data) != num(rhs.value())
? wxT("1") : wxT("0"));
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_greater(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(num(m_data) > num(rhs.value())
? wxT("1") : wxT("0"));
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_lower(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(num(m_data) < num(rhs.value())
? wxT("1") : wxT("0"));
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_lower_equal(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(num(m_data) <= num(rhs.value())
? wxT("1") : wxT("0"));
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_greater_equal(const pgsVariable &rhs) const
{
if (rhs.is_number())
{
return pnew pgsNumber(num(m_data) >= num(rhs.value())
? wxT("1") : wxT("0"));
}
else
{
throw pgsArithmeticException(m_data, rhs.value());
}
}
pgsOperand pgsNumber::pgs_not() const
{
return pnew pgsNumber(num(m_data) == 0 ? wxT("1") : wxT("0"));
}
bool pgsNumber::pgs_is_true() const
{
return (num(m_data) != 0 ? true : false);
}
pgsOperand pgsNumber::pgs_almost_equal(const pgsVariable &rhs) const
{
return pgs_equal(rhs);
}
pgsNumber pgsNumber::number() const
{
return pgsNumber(*this);
}
pgsRecord pgsNumber::record() const
{
pgsRecord rec(1);;
rec.insert(0, 0, this->clone());
return rec;
}
pgsString pgsNumber::string() const
{
return pgsString(m_data);
}
| 21.094077 | 79 | 0.624381 | cjayho |
3abc742e2dc4d2957a0858c20671fa3c02e871c3 | 1,577 | hpp | C++ | include/eagine/valid_if/lt_size_ge0.hpp | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | 1 | 2022-01-25T10:31:51.000Z | 2022-01-25T10:31:51.000Z | include/eagine/valid_if/lt_size_ge0.hpp | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | null | null | null | include/eagine/valid_if/lt_size_ge0.hpp | matus-chochlik/eagine-core | 5bc2d6b9b053deb3ce6f44f0956dfccd75db4649 | [
"BSL-1.0"
] | null | null | null | /// @file
///
/// Copyright Matus Chochlik.
/// 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
///
#ifndef EAGINE_VALID_IF_LT_SIZE_GE0_HPP
#define EAGINE_VALID_IF_LT_SIZE_GE0_HPP
#include "in_class.hpp"
namespace eagine {
/// @brief Policy for values valid if >= 0 and < container.size().
/// @ingroup valid_if
template <typename T, typename C>
struct valid_if_lt_size_ge0_policy {
/// @brief Indicates value validity, true if 0 <= x < c.size().
auto operator()(const T x, const C& c) const {
return (T(0) <= x) && (x < c.size());
}
/// @brief Indicates value validity, true if 0 <= x < c.size() - o.
auto operator()(const T x, const C& c, const T o) const {
return (T(0) <= x) && (x < c.size() - o);
}
struct do_log {
template <typename X, typename = disable_if_same_t<X, do_log>>
constexpr do_log(X&&) noexcept {}
template <typename Log>
void operator()(Log& log, const T& v, const C& c) const {
log << "Value " << v << ", less than zero or "
<< "not less than c.size() = " << c.size() << " is invalid";
}
};
};
/// @brief Specialization of valid_if, for values valid if >= 0 and < container.size().
/// @ingroup valid_if
/// @see valid_if_le_size_ge0
template <typename C, typename T>
using valid_if_lt_size_ge0 =
in_class_valid_if<T, C, valid_if_lt_size_ge0_policy<T, C>>;
} // namespace eagine
#endif // EAGINE_VALID_IF_LT_SIZE_GE0_HPP
| 29.754717 | 87 | 0.630311 | matus-chochlik |
3abe75da0427aec2079f71bdd10276f43d9c79ee | 1,128 | cpp | C++ | test/matcher.cpp | OneBit74/ezpz | 16c899275feef45bc535fb2fa60fd0a1f563882f | [
"MIT"
] | null | null | null | test/matcher.cpp | OneBit74/ezpz | 16c899275feef45bc535fb2fa60fd0a1f563882f | [
"MIT"
] | null | null | null | test/matcher.cpp | OneBit74/ezpz | 16c899275feef45bc535fb2fa60fd0a1f563882f | [
"MIT"
] | null | null | null | #include "ezpz/ezpz.hpp"
#include <gtest/gtest.h>
using namespace ezpz;
TEST(matcher,accept_if){
std::vector<int> range = {1,2,3,4,5,6};
forward_range_context<std::vector<int>> ctx(std::move(range));
auto even = accept_if([](int val){return (val+1)%2;});
auto odd = accept_if([](int val){return val%2;});
EXPECT_TRUE(parse(ctx,odd+even+odd+even+odd+even+eoi));
}
TEST(matcher,ws){
basic_context ctx;
ctx.input = " \t \t \n\t\n ";
EXPECT_TRUE(parse(ctx,ws));
EXPECT_TRUE(ctx.done());
}
TEST(matcher,token){
EXPECT_TRUE(parse("aaa",token('a')));
EXPECT_FALSE(parse("bbb",token('a')));
EXPECT_TRUE(parse("aaa",token('a')+token('a')+token('a')+eoi));
}
TEST(matcher,text_parser){
bool success;
auto parser = "hello" + make_rpo([&](auto&){
success = true;
return true;
});
success = false;
EXPECT_TRUE(parse("hello",parser));
EXPECT_TRUE(success);
success = false;
EXPECT_FALSE(parse("hell",parser));
EXPECT_FALSE(success);
success = false;
EXPECT_TRUE(parse("helloo",parser));
EXPECT_TRUE(success);
success = false;
EXPECT_FALSE(parse("",parser));
EXPECT_FALSE(success);
success = false;
}
| 23.020408 | 64 | 0.675532 | OneBit74 |
3ac335005474a4a7df5303effb8c8bb4cb5578c1 | 6,565 | cpp | C++ | src/multiple_shooting_ocp.cpp | sotarokatayama/nmpcsolver | 7ee1710d4c8d2f4bceea70d5a2560d12eec29c8f | [
"MIT"
] | 65 | 2019-09-17T07:00:14.000Z | 2022-03-30T07:09:14.000Z | src/multiple_shooting_ocp.cpp | sotarokatayama/nmpcsolver | 7ee1710d4c8d2f4bceea70d5a2560d12eec29c8f | [
"MIT"
] | 12 | 2018-12-19T19:20:43.000Z | 2019-08-27T20:16:45.000Z | src/multiple_shooting_ocp.cpp | sotarokatayama/nmpcsolver | 7ee1710d4c8d2f4bceea70d5a2560d12eec29c8f | [
"MIT"
] | 15 | 2019-09-16T16:07:58.000Z | 2022-03-13T10:39:41.000Z | #include "multiple_shooting_ocp.hpp"
namespace cgmres {
MultipleShootingOCP::MultipleShootingOCP(const double T_f, const double alpha,
const int N)
: OptimalControlProblem(),
horizon_(T_f, alpha),
dim_solution_(N*(model_.dim_control_input()+model_.dim_constraints())),
N_(N),
dx_vec_(linearalgebra::NewVector(model_.dim_state())) {
}
MultipleShootingOCP::MultipleShootingOCP(const double T_f, const double alpha,
const int N, const double initial_time)
: OptimalControlProblem(),
horizon_(T_f, alpha, initial_time),
dim_solution_(N*(model_.dim_control_input()+model_.dim_constraints())),
N_(N),
dx_vec_(linearalgebra::NewVector(model_.dim_state())) {
}
MultipleShootingOCP::~MultipleShootingOCP() {
linearalgebra::DeleteVector(dx_vec_);
}
void MultipleShootingOCP::
computeOptimalityResidualForControlInputAndConstraints(
const double time, const double* state_vec,
const double* control_input_and_constraints_seq,
double const* const* state_mat, double const* const* lambda_mat,
double* optimality_redisual_for_control_input_and_constraints) {
// Set the length of the horizon and discretize the horizon.
double horizon_length = horizon_.getLength(time);
double delta_tau = horizon_length / N_;
// Compute optimality error for control input and constraints.
model_.huFunc(
time, state_vec, control_input_and_constraints_seq,
lambda_mat[0],
optimality_redisual_for_control_input_and_constraints);
double tau = time + delta_tau;
for (int i=1; i<N_; ++i, tau+=delta_tau) {
int i_total = i * dim_control_input_and_constraints_;
model_.huFunc(
tau, state_mat[i-1], &(control_input_and_constraints_seq[i_total]),
lambda_mat[i],
&(optimality_redisual_for_control_input_and_constraints[i_total]));
}
}
void MultipleShootingOCP::computeOptimalityResidualForStateAndLambda(
const double time, const double* state_vec,
const double* control_input_and_constraints_seq,
double const* const* state_mat, double const* const* lambda_mat,
double** optimality_residual_for_state,
double** optimality_residual_for_lambda) {
// Set the length of the horizon and discretize the horizon.
double horizon_length = horizon_.getLength(time);
double delta_tau = horizon_length / N_;
// Compute optimality error for state.
model_.stateFunc(time, state_vec, control_input_and_constraints_seq, dx_vec_);
for (int i=0; i<dim_state_; ++i) {
optimality_residual_for_state[0][i] =
state_mat[0][i] - state_vec[i] - delta_tau * dx_vec_[i];
}
double tau = time + delta_tau;
for (int i=1; i<N_; ++i, tau+=delta_tau) {
int i_total = i * dim_control_input_and_constraints_;
model_.stateFunc(tau, state_mat[i-1],
&(control_input_and_constraints_seq[i_total]), dx_vec_);
for (int j=0; j<dim_state_; ++j) {
optimality_residual_for_state[i][j] =
state_mat[i][j] - state_mat[i-1][j] - delta_tau * dx_vec_[j];
}
}
// Compute optimality error for lambda.
model_.phixFunc(tau, state_mat[N_-1], dx_vec_);
for (int i=0; i<dim_state_; ++i) {
optimality_residual_for_lambda[N_-1][i] = lambda_mat[N_-1][i] - dx_vec_[i];
}
for (int i=N_-1; i>=1; --i, tau-=delta_tau) {
int i_total = i * dim_control_input_and_constraints_;
model_.hxFunc(tau, state_mat[i-1],
&(control_input_and_constraints_seq[i_total]),
lambda_mat[i], dx_vec_);
for (int j=0; j<dim_state_; ++j) {
optimality_residual_for_lambda[i-1][j] =
lambda_mat[i-1][j] - lambda_mat[i][j] - delta_tau * dx_vec_[j];
}
}
}
void MultipleShootingOCP::computeStateAndLambdaFromOptimalityResidual(
const double time, const double* state_vec,
const double* control_input_and_constraints_seq,
double const* const* optimality_residual_for_state,
double const* const* optimality_residual_for_lambda,
double** state_mat, double** lambda_mat) {
// Set the length of the horizon and discretize the horizon.
double horizon_length = horizon_.getLength(time);
double delta_tau = horizon_length / N_;
// Compute the sequence of state under the error for state.
model_.stateFunc(time, state_vec, control_input_and_constraints_seq, dx_vec_);
for (int i=0; i<dim_state_; ++i) {
state_mat[0][i] =
state_vec[i]
+ delta_tau * dx_vec_[i] + optimality_residual_for_state[0][i];
}
double tau = time + delta_tau;
for (int i=1; i<N_; ++i, tau+=delta_tau) {
int i_total = i * dim_control_input_and_constraints_;
model_.stateFunc(tau, state_mat[i-1],
&(control_input_and_constraints_seq[i_total]), dx_vec_);
for (int j=0; j<dim_state_; ++j) {
state_mat[i][j] =
state_mat[i-1][j]
+ delta_tau * dx_vec_[j] + optimality_residual_for_state[i][j];
}
}
// Compute the sequence of lambda under the error for lambda.
model_.phixFunc(tau, state_mat[N_-1], dx_vec_);
for (int i=0; i<dim_state_; ++i) {
lambda_mat[N_-1][i] = dx_vec_[i] + optimality_residual_for_lambda[N_-1][i];
}
for (int i=N_-1; i>=1; --i, tau-=delta_tau) {
int i_total = i * dim_control_input_and_constraints_;
model_.hxFunc(tau, state_mat[i-1],
&(control_input_and_constraints_seq[i_total]),
lambda_mat[i], dx_vec_);
for (int j=0; j<dim_state_; ++j) {
lambda_mat[i-1][j] =
lambda_mat[i][j]
+ delta_tau * dx_vec_[j] + optimality_residual_for_lambda[i-1][j];
}
}
}
void MultipleShootingOCP::predictStateFromSolution(
const double current_time, const double* current_state,
const double* solution_vec, const double prediction_length,
double* predicted_state) {
model_.stateFunc(current_time, current_state, solution_vec, dx_vec_);
for (int i=0; i<dim_state_; ++i) {
predicted_state[i] = current_state[i] + prediction_length * dx_vec_[i];
}
}
void MultipleShootingOCP::resetHorizonLength(const double T_f,
const double alpha,
const double initial_time) {
horizon_.resetLength(T_f, alpha, initial_time);
}
void MultipleShootingOCP::resetHorizonLength(const double initial_time) {
horizon_.resetLength(initial_time);
}
int MultipleShootingOCP::dim_solution() const {
return dim_solution_;
}
int MultipleShootingOCP::N() const {
return N_;
}
} // namespace cgmres | 39.311377 | 81 | 0.68393 | sotarokatayama |
3ad029635fa26e7b7ad6bad6a6a58b62421b4b62 | 6,447 | cc | C++ | DEM/Src/nebula2/src/scene/nblendshapenode_main.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | 2 | 2017-04-30T20:24:29.000Z | 2019-02-12T08:36:26.000Z | DEM/Src/nebula2/src/scene/nblendshapenode_main.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | DEM/Src/nebula2/src/scene/nblendshapenode_main.cc | moltenguy1/deusexmachina | 134f4ca4087fff791ec30562cb250ccd50b69ee1 | [
"MIT"
] | null | null | null | //------------------------------------------------------------------------------
// nblendshapenode_main.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "scene/nblendshapenode.h"
#include "gfx2/nmesh2.h"
#include "scene/nanimator.h"
nNebulaClass(nBlendShapeNode, "nmaterialnode");
//------------------------------------------------------------------------------
/**
*/
nBlendShapeNode::nBlendShapeNode() :
numShapes(0),
groupIndex(0),
shapeArray(MaxShapes)
{
//empty
}
//------------------------------------------------------------------------------
/**
*/
nBlendShapeNode::~nBlendShapeNode()
{
// empty
}
//------------------------------------------------------------------------------
/**
Indicate to scene server that we provide geometry
*/
bool
nBlendShapeNode::HasGeometry() const
{
return true;
}
//------------------------------------------------------------------------------
/**
This method must return the mesh usage flag combination required by
this shape node class. Subclasses should override this method
based on their requirements.
@return a combination on nMesh2::Usage flags
*/
int
nBlendShapeNode::GetMeshUsage() const
{
return nMesh2::WriteOnce | nMesh2::NeedsVertexShader;
}
//------------------------------------------------------------------------------
/**
Load the resources needed by this object.
*/
bool
nBlendShapeNode::LoadResources()
{
nMaterialNode::LoadResources();
if (!this->refMeshArray.isvalid())
{
this->refMeshArray = nGfxServer2::Instance()->NewMeshArray(0);
}
// update resouce filenames in mesharray
int i;
for (i = 0; i < this->GetNumShapes(); i++)
{
this->refMeshArray->SetFilenameAt(i, this->shapeArray[i].meshName);
this->refMeshArray->SetUsageAt(i, this->GetMeshUsage());
}
this->resourcesValid &= this->refMeshArray->Load();
// update shape bounding boxes
if (true == this->resourcesValid)
{
for (i = 0; i < this->GetNumShapes(); i++)
{
nMesh2* mesh = this->refMeshArray->GetMeshAt(i);
if (0 != mesh)
{
this->shapeArray[i].localBox = mesh->Group(this->groupIndex).Box;
}
}
}
return this->resourcesValid;
}
//------------------------------------------------------------------------------
/**
Unload the resources.
*/
void
nBlendShapeNode::UnloadResources()
{
nMaterialNode::UnloadResources();
if (this->refMeshArray.isvalid())
{
this->refMeshArray->Unload();
this->refMeshArray->Release();
this->refMeshArray.invalidate();
}
}
//------------------------------------------------------------------------------
/**
Set the mesh resource name at index.
Updates the number of current valid shapes.
@param index
@param name name of the resource to set, 0 to unset a resource
*/
void
nBlendShapeNode::SetMeshAt(int index, const char* name)
{
n_assert((index >= 0) && (index < MaxShapes));
if (this->shapeArray[index].meshName != name)
{
this->resourcesValid = false;
this->shapeArray[index].meshName = name;
if (0 != name)
{
// increase shapes count
this->numShapes = n_max(index+1, this->numShapes);
}
else
{
// decrease shapes count if this was the last element
if (index + 1 == this->numShapes)
{
this->numShapes--;
}
}
}
}
//------------------------------------------------------------------------------
/**
Gives the weights to the shader
*/
void
nBlendShapeNode::UpdateShaderState()
{
// set shader parameter
nShader2* shader = nGfxServer2::Instance()->GetShader();
n_assert(shader);
int numShapes = this->GetNumShapes();
shader->SetInt(nShaderState::VertexStreams, numShapes);
if (numShapes > 0)
{
nFloat4 weights = {0.0f, 0.0f, 0.0f, 0.0f};
if (numShapes > 0) weights.x = this->GetWeightAt(0);
if (numShapes > 1) weights.y = this->GetWeightAt(1);
if (numShapes > 2) weights.z = this->GetWeightAt(2);
if (numShapes > 3) weights.w = this->GetWeightAt(3);
shader->SetFloat4(nShaderState::VertexWeights1, weights);
}
if (numShapes > 4)
{
nFloat4 weights = {0.0f, 0.0f, 0.0f, 0.0f};
if (numShapes > 4) weights.x = this->GetWeightAt(4);
if (numShapes > 5) weights.y = this->GetWeightAt(5);
if (numShapes > 6) weights.z = this->GetWeightAt(6);
if (numShapes > 7) weights.w = this->GetWeightAt(7);
shader->SetFloat4(nShaderState::VertexWeights2, weights);
}
}
//------------------------------------------------------------------------------
/**
Perform pre-instancing actions needed for rendering geometry. This
is called once before multiple instances of this shape node are
actually rendered.
*/
bool
nBlendShapeNode::ApplyGeometry(nSceneServer* /*sceneServer*/)
{
// set mesh, vertex and index range
nGfxServer2::Instance()->SetMeshArray(this->refMeshArray.get());
const nMeshGroup& curGroup = this->refMeshArray->GetMeshAt(0)->Group(this->groupIndex);
nGfxServer2::Instance()->SetVertexRange(curGroup.FirstVertex, curGroup.NumVertices);
nGfxServer2::Instance()->SetIndexRange(curGroup.FirstIndex, curGroup.NumIndices);
return true;
}
//------------------------------------------------------------------------------
/**
Update geometry, set as current mesh in the gfx server and
call nGfxServer2::DrawIndexed().
- 15-Jan-04 floh AreResourcesValid()/LoadResource() moved to scene server
- 01-Feb-05 floh use nBlendShapeDeformer on CPU
*/
bool
nBlendShapeNode::RenderGeometry(nSceneServer* /*sceneServer*/, nRenderContext* renderContext)
{
// invoke blend shape animators (manipulating the weights)
this->InvokeAnimators(nAnimator::BlendShape, renderContext);
// update shader state
this->UpdateShaderState();
// draw the geometry
nGfxServer2::Instance()->DrawIndexedNS(nGfxServer2::TriangleList);
return true;
}
| 30.554502 | 94 | 0.520707 | moltenguy1 |
3ad24fa8d3d2be9928be4210296fa640e61714bd | 3,618 | hpp | C++ | NetIO.hpp | kzoacn/QOT | b6db9c957bc81139301ded0e661ebc6d2a7cbe01 | [
"MIT"
] | null | null | null | NetIO.hpp | kzoacn/QOT | b6db9c957bc81139301ded0e661ebc6d2a7cbe01 | [
"MIT"
] | null | null | null | NetIO.hpp | kzoacn/QOT | b6db9c957bc81139301ded0e661ebc6d2a7cbe01 | [
"MIT"
] | null | null | null | #ifndef RECORD_IO_CHANNEL
#define RECORD_IO_CHANNEL
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <vector>
using std::string;
using std::vector;
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#include <netinet/in.h>
#include <sys/socket.h>
class NetIO { public:
bool is_server;
int mysocket = -1;
int consocket = -1;
FILE * stream = nullptr;
char * buffer = nullptr;
bool has_sent = false;
string addr;
int port;
uint64_t counter = 0;
NetIO(const char * address, int port,bool quiet = false) {
this->port = port;
is_server = (address == nullptr);
if (address == nullptr) {
struct sockaddr_in dest;
struct sockaddr_in serv;
socklen_t socksize = sizeof(struct sockaddr_in);
memset(&serv, 0, sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY); /* set our address to any interface */
serv.sin_port = htons(port); /* set the server port number */
mysocket = socket(AF_INET, SOCK_STREAM, 0);
int reuse = 1;
setsockopt(mysocket, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse));
if(bind(mysocket, (struct sockaddr *)&serv, sizeof(struct sockaddr)) < 0) {
perror("error: bind");
exit(1);
}
if(listen(mysocket, 1) < 0) {
perror("error: listen");
exit(1);
}
consocket = accept(mysocket, (struct sockaddr *)&dest, &socksize);
close(mysocket);
}
else {
addr = string(address);
struct sockaddr_in dest;
memset(&dest, 0, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_addr.s_addr = inet_addr(address);
dest.sin_port = htons(port);
while(1) {
consocket = socket(AF_INET, SOCK_STREAM, 0);
if (connect(consocket, (struct sockaddr *)&dest, sizeof(struct sockaddr)) == 0) {
break;
}
close(consocket);
usleep(1000);
}
}
set_nodelay();
stream = fdopen(consocket, "wb+");
const int NETWORK_BUFFER_SIZE=65536;
buffer = new char[NETWORK_BUFFER_SIZE];
memset(buffer, 0, NETWORK_BUFFER_SIZE);
setvbuf(stream, buffer, _IOFBF, NETWORK_BUFFER_SIZE);
if(!quiet)
std::cout << "connected\n";
}
void sync() {
int tmp = 0;
if(is_server) {
send_data(&tmp, 1);
recv_data(&tmp, 1);
} else {
recv_data(&tmp, 1);
send_data(&tmp, 1);
flush();
}
}
~NetIO(){
fflush(stream);
close(consocket);
//delete[] buffer;
}
void set_nodelay() {
const int one=1;
setsockopt(consocket,IPPROTO_TCP,TCP_NODELAY,&one,sizeof(one));
}
void set_delay() {
const int zero = 0;
setsockopt(consocket,IPPROTO_TCP,TCP_NODELAY,&zero,sizeof(zero));
}
void flush() {
fflush(stream);
}
void send_data(const void * data, int len) {
counter += len;
int sent = 0;
while(sent < len) {
int res = fwrite(sent + (char*)data, 1, len - sent, stream);
if (res >= 0)
sent+=res;
else
fprintf(stderr,"error: net_send_data %d\n", res);
}
has_sent = true;
}
void recv_data(void * data, int len) {
if(has_sent)
fflush(stream);
has_sent = false;
int sent = 0;
while(sent < len) {
int res = fread(sent + (char*)data, 1, len - sent, stream);
if (res >= 0)
sent += res;
else
fprintf(stderr,"error: net_send_data %d\n", res);
}
}
void send_string(string s){
int size=s.length();
send_data(&size,4);
send_data(s.data(),size);
}
void recv_string(string &s){
int size;
recv_data(&size,4);
char *tmp=new char[size+1];
recv_data(tmp,size);
s=string(tmp);
delete[] tmp;
}
};
#endif //NETWORK_IO_CHANNEL
| 21.795181 | 86 | 0.634052 | kzoacn |
3ad87838128552530acb61fdbb77d5ba7c2b2700 | 3,236 | hpp | C++ | include/unifex/just_error.hpp | Chlorie/libunifex | 9869196338016939265964b82c7244915de6a12f | [
"Apache-2.0"
] | 1 | 2021-11-23T11:30:39.000Z | 2021-11-23T11:30:39.000Z | include/unifex/just_error.hpp | Chlorie/libunifex | 9869196338016939265964b82c7244915de6a12f | [
"Apache-2.0"
] | null | null | null | include/unifex/just_error.hpp | Chlorie/libunifex | 9869196338016939265964b82c7244915de6a12f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include <unifex/config.hpp>
#include <unifex/receiver_concepts.hpp>
#include <unifex/sender_concepts.hpp>
#include <unifex/blocking.hpp>
#include <unifex/std_concepts.hpp>
#include <exception>
#include <tuple>
#include <type_traits>
#include <utility>
#include <unifex/detail/prologue.hpp>
namespace unifex {
namespace _just_error {
template <typename Receiver, typename Error>
struct _op {
struct type;
};
template <typename Receiver, typename Error>
using operation = typename _op<remove_cvref_t<Receiver>, Error>::type;
template <typename Receiver, typename Error>
struct _op<Receiver, Error>::type {
UNIFEX_NO_UNIQUE_ADDRESS Error error_;
UNIFEX_NO_UNIQUE_ADDRESS Receiver receiver_;
void start() & noexcept {
unifex::set_error((Receiver &&) receiver_, (Error &&) error_);
}
};
template <typename Error>
struct _sender {
class type;
};
template <typename Error>
using sender = typename _sender<std::decay_t<Error>>::type;
template <typename Error>
class _sender<Error>::type {
UNIFEX_NO_UNIQUE_ADDRESS Error error_;
public:
template <
template <typename...> class Variant,
template <typename...> class Tuple>
using value_types = Variant<>;
template <template <typename...> class Variant>
using error_types = Variant<Error>;
static constexpr bool sends_done = false;
template<typename Error2>
explicit type(std::in_place_t, Error2&& error)
noexcept(std::is_nothrow_constructible_v<Error, Error2>)
: error_((Error2 &&) error) {}
template(typename This, typename Receiver)
(requires same_as<remove_cvref_t<This>, type> AND
receiver<Receiver, Error> AND
constructible_from<Error, member_t<This, Error>>)
friend auto tag_invoke(tag_t<connect>, This&& that, Receiver&& r)
noexcept(std::is_nothrow_constructible_v<Error, member_t<This, Error>>)
-> operation<Receiver, Error> {
return {static_cast<This&&>(that).error_, static_cast<Receiver&&>(r)};
}
friend constexpr blocking_kind tag_invoke(tag_t<blocking>, const type&) noexcept {
return blocking_kind::always_inline;
}
};
} // namespace _just_error
namespace _just_error_cpo {
inline const struct just_error_fn {
template <typename Error>
constexpr auto operator()(Error&& error) const
noexcept(std::is_nothrow_constructible_v<std::decay_t<Error>, Error>)
-> _just_error::sender<Error> {
return _just_error::sender<Error>{std::in_place, (Error&&) error};
}
} just_error{};
} // namespace _just_error_cpo
using _just_error_cpo::just_error;
} // namespace unifex
#include <unifex/detail/epilogue.hpp>
| 29.688073 | 84 | 0.729604 | Chlorie |
3ad88da2e652ea769cdd9b55fe7a62bffc14ca7d | 14,079 | cpp | C++ | Source/SIMPLib/CoreFilters/ReplaceValueInArray.cpp | mmarineBlueQuartz/SIMPL | 834f9009944efe69d94b5b77a641d96db3e9543b | [
"NRL"
] | null | null | null | Source/SIMPLib/CoreFilters/ReplaceValueInArray.cpp | mmarineBlueQuartz/SIMPL | 834f9009944efe69d94b5b77a641d96db3e9543b | [
"NRL"
] | 2 | 2019-02-23T20:46:12.000Z | 2019-07-11T15:34:13.000Z | Source/SIMPLib/CoreFilters/ReplaceValueInArray.cpp | mmarineBlueQuartz/SIMPL | 834f9009944efe69d94b5b77a641d96db3e9543b | [
"NRL"
] | null | null | null | /* ============================================================================
* Copyright (c) 2009-2016 BlueQuartz Software, LLC
*
* 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 BlueQuartz Software, the US Air Force, 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.
*
* The code contained herein was partially funded by the followig contracts:
* United States Air Force Prime Contract FA8650-07-D-5800
* United States Air Force Prime Contract FA8650-10-D-5210
* United States Prime Contract Navy N00173-07-C-2068
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
#include "ReplaceValueInArray.h"
#include "SIMPLib/Common/Constants.h"
#include "SIMPLib/Common/TemplateHelpers.h"
#include "SIMPLib/FilterParameters/AbstractFilterParametersReader.h"
#include "SIMPLib/FilterParameters/DataArraySelectionFilterParameter.h"
#include "SIMPLib/FilterParameters/DoubleFilterParameter.h"
#include "SIMPLib/SIMPLibVersion.h"
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ReplaceValueInArray::ReplaceValueInArray()
: m_SelectedArray("", "", "")
, m_RemoveValue(0.0)
, m_ReplaceValue(0.0)
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
ReplaceValueInArray::~ReplaceValueInArray() = default;
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ReplaceValueInArray::setupFilterParameters()
{
FilterParameterVector parameters;
parameters.push_back(SIMPL_NEW_DOUBLE_FP("Value to Replace", RemoveValue, FilterParameter::Parameter, ReplaceValueInArray));
parameters.push_back(SIMPL_NEW_DOUBLE_FP("New Value", ReplaceValue, FilterParameter::Parameter, ReplaceValueInArray));
{
DataArraySelectionFilterParameter::RequirementType req = DataArraySelectionFilterParameter::CreateCategoryRequirement(SIMPL::Defaults::AnyPrimitive, 1, AttributeMatrix::Category::Any);
parameters.push_back(SIMPL_NEW_DA_SELECTION_FP("Attribute Array", SelectedArray, FilterParameter::RequiredArray, ReplaceValueInArray, req));
}
setFilterParameters(parameters);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ReplaceValueInArray::readFilterParameters(AbstractFilterParametersReader* reader, int index)
{
reader->openFilterGroup(this, index);
setSelectedArray(reader->readDataArrayPath("SelectedArray", getSelectedArray()));
setRemoveValue(reader->readValue("RemoveValue", getRemoveValue()));
setReplaceValue(reader->readValue("ReplaceValue", getReplaceValue()));
reader->closeFilterGroup();
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
template <typename T> void checkValuesInt(AbstractFilter* filter, double removeValue, double replaceValue, QString strType)
{
QString ss;
if(!((removeValue >= std::numeric_limits<T>::min()) && (removeValue <= std::numeric_limits<T>::max())))
{
ss = QObject::tr("The %1 remove value was invalid. The valid range is %2 to %3").arg(strType).arg(std::numeric_limits<T>::min()).arg(std::numeric_limits<T>::max());
filter->setErrorCondition(-100);
filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition());
}
if(!((replaceValue >= std::numeric_limits<T>::min()) && (replaceValue <= std::numeric_limits<T>::max())))
{
ss = QObject::tr("The %1 replace value was invalid. The valid range is %2 to %3").arg(strType).arg(std::numeric_limits<T>::min()).arg(std::numeric_limits<T>::max());
filter->setErrorCondition(-100);
filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition());
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
template <typename T> void checkValuesFloatDouble(AbstractFilter* filter, double removeValue, double replaceValue, QString strType)
{
QString ss;
if(!(((removeValue >= static_cast<T>(-1) * std::numeric_limits<T>::max()) && (removeValue <= static_cast<T>(-1) * std::numeric_limits<T>::min())) || (removeValue == 0) ||
((removeValue >= std::numeric_limits<T>::min()) && (removeValue <= std::numeric_limits<T>::max()))))
{
ss = QObject::tr("The %1 remove value was invalid. The valid ranges are -%3 to -%2, 0, %2 to %3").arg(strType).arg(std::numeric_limits<T>::min()).arg(std::numeric_limits<T>::max());
filter->setErrorCondition(-101);
filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition());
}
if(!(((replaceValue >= static_cast<T>(-1) * std::numeric_limits<T>::max()) && (replaceValue <= static_cast<T>(-1) * std::numeric_limits<T>::min())) || (replaceValue == 0) ||
((replaceValue >= std::numeric_limits<T>::min()) && (replaceValue <= std::numeric_limits<T>::max()))))
{
ss = QObject::tr("The %1 replace value was invalid. The valid ranges are -%3 to -%2, 0, %2 to %3").arg(strType).arg(std::numeric_limits<T>::min()).arg(std::numeric_limits<T>::max());
filter->setErrorCondition(-101);
filter->notifyErrorMessage(filter->getHumanLabel(), ss, filter->getErrorCondition());
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
template <typename T> void replaceValue(AbstractFilter* filter, IDataArray::Pointer inDataPtr, double removeValue, double replaceValue)
{
typename DataArray<T>::Pointer inputArrayPtr = std::dynamic_pointer_cast<DataArray<T>>(inDataPtr);
T removeVal = static_cast<T>(removeValue);
T replaceVal = static_cast<T>(replaceValue);
T* inData = inputArrayPtr->getPointer(0);
size_t numTuples = inputArrayPtr->getNumberOfTuples();
for(size_t iter = 0; iter < numTuples; iter++)
{
if(inData[iter] == removeVal)
{
inData[iter] = replaceVal;
}
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ReplaceValueInArray::initialize()
{
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ReplaceValueInArray::dataCheck()
{
setErrorCondition(0);
setWarningCondition(0);
m_ArrayPtr = getDataContainerArray()->getPrereqIDataArrayFromPath<IDataArray, AbstractFilter>(this, getSelectedArray());
if(getErrorCondition() < 0)
{
return;
}
if(m_ArrayPtr.lock()->getNumberOfComponents() > 1)
{
QString ss = QObject::tr("Selected array '%1' must be a scalar array (1 component). The number of components is %2")
.arg(getSelectedArray().getDataArrayName())
.arg(m_ArrayPtr.lock()->getNumberOfComponents());
setErrorCondition(-11002);
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
return;
}
QString dType = m_ArrayPtr.lock()->getTypeAsString();
if(dType.compare(SIMPL::TypeNames::Int8) == 0)
{
checkValuesInt<int8_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::Int8);
}
else if(dType.compare(SIMPL::TypeNames::UInt8) == 0)
{
checkValuesInt<uint8_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::UInt8);
}
else if(dType.compare(SIMPL::TypeNames::Int16) == 0)
{
checkValuesInt<int16_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::Int16);
}
else if(dType.compare(SIMPL::TypeNames::UInt16) == 0)
{
checkValuesInt<uint16_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::UInt16);
}
else if(dType.compare(SIMPL::TypeNames::Int32) == 0)
{
checkValuesInt<int32_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::Int32);
}
else if(dType.compare(SIMPL::TypeNames::UInt32) == 0)
{
checkValuesInt<uint32_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::UInt32);
}
else if(dType.compare(SIMPL::TypeNames::Int64) == 0)
{
checkValuesInt<int64_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::Int64);
}
else if(dType.compare(SIMPL::TypeNames::UInt64) == 0)
{
checkValuesInt<uint64_t>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::UInt64);
}
else if(dType.compare(SIMPL::TypeNames::Float) == 0)
{
checkValuesFloatDouble<float>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::Float);
}
else if(dType.compare(SIMPL::TypeNames::Double) == 0)
{
checkValuesFloatDouble<double>(this, m_RemoveValue, m_ReplaceValue, SIMPL::TypeNames::Double);
}
else if(dType.compare(SIMPL::TypeNames::Bool) == 0)
{
if(m_RemoveValue != 0.0)
{
m_RemoveValue = 1.0; // anything that is not a zero is a one
}
if(m_ReplaceValue != 0.0)
{
m_ReplaceValue = 1.0; // anything that is not a zero is a one
}
}
else
{
setErrorCondition(-4060);
QString ss = QObject::tr("Incorrect data scalar type");
notifyErrorMessage(getHumanLabel(), ss, getErrorCondition());
}
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ReplaceValueInArray::preflight()
{
setInPreflight(true);
emit preflightAboutToExecute();
emit updateFilterParameters(this);
dataCheck();
emit preflightExecuted();
setInPreflight(false);
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void ReplaceValueInArray::execute()
{
setErrorCondition(0);
setWarningCondition(0);
dataCheck();
if(getErrorCondition() < 0)
{
return;
}
EXECUTE_FUNCTION_TEMPLATE(this, replaceValue, m_ArrayPtr.lock(), this, m_ArrayPtr.lock(), m_RemoveValue, m_ReplaceValue)
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
AbstractFilter::Pointer ReplaceValueInArray::newFilterInstance(bool copyFilterParameters) const
{
ReplaceValueInArray::Pointer filter = ReplaceValueInArray::New();
if(copyFilterParameters)
{
copyFilterParameterInstanceVariables(filter.get());
}
return filter;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString ReplaceValueInArray::getCompiledLibraryName() const
{
return Core::CoreBaseName;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString ReplaceValueInArray::getBrandingString() const
{
return "SIMPLib Core Filter";
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString ReplaceValueInArray::getFilterVersion() const
{
QString version;
QTextStream vStream(&version);
vStream << SIMPLib::Version::Major() << "." << SIMPLib::Version::Minor() << "." << SIMPLib::Version::Patch();
return version;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString ReplaceValueInArray::getGroupName() const
{
return SIMPL::FilterGroups::CoreFilters;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QUuid ReplaceValueInArray::getUuid()
{
return QUuid("{a37f2e24-7400-5005-b9a7-b2224570cbe9}");
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString ReplaceValueInArray::getSubGroupName() const
{
return SIMPL::FilterSubGroups::MemoryManagementFilters;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
const QString ReplaceValueInArray::getHumanLabel() const
{
return "Replace Value in Array";
}
| 40.690751 | 188 | 0.55977 | mmarineBlueQuartz |
3ad9737debe98bccda421d69e986f4ede67e9272 | 412 | cpp | C++ | test/main.cpp | TimQuelch/soa | 6a3a18f845e1f8c6e361b328ceae15c7df336d1e | [
"MIT"
] | null | null | null | test/main.cpp | TimQuelch/soa | 6a3a18f845e1f8c6e361b328ceae15c7df336d1e | [
"MIT"
] | null | null | null | test/main.cpp | TimQuelch/soa | 6a3a18f845e1f8c6e361b328ceae15c7df336d1e | [
"MIT"
] | null | null | null | #include <iostream>
#include "soa.h"
int main() {
auto s = soa::soa<int, double, float>{};
s.push_back({1, 1.2, 2.3f});
s.push_back({5, 6, 7});
//const auto s2 = s;
//auto a = s[0];
//auto b = s2[1];
//std::cout << std::get<0>(a) << std::get<1>(a) << std::get<2>(a) << std::endl;
//std::cout << std::get<0>(b) << std::get<1>(b) << std::get<2>(b) << std::endl;
return 0;
}
| 22.888889 | 83 | 0.478155 | TimQuelch |
3add21d670744939cdf7fe878fbf69e4dce0894a | 3,532 | cpp | C++ | src/cpSerDesFactory.cpp | asc135/CodePort | 306d40d0a6d5ccb249b22249f2b3702ac09c021b | [
"BSD-3-Clause"
] | null | null | null | src/cpSerDesFactory.cpp | asc135/CodePort | 306d40d0a6d5ccb249b22249f2b3702ac09c021b | [
"BSD-3-Clause"
] | null | null | null | src/cpSerDesFactory.cpp | asc135/CodePort | 306d40d0a6d5ccb249b22249f2b3702ac09c021b | [
"BSD-3-Clause"
] | null | null | null | // ----------------------------------------------------------------------------
// CodePort++
//
// A Portable Operating System Abstraction Library
// Copyright 2010 Amardeep S. Chana. All rights reserved.
// Use of this software is bound by the terms of the Modified BSD License.
//
// Module Name: cpSerDesFactory.cpp
//
// Description: Serializer/Deserializer instance factory.
//
// Platform: common
//
// History:
// 2011-06-23 asc Creation.
// 2012-08-10 asc Moved identifiers to cp namespace.
// 2013-11-15 asc Added IDL ser/des.
// ----------------------------------------------------------------------------
#include "cpSerDesNative.h"
#include "cpSerDesXml.h"
#include "cpSerDesIdl.h"
namespace cp
{
// singleton instance
SerDesFactory *SerDesFactory::m_PtrInstance = NULL;
// ----------------------------------------------------------------------------
// constructor
SerDesFactory::SerDesFactory() :
m_Mutex("SerDes Factory Mutex")
{
SerDes *ptr;
// populate the pool with intrinsic serializers
ptr = new (CP_NEW) SerDesNative;
SerDesPut(ptr);
ptr = new (CP_NEW) SerDesXml;
SerDesPut(ptr);
ptr = new (CP_NEW) SerDesIdl;
SerDesPut(ptr);
}
// destructor
SerDesFactory::~SerDesFactory()
{
}
// singleton instance get method
SerDesFactory *SerDesFactory::InstanceGet()
{
if (m_PtrInstance == NULL)
{
m_PtrInstance = new (CP_NEW) SerDesFactory;
}
if (m_PtrInstance == NULL)
{
LogErr << "SerDesFactory::InstanceGet(): Failed to create SerDesFactory instance."
<< std::endl;
}
return m_PtrInstance;
}
// detect the encoding of a serialized stream
String SerDesFactory::DetectEncoding(StreamBase &Stream)
{
String rv;
SerDesPoolMap_t::iterator i;
m_Mutex.Lock();
i = m_Pools.begin();
while (i != m_Pools.end())
{
if ((i->second.size() > 0) && (i->second.front()->CheckEncoding(Stream)))
{
rv = (i->first);
break;
}
++i;
}
m_Mutex.Unlock();
return rv;
}
// acquire an encoder
SerDes *SerDesFactory::SerDesGet(String const &Enc)
{
SerDes *rv = NULL;
SerDesPoolMap_t::iterator i;
m_Mutex.Lock();
// search for the encoder type in the pool map
i = m_Pools.find(Enc);
if (i != m_Pools.end())
{
// there should always be a minimum of one encoder in each pool
if (i->second.size() > 0)
{
// see how many are in the pool and always keep at least one
// so you can make more using its CreateInstance() method
if (i->second.size() > 1)
{
// if more then one, return one of them
rv = i->second.front();
i->second.pop_front();
}
else
{
// if just one, create another and return that
rv = i->second.front()->CreateInstance();
}
}
else
{
LogErr << "SerDesFactory::SerDesGet(): Error - found an empty serializer pool: "
<< Enc << std::endl;
}
}
m_Mutex.Unlock();
return rv;
}
// return an encoder
bool SerDesFactory::SerDesPut(SerDes * &pSerDes)
{
bool rv = false;
if (pSerDes != NULL)
{
m_Mutex.Lock();
m_Pools[pSerDes->NameGet()].push_back(pSerDes);
m_Mutex.Unlock();
pSerDes = NULL;
rv = true;
}
return rv;
}
} // namespace cp
| 21.802469 | 92 | 0.538788 | asc135 |
3adf46bda23f337e464782559a505d968e0df2c3 | 406 | cpp | C++ | basics/cli.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 77 | 2019-10-28T05:38:51.000Z | 2022-03-15T01:53:48.000Z | basics/cli.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 3 | 2019-12-26T15:39:55.000Z | 2020-10-29T14:55:50.000Z | basics/cli.cpp | iarjunphp/CPP-Learning | 4946f861cb3f57da2b0beba07a206fafe261aaf4 | [
"MIT"
] | 24 | 2020-01-08T04:12:52.000Z | 2022-03-12T22:26:07.000Z | #include <iostream>
using namespace std;
// argc(ARGument Count) i indicates how many parameters are passed
//argv(ARGument Vector) indicates array of character pointers listing all the arguments
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";
for (int i = 0; i < argc; ++i)
cout << argv[i] << "\n";
return 0;
} | 27.066667 | 87 | 0.598522 | iarjunphp |
3ae0b5d80e5ea4425ddccff702595162ea2819d6 | 5,203 | hpp | C++ | Siv3D/include/Siv3D/BlendState.hpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 2 | 2021-11-22T00:52:48.000Z | 2021-12-24T09:33:55.000Z | Siv3D/include/Siv3D/BlendState.hpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 32 | 2021-10-09T10:04:11.000Z | 2022-02-25T06:10:13.000Z | Siv3D/include/Siv3D/BlendState.hpp | tas9n/OpenSiv3D | c561cba1d88eb9cd9606ba983fcc1120192d5615 | [
"MIT"
] | 1 | 2021-12-31T05:08:00.000Z | 2021-12-31T05:08:00.000Z | //-----------------------------------------------
//
// This file is part of the Siv3D Engine.
//
// Copyright (c) 2008-2022 Ryo Suzuki
// Copyright (c) 2016-2022 OpenSiv3D Project
//
// Licensed under the MIT License.
//
//-----------------------------------------------
# pragma once
# if __has_include(<bit>)
# include <bit>
# endif
# include <cstring>
# include <functional>
# include "Common.hpp"
# include "Utility.hpp"
namespace s3d
{
/// @brief ブレンドモード
enum class Blend : uint8
{
Zero = 1,
One = 2,
SrcColor = 3,
InvSrcColor = 4,
SrcAlpha = 5,
InvSrcAlpha = 6,
DestAlpha = 7,
InvDestAlpha = 8,
DestColor = 9,
InvDestColor = 10,
SrcAlphaSat = 11,
BlendFactor = 14,
InvBlendFactor = 15,
Src1Color = 16,
InvSrc1Color = 17,
Src1Alpha = 18,
InvSrc1Alpha = 19
};
/// @brief ブレンド式
enum class BlendOp : uint8
{
Add = 1,
Subtract = 2,
RevSubtract = 3,
Min = 4,
Max = 5
};
/// @brief ブレンドステート
struct BlendState
{
private:
enum class Predefined
{
NonPremultiplied,
Premultiplied,
Opaque,
Additive,
AdditiveRGB,
Subtractive,
Multiplicative,
Multiplicative2X,
OpaqueAlphaToCoverage,
MaxAlpha,
Default2D = NonPremultiplied,
Default3D = Opaque,
};
public:
using storage_type = uint32;
bool enable : 1 = true;
bool writeR : 1 = true;
bool writeG : 1 = true;
Blend src : 5 = Blend::SrcAlpha;
Blend dst : 5 = Blend::InvSrcAlpha;
BlendOp op : 3 = BlendOp::Add;
bool alphaToCoverageEnable : 1 = false;
bool writeB : 1 = true;
bool writeA : 1 = true;
Blend srcAlpha : 5 = Blend::Zero;
Blend dstAlpha : 5 = Blend::One;
BlendOp opAlpha : 3 = BlendOp::Add;
SIV3D_NODISCARD_CXX20
explicit constexpr BlendState(
bool _enable = true,
Blend _src = Blend::SrcAlpha,
Blend _dst = Blend::InvSrcAlpha,
BlendOp _op = BlendOp::Add,
Blend _srcAlpha = Blend::Zero,
Blend _dstAlpha = Blend::One,
BlendOp _opAlpha = BlendOp::Add,
bool _alphaToCoverageEnable = false,
bool _writeR = true,
bool _writeG = true,
bool _writeB = true,
bool _writeA = true
) noexcept;
SIV3D_NODISCARD_CXX20
constexpr BlendState(Predefined predefined) noexcept;
[[nodiscard]]
storage_type asValue() const noexcept;
[[nodiscard]]
bool operator ==(const BlendState& other) const noexcept;
[[nodiscard]]
bool operator !=(const BlendState& other) const noexcept;
/// @brief デフォルトのブレンド
/// @remark BlendState{ true, Blend::SrcAlpha, Blend::InvSrcAlpha, BlendOp::Add, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined NonPremultiplied = Predefined::NonPremultiplied;
/// @brief 乗算済みアルファブレンド
/// @remark BlendState{ true, Blend::One, Blend::InvSrcAlpha, BlendOp::Add, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined Premultiplied = Predefined::Premultiplied;
/// @brief 不透明
/// @remark BlendState{ false }
static constexpr Predefined Opaque = Predefined::Opaque;
/// @brief 加算ブレンド
/// @remark BlendState{ true, Blend::SrcAlpha, Blend::One, BlendOp::Add, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined Additive = Predefined::Additive;
/// @brief 加算ブレンド (RGB)
/// @remark BlendState{ true, Blend::One, Blend::One, BlendOp::Add, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined AdditiveRGB = Predefined::AdditiveRGB;
/// @brief 減算ブレンド
/// @remark BlendState{ true, Blend::SrcAlpha, Blend::One, BlendOp::RevSubtract, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined Subtractive = Predefined::Subtractive;
/// @brief 乗算ブレンド
/// @remark BlendState{ true, Blend::Zero, Blend::SrcColor, BlendOp::Add, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined Multiplicative = Predefined::Multiplicative;
/// @brief 2X 乗算ブレンド
/// @remark BlendState{ true, Blend::DestColor, Blend::SrcColor, BlendOp::Add, Blend::Zero, Blend::One, BlendOp::Add }
static constexpr Predefined Multiplicative2X = Predefined::Multiplicative2X;
/// @brief Alpha to Coverage
/// @remark BlendState{ false, .alphaToCoverageEnable = true }
static constexpr Predefined OpaqueAlphaToCoverage = Predefined::OpaqueAlphaToCoverage;
/// @brief アルファの最大値のみ更新
/// @remark BlendState{ true, Blend::Zero, Blend::One, BlendOp::Add, Blend::SrcAlpha, Blend::DestAlpha, BlendOp::Max }
static constexpr Predefined MaxAlpha = Predefined::MaxAlpha;
/// @brief デフォルトのブレンド
/// @remark BlendState{ true }
static constexpr Predefined Default2D = Predefined::Default2D;
/// @brief デフォルトのブレンド
/// @remark BlendState{ false }
static constexpr Predefined Default3D = Predefined::Default3D;
};
static_assert(sizeof(BlendState) == sizeof(BlendState::storage_type));
}
//////////////////////////////////////////////////
//
// Hash
//
//////////////////////////////////////////////////
template <>
struct std::hash<s3d::BlendState>
{
[[nodiscard]]
size_t operator ()(const s3d::BlendState& value) const noexcept
{
return hash<s3d::BlendState::storage_type>()(value.asValue());
}
};
# include "detail/BlendState.ipp"
| 22.52381 | 122 | 0.650586 | tas9n |
3ae28e8f0b9a1372061209a0b9e1329f6d92b89f | 3,031 | cc | C++ | unittests/message/list_parts_result_unittest.cc | allisrc/aliyun-oss-cpp-sdk | e2e166ff031552a93baacc105098c67ee4bf448a | [
"Apache-2.0"
] | null | null | null | unittests/message/list_parts_result_unittest.cc | allisrc/aliyun-oss-cpp-sdk | e2e166ff031552a93baacc105098c67ee4bf448a | [
"Apache-2.0"
] | null | null | null | unittests/message/list_parts_result_unittest.cc | allisrc/aliyun-oss-cpp-sdk | e2e166ff031552a93baacc105098c67ee4bf448a | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "gtest/gtest.h"
#include "oss_sdk_cpp/message/list_parts_result.h"
namespace oss {
static const char* kXmlContent =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<ListPartsResult>\n"
" <Bucket>wuhawukawuha12</Bucket>\n"
" <Key>niu.c</Key>\n"
" <UploadId>627213BC81394969B70221F09C2032F7</UploadId>\n"
" <StorageClass>Standard</StorageClass>\n"
" <PartNumberMarker>0</PartNumberMarker>\n"
" <NextPartNumberMarker>2</NextPartNumberMarker>\n"
" <MaxParts>2</MaxParts>\n"
" <IsTruncated>true</IsTruncated>\n"
" <Part>\n"
" <PartNumber>1</PartNumber>\n"
" <LastModified>2015-11-23T05:53:30.000Z</LastModified>\n"
" <ETag>\"2C0FC53DB041AB32EC663867DF02EDE3\"</ETag>\n"
" <Size>102400</Size>\n"
" </Part>\n"
" <Part>\n"
" <PartNumber>2</PartNumber>\n"
" <LastModified>2015-11-23T05:53:30.000Z</LastModified>\n"
" <ETag>\"24196B4D8EAB6F08A4B141D3D594531C\"</ETag>\n"
" <Size>102400</Size>\n"
" </Part>\n"
"</ListPartsResult>\n"
"";
TEST(ListPartsResult, allinone) {
ListPartsResult result;
bool parse_ok = result.DeserializeFromXml(kXmlContent);
EXPECT_TRUE(parse_ok);
EXPECT_EQ(result.GetBucketName(), "wuhawukawuha12");
EXPECT_EQ(result.GetKey(), "niu.c");
EXPECT_EQ(result.GetUploadId(), "627213BC81394969B70221F09C2032F7");
EXPECT_EQ(result.GetStorageClass(), "Standard");
EXPECT_EQ(result.GetPartNumberMarker(), 0);
EXPECT_EQ(result.GetNextPartNumberMarker(), 2);
EXPECT_EQ(result.GetMaxParts(), 2);
EXPECT_EQ(result.GetIsTruncated(), true);
auto& parts = result.GetParts();
auto& part = parts.front();
EXPECT_EQ(parts.size(), 2u);
EXPECT_EQ(part.GetPartNumber(), 1);
EXPECT_EQ(part.GetLastModified(), "2015-11-23T05:53:30.000Z");
EXPECT_EQ(part.GetEtag(), "\"2C0FC53DB041AB32EC663867DF02EDE3\"");
EXPECT_EQ(part.GetSize(), 102400u);
}
TEST(ListPartsResult, ParseFailed) {
ListPartsResult result;
bool parse_ok = true;
parse_ok = result.DeserializeFromXml("I am invalid xml text");
EXPECT_FALSE(parse_ok);
parse_ok = result.DeserializeFromXml(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Test>ab</Test>\n");
EXPECT_FALSE(parse_ok);
}
} // namespace oss
| 34.83908 | 80 | 0.702408 | allisrc |
3ae3c66b0f17da64d41dd09192f54485cda146ee | 1,996 | cpp | C++ | demo/src/components/playerweapon.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | 2 | 2017-11-13T11:29:03.000Z | 2017-11-13T12:09:12.000Z | demo/src/components/playerweapon.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | demo/src/components/playerweapon.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | #include "playerweapon.h"
#include <iostream>
#include <ceppengine/gameobject.h>
#include <ceppengine/engine.h>
#include "projectile.h"
#include "delayeddestruction.h"
using namespace cepp;
PlayerWeapon::PlayerWeapon() : mShooting(false), mShootKey(' ')
{
}
std::string PlayerWeapon::typeName() const
{
return "PlayerWeapon";
}
bool PlayerWeapon::isShooting() const
{
return mShooting;
}
int PlayerWeapon::shootKey() const
{
return mShootKey;
}
void PlayerWeapon::setShootKey(int key)
{
mShootKey = key;
}
void PlayerWeapon::start()
{
mInputMod = Engine::instance()->inputModule();
mAudioSource = (AudioSource*)gameObject()->getComponent("AudioSource");
}
void PlayerWeapon::update(float deltaTime)
{
mShooting = false;
if(mInputMod->isKeyPressed(mShootKey)) {
GameObject *proj = makeProjectile();
proj->setParent(gameObject()->scene()->rootObject());
proj->setPosition(gameObject()->position() + (-gameObject()->right()) * 0.2f + Vector3(0, 0.1f, 0));
mAudioSource->play();
mShooting = true;
}
}
GameObject *PlayerWeapon::makeProjectile()
{
GameObject *go = new GameObject("Projectile");
SpriteRenderer *r = (SpriteRenderer*)go->addComponent(new SpriteRenderer());
r->setSprite((Sprite*)Engine::instance()->assetLoader()->loadAsset("/projectile.sprite", "Sprite"));
AudioSource *audio = (AudioSource*)go->addComponent(new AudioSource());
audio->setClip((AudioClip*)Engine::instance()->assetLoader()->loadAsset("/explosion.wav", "AudioClip"));
Projectile *p = (Projectile*)go->addComponent(new Projectile());
p->setDirection(-(gameObject()->right()));
p->setRange(0.5f);
p->setSpeed(5.f);
p->setExplosionSprite((Sprite*)Engine::instance()->assetLoader()->loadAsset("/projectile_explosion.sprite", "Sprite"));
p->setTarget("Enemy");
DelayedDestruction *d = (DelayedDestruction*)go->addComponent(new DelayedDestruction());
d->setDelay(5.0f);
return go;
}
| 28.112676 | 123 | 0.683367 | Winded |
3ae65a8d7cd718c00db5fd461963a5919cded111 | 12,418 | cpp | C++ | Eudora71/Eudora/PgDocumentFrame.cpp | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 10 | 2018-05-23T10:43:48.000Z | 2021-12-02T17:59:48.000Z | Eudora71/Eudora/PgDocumentFrame.cpp | dusong7/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 1 | 2019-03-19T03:56:36.000Z | 2021-05-26T18:36:03.000Z | Eudora71/Eudora/PgDocumentFrame.cpp | evilneuro/eudora-win | 850a6619e6b0d5abc770bca8eb5f3b9001b7ccd2 | [
"BSD-3-Clause-Clear"
] | 11 | 2018-05-23T10:43:53.000Z | 2021-12-27T15:42:58.000Z | // PgDocumentFrame.cpp : implementation file
//
// Copyright (c) 1997-2001 by QUALCOMM, Incorporated
/* Copyright (c) 2016, Computer History Museum
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to
the limitations in the disclaimer below) 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 Computer History Museum nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS LICENSE. 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 "stdafx.h"
#include "resource.h"
#include "mainfrm.h"
#include "rs.h"
#include "utils.h"
#include "helpcntx.h"
#include "QCProtocol.h"
#include "PgDocumentFrame.h"
#include "font.h"
#include "QCChildToolBar.h"
#include "TBarMenuButton.h"
#include "TBarCombo.h"
#include "TBarMenuButton.h"
#include "ColorToolbarButton.h"
#include "QCFindMgr.h"
#include "QCSharewareManager.h"
#include "PaigeEdtView.h"
#include "EmoticonToolbarButton.h"
#include "DebugNewHelpers.h"
#define DIM( a ) ( sizeof( a ) / sizeof( a[0] ) )
static UINT theFullFeatureFormatButtons[] = {
ID_FONT,
ID_SEPARATOR,
ID_EDIT_TEXT_SIZE,
ID_SEPARATOR,
ID_EDIT_TEXT_BOLD,
ID_EDIT_TEXT_ITALIC,
ID_EDIT_TEXT_UNDERLINE,
ID_EDIT_TEXT_STRIKEOUT,
ID_EDIT_TEXT_LAST_TEXT_COLOR,
ID_EDIT_TEXT_TT,
ID_SEPARATOR,
ID_EDIT_TEXT_LEFT,
ID_EDIT_TEXT_CENTER,
ID_EDIT_TEXT_RIGHT,
ID_SEPARATOR,
ID_EDIT_TEXT_INDENT_IN,
ID_EDIT_TEXT_INDENT_OUT,
ID_SEPARATOR,
ID_BLKFMT_BULLETTED_LIST,
ID_EDIT_INSERT_LINK,
ID_SEPARATOR,
ID_EDIT_TEXT_CLEAR,
ID_SEPARATOR,
ID_EDIT_INSERT,
ID_SEPARATOR,
ID_EDIT_LAST_EMOTICON
};
static UINT theReducedFeatureFormatButtons[] = {
ID_FONT,
ID_SEPARATOR,
ID_EDIT_TEXT_SIZE,
ID_SEPARATOR,
ID_EDIT_TEXT_BOLD,
ID_EDIT_TEXT_ITALIC,
ID_EDIT_TEXT_UNDERLINE,
ID_SEPARATOR,
ID_EDIT_TEXT_CLEAR
};
BEGIN_BUTTON_MAP( thePgDocFrameButtonMap )
STD_BUTTON( ID_EDIT_TEXT_BOLD, TBBS_INDETERMINATE )
STD_BUTTON( ID_EDIT_TEXT_ITALIC, TBBS_INDETERMINATE )
STD_BUTTON( ID_EDIT_TEXT_UNDERLINE, TBBS_INDETERMINATE )
STD_BUTTON( ID_EDIT_TEXT_STRIKEOUT, TBBS_INDETERMINATE )
STD_BUTTON( ID_EDIT_TEXT_TT, TBBS_INDETERMINATE )
STD_BUTTON( ID_BLKFMT_BULLETTED_LIST, TBBS_CHECKBOX )
STD_BUTTON( ID_EDIT_TEXT_LEFT, TBBS_CHECKBOX )
STD_BUTTON( ID_EDIT_TEXT_CENTER, TBBS_CHECKBOX )
STD_BUTTON( ID_EDIT_TEXT_RIGHT, TBBS_CHECKBOX )
STD_BUTTON( ID_EDIT_INSERT_LINK, TBBS_BUTTON )
TBARCOMBO_BUTTON( ID_FONT, IDC_FONT_COMBO, 0, WS_VSCROLL | CBS_DROPDOWNLIST | CBS_SORT, 115, 40, 115 )
TBARMENU_BUTTON( ID_EDIT_INSERT, TBBS_BUTTON )
TBARMENU_BUTTON( ID_EDIT_TEXT_SIZE, TBBS_BUTTON )
COLOR_BUTTON(ID_EDIT_TEXT_LAST_TEXT_COLOR, ID_EDIT_TEXT_COLOR, 0, NULL)
EMOTICON_BUTTON(ID_EDIT_LAST_EMOTICON, ID_EDIT_EMOTICON, 0, NULL)
END_BUTTON_MAP()
/////////////////////////////////////////////////////////////////////////////
// PgDocumentFrame
IMPLEMENT_DYNCREATE(PgDocumentFrame, CMDIChild)
PgDocumentFrame::PgDocumentFrame()
{
m_pToolBarManager = NULL;
m_pFormattingToolBar = NULL;
}
PgDocumentFrame::~PgDocumentFrame()
{
delete m_pToolBarManager;
}
BEGIN_MESSAGE_MAP(PgDocumentFrame, CMDIChild)
//{{AFX_MSG_MAP(PgDocumentFrame)
ON_WM_CREATE()
ON_WM_CONTEXTMENU()
//}}AFX_MSG_MAP
ON_COMMAND(ID_EDIT_CHECKSPELLING, OnCheckSpelling)
ON_UPDATE_COMMAND_UI(ID_EDIT_FIND_FINDTEXT, OnUpdateEditFindFindText)
ON_UPDATE_COMMAND_UI(ID_EDIT_FIND_FINDTEXTAGAIN, OnUpdateEditFindFindTextAgain)
ON_REGISTERED_MESSAGE(WM_FINDREPLACE, OnFindReplace)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// PgDocumentFrame message handlers
int PgDocumentFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
DWORD dwStyle;
DWORD dwExStyle;
INT i;
CComboBox* pCombo;
CStringArray theArray;
CMDIFrameWnd* pMainFrame;
BOOL bMaximized;
CMenu* pEditTextMenu;
CMenu* pMenu;
CTBarMenuButton* pMenuButton;
if (CMDIChild::OnCreate(lpCreateStruct) == -1)
return -1;
m_pToolBarManager = DEBUG_NEW_MFCOBJ_NOTHROW SECToolBarManager( this );
m_pFormattingToolBar = DEBUG_NEW_MFCOBJ_NOTHROW QCChildToolBar;
if( ( m_pToolBarManager == NULL ) ||
( m_pFormattingToolBar == NULL ) )
{
ASSERT( 0 );
return FALSE;
}
m_pFormattingToolBar->SetManager( m_pToolBarManager );
m_pFormattingToolBar->m_bAutoDelete = TRUE;
m_pToolBarManager->LoadToolBarResource( MAKEINTRESOURCE( IDR_COMPMESS ), MAKEINTRESOURCE( IDR_COMPMESS ) );
m_pToolBarManager->SetButtonMap( thePgDocFrameButtonMap );
if ( GetIniShort( IDS_INI_SHOW_COOLBAR ) )
{
m_pToolBarManager->EnableCoolLook( TRUE );
}
EnableDocking(CBRS_ALIGN_TOP);
dwStyle = WS_VISIBLE | WS_CHILD | CBRS_TOP | CBRS_SIZE_DYNAMIC | CBRS_FLYBY ;
if( GetIniShort( IDS_INI_SHOW_TOOLTIPS ) )
{
dwStyle |= CBRS_TOOLTIPS;
}
dwExStyle = 0L;
//dwExStyle = CBRS_EX_SIZE_TO_FIT;
if( m_pToolBarManager->CoolLookEnabled() )
{
dwExStyle |= CBRS_EX_COOLBORDERS;
}
// now create the formatting tool bar
if( ! GetIniShort( IDS_INI_SHOW_STYLED_TEXT_TOOLBAR ) )
{
dwStyle = dwStyle & ~WS_VISIBLE;
}
if( ! m_pFormattingToolBar->CreateEx( dwExStyle, this, dwStyle, AFX_IDW_TOOLBAR+7, _T( "Format" ) ) )
{
ASSERT( 0 );
return FALSE;
}
m_pToolBarManager->SetToolBarInfo( m_pFormattingToolBar );
m_pFormattingToolBar->EnableDocking(CBRS_ALIGN_TOP);
// Shareware: In reduced feature mode, you get a less-capable format toolbar
if (UsingFullFeatureSet())
{
// FULL FEATURE mode
m_pFormattingToolBar->SetButtons( theFullFeatureFormatButtons, DIM( theFullFeatureFormatButtons ) );
}
else
{
// REDUCED FEATURE mode
m_pFormattingToolBar->SetButtons( theReducedFeatureFormatButtons, DIM( theReducedFeatureFormatButtons ) );
}
DockControlBar( m_pFormattingToolBar );
// get the face names
EnumFontFaces( theArray );
pCombo = ( CComboBox* ) ( m_pFormattingToolBar->GetDlgItem( IDC_FONT_COMBO ) );
for( i = 0; i < theArray.GetSize(); i ++ )
{
pCombo->AddString( theArray[i] );
}
// get the main frame window
pMainFrame = ( CMDIFrameWnd* ) AfxGetApp()->m_pMainWnd;
// see if it's maximized
bMaximized = FALSE;
pMainFrame->MDIGetActive( &bMaximized );
i = ( bMaximized ? 1 : 0 );
// get the main window
VERIFY( pEditTextMenu = pMainFrame->GetMenu() );
// get the edit menu
VERIFY( pEditTextMenu = pEditTextMenu->GetSubMenu( 1 + i ) );
// Shareware: In reduced feature mode, you cannot right-click
if (UsingFullFeatureSet())
{
// FULL FEATURE mode
// get the insert menu
VERIFY( pMenu = pEditTextMenu->GetSubMenu( 11 ) );
i = m_pFormattingToolBar->CommandToIndex( ID_EDIT_INSERT );
VERIFY( pMenuButton = ( CTBarMenuButton* ) ( m_pFormattingToolBar->GetButton( i ) ) );
pMenuButton->SetHMenu( pMenu->GetSafeHmenu() );
}
// get the text menu
VERIFY( pEditTextMenu = pEditTextMenu->GetSubMenu( 10 ) );
// get the size menu
VERIFY( pMenu = pEditTextMenu->GetSubMenu( 10 ) );
i = m_pFormattingToolBar->CommandToIndex( ID_EDIT_TEXT_SIZE );
VERIFY( pMenuButton = ( CTBarMenuButton* ) ( m_pFormattingToolBar->GetButton( i ) ) );
pMenuButton->SetHMenu( pMenu->GetSafeHmenu() );
RecalcLayout();
return 0;
}
QCChildToolBar* PgDocumentFrame::GetFormatToolbar()
{
if( m_pFormattingToolBar )
{
return m_pFormattingToolBar;
}
return NULL;
}
// --------------------------------------------------------------------------
//
// FIND TEXT
//
void PgDocumentFrame::OnUpdateEditFindFindText(CCmdUI* pCmdUI) // Find (Ctrl-F)
{
pCmdUI->Enable(TRUE);
}
void PgDocumentFrame::OnUpdateEditFindFindTextAgain(CCmdUI* pCmdUI) // Find Again (F3)
{
QCFindMgr *pFindMgr = QCFindMgr::GetFindMgr();
ASSERT(pFindMgr);
if ((pFindMgr) && (pFindMgr->CanFindAgain()))
pCmdUI->Enable(TRUE);
else
pCmdUI->Enable(FALSE);
}
LONG PgDocumentFrame::OnFindReplace(WPARAM wParam, LPARAM lParam) // WM_FINDREPLACE
{
QCProtocol *pProtocol;
QCFindMgr *pFindMgr = QCFindMgr::GetFindMgr();
ASSERT(pFindMgr);
if (!pFindMgr)
return (EuFIND_ERROR);
// This is our internal message to ask if we support find.
// Return non-zero (TRUE).
if (pFindMgr->IsAck(wParam, lParam))
return (EuFIND_ACK_YES);
LPFINDREPLACE lpFR = (LPFINDREPLACE) lParam;
ASSERT(lpFR);
if (!lpFR)
return (EuFIND_ERROR);
if (lpFR->Flags & FR_DIALOGTERM)
{
ASSERT(0); // Should never fwd a terminating msg
return (EuFIND_ERROR);
}
CWnd *pwndFocus = GetActiveView();
if(!pwndFocus)
return (EuFIND_ERROR);
pProtocol = QCProtocol::QueryProtocol( QCP_FIND, pwndFocus );
if( ( pProtocol != NULL ) &&
( pProtocol->DoFindNext( lpFR->lpstrFindWhat, (lpFR->Flags & FR_MATCHCASE), (lpFR->Flags & FR_WHOLEWORD), TRUE) ) )
{
// activate the window
pwndFocus->GetParentFrame()->ActivateFrame();
return (EuFIND_OK);
}
return (EuFIND_NOTFOUND);
}
void PgDocumentFrame::OnContextMenu(CWnd* pWnd, CPoint point)
{
// Get the menu that contains all the context popups
CMenu menu;
HMENU hMenu = ::QCLoadMenu(IDR_CONTEXT_POPUPS);
if (!hMenu || !menu.Attach(hMenu))
{
ASSERT(0); // resources hosed?
return;
}
// MP_POPUP_RECEIVED_MSG is the offset for the read message submenu.
CMenu* pMenuPopup = menu.GetSubMenu(MP_POPUP_COMP_MSG);
if (!pMenuPopup)
ASSERT(0); // resources hosed?
else
{
//
// Since the popup menu we get from GetSubMenu() is a pointer
// to a temporary object, let's make a local copy of the
// object so that we have explicit control over its lifetime.
//
// Note that we edit the context menu on-the-fly in order to
// stick in the latest/greatest Transfer menu, display the
// edited context menu, then remove the Transfer menu.
//
CMenu tempPopupMenu;
tempPopupMenu.Attach(pMenuPopup->GetSafeHmenu());
tempPopupMenu.DeleteMenu(ID_EDIT_PASTE_SPECIAL, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(ID_EDIT_PASTEASQUOTATION, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(ID_MESSAGE_ATTACHFILE, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(ID_MESSAGE_SENDAGAIN, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(ID_MESSAGE_CHANGEQUEUEING, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(ID_SEARCH_MAILBOX_FOR_SEL, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(ID_SEARCH_MAILFOLDER_FOR_SEL, MF_BYCOMMAND);
tempPopupMenu.DeleteMenu(6, MF_BYPOSITION); // a separator...
CContextMenu::MatchCoordinatesToWindow(pWnd->GetSafeHwnd(), point);
CContextMenu(&tempPopupMenu, point.x, point.y);
VERIFY(tempPopupMenu.Detach());
}
menu.DestroyMenu();
}
void PgDocumentFrame::OnCheckSpelling()
{
// Shareware: In reduced feature mode, you cannot spell check
if (UsingFullFeatureSet())
{
// FULL FEATURE mode
CView* View = GetActiveView();
if(!View)
return;
QCProtocol* pProtocol = QCProtocol::QueryProtocol( QCP_SPELL, View );
if (pProtocol && ((CPaigeEdtView*)pProtocol)->HasSelection())
{
if(pProtocol->CheckSpelling(FALSE)==NO_MISSPELLINGS)
::MessageBox( NULL, (LPCTSTR)CRString(IDS_SPELL_NO_MISSPELLINGS),
(LPCTSTR)CRString(IDS_EUDORA), MB_OK);
}
else
{
int nBodyResult = NO_MISSPELLINGS;
if (pProtocol)
nBodyResult = pProtocol->CheckSpelling(FALSE);
if (nBodyResult == NO_MISSPELLINGS)
AfxMessageBox(IDS_SPELL_NO_MISSPELLINGS);
}
}
} | 28.416476 | 129 | 0.741263 | dusong7 |
3ae669a429c9317bf7aaf012f1978155587393f9 | 2,885 | cpp | C++ | TwoDimensionalArrays/Exercise.Var.3.cpp | melnychenkohub/Elementary | 80947a62466b54b1e78ece7811384960adbf31a0 | [
"Unlicense"
] | null | null | null | TwoDimensionalArrays/Exercise.Var.3.cpp | melnychenkohub/Elementary | 80947a62466b54b1e78ece7811384960adbf31a0 | [
"Unlicense"
] | null | null | null | TwoDimensionalArrays/Exercise.Var.3.cpp | melnychenkohub/Elementary | 80947a62466b54b1e78ece7811384960adbf31a0 | [
"Unlicense"
] | null | null | null | #include <iostream>
using std::cout;
#include "DynamicCreateArray.h"
#include "FillArray.h"
#include "PrintArray.h"
#include "DynamicDeleteArray.h"
void Var3(void)
{
cout << "\nExercise. Variant 3 start.";
int row = 0, column = 0;
int **arr = DynamicCrteIntArr(row, column);
FillArr(arr, row, column);
const bool show = 0; // if show true, show uncompressed print; else compressed print;
PrintArr(arr, row, column, show);
int i, j, countColmn = 0; // 1) start.
for (j = 0; j < column; j++)
{
for (i = 0; i < row; i++)
{
if (0 == *(*(arr + i) + j))
{
countColmn++;
break;
}
}
}
cout << "Amount column with 0: " << countColmn << " of " << column << ".\n"; // 1) end.
int a, k, count = 0, arrSeriaIndx = 0, memIndx = 0; // 2) start.
// NOTE: The greater the array, the greater the value to be entered to sizeInfoArr.
const int sizeInfoArr = row * column; // const value for dynamic memory allocation without request;
int *const maxSeriaInRowArr = DynamicCrteIntArr(sizeInfoArr);
int *const rowIndxWithMaxSeriaArr = DynamicCrteIntArr(sizeInfoArr);
int *const numArr = DynamicCrteIntArr(sizeInfoArr);
int *const memIndxArr = new int[column];
bool flag = 0;
for (a = 0; a < row; a++)
{
for (i = 0; i < column; i++)
{
for (k = 0; k < memIndx; k++) // block search duplicate values of indexes;
{
if (i == *(memIndxArr + k))
{
flag = 1;
break;
}
}
if (flag) // block skip iteration, if found duplicate values of indexes;
{
flag = 0;
continue;
}
for (j = 0; j < column; j++)
{
if (*(*(arr + a) + i) == *(*(arr + a) + j)) // important, all info, counter block;
{
count++;
flag = 1;
}
if (count > 1 && flag) // block writes duplicate values of indexes;
{
*(memIndxArr + memIndx++) = j;
flag = 0;
}
}
if (count > 1) // block writes all info to appropriate arrays;
{
if (sizeInfoArr > arrSeriaIndx)
{
*(numArr + arrSeriaIndx) = *(*(arr + a) + i);
*(maxSeriaInRowArr + arrSeriaIndx) = count;
*(rowIndxWithMaxSeriaArr + arrSeriaIndx) = a;
arrSeriaIndx++;
}
}
count = 0;
}
memIndx = 0;
}
if (arrSeriaIndx > 0)
{
cout << "Info on all series of equal numbers in a row(s) in this array:\n";
for (i = 0; i < arrSeriaIndx; i++)
{
cout << "Seria of " << *(maxSeriaInRowArr + i) << " equal numbers: " << *(numArr + i) << ", in this array, are in " << *(rowIndxWithMaxSeriaArr + i) << " row.\n";
}
}
else
cout << "A series of identical numbers in any row(s) is not found in the array.\n"; // 2) end.
DynamicDelArr(arr, row);
DynamicDelArr(maxSeriaInRowArr);
DynamicDelArr(rowIndxWithMaxSeriaArr);
DynamicDelArr(numArr);
DynamicDelArr(memIndxArr);
cout << "Exercise. Variant 3 end.\n";
cout << "..................................................................\n\n";
} | 28.284314 | 165 | 0.578856 | melnychenkohub |
3aea9af5ec3bb7cd0546bbb889bc7e06189ccd99 | 123 | cpp | C++ | docs/mfc/reference/codesnippet/CPP/ctreectrl-class_8.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 14 | 2018-01-28T18:10:55.000Z | 2021-11-16T13:21:18.000Z | docs/mfc/reference/codesnippet/CPP/ctreectrl-class_8.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | null | null | null | docs/mfc/reference/codesnippet/CPP/ctreectrl-class_8.cpp | jmittert/cpp-docs | cea5a8ee2b4764b2bac4afe5d386362ffd64e55a | [
"CC-BY-4.0",
"MIT"
] | 2 | 2018-10-10T07:37:30.000Z | 2019-06-21T15:18:07.000Z | // Delete all of the items from the tree control.
m_TreeCtrl.DeleteAllItems();
ASSERT(m_TreeCtrl.GetCount() == 0); | 41 | 52 | 0.699187 | jmittert |
3aec70c3f1f15b7b64b06a9b1241b1cfc4d54569 | 1,355 | cpp | C++ | include/hydro/system/HSetter.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/system/HSetter.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | include/hydro/system/HSetter.cpp | hydraate/hydro | 42037a8278dcfdca68fb5cceaf6988da861f0eff | [
"Apache-2.0"
] | null | null | null | //
// __ __ __
// / / / /__ __ ____/ /_____ ____
// / /_/ // / / // __ // ___// __ \
// / __ // /_/ // /_/ // / / /_/ /
// /_/ /_/ \__, / \__,_//_/ \____/
// /____/
//
// The Hydro Programming Language
//
#include "HSetter.hpp"
#include "HProperty.hpp"
#include "HvmEnv.hpp"
namespace hydro
{
HSetter::HSetter(HvmEnv *env, HClass *setterClass, const VM_Setter *vsetter, HProperty *ownerProperty, function_glue *glue) : HObject{env, setterClass}, RuntimeContext{ownerProperty->ownerClass()}, _vsetter{vsetter}, _glue{glue} {}
HSetter::~HSetter() {}
void HSetter::set(HvmContext *threadContext, VM *vm, HObject *instance, const hvalue value)
{
if(!_glue)
{
// auto property
auto fields = instance->mContext->fields;
uint32_t n = instance->mContext->_size;
for(uint32_t i = 0; i < n; i++)
{
if(fields[i]->data == _vsetter->property)
{
fields[i]->value = value;
return;
}
}
// fail
return;
}
std::list<hvalue> args;
args.push_back(value);
_glue->call(threadContext, this, vm, args, instance);
}
} // namespace hydro
| 26.568627 | 231 | 0.487823 | hydraate |
3af0ee64eb0299c498ea63f459f12f19327bf61a | 222 | hpp | C++ | include/Game/notification.hpp | Lucrecious/DungeonGame | 9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5 | [
"MIT"
] | null | null | null | include/Game/notification.hpp | Lucrecious/DungeonGame | 9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5 | [
"MIT"
] | null | null | null | include/Game/notification.hpp | Lucrecious/DungeonGame | 9e427c4eba18cdc0aa93a6e28e505a8ecb1357e5 | [
"MIT"
] | null | null | null | #ifndef NOTIFICATION_H
#define NOTIFICATION_H
#include <Game/turn.hpp>
#include <Global/kind.hpp>
class Notification {
public:
virtual Turn getInput() const = 0;
virtual void notify(Vector, Kind) const = 0;
};
#endif
| 15.857143 | 45 | 0.738739 | Lucrecious |
3af46d95e7b17d1be3192e5d54cc88cb3a440ea1 | 8,637 | cc | C++ | xls/passes/dfe_pass_test.cc | RobSpringer/xls | a5521c7ecbd1a071828760cf429d74810f248681 | [
"Apache-2.0"
] | null | null | null | xls/passes/dfe_pass_test.cc | RobSpringer/xls | a5521c7ecbd1a071828760cf429d74810f248681 | [
"Apache-2.0"
] | null | null | null | xls/passes/dfe_pass_test.cc | RobSpringer/xls | a5521c7ecbd1a071828760cf429d74810f248681 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 The XLS 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 "xls/passes/dfe_pass.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "xls/common/status/matchers.h"
#include "xls/ir/function.h"
#include "xls/ir/function_builder.h"
#include "xls/ir/ir_test_base.h"
#include "xls/passes/pass_base.h"
namespace xls {
namespace {
using status_testing::IsOkAndHolds;
using status_testing::StatusIs;
class DeadFunctionEliminationPassTest : public IrTestBase {
protected:
DeadFunctionEliminationPassTest() = default;
absl::StatusOr<bool> Run(Package* p) {
PassResults results;
return DeadFunctionEliminationPass().Run(p, PassOptions(), &results);
}
absl::StatusOr<Function*> MakeFunction(absl::string_view name, Package* p) {
FunctionBuilder fb(name, p);
fb.Param("arg", p->GetBitsType(32));
return fb.Build();
}
};
TEST_F(DeadFunctionEliminationPassTest, NoDeadFunctions) {
auto p = std::make_unique<Package>(TestName());
XLS_ASSERT_OK_AND_ASSIGN(Function * a, MakeFunction("a", p.get()));
XLS_ASSERT_OK_AND_ASSIGN(Function * b, MakeFunction("b", p.get()));
FunctionBuilder fb("the_entry", p.get());
BValue x = fb.Param("x", p->GetBitsType(32));
fb.Add(fb.Invoke({x}, a), fb.Invoke({x}, b));
XLS_ASSERT_OK(fb.Build().status());
XLS_ASSERT_OK(p->SetTopByName("the_entry"));
EXPECT_EQ(p->functions().size(), 3);
EXPECT_THAT(Run(p.get()), IsOkAndHolds(false));
EXPECT_EQ(p->functions().size(), 3);
}
TEST_F(DeadFunctionEliminationPassTest, OneDeadFunction) {
auto p = std::make_unique<Package>(TestName());
XLS_ASSERT_OK_AND_ASSIGN(Function * a, MakeFunction("a", p.get()));
XLS_ASSERT_OK(MakeFunction("dead", p.get()).status());
FunctionBuilder fb("the_entry", p.get());
BValue x = fb.Param("x", p->GetBitsType(32));
fb.Add(fb.Invoke({x}, a), fb.Invoke({x}, a));
XLS_ASSERT_OK(fb.Build().status());
XLS_ASSERT_OK(p->SetTopByName("the_entry"));
EXPECT_EQ(p->functions().size(), 3);
EXPECT_THAT(Run(p.get()), IsOkAndHolds(true));
EXPECT_EQ(p->functions().size(), 2);
}
TEST_F(DeadFunctionEliminationPassTest, OneDeadFunctionButNoEntry) {
// If no entry function is specified, then DFS cannot happen as all functions
// are live.
auto p = std::make_unique<Package>(TestName());
XLS_ASSERT_OK_AND_ASSIGN(Function * a, MakeFunction("a", p.get()));
XLS_ASSERT_OK(MakeFunction("dead", p.get()).status());
FunctionBuilder fb("blah", p.get());
BValue x = fb.Param("x", p->GetBitsType(32));
fb.Add(fb.Invoke({x}, a), fb.Invoke({x}, a));
XLS_ASSERT_OK(fb.Build().status());
EXPECT_EQ(p->functions().size(), 3);
EXPECT_THAT(Run(p.get()), IsOkAndHolds(false));
EXPECT_EQ(p->functions().size(), 3);
}
TEST_F(DeadFunctionEliminationPassTest, ProcCallingFunction) {
auto p = std::make_unique<Package>(TestName());
XLS_ASSERT_OK_AND_ASSIGN(Function * f,
MakeFunction("called_by_proc", p.get()));
XLS_ASSERT_OK(MakeFunction("not_called_by_proc", p.get()).status());
TokenlessProcBuilder b(TestName(), Value(UBits(0, 32)), "tkn", "st", p.get());
BValue invoke = b.Invoke({b.GetStateParam()}, f);
XLS_ASSERT_OK_AND_ASSIGN(Proc * proc, b.Build(invoke));
XLS_ASSERT_OK(p->SetTop(proc));
EXPECT_EQ(p->functions().size(), 2);
XLS_EXPECT_OK(p->GetFunction("not_called_by_proc").status());
EXPECT_THAT(Run(p.get()), IsOkAndHolds(true));
EXPECT_EQ(p->functions().size(), 1);
EXPECT_THAT(p->GetFunction("not_called_by_proc"),
StatusIs(absl::StatusCode::kNotFound));
}
TEST_F(DeadFunctionEliminationPassTest, MultipleProcs) {
auto p = std::make_unique<Package>(TestName());
Type* u32 = p->GetBitsType(32);
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch_in_a,
p->CreateStreamingChannel("in_a", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch_out_a,
p->CreateStreamingChannel("out_a", ChannelOps::kSendOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch_a_to_b,
p->CreateStreamingChannel("a_to_b", ChannelOps::kSendReceive, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch_b_to_a,
p->CreateStreamingChannel("b_to_a", ChannelOps::kSendReceive, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch_in_c,
p->CreateStreamingChannel("in_c", ChannelOps::kReceiveOnly, u32));
XLS_ASSERT_OK_AND_ASSIGN(
Channel * ch_out_c,
p->CreateStreamingChannel("out_c", ChannelOps::kSendOnly, u32));
{
TokenlessProcBuilder b("A", Value::Tuple({}), "tkn", "st", p.get());
b.Send(ch_a_to_b, b.Receive(ch_in_a));
b.Send(ch_out_a, b.Receive(ch_b_to_a));
XLS_ASSERT_OK_AND_ASSIGN(Proc * a, b.Build(b.GetStateParam()));
XLS_ASSERT_OK(p->SetTop(a));
}
{
TokenlessProcBuilder b("B", Value::Tuple({}), "tkn", "st", p.get());
b.Send(ch_b_to_a, b.Receive(ch_a_to_b));
XLS_ASSERT_OK(b.Build(b.GetStateParam()).status());
}
{
TokenlessProcBuilder b("C", Value::Tuple({}), "tkn", "st", p.get());
b.Send(ch_out_c, b.Receive(ch_in_c));
XLS_ASSERT_OK(b.Build(b.GetStateParam()).status());
}
// Proc "C" should be removed as well as the its channels.
EXPECT_EQ(p->procs().size(), 3);
XLS_EXPECT_OK(p->GetProc("C").status());
EXPECT_EQ(p->channels().size(), 6);
XLS_EXPECT_OK(p->GetChannel("in_c").status());
XLS_EXPECT_OK(p->GetChannel("out_c").status());
EXPECT_THAT(Run(p.get()), IsOkAndHolds(true));
EXPECT_EQ(p->procs().size(), 2);
EXPECT_THAT(p->GetProc("C"), StatusIs(absl::StatusCode::kNotFound));
EXPECT_EQ(p->channels().size(), 4);
EXPECT_THAT(p->GetChannel("in_c").status(),
StatusIs(absl::StatusCode::kNotFound));
EXPECT_THAT(p->GetChannel("out_c"), StatusIs(absl::StatusCode::kNotFound));
}
TEST_F(DeadFunctionEliminationPassTest, MapAndCountedFor) {
// If no entry function is specified, then DFS cannot happen as all functions
// are live.
auto p = std::make_unique<Package>(TestName());
XLS_ASSERT_OK_AND_ASSIGN(Function * a, MakeFunction("a", p.get()));
Function* body;
{
FunctionBuilder fb("jesse_the_loop_body", p.get());
fb.Param("i", p->GetBitsType(32));
fb.Param("arg", p->GetBitsType(32));
fb.Literal(UBits(123, 32));
XLS_ASSERT_OK_AND_ASSIGN(body, fb.Build());
}
FunctionBuilder fb("the_entry", p.get());
BValue x = fb.Param("x", p->GetBitsType(32));
BValue ar = fb.Param("ar", p->GetArrayType(42, p->GetBitsType(32)));
BValue mapped_ar = fb.Map(ar, a);
BValue for_loop = fb.CountedFor(x, /*trip_count=*/42, /*stride=*/1, body);
fb.Tuple({mapped_ar, for_loop});
XLS_ASSERT_OK(fb.Build().status());
XLS_ASSERT_OK(p->SetTopByName("the_entry"));
EXPECT_EQ(p->functions().size(), 3);
EXPECT_THAT(Run(p.get()), IsOkAndHolds(false));
EXPECT_EQ(p->functions().size(), 3);
}
TEST_F(DeadFunctionEliminationPassTest, BlockWithInstantiation) {
auto p = CreatePackage();
Type* u32 = p->GetBitsType(32);
auto build_subblock = [&](absl::string_view name) -> absl::StatusOr<Block*> {
BlockBuilder bb(name, p.get());
bb.OutputPort("out", bb.InputPort("in", u32));
return bb.Build();
};
XLS_ASSERT_OK_AND_ASSIGN(Block * used_subblock,
build_subblock("used_subblock"));
XLS_ASSERT_OK(build_subblock("unused_subblock").status());
BlockBuilder bb("my_block", p.get());
XLS_ASSERT_OK_AND_ASSIGN(
Instantiation * instantiation,
bb.block()->AddBlockInstantiation("inst", used_subblock));
BValue in = bb.InputPort("in0", u32);
bb.InstantiationInput(instantiation, "in", in);
BValue inst_out = bb.InstantiationOutput(instantiation, "out");
bb.OutputPort("out", inst_out);
XLS_ASSERT_OK_AND_ASSIGN(Block * top, bb.Build());
XLS_ASSERT_OK(p->SetTop(top));
EXPECT_EQ(p->blocks().size(), 3);
XLS_EXPECT_OK(p->GetBlock("unused_subblock").status());
EXPECT_THAT(Run(p.get()), IsOkAndHolds(true));
EXPECT_EQ(p->blocks().size(), 2);
EXPECT_THAT(p->GetBlock("unused_subblock"),
StatusIs(absl::StatusCode::kNotFound));
}
} // namespace
} // namespace xls
| 36.138075 | 80 | 0.687739 | RobSpringer |
3af6836350ca35b4fa05f2778ab19d4c86900e94 | 3,436 | cpp | C++ | Runtime/Weapon/CWeapon.cpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | null | null | null | Runtime/Weapon/CWeapon.cpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | null | null | null | Runtime/Weapon/CWeapon.cpp | Jcw87/urde | fb9ea9092ad00facfe957ece282a86c194e9cbda | [
"MIT"
] | null | null | null | #include "Runtime/Weapon/CWeapon.hpp"
#include "Runtime/CStateManager.hpp"
#include "Runtime/World/CActorParameters.hpp"
#include "Runtime/World/CScriptWater.hpp"
#include "TCastTo.hpp" // Generated file, do not modify include path
namespace metaforce {
CWeapon::CWeapon(TUniqueId uid, TAreaId aid, bool active, TUniqueId owner, EWeaponType type, std::string_view name,
const zeus::CTransform& xf, const CMaterialFilter& filter, const CMaterialList& mList,
const CDamageInfo& dInfo, EProjectileAttrib attribs, CModelData&& mData)
: CActor(uid, active, name, CEntityInfo(aid, CEntity::NullConnectionList), xf, std::move(mData), mList,
CActorParameters::None().HotInThermal(true), kInvalidUniqueId)
, xe8_projectileAttribs(attribs)
, xec_ownerId(owner)
, xf0_weaponType(type)
, xf8_filter(filter)
, x110_origDamageInfo(dInfo)
, x12c_curDamageInfo(dInfo) {}
void CWeapon::Accept(metaforce::IVisitor& visitor) { visitor.Visit(this); }
void CWeapon::Think(float dt, CStateManager& mgr) {
x148_curTime += dt;
if ((xe8_projectileAttribs & EProjectileAttrib::DamageFalloff) == EProjectileAttrib::DamageFalloff) {
float damMul = std::max(0.f, 1.f - x148_curTime * x14c_damageFalloffSpeed);
x12c_curDamageInfo.SetDamage(x110_origDamageInfo.GetDamage() * damMul);
x12c_curDamageInfo.SetRadius(x110_origDamageInfo.GetRadius() * damMul);
x12c_curDamageInfo.SetKnockBackPower(x110_origDamageInfo.GetKnockBackPower() * damMul);
x12c_curDamageInfo.SetWeaponMode(x110_origDamageInfo.GetWeaponMode());
x12c_curDamageInfo.SetNoImmunity(false);
} else {
x12c_curDamageInfo = x110_origDamageInfo;
}
CEntity::Think(dt, mgr);
}
void CWeapon::Render(CStateManager&) {
// Empty
}
EWeaponCollisionResponseTypes CWeapon::GetCollisionResponseType(const zeus::CVector3f&, const zeus::CVector3f&,
const CWeaponMode&, EProjectileAttrib) const {
return EWeaponCollisionResponseTypes::Projectile;
}
void CWeapon::FluidFXThink(EFluidState state, CScriptWater& water, CStateManager& mgr) {
bool doRipple = true;
float mag = 0.f;
switch (xf0_weaponType) {
case EWeaponType::Power:
mag = 0.1f;
break;
case EWeaponType::Ice:
mag = 0.3f;
break;
case EWeaponType::Wave:
mag = 0.1f;
break;
case EWeaponType::Plasma:
break;
case EWeaponType::Missile:
mag = 0.5f;
break;
case EWeaponType::Phazon:
mag = 0.1f;
break;
default:
doRipple = false;
break;
}
if (True(xe8_projectileAttribs & EProjectileAttrib::ComboShot) &&
state != EFluidState::InFluid)
mag += 0.5f;
if (True(xe8_projectileAttribs & EProjectileAttrib::Charged))
mag += 0.25f;
if (mag > 1.f)
mag = 1.f;
if (doRipple) {
zeus::CVector3f pos = GetTranslation();
pos.z() = float(water.GetTriggerBoundsWR().max.z());
if (True(xe8_projectileAttribs & EProjectileAttrib::ComboShot)) {
if (!water.CanRippleAtPoint(pos))
doRipple = false;
} else if (state == EFluidState::InFluid) {
doRipple = false;
}
if (doRipple) {
water.GetFluidPlane().AddRipple(mag, x8_uid, pos, water, mgr);
mgr.GetFluidPlaneManager()->CreateSplash(x8_uid, mgr, water, pos, mag,
state == EFluidState::EnteredFluid || state == EFluidState::LeftFluid);
}
}
}
} // namespace metaforce
| 33.686275 | 118 | 0.688882 | Jcw87 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.