hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 77k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 653k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5556856e69e58b93e63f1d6ae863a06e8f85eec1 | 1,160 | cc | C++ | src/node_linux.cc | cuijinyu/node-mechine-code | edd1a4f58f0baf49e272f85426a4afcc762e7ddc | [
"MIT"
] | 11 | 2018-09-07T07:54:29.000Z | 2022-01-26T03:23:10.000Z | src/node_linux.cc | cuijinyu/node-mechine-code | edd1a4f58f0baf49e272f85426a4afcc762e7ddc | [
"MIT"
] | null | null | null | src/node_linux.cc | cuijinyu/node-mechine-code | edd1a4f58f0baf49e272f85426a4afcc762e7ddc | [
"MIT"
] | 1 | 2019-05-25T05:38:46.000Z | 2019-05-25T05:38:46.000Z | #include "mechine_linux.cc"
#include<node.h>
#include<iostream>
namespace demo {
using std::cout;
using std::endl;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Exception;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate * isolate = args.GetIsolate();
map<string, string> infos = getInfo();
const char * cpuId = infos["cpuId"].data();
const char * baseBoard = infos["baseBoard"].data();
const char * macAddress = infos["macAddress"].data();
cout << "cpuId---->" <<cpuId;
cout << "baseBoard---->" <<baseBoard;
cout << "macAddress---->" <<macAddress;
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "processorId"), String::NewFromUtf8(isolate, cpuId));
obj->Set(String::NewFromUtf8(isolate, "baseBoard"), String::NewFromUtf8(isolate, baseBoard));
obj->Set(String::NewFromUtf8(isolate, "macAddress"), String::NewFromUtf8(isolate, macAddress));
args.GetReturnValue().Set(obj);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "exports", Method);
}
NODE_MODULE(addon, init);
} | 32.222222 | 97 | 0.693966 |
555e005b05ac3829addccd594298ddd68e224ec4 | 14,462 | cpp | C++ | renderdoc/driver/gl/gl_replay_win32.cpp | yangzhengxing/renderdoc | 214450227ea96df0b2b079632b1f20e23a3fd8fe | [
"MIT"
] | null | null | null | renderdoc/driver/gl/gl_replay_win32.cpp | yangzhengxing/renderdoc | 214450227ea96df0b2b079632b1f20e23a3fd8fe | [
"MIT"
] | null | null | null | renderdoc/driver/gl/gl_replay_win32.cpp | yangzhengxing/renderdoc | 214450227ea96df0b2b079632b1f20e23a3fd8fe | [
"MIT"
] | null | null | null | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015-2017 Baldur Karlsson
* Copyright (c) 2014 Crytek
*
* 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 "gl_replay.h"
#include "gl_driver.h"
#include "gl_resources.h"
PFNWGLCREATECONTEXTATTRIBSARBPROC createContextAttribs = NULL;
PFNWGLGETPIXELFORMATATTRIBIVARBPROC getPixelFormatAttrib = NULL;
typedef PROC(WINAPI *WGLGETPROCADDRESSPROC)(const char *);
typedef HGLRC(WINAPI *WGLCREATECONTEXTPROC)(HDC);
typedef BOOL(WINAPI *WGLMAKECURRENTPROC)(HDC, HGLRC);
typedef BOOL(WINAPI *WGLDELETECONTEXTPROC)(HGLRC);
WGLGETPROCADDRESSPROC wglGetProc = NULL;
WGLCREATECONTEXTPROC wglCreateRC = NULL;
WGLMAKECURRENTPROC wglMakeCurrentProc = NULL;
WGLDELETECONTEXTPROC wglDeleteRC = NULL;
void GLReplay::MakeCurrentReplayContext(GLWindowingData *ctx)
{
static GLWindowingData *prev = NULL;
if(wglMakeCurrentProc && ctx && ctx != prev)
{
prev = ctx;
wglMakeCurrentProc(ctx->DC, ctx->ctx);
m_pDriver->ActivateContext(*ctx);
}
}
void GLReplay::SwapBuffers(GLWindowingData *ctx)
{
::SwapBuffers(ctx->DC);
}
void GLReplay::CloseReplayContext()
{
if(wglDeleteRC)
{
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(m_ReplayCtx.ctx);
ReleaseDC(m_ReplayCtx.wnd, m_ReplayCtx.DC);
::DestroyWindow(m_ReplayCtx.wnd);
}
}
uint64_t GLReplay::MakeOutputWindow(WindowingSystem system, void *data, bool depth)
{
RDCASSERT(system == eWindowingSystem_Win32 || system == eWindowingSystem_Unknown, system);
HWND w = (HWND)data;
if(w == NULL)
w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
GetModuleHandle(NULL), NULL);
HDC DC = GetDC(w);
PIXELFORMATDESCRIPTOR pfd = {0};
int attrib = eWGL_NUMBER_PIXEL_FORMATS_ARB;
int value = 1;
getPixelFormatAttrib(DC, 1, 0, 1, &attrib, &value);
int pf = 0;
int numpfs = value;
for(int i = 1; i <= numpfs; i++)
{
// verify that we have the properties we want
attrib = eWGL_DRAW_TO_WINDOW_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value == 0)
continue;
attrib = eWGL_ACCELERATION_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value == eWGL_NO_ACCELERATION_ARB)
continue;
attrib = eWGL_SUPPORT_OPENGL_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value == 0)
continue;
attrib = eWGL_DOUBLE_BUFFER_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value == 0)
continue;
attrib = eWGL_PIXEL_TYPE_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value != eWGL_TYPE_RGBA_ARB)
continue;
// we have an opengl-capable accelerated RGBA context.
// we use internal framebuffers to do almost all rendering, so we just need
// RGB (color bits > 24) and SRGB buffer.
attrib = eWGL_COLOR_BITS_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value < 24)
continue;
attrib = WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB;
getPixelFormatAttrib(DC, i, 0, 1, &attrib, &value);
if(value == 0)
continue;
// this one suits our needs, choose it
pf = i;
break;
}
if(pf == 0)
{
ReleaseDC(w, DC);
RDCERR("Couldn't choose pixel format");
return NULL;
}
BOOL res = DescribePixelFormat(DC, pf, sizeof(pfd), &pfd);
if(res == FALSE)
{
ReleaseDC(w, DC);
RDCERR("Couldn't describe pixel format");
return NULL;
}
res = SetPixelFormat(DC, pf, &pfd);
if(res == FALSE)
{
ReleaseDC(w, DC);
RDCERR("Couldn't set pixel format");
return NULL;
}
int attribs[64] = {0};
int i = 0;
attribs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
attribs[i++] = GLCoreVersion / 10;
attribs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB;
attribs[i++] = GLCoreVersion % 10;
attribs[i++] = WGL_CONTEXT_FLAGS_ARB;
#if ENABLED(RDOC_DEVEL)
attribs[i++] = WGL_CONTEXT_DEBUG_BIT_ARB;
#else
attribs[i++] = 0;
#endif
attribs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB;
attribs[i++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
HGLRC rc = createContextAttribs(DC, m_ReplayCtx.ctx, attribs);
if(rc == NULL)
{
ReleaseDC(w, DC);
RDCERR("Couldn't create %d.%d context - something changed since creation", GLCoreVersion / 10,
GLCoreVersion % 10);
return 0;
}
OutputWindow win;
win.DC = DC;
win.ctx = rc;
win.wnd = w;
RECT rect = {0};
GetClientRect(w, &rect);
win.width = rect.right - rect.left;
win.height = rect.bottom - rect.top;
m_pDriver->RegisterContext(win, m_ReplayCtx.ctx, true, true);
InitOutputWindow(win);
CreateOutputWindowBackbuffer(win, depth);
uint64_t ret = m_OutputWindowID++;
m_OutputWindows[ret] = win;
return ret;
}
void GLReplay::DestroyOutputWindow(uint64_t id)
{
auto it = m_OutputWindows.find(id);
if(id == 0 || it == m_OutputWindows.end())
return;
OutputWindow &outw = it->second;
MakeCurrentReplayContext(&outw);
WrappedOpenGL &gl = *m_pDriver;
gl.glDeleteFramebuffers(1, &outw.BlitData.readFBO);
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(outw.ctx);
ReleaseDC(outw.wnd, outw.DC);
m_OutputWindows.erase(it);
}
void GLReplay::GetOutputWindowDimensions(uint64_t id, int32_t &w, int32_t &h)
{
if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end())
return;
OutputWindow &outw = m_OutputWindows[id];
RECT rect = {0};
GetClientRect(outw.wnd, &rect);
w = rect.right - rect.left;
h = rect.bottom - rect.top;
}
bool GLReplay::IsOutputWindowVisible(uint64_t id)
{
if(id == 0 || m_OutputWindows.find(id) == m_OutputWindows.end())
return false;
return (IsWindowVisible(m_OutputWindows[id].wnd) == TRUE);
}
const GLHookSet &GetRealGLFunctions();
ReplayCreateStatus GL_CreateReplayDevice(const char *logfile, IReplayDriver **driver)
{
RDCDEBUG("Creating an OpenGL replay device");
HMODULE lib = NULL;
lib = LoadLibraryA("opengl32.dll");
if(lib == NULL)
{
RDCERR("Failed to load opengl32.dll");
return eReplayCreate_APIInitFailed;
}
GLInitParams initParams;
RDCDriver driverType = RDC_OpenGL;
string driverName = "OpenGL";
uint64_t machineIdent = 0;
if(logfile)
{
auto status = RenderDoc::Inst().FillInitParams(logfile, driverType, driverName, machineIdent,
(RDCInitParams *)&initParams);
if(status != eReplayCreate_Success)
return status;
}
PIXELFORMATDESCRIPTOR pfd = {0};
if(wglGetProc == NULL)
{
wglGetProc = (WGLGETPROCADDRESSPROC)GetProcAddress(lib, "wglGetProcAddress");
wglCreateRC = (WGLCREATECONTEXTPROC)GetProcAddress(lib, "wglCreateContext");
wglMakeCurrentProc = (WGLMAKECURRENTPROC)GetProcAddress(lib, "wglMakeCurrent");
wglDeleteRC = (WGLDELETECONTEXTPROC)GetProcAddress(lib, "wglDeleteContext");
if(wglGetProc == NULL || wglCreateRC == NULL || wglMakeCurrentProc == NULL || wglDeleteRC == NULL)
{
RDCERR("Couldn't get wgl function addresses");
return eReplayCreate_APIInitFailed;
}
WNDCLASSEX wc;
RDCEraseEl(wc);
wc.style = CS_OWNDC;
wc.cbSize = sizeof(WNDCLASSEX);
wc.lpfnWndProc = DefWindowProc;
wc.hInstance = GetModuleHandle(NULL);
wc.hCursor = LoadCursor(NULL, IDC_ARROW);
wc.lpszClassName = L"renderdocGLclass";
if(!RegisterClassEx(&wc))
{
RDCERR("Couldn't register GL window class");
return eReplayCreate_APIInitFailed;
}
RDCEraseEl(pfd);
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iLayerType = PFD_MAIN_PLANE;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 24;
pfd.cStencilBits = 0;
}
HWND w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"", WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL,
GetModuleHandle(NULL), NULL);
HDC dc = GetDC(w);
int pf = ChoosePixelFormat(dc, &pfd);
if(pf == 0)
{
RDCERR("Couldn't choose pixel format");
return eReplayCreate_APIInitFailed;
}
BOOL res = SetPixelFormat(dc, pf, &pfd);
if(res == FALSE)
{
RDCERR("Couldn't set pixel format");
return eReplayCreate_APIInitFailed;
}
HGLRC rc = wglCreateRC(dc);
if(rc == NULL)
{
RDCERR("Couldn't create simple RC");
return eReplayCreate_APIInitFailed;
}
res = wglMakeCurrentProc(dc, rc);
if(res == FALSE)
{
RDCERR("Couldn't make simple RC current");
return eReplayCreate_APIInitFailed;
}
createContextAttribs =
(PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProc("wglCreateContextAttribsARB");
getPixelFormatAttrib =
(PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProc("wglGetPixelFormatAttribivARB");
if(createContextAttribs == NULL || getPixelFormatAttrib == NULL)
{
RDCERR("RenderDoc requires WGL_ARB_create_context and WGL_ARB_pixel_format");
return eReplayCreate_APIHardwareUnsupported;
}
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(rc);
ReleaseDC(w, dc);
DestroyWindow(w);
GLReplay::PreContextInitCounters();
// we don't use the default framebuffer (backbuffer) for anything, so we make it
// tiny and with no depth/stencil bits
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 0;
pfd.cStencilBits = 0;
w = CreateWindowEx(WS_EX_CLIENTEDGE, L"renderdocGLclass", L"RenderDoc replay window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 32, 32, NULL, NULL,
GetModuleHandle(NULL), NULL);
dc = GetDC(w);
pf = ChoosePixelFormat(dc, &pfd);
if(pf == 0)
{
RDCERR("Couldn't choose pixel format");
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIInitFailed;
}
res = SetPixelFormat(dc, pf, &pfd);
if(res == FALSE)
{
RDCERR("Couldn't set pixel format");
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIInitFailed;
}
int attribs[64] = {0};
int i = 0;
attribs[i++] = WGL_CONTEXT_MAJOR_VERSION_ARB;
int &major = attribs[i];
attribs[i++] = 0;
attribs[i++] = WGL_CONTEXT_MINOR_VERSION_ARB;
int &minor = attribs[i];
attribs[i++] = 0;
attribs[i++] = WGL_CONTEXT_FLAGS_ARB;
#if ENABLED(RDOC_DEVEL)
attribs[i++] = WGL_CONTEXT_DEBUG_BIT_ARB;
#else
attribs[i++] = 0;
#endif
attribs[i++] = WGL_CONTEXT_PROFILE_MASK_ARB;
attribs[i++] = WGL_CONTEXT_CORE_PROFILE_BIT_ARB;
// try to create all versions from 4.5 down to 3.2 in order to get the
// highest versioned context we can
struct
{
int major;
int minor;
} versions[] = {
{4, 5}, {4, 4}, {4, 3}, {4, 2}, {4, 1}, {4, 0}, {3, 3}, {3, 2},
};
rc = NULL;
for(size_t v = 0; v < ARRAY_COUNT(versions); v++)
{
major = versions[v].major;
minor = versions[v].minor;
rc = createContextAttribs(dc, NULL, attribs);
if(rc)
break;
}
if(rc == NULL)
{
RDCERR("Couldn't create 3.2 RC - RenderDoc requires OpenGL 3.2 availability");
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIHardwareUnsupported;
}
GLCoreVersion = major * 10 + minor;
res = wglMakeCurrentProc(dc, rc);
if(res == FALSE)
{
RDCERR("Couldn't make 3.2 RC current");
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(rc);
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIInitFailed;
}
PFNGLGETINTEGERVPROC getInt = (PFNGLGETINTEGERVPROC)GetProcAddress(lib, "glGetIntegerv");
PFNGLGETSTRINGPROC getStr = (PFNGLGETSTRINGPROC)GetProcAddress(lib, "glGetString");
PFNGLGETSTRINGIPROC getStri = (PFNGLGETSTRINGIPROC)wglGetProc("glGetStringi");
if(getInt == NULL || getStr == NULL || getStri == NULL)
{
RDCERR("Couldn't get glGetIntegerv (%p), glGetString (%p) or glGetStringi (%p) entry points",
getInt, getStr, getStri);
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(rc);
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIInitFailed;
}
bool missingExt = CheckReplayContext(getStr, getInt, getStri);
if(missingExt)
{
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(rc);
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIInitFailed;
}
const GLHookSet &real = GetRealGLFunctions();
bool extensionsValidated = ValidateFunctionPointers(real);
if(!extensionsValidated)
{
wglMakeCurrentProc(NULL, NULL);
wglDeleteRC(rc);
ReleaseDC(w, dc);
GLReplay::PostContextShutdownCounters();
return eReplayCreate_APIInitFailed;
}
WrappedOpenGL *gl = new WrappedOpenGL(logfile, real);
gl->Initialise(initParams);
if(gl->GetSerialiser()->HasError())
{
delete gl;
return eReplayCreate_FileIOFailed;
}
RDCLOG("Created device.");
GLReplay *replay = gl->GetReplay();
replay->SetProxy(logfile == NULL);
GLWindowingData data;
data.DC = dc;
data.ctx = rc;
data.wnd = w;
replay->SetReplayData(data);
*driver = (IReplayDriver *)replay;
return eReplayCreate_Success;
}
| 27.704981 | 102 | 0.679021 |
555eb04b23df36f8bbe34884d1adb71ad6759a83 | 2,712 | cpp | C++ | src/camera/CameraParams.cpp | huskyroboticsteam/PY2020 | cd6368d85866204dbdca6aefacac69059e780aa2 | [
"Apache-2.0"
] | 11 | 2019-10-03T01:17:16.000Z | 2020-10-25T02:38:32.000Z | src/camera/CameraParams.cpp | huskyroboticsteam/PY2020 | cd6368d85866204dbdca6aefacac69059e780aa2 | [
"Apache-2.0"
] | 53 | 2019-10-03T02:11:04.000Z | 2021-06-05T03:11:55.000Z | src/camera/CameraParams.cpp | huskyroboticsteam/Resurgence | 649f78103b6d76709fdf55bb38d08c0ff50da140 | [
"Apache-2.0"
] | 3 | 2019-09-20T04:09:29.000Z | 2020-08-18T22:25:20.000Z | #include "CameraParams.h"
#include <opencv2/core.hpp>
namespace cam {
////////////// CONSTRUCTORS //////////////
CameraParams::CameraParams() {
}
void CameraParams::init(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff,
cv::Size image_size) {
if (camera_matrix.size() != cv::Size(3, 3)) {
throw std::invalid_argument("Camera matrix must be 3x3");
}
int n_coeffs = dist_coeff.rows * dist_coeff.cols;
if (!(n_coeffs == 4 || n_coeffs == 5 || n_coeffs == 8 || n_coeffs == 12 ||
n_coeffs == 14)) {
throw std::invalid_argument(
"Number of distortion coefficients must be 4, 5, 8, 12, or 14");
}
if (image_size.empty()) {
throw std::invalid_argument("Image size must not be empty");
}
dist_coeff.reshape(1, {n_coeffs, 1}).copyTo(this->_dist_coeff);
camera_matrix.copyTo(this->_camera_matrix);
this->_image_size = image_size;
}
CameraParams::CameraParams(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff,
cv::Size image_size) {
init(camera_matrix, dist_coeff, image_size);
}
CameraParams::CameraParams(const CameraParams& other) {
cv::Mat newCam, newDist;
other._camera_matrix.copyTo(newCam);
other._dist_coeff.copyTo(newDist);
this->_camera_matrix = newCam;
this->_dist_coeff = newDist;
this->_image_size = other._image_size;
}
bool CameraParams::empty() const {
return _camera_matrix.empty() || _dist_coeff.empty() || _image_size.empty();
}
////////////// ACCESSORS /////////////////
cv::Mat CameraParams::getCameraMatrix() const {
return _camera_matrix;
}
cv::Mat CameraParams::getDistCoeff() const {
return _dist_coeff;
}
cv::Size CameraParams::getImageSize() const {
return _image_size;
}
////////////// SERIALIZATION //////////////
void CameraParams::readFromFileNode(const cv::FileNode& file_node) {
cv::Mat cam, dist;
file_node[KEY_CAMERA_MATRIX] >> cam;
file_node[KEY_DIST_COEFFS] >> dist;
int w, h;
w = (int)file_node[KEY_IMAGE_WIDTH];
h = (int)file_node[KEY_IMAGE_HEIGHT];
cv::Size size(w, h);
// call init to do validation
init(cam, dist, size);
}
void CameraParams::writeToFileStorage(cv::FileStorage& file_storage) const {
file_storage << "{";
file_storage << KEY_IMAGE_WIDTH << _image_size.width;
file_storage << KEY_IMAGE_HEIGHT << _image_size.height;
file_storage << KEY_CAMERA_MATRIX << _camera_matrix;
file_storage << KEY_DIST_COEFFS << _dist_coeff;
file_storage << "}";
}
void read(const cv::FileNode& node, CameraParams& params, const CameraParams& default_value) {
if (node.empty()) {
params = default_value;
} else {
params.readFromFileNode(node);
}
}
void write(cv::FileStorage& fs, const std::string& name, const CameraParams& params) {
params.writeToFileStorage(fs);
}
} // namespace cam
| 26.851485 | 94 | 0.696165 |
5561aca0f75c7279a4e60441e8f0e6ae404732fd | 9,253 | cpp | C++ | src/heuristics/rcHeuristics/RCModelFactory.cpp | Songtuan-Lin/pandaPIengine | be019b16fec6f679fa3db31b97ccbe9491769d65 | [
"BSD-3-Clause"
] | 5 | 2021-04-06T22:06:47.000Z | 2021-07-20T14:56:13.000Z | src/heuristics/rcHeuristics/RCModelFactory.cpp | Songtuan-Lin/pandaPIengine | be019b16fec6f679fa3db31b97ccbe9491769d65 | [
"BSD-3-Clause"
] | 2 | 2021-04-07T12:17:39.000Z | 2021-09-03T10:30:26.000Z | src/heuristics/rcHeuristics/RCModelFactory.cpp | Songtuan-Lin/pandaPIengine | be019b16fec6f679fa3db31b97ccbe9491769d65 | [
"BSD-3-Clause"
] | 6 | 2021-06-16T13:41:06.000Z | 2022-03-30T07:13:18.000Z | /*
* RCModelFactory.cpp
*
* Created on: 09.02.2020
* Author: dh
*/
#include "RCModelFactory.h"
namespace progression {
RCModelFactory::RCModelFactory(Model* htn) {
this->htn = htn;
}
RCModelFactory::~RCModelFactory() {
// TODO Auto-generated destructor stub
}
Model* RCModelFactory::getRCmodelSTRIPS() {
return this->getRCmodelSTRIPS(1);
}
Model* RCModelFactory::getRCmodelSTRIPS(int costsMethodActions) {
Model* rc = new Model();
rc->isHtnModel = false;
rc->numStateBits = htn->numStateBits + htn->numActions + htn->numTasks;
rc->numVars = htn->numVars + htn->numActions + htn->numTasks; // first part might be SAS+
rc->numActions = htn->numActions + htn->numMethods;
rc->numTasks = rc->numActions;
rc->precLists = new int*[rc->numActions];
rc->addLists = new int*[rc->numActions];
rc->delLists = new int*[rc->numActions];
rc->numPrecs = new int[rc->numActions];
rc->numAdds = new int[rc->numActions];
rc->numDels = new int[rc->numActions];
// add new prec and add effect to actions
for(int i = 0; i < htn->numActions; i++) {
rc->numPrecs[i] = htn->numPrecs[i] + 1;
rc->precLists[i] = new int[rc->numPrecs[i]];
for(int j = 0; j < rc->numPrecs[i] - 1; j++) {
rc->precLists[i][j] = htn->precLists[i][j];
}
rc->precLists[i][rc->numPrecs[i] - 1] = t2tdr(i);
rc->numAdds[i] = htn->numAdds[i] + 1;
rc->addLists[i] = new int[rc->numAdds[i]];
for(int j = 0; j < rc->numAdds[i] - 1; j++) {
rc->addLists[i][j] = htn->addLists[i][j];
}
rc->addLists[i][rc->numAdds[i] - 1] = t2bur(i);
rc->numDels[i] = htn->numDels[i];
rc->delLists[i] = new int[rc->numDels[i]];
for(int j = 0; j < rc->numDels[i]; j++) {
rc->delLists[i][j] = htn->delLists[i][j];
}
}
// create actions for methods
for(int im = 0; im < htn->numMethods; im++) {
int ia = htn->numActions + im;
rc->numPrecs[ia] = htn->numDistinctSTs[im];
rc->precLists[ia] = new int[rc->numPrecs[ia]];
for(int ist = 0; ist < htn->numDistinctSTs[im]; ist++) {
int st = htn->sortedDistinctSubtasks[im][ist];
rc->precLists[ia][ist] = t2bur(st);
}
rc->numAdds[ia] = 1;
rc->addLists[ia] = new int[1];
rc->addLists[ia][0] = t2bur(htn->decomposedTask[im]);
rc->numDels[ia] = 0;
rc->delLists[ia] = nullptr;
}
// set names of state features
rc->factStrs = new string[rc->numStateBits];
for(int i = 0; i < htn->numStateBits; i++) {
rc->factStrs[i] = htn->factStrs[i];
}
for(int i = 0; i < htn->numActions; i++) {
rc->factStrs[t2tdr(i)] = "tdr-" + htn->taskNames[i];
}
for(int i = 0; i < htn->numTasks; i++) {
rc->factStrs[t2bur(i)] = "bur-" + htn->taskNames[i];
}
// set action names
rc->taskNames = new string[rc->numTasks];
for(int i = 0; i < htn->numActions; i++) {
rc->taskNames[i] = htn->taskNames[i];
}
for(int im = 0; im < htn->numMethods; im++) {
int ia = htn->numActions + im;
rc->taskNames[ia] = htn->methodNames[im] + "@" + htn->taskNames[htn->decomposedTask[im]];
}
// set variable names
rc->varNames = new string[rc->numVars];
for(int i = 0; i < htn->numVars; i++) {
rc->varNames[i] = htn->varNames[i];
}
for(int i = 0; i < htn->numActions; i++) {
// todo: the index transformation does not use the functions
// defined above and needs to be redone when changing them
int inew = htn->numVars + i;
rc->varNames[inew] = "tdr-" + htn->taskNames[i];
}
for(int i = 0; i < htn->numTasks; i++) {
// todo: transformation needs to be redone when changing them
int inew = htn->numVars + htn->numActions + i;
rc->varNames[inew] = "bur-" + htn->taskNames[i];
}
// set indices of first and last bit
rc->firstIndex = new int[rc->numVars];
rc->lastIndex = new int[rc->numVars];
for(int i = 0; i < htn->numVars; i++) {
rc->firstIndex[i] = htn->firstIndex[i];
rc->lastIndex[i] = htn->lastIndex[i];
}
for(int i = htn->numVars; i < rc->numVars; i++) {
rc->firstIndex[i] = rc->lastIndex[i - 1] + 1;
rc->lastIndex[i] = rc->firstIndex[i];
}
// set action costs
rc->actionCosts = new int[rc->numActions];
for(int i = 0; i < htn->numActions; i++) {
rc->actionCosts[i] = htn->actionCosts[i];
}
for(int i = htn->numActions; i < rc->numActions; i++) {
rc->actionCosts[i] = costsMethodActions;
}
set<int> precless;
for(int i = 0; i < rc->numActions; i++) {
if (rc->numPrecs[i] == 0) {
precless.insert(i);
}
}
rc->numPrecLessActions = precless.size();
rc->precLessActions = new int[rc->numPrecLessActions];
int j = 0;
for(int pl : precless) {
rc->precLessActions[j++] = pl;
}
rc->isPrimitive = new bool[rc->numActions];
for(int i = 0; i < rc->numActions; i++)
rc->isPrimitive[i] = true;
createInverseMappings(rc);
set<int> s;
for(int i = 0; i < htn->s0Size; i++) {
s.insert(htn->s0List[i]);
}
for(int i = 0; i < htn->numActions; i++) {
s.insert(t2tdr(i));
}
rc->s0Size = s.size();
rc->s0List = new int[rc->s0Size];
int i = 0;
for (int f : s) {
rc->s0List[i++] = f;
}
rc->gSize = 1 + htn->gSize;
rc->gList = new int[rc->gSize];
for(int i = 0; i < htn->gSize; i++) {
rc->gList[i] = htn->gList[i];
}
rc->gList[rc->gSize - 1] = t2bur(htn->initialTask);
#ifndef NDEBUG
for(int i = 0; i < rc->numActions; i++) {
set<int> prec;
for(int j = 0; j < rc->numPrecs[i]; j++) {
prec.insert(rc->precLists[i][j]);
}
assert(prec.size() == rc->numPrecs[i]); // precondition contained twice?
set<int> add;
for(int j = 0; j < rc->numAdds[i]; j++) {
add.insert(rc->addLists[i][j]);
}
assert(add.size() == rc->numAdds[i]); // add contained twice?
set<int> del;
for(int j = 0; j < rc->numDels[i]; j++) {
del.insert(rc->delLists[i][j]);
}
assert(del.size() == rc->numDels[i]); // del contained twice?
}
// are subtasks represented in preconditions?
for(int i = 0; i < htn->numMethods; i++) {
for(int j = 0; j < htn->numSubTasks[i]; j++) {
int f = t2bur(htn->subTasks[i][j]);
bool contained = false;
int mAction = htn->numActions + i;
for(int k = 0; k < rc->numPrecs[mAction]; k++) {
if(rc->precLists[mAction][k] == f) {
contained = true;
break;
}
}
assert(contained); // is subtask contained in the respective action's preconditions?
}
}
// are preconditions represented in subtasks?
for(int i = htn->numActions; i < rc->numActions; i++) {
int m = i - htn->numActions;
for(int j = 0; j < rc->numPrecs[i]; j++) {
int f = rc->precLists[i][j];
int task = f - (htn->numStateBits + htn->numActions);
bool contained = false;
for(int k = 0; k < htn->numSubTasks[m]; k++) {
int subtask = htn->subTasks[m][k];
if(subtask == task) {
contained = true;
break;
}
}
assert(contained);
}
}
#endif
return rc;
}
void RCModelFactory::createInverseMappings(Model* c){
set<int>* precToActionTemp = new set<int>[c->numStateBits];
for (int i = 0; i < c->numActions; i++) {
for (int j = 0; j < c->numPrecs[i]; j++) {
int f = c->precLists[i][j];
precToActionTemp[f].insert(i);
}
}
c->precToActionSize = new int[c->numStateBits];
c->precToAction = new int*[c->numStateBits];
for (int i = 0; i < c->numStateBits; i++) {
c->precToActionSize[i] = precToActionTemp[i].size();
c->precToAction[i] = new int[c->precToActionSize[i]];
int cur = 0;
for (int ac : precToActionTemp[i]) {
c->precToAction[i][cur++] = ac;
}
}
delete[] precToActionTemp;
}
/*
* The original state bits are followed by one bit per action that is set iff
* the action is reachable from the top. Then, there is one bit for each task
* indicating that task has been reached bottom-up.
*/
int RCModelFactory::t2tdr(int task) {
return htn->numStateBits + task;
}
int RCModelFactory::t2bur(int task) {
return htn->numStateBits + htn->numActions + task;
}
pair<int, int> RCModelFactory::rcStateFeature2HtnIndex(string s) {
//cout << "searching index for \"" << s << "\"" << endl;
s = s.substr(0, s.length() - 2); // ends with "()" due to grounded representation
int type = -1;
int index = -1;
if((s.rfind("bur-", 0) == 0)) {
type = fTask;
s = s.substr(4, s.length() - 4);
for(int i = 0; i < htn->numTasks; i++) {
if(s.compare(su.toLowerString(su.cleanStr(htn->taskNames[i]))) == 0) {
index = i;
#ifndef NDEBUG
// the name has been cleaned, check whether it is unique
for(int j = i + 1; j < htn->numTasks; j++) {
assert(s.compare(su.toLowerString(su.cleanStr(htn->taskNames[j]))) != 0);
}
#endif
break;
}
}
} else {
type = fFact;
for(int i = 0; i < htn->numStateBits; i++) {
if(s.compare(su.toLowerString(su.cleanStr(htn->factStrs[i]))) == 0) {
index = i;
#ifndef NDEBUG
// the name has been cleaned, check whether it is unique
for(int j = i + 1; j < htn->numStateBits; j++) {
assert(s.compare(su.toLowerString(su.cleanStr(htn->factStrs[j]))) != 0);
}
#endif
break;
}
}
}
//cout << "Type " << type << endl;
//cout << "Index " << index << endl;
return make_pair(type, index);
}
} /* namespace progression */
| 28.915625 | 93 | 0.584675 |
5563e17227c0e9ac9e3f36e11978115c10de87cf | 3,764 | cpp | C++ | src/vismethods/boxplot.cpp | jakobtroidl/Barrio | 55c447325f2e83a21b39c54cdca37b2779d0569c | [
"MIT"
] | null | null | null | src/vismethods/boxplot.cpp | jakobtroidl/Barrio | 55c447325f2e83a21b39c54cdca37b2779d0569c | [
"MIT"
] | 3 | 2021-11-02T22:24:04.000Z | 2021-11-29T18:01:51.000Z | src/vismethods/boxplot.cpp | jakobtroidl/Barrio | 55c447325f2e83a21b39c54cdca37b2779d0569c | [
"MIT"
] | null | null | null | #include "boxplot.h"
Boxplot::Boxplot(Boxplot* boxplot)
{
m_datacontainer = boxplot->m_datacontainer;
m_global_vis_parameters = boxplot->m_global_vis_parameters;
}
Boxplot::Boxplot(GlobalVisParameters* visparams, DataContainer* datacontainer)
{
m_global_vis_parameters = visparams;
m_datacontainer = datacontainer;
}
Boxplot::~Boxplot()
{
}
QString Boxplot::createJSONString(QList<int>* selectedObjects)
{
QJsonArray document;
for (auto i : *selectedObjects)
{
Object* mito = m_datacontainer->getObject(i);
std::vector<int>* mito_indices = mito->get_indices_list();
std::vector<VertexData>* vertices = m_datacontainer->getMesh()->getVerticesList();
QJsonObject mito_json;
QJsonArray mito_distances;
for (auto j : *mito_indices)
{
VertexData vertex = vertices->at(j);
double distance_to_cell = vertex.distance_to_cell;
if (distance_to_cell < 1000.0) {
mito_distances.push_back(QJsonValue::fromVariant(distance_to_cell));
}
}
mito_json.insert("key", mito->getName().c_str());
mito_json.insert("value", mito_distances);
document.push_back(mito_json);
}
QJsonDocument doc(document);
return doc.toJson(QJsonDocument::Indented);
}
QWebEngineView* Boxplot::initVisWidget(int ID, SpecificVisParameters params)
{
m_settings = params.settings;
bool normalized = m_settings.value("normalized").toBool();
QString json = createJSONString(&m_global_vis_parameters->selected_objects);
m_data = new BoxplotData(json, m_datacontainer, m_global_vis_parameters, normalized);
setSpecificVisParameters(params);
m_web_engine_view = new QWebEngineView();
QWebChannel* channel = new QWebChannel(m_web_engine_view->page());
m_web_engine_view->page()->setWebChannel(channel);
channel->registerObject(QStringLiteral("boxplot_data"), m_data);
m_web_engine_view->load(getHTMLPath(m_index_filename));
return m_web_engine_view;
}
QWebEngineView* Boxplot::getWebEngineView()
{
return m_web_engine_view;
}
bool Boxplot::update()
{
QString json = createJSONString(&m_global_vis_parameters->selected_objects);
m_data->setJSONString(json);
return true;
}
Boxplot* Boxplot::clone()
{
return new Boxplot(this);
}
bool Boxplot::update_needed()
{
return true;
}
VisType Boxplot::getType()
{
return VisType::BOXPLOT;
}
void Boxplot::setSpecificVisParameters(SpecificVisParameters params)
{
m_data->setColors(params.colors);
}
BoxplotData::BoxplotData(QString json_data, DataContainer* data_container, GlobalVisParameters* global_vis_parameters, bool normalized)
{
m_json_string = json_data;
m_datacontainer = data_container;
m_global_vis_parameters = global_vis_parameters;
m_normalized = normalized;
}
BoxplotData::~BoxplotData()
{
}
Q_INVOKABLE QString BoxplotData::getData()
{
return Q_INVOKABLE m_json_string;
}
Q_INVOKABLE QString BoxplotData::getColormap()
{
return Q_INVOKABLE m_colors;
}
Q_INVOKABLE bool BoxplotData::getNormalized()
{
return Q_INVOKABLE m_normalized;
}
Q_INVOKABLE void BoxplotData::setHighlightedFrame(const QString& name)
{
int hvgx = m_datacontainer->getIndexByName(name);
if (!m_global_vis_parameters->highlighted_group_boxes.contains(hvgx))
{
m_global_vis_parameters->highlighted_group_boxes.append(hvgx);
}
m_global_vis_parameters->needs_update = true;
return Q_INVOKABLE void();
}
Q_INVOKABLE void BoxplotData::removeHighlightedFrame(const QString& name_to_remove)
{
int hvgx_id = m_datacontainer->getIndexByName(name_to_remove);
QVector<int>* highlighted = &m_global_vis_parameters->highlighted_group_boxes;
if (highlighted->contains(hvgx_id))
{
QMutableVectorIterator<int> it(*highlighted);
while (it.hasNext())
{
if (it.next() == hvgx_id) {
it.remove();
}
}
}
m_global_vis_parameters->needs_update = true;
return Q_INVOKABLE void();
}
| 24.283871 | 135 | 0.772848 |
5568cae4112ad35a5722916126cef4f92baa52be | 5,227 | hpp | C++ | libmikroxml/mikroxml/mikroxml.hpp | rantingmong/svgrenderer | 082879b448a2c241f69e383620b59e307298bb77 | [
"MIT"
] | 1 | 2021-03-29T19:30:47.000Z | 2021-03-29T19:30:47.000Z | libmikroxml/mikroxml/mikroxml.hpp | rantingmong/svgrenderer | 082879b448a2c241f69e383620b59e307298bb77 | [
"MIT"
] | null | null | null | libmikroxml/mikroxml/mikroxml.hpp | rantingmong/svgrenderer | 082879b448a2c241f69e383620b59e307298bb77 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <utki/Buf.hpp>
#include <utki/Exc.hpp>
namespace mikroxml{
class Parser{
enum class State_e{
IDLE,
TAG,
TAG_SEEK_GT,
TAG_EMPTY,
DECLARATION,
DECLARATION_END,
COMMENT,
COMMENT_END,
ATTRIBUTES,
ATTRIBUTE_NAME,
ATTRIBUTE_SEEK_TO_EQUALS,
ATTRIBUTE_SEEK_TO_VALUE,
ATTRIBUTE_VALUE,
CONTENT,
REF_CHAR,
DOCTYPE,
DOCTYPE_BODY,
DOCTYPE_TAG,
DOCTYPE_ENTITY_NAME,
DOCTYPE_ENTITY_SEEK_TO_VALUE,
DOCTYPE_ENTITY_VALUE,
DOCTYPE_SKIP_TAG,
SKIP_UNKNOWN_EXCLAMATION_MARK_CONSTRUCT
} state = State_e::IDLE;
void parseIdle(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseTagEmpty(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseTagSeekGt(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDeclaration(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDeclarationEnd(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseComment(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseCommentEnd(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseAttributes(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseAttributeName(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseAttributeSeekToEquals(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseAttributeSeekToValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseAttributeValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseContent(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseRefChar(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctype(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctypeBody(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctypeTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctypeSkipTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctypeEntityName(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctypeEntitySeekToValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseDoctypeEntityValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void parseSkipUnknownExclamationMarkConstruct(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e);
void handleAttributeParsed();
void processParsedTagName();
void processParsedRefChar();
std::vector<char> buf;
std::vector<char> name; //general variable for storing name of something (attribute name, entity name, etc.)
std::vector<char> refCharBuf;
char attrValueQuoteChar;
State_e stateAfterRefChar;
unsigned lineNumber = 1;
std::map<std::string, std::vector<char>> doctypeEntities;
public:
Parser();
class Exc : public utki::Exc{
public:
Exc(const std::string& message) : utki::Exc(message){}
};
class MalformedDocumentExc : public Exc{
public:
MalformedDocumentExc(unsigned lineNumber, const std::string& message);
};
virtual void onElementStart(const utki::Buf<char> name) = 0;
/**
* @brief Element end.
* @param name - name of the element which has ended. Name is empty if empty element has ended.
*/
virtual void onElementEnd(const utki::Buf<char> name) = 0;
/**
* @brief Attributes section end notification.
* This callback is called when all attributes of the last element have been parsed.
* @param isEmptyElement - indicates weather the element is empty element or not.
*/
virtual void onAttributesEnd(bool isEmptyElement) = 0;
/**
* @brief Attribute parsed notification.
* This callback may be called after 'onElementStart' notification. It can be called several times, once for each parsed attribute.
* @param name - name of the parsed attribute.
* @param value - value of the parsed attribute.
*/
virtual void onAttributeParsed(const utki::Buf<char> name, const utki::Buf<char> value) = 0;
/**
* @brief Content parsed notification.
* This callback may be called after 'onAttributesEnd' notification.
* @param str - parsed content.
*/
virtual void onContentParsed(const utki::Buf<char> str) = 0;
/**
* @brief feed UTF-8 data to parser.
* @param data - data to be fed to parser.
*/
void feed(const utki::Buf<char> data);
/**
* @brief feed UTF-8 data to parser.
* @param data - data to be fed to parser.
*/
void feed(const utki::Buf<std::uint8_t> data){
this->feed(utki::wrapBuf(reinterpret_cast<const char*>(&*data.begin()), data.size()));
}
/**
* @brief Parse in string.
* @param str - string to parse.
*/
void feed(const std::string& str);
/**
* @brief Finalize parsing after all data has been fed.
*/
void end();
virtual ~Parser()noexcept{}
};
}
| 35.080537 | 132 | 0.726229 |
556b6070e185d3ad180455bf7f53800ef7ee2f7e | 165 | cpp | C++ | 319-bulb-switcher/319-bulb-switcher.cpp | shreydevep/DSA | 688af414c1fada1b82a4b4e9506747352007c894 | [
"MIT"
] | null | null | null | 319-bulb-switcher/319-bulb-switcher.cpp | shreydevep/DSA | 688af414c1fada1b82a4b4e9506747352007c894 | [
"MIT"
] | null | null | null | 319-bulb-switcher/319-bulb-switcher.cpp | shreydevep/DSA | 688af414c1fada1b82a4b4e9506747352007c894 | [
"MIT"
] | null | null | null | class Solution {
public:
int bulbSwitch(int n) {
int cnt = 0;
for(int i=1;i*i<=n;++i){
cnt++;
}
return cnt;
}
}; | 15 | 31 | 0.406061 |
556cc6b2535fd02c5d18fa71c1b6111a7f3fc091 | 6,003 | cc | C++ | webkit/fileapi/media/picasa/pmp_column_reader_unittest.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | webkit/fileapi/media/picasa/pmp_column_reader_unittest.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | webkit/fileapi/media/picasa/pmp_column_reader_unittest.cc | codenote/chromium-test | 0637af0080f7e80bf7d20b29ce94c5edc817f390 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T07:25:45.000Z | 2020-11-04T07:25:45.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <vector>
#include "base/file_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/fileapi/media/picasa/pmp_column_reader.h"
#include "webkit/fileapi/media/picasa/pmp_constants.h"
#include "webkit/fileapi/media/picasa/pmp_test_helper.h"
namespace {
using picasaimport::PmpColumnReader;
using picasaimport::PmpTestHelper;
// Overridden version of Read method to make test code templatable.
bool DoRead(const PmpColumnReader* reader, uint32 row, std::string* target) {
return reader->ReadString(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, uint32* target) {
return reader->ReadUInt32(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, double* target) {
return reader->ReadDouble64(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, uint8* target) {
return reader->ReadUInt8(row, target);
}
bool DoRead(const PmpColumnReader* reader, uint32 row, uint64* target) {
return reader->ReadUInt64(row, target);
}
// TestValid
template<class T>
void TestValid(const picasaimport::PmpFieldType field_type,
const std::vector<T>& elems) {
PmpTestHelper test_helper;
ASSERT_TRUE(test_helper.Init());
PmpColumnReader reader;
uint32 rows_read = 0xFF;
std::vector<uint8> data =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems);
ASSERT_TRUE(test_helper.InitColumnReaderFromBytes(&reader, data, &rows_read));
EXPECT_EQ(elems.size(), rows_read);
for (uint32 i = 0; i < elems.size() && i < rows_read; i++) {
T target;
EXPECT_TRUE(DoRead(&reader, i, &target));
EXPECT_EQ(elems[i], target);
}
}
template<class T>
void TestMalformed(const picasaimport::PmpFieldType field_type,
const std::vector<T>& elems) {
PmpTestHelper test_helper;
ASSERT_TRUE(test_helper.Init());
PmpColumnReader reader1, reader2, reader3, reader4;
std::vector<uint8> data_too_few_declared_rows =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size()-1, elems);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader1, data_too_few_declared_rows, NULL));
std::vector<uint8> data_too_many_declared_rows =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size()+1, elems);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader2, data_too_many_declared_rows, NULL));
std::vector<uint8> data_truncated =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems);
data_truncated.resize(data_truncated.size()-10);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader3, data_truncated, NULL));
std::vector<uint8> data_padded =
PmpTestHelper::MakeHeaderAndBody(field_type, elems.size(), elems);
data_padded.resize(data_padded.size()+10);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader4, data_padded, NULL));
}
template<class T>
void TestPrimitive(const picasaimport::PmpFieldType field_type) {
// Make an ascending vector of the primitive.
uint32 n = 100;
std::vector<T> data(n, 0);
for (uint32 i = 0; i < n; i++) {
data[i] = i*3;
}
TestValid<T>(field_type, data);
TestMalformed<T>(field_type, data);
}
TEST(PmpColumnReaderTest, HeaderParsingAndValidation) {
PmpTestHelper test_helper;
ASSERT_TRUE(test_helper.Init());
PmpColumnReader reader1, reader2, reader3, reader4, reader5;
// Good header.
uint32 rows_read = 0xFF;
std::vector<uint8> good_header = PmpTestHelper::MakeHeader(
picasaimport::PMP_TYPE_STRING, 0);
ASSERT_TRUE(test_helper.InitColumnReaderFromBytes(
&reader1, good_header, &rows_read));
EXPECT_EQ(0U, rows_read) << "Read non-zero rows from header-only data.";
// Botch up elements of the header.
std::vector<uint8> bad_magic_byte = PmpTestHelper::MakeHeader(
picasaimport::PMP_TYPE_STRING, 0);
bad_magic_byte[0] = 0xff;
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader2, bad_magic_byte, NULL));
// Corrupt means the type fields don't agree.
std::vector<uint8> corrupt_type = PmpTestHelper::MakeHeader(
picasaimport::PMP_TYPE_STRING, 0);
corrupt_type[picasaimport::kPmpFieldType1Offset] = 0xff;
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader3, corrupt_type, NULL));
std::vector<uint8> invalid_type = PmpTestHelper::MakeHeader(
picasaimport::PMP_TYPE_STRING, 0);
invalid_type[picasaimport::kPmpFieldType1Offset] = 0xff;
invalid_type[picasaimport::kPmpFieldType2Offset] = 0xff;
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader4, invalid_type, NULL));
std::vector<uint8> incomplete_header = PmpTestHelper::MakeHeader(
picasaimport::PMP_TYPE_STRING, 0);
incomplete_header.resize(10);
EXPECT_FALSE(test_helper.InitColumnReaderFromBytes(
&reader5, incomplete_header, NULL));
}
TEST(PmpColumnReaderTest, StringParsing) {
std::vector<std::string> empty_strings(100, "");
// Test empty strings read okay.
TestValid(picasaimport::PMP_TYPE_STRING, empty_strings);
std::vector<std::string> mixed_strings;
mixed_strings.push_back("");
mixed_strings.push_back("Hello");
mixed_strings.push_back("World");
mixed_strings.push_back("");
mixed_strings.push_back("123123");
mixed_strings.push_back("Q");
mixed_strings.push_back("");
// Test that a mixed set of strings read correctly.
TestValid(picasaimport::PMP_TYPE_STRING, mixed_strings);
// Test with the data messed up in a variety of ways.
TestMalformed(picasaimport::PMP_TYPE_STRING, mixed_strings);
}
TEST(PmpColumnReaderTest, PrimitiveParsing) {
TestPrimitive<uint32>(picasaimport::PMP_TYPE_UINT32);
TestPrimitive<double>(picasaimport::PMP_TYPE_DOUBLE64);
TestPrimitive<uint8>(picasaimport::PMP_TYPE_UINT8);
TestPrimitive<uint64>(picasaimport::PMP_TYPE_UINT64);
}
} // namespace
| 33.35 | 80 | 0.746294 |
5571b7ca836a9d01adde6967d32f705483a08ef8 | 5,851 | cpp | C++ | tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp | kitsudaiki/libKitsunemimiCommon | 65c60deddf9fb813035fc2f3251c5ae5c8f7423f | [
"MIT"
] | null | null | null | tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp | kitsudaiki/libKitsunemimiCommon | 65c60deddf9fb813035fc2f3251c5ae5c8f7423f | [
"MIT"
] | 49 | 2020-08-24T18:09:35.000Z | 2022-02-13T22:19:39.000Z | tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp | tobiasanker/libKitsunemimiCommon | d40d1314db0a6d7e04afded09cb4934e01828ac4 | [
"MIT"
] | 1 | 2020-08-29T14:30:41.000Z | 2020-08-29T14:30:41.000Z | /**
* @file statemachine_test.cpp
*
* @author Tobias Anker <tobias.anker@kitsunemimi.moe>
*
* @copyright MIT License
*/
#include "statemachine_test.h"
#include <libKitsunemimiCommon/statemachine.h>
namespace Kitsunemimi
{
Statemachine_Test::Statemachine_Test()
: Kitsunemimi::CompareTestHelper("Statemachine_Test")
{
createNewState_test();
addTransition_test();
goToNextState_test();
setInitialChildState_test();
addChildState_test();
getCurrentStateId_test();
isInState_test();
}
/**
* createNewState_test
*/
void
Statemachine_Test::createNewState_test()
{
Statemachine statemachine;
TEST_EQUAL(statemachine.createNewState(SOURCE_STATE), true);
TEST_EQUAL(statemachine.createNewState(SOURCE_STATE), false);
}
/**
* setCurrentState_test
*/
void
Statemachine_Test::setCurrentState_test()
{
Statemachine statemachine;
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
TEST_EQUAL(statemachine.setCurrentState(SOURCE_STATE), true);
TEST_EQUAL(statemachine.setCurrentState(FAIL), false);
}
/**
* addTransition_test
*/
void
Statemachine_Test::addTransition_test()
{
Statemachine statemachine;
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE), true);
TEST_EQUAL(statemachine.addTransition(FAIL, GO, NEXT_STATE), false);
TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, FAIL), false);
TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE), false);
}
/**
* goToNextState_test
*/
void
Statemachine_Test::goToNextState_test()
{
Statemachine statemachine;
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE);
TEST_EQUAL(statemachine.goToNextState(FAIL), false);
TEST_EQUAL(statemachine.goToNextState(GO), true);
TEST_EQUAL(statemachine.goToNextState(GO), false);
}
/**
* setInitialChildState_test
*/
void
Statemachine_Test::setInitialChildState_test()
{
Statemachine statemachine;
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
TEST_EQUAL(statemachine.setInitialChildState(SOURCE_STATE, NEXT_STATE), true);
TEST_EQUAL(statemachine.setInitialChildState(FAIL, NEXT_STATE), false);
TEST_EQUAL(statemachine.setInitialChildState(SOURCE_STATE, FAIL), false);
}
/**
* addChildState_test
*/
void
Statemachine_Test::addChildState_test()
{
Statemachine statemachine;
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
TEST_EQUAL(statemachine.addChildState(SOURCE_STATE, NEXT_STATE), true);
TEST_EQUAL(statemachine.addChildState(FAIL, NEXT_STATE), false);
TEST_EQUAL(statemachine.addChildState(SOURCE_STATE, FAIL), false);
}
/**
* getCurrentStateId_test
*/
void
Statemachine_Test::getCurrentStateId_test()
{
Statemachine statemachine;
TEST_EQUAL(statemachine.getCurrentStateId(), 0);
// init state
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
statemachine.createNewState(CHILD_STATE);
statemachine.createNewState(TARGET_STATE);
// build state-machine
statemachine.addChildState(NEXT_STATE, CHILD_STATE);
statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE);
statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE);
statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE);
TEST_EQUAL(statemachine.getCurrentStateId(), SOURCE_STATE);
statemachine.goToNextState(GO);
TEST_EQUAL(statemachine.getCurrentStateId(), CHILD_STATE);
statemachine.goToNextState(GOGO);
TEST_EQUAL(statemachine.getCurrentStateId(), TARGET_STATE);
}
/**
* @brief getCurrentStateName_test
*/
void
Statemachine_Test::getCurrentStateName_test()
{
Statemachine statemachine;
TEST_EQUAL(statemachine.getCurrentStateId(), 0);
// init state
statemachine.createNewState(SOURCE_STATE, "SOURCE_STATE");
statemachine.createNewState(NEXT_STATE, "NEXT_STATE");
statemachine.createNewState(CHILD_STATE, "CHILD_STATE");
statemachine.createNewState(TARGET_STATE, "TARGET_STATE");
// build state-machine
statemachine.addChildState(NEXT_STATE, CHILD_STATE);
statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE);
statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE);
statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE);
TEST_EQUAL(statemachine.getCurrentStateId(), SOURCE_STATE);
statemachine.goToNextState(GO);
TEST_EQUAL(statemachine.getCurrentStateName(), "CHILD_STATE");
statemachine.goToNextState(GOGO);
TEST_EQUAL(statemachine.getCurrentStateName(), "TARGET_STATE");
}
/**
* isInState_test
*/
void
Statemachine_Test::isInState_test()
{
Statemachine statemachine;
TEST_EQUAL(statemachine.getCurrentStateId(), 0);
// init state
statemachine.createNewState(SOURCE_STATE);
statemachine.createNewState(NEXT_STATE);
statemachine.createNewState(CHILD_STATE);
statemachine.createNewState(TARGET_STATE);
// build state-machine
statemachine.addChildState(NEXT_STATE, CHILD_STATE);
statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE);
statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE);
statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE);
TEST_EQUAL(statemachine.isInState(SOURCE_STATE), true);
TEST_EQUAL(statemachine.isInState(FAIL), false);
statemachine.goToNextState(GO);
TEST_EQUAL(statemachine.isInState(CHILD_STATE), true);
TEST_EQUAL(statemachine.isInState(NEXT_STATE), true);
TEST_EQUAL(statemachine.isInState(SOURCE_STATE), false);
}
} // namespace Kitsunemimi
| 26.595455 | 82 | 0.766194 |
5574c5de3bab02af2bbfed26f5cfe2ba8ae4a69e | 5,927 | cpp | C++ | globe/globe_shader.cpp | MarkY-LunarG/LunarGlobe | d32a6145eebc68ad4d7e28bdd4fab88cbdd33545 | [
"Apache-2.0"
] | 2 | 2018-06-20T15:19:38.000Z | 2018-07-13T15:13:30.000Z | globe/globe_shader.cpp | MarkY-LunarG/LunarGlobe | d32a6145eebc68ad4d7e28bdd4fab88cbdd33545 | [
"Apache-2.0"
] | 25 | 2018-07-27T23:02:01.000Z | 2019-03-15T17:00:05.000Z | globe/globe_shader.cpp | MarkY-LunarG/LunarGravity | d32a6145eebc68ad4d7e28bdd4fab88cbdd33545 | [
"Apache-2.0"
] | null | null | null | //
// Project: LunarGlobe
// SPDX-License-Identifier: Apache-2.0
//
// File: globe/globe_shader.cpp
// Copyright(C): 2018-2019; LunarG, Inc.
// Author(s): Mark Young <marky@lunarg.com>
//
#include <cstring>
#include <fstream>
#include <string>
#include <sstream>
#include "globe_logger.hpp"
#include "globe_event.hpp"
#include "globe_submit_manager.hpp"
#include "globe_shader.hpp"
#include "globe_texture.hpp"
#include "globe_resource_manager.hpp"
#include "globe_app.hpp"
#if defined(VK_USE_PLATFORM_WIN32_KHR)
const char directory_symbol = '\\';
#else
const char directory_symbol = '/';
#endif
static const char main_shader_func_name[] = "main";
GlobeShader* GlobeShader::LoadFromFile(VkDevice vk_device, const std::string& shader_name,
const std::string& directory) {
GlobeShaderStageInitData shader_data[GLOBE_SHADER_STAGE_ID_NUM_STAGES] = {{}, {}, {}, {}, {}, {}};
for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) {
std::string full_shader_name = directory;
full_shader_name += directory_symbol;
full_shader_name += shader_name;
switch (stage) {
case GLOBE_SHADER_STAGE_ID_VERTEX:
full_shader_name += "-vs.spv";
break;
case GLOBE_SHADER_STAGE_ID_TESSELLATION_CONTROL:
full_shader_name += "-cs.spv";
break;
case GLOBE_SHADER_STAGE_ID_TESSELLATION_EVALUATION:
full_shader_name += "-es.spv";
break;
case GLOBE_SHADER_STAGE_ID_GEOMETRY:
full_shader_name += "-gs.spv";
break;
case GLOBE_SHADER_STAGE_ID_FRAGMENT:
full_shader_name += "-fs.spv";
break;
case GLOBE_SHADER_STAGE_ID_COMPUTE:
full_shader_name += "-cp.spv";
break;
default:
continue;
}
std::ifstream* infile = nullptr;
std::string line;
std::stringstream strstream;
size_t shader_spv_size;
infile = new std::ifstream(full_shader_name.c_str(), std::ifstream::in | std::ios::binary);
if (nullptr == infile || infile->fail()) {
continue;
}
strstream << infile->rdbuf();
infile->close();
delete infile;
// Read the file contents
shader_spv_size = strstream.str().size();
shader_data[stage].spirv_content.resize((shader_spv_size / sizeof(uint32_t)));
memcpy(shader_data[stage].spirv_content.data(), strstream.str().c_str(), shader_spv_size);
shader_data[stage].valid = true;
}
return new GlobeShader(vk_device, shader_name, shader_data);
}
GlobeShader::GlobeShader(VkDevice vk_device, const std::string& shader_name,
const GlobeShaderStageInitData shader_data[GLOBE_SHADER_STAGE_ID_NUM_STAGES])
: _initialized(true), _vk_device(vk_device), _shader_name(shader_name) {
GlobeLogger& logger = GlobeLogger::getInstance();
uint32_t num_loaded_shaders = 0;
for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) {
if (shader_data[stage].valid) {
_shader_data[stage].vk_shader_flag = static_cast<VkShaderStageFlagBits>(1 << stage);
VkShaderModuleCreateInfo shader_module_create_info;
shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shader_module_create_info.pNext = nullptr;
shader_module_create_info.codeSize = shader_data[stage].spirv_content.size() * sizeof(uint32_t);
shader_module_create_info.pCode = shader_data[stage].spirv_content.data();
shader_module_create_info.flags = 0;
VkResult vk_result = vkCreateShaderModule(vk_device, &shader_module_create_info, NULL,
&_shader_data[stage].vk_shader_module);
if (VK_SUCCESS != vk_result) {
_initialized = false;
_shader_data[stage].valid = false;
std::string error_msg = "GlobeTexture::Read failed to read shader ";
error_msg += shader_name;
error_msg += " with error ";
error_msg += vk_result;
logger.LogError(error_msg);
} else {
num_loaded_shaders++;
_shader_data[stage].valid = true;
}
} else {
_shader_data[stage].valid = false;
}
}
if (num_loaded_shaders == 0 && _initialized) {
_initialized = false;
}
}
GlobeShader::~GlobeShader() {
if (_initialized) {
for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) {
if (_shader_data[stage].valid) {
vkDestroyShaderModule(_vk_device, _shader_data[stage].vk_shader_module, nullptr);
_shader_data[stage].valid = false;
_shader_data[stage].vk_shader_module = VK_NULL_HANDLE;
}
}
_initialized = false;
}
}
bool GlobeShader::GetPipelineShaderStages(std::vector<VkPipelineShaderStageCreateInfo>& pipeline_stages) const {
if (!_initialized) {
return false;
}
VkPipelineShaderStageCreateInfo cur_stage_create_info = {};
cur_stage_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
cur_stage_create_info.pName = main_shader_func_name;
for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) {
if (_shader_data[stage].valid) {
cur_stage_create_info.stage = _shader_data[stage].vk_shader_flag;
cur_stage_create_info.module = _shader_data[stage].vk_shader_module;
pipeline_stages.push_back(cur_stage_create_info);
}
}
return true;
} | 40.047297 | 112 | 0.62578 |
55769a005a140f772cd2ea9a01a12416aa6e3b4f | 15,261 | cpp | C++ | software/imageread/xi_input_image.cpp | yhyoung/CHaiDNN | 1877a81e0d1b44773af455b0eab4399636bbc181 | [
"Apache-2.0"
] | 288 | 2018-03-23T01:41:40.000Z | 2022-03-03T08:52:54.000Z | software/imageread/xi_input_image.cpp | yhyoung/CHaiDNN | 1877a81e0d1b44773af455b0eab4399636bbc181 | [
"Apache-2.0"
] | 171 | 2018-03-25T11:03:23.000Z | 2022-01-29T14:16:59.000Z | software/imageread/xi_input_image.cpp | yhyoung/CHaiDNN | 1877a81e0d1b44773af455b0eab4399636bbc181 | [
"Apache-2.0"
] | 154 | 2018-03-23T01:31:33.000Z | 2022-03-04T14:26:40.000Z | /*----------------------------------------------------
Copyright 2017 Xilinx, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
----------------------------------------------------*/
#include "xi_input_image.hpp"
void loadMeanTXT(float *ptrRetArray, const char* path, int nElems)
{
FILE* fp = fopen(path, "r");
if(fp == NULL)
{
printf("\n** Cannot open mean file (or) No mean file : %s **\n", path);
//return NULL;
}
for(int i = 0; i < nElems; i++)
{
fscanf(fp, "%f ", ptrRetArray+i);
}
fclose(fp);
}
//int loadAndPrepareImage(cv::Mat &frame, short *inptr, float* mean_data, int img_w, int img_h, int img_channel, int resize_h, int resize_w, const char *mean_path, int mean_status)
int loadAndPrepareImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer)
{
short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2];
short *mean_ptr = (short *)xChangeHostInpLayer->mean;
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle
int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //??
int mean_sub_flag = params_ptr[26];
int scale = 1;
int h_off = 0;
int w_off = 0;
int mean_idx = 0;
int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits;
cv::Mat cv_img[1], cv_cropped_img[1];
if((resize_h != frame.rows) || (resize_w != frame.cols))
{
cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w));
if(resize_h > height)
{
h_off = (resize_h - height) / 2;
w_off = (resize_w - width) / 2;
cv::Rect roi(w_off, h_off, height, width);
cv_cropped_img[0] = cv_img[0](roi);
}
else
cv_cropped_img[0] = cv_img[0];
}
else
{
frame.copyTo(cv_cropped_img[0]);
}
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
//float pixel;
uchar pixel;
int input_index=0;
float float_val;
short fxval;
for (int h = 0; h < height; ++h)
{
const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);//data;
int img_index = 0;
for (int w = 0; w < width; ++w)
{
//TODO : Generic for 4
for (int ch = 0; ch < 4; ++ch)
{
if(ch < img_channel)
{
//pixel = static_cast<float>(ptr[img_index++]);
pixel = ptr[img_index++];
short pixel1 = (short)pixel << fbits_input;
if(mean_sub_flag == 1)
mean_idx = ch;
else
mean_idx = (ch * resize_h + h + h_off) * resize_w + w + w_off;
//float_val = (pixel - mean_ptr[mean_idx]) * scale;
//short ival = (short)float_val;
//fxval = ConvertToFP(float_val, ival, fbits_input);
fxval = pixel1 - mean_ptr[mean_idx];
}
else
{
float_val = 0;
fxval = 0;
in_ptr[input_index] = 0;
}
in_ptr[input_index] = fxval;
#if FILE_WRITE
float_val = ((float)fxval)/(1 << fbits_input);
fprintf(fp,"%f ", float_val);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
// loadAndPrepareImage
#if 0
int loadMeanSubtractedImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer)
{
short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2];
float *mean_ptr = (float *)xChangeHostInpLayer->mean;
float *variance_ptr = (float *)xChangeHostInpLayer->variance;
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle
int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //??
int mean_sub_flag = params_ptr[26];
int scale = 1;
int h_off = 0;
int w_off = 0;
int mean_idx = 0;
int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits;
cv::Mat cv_img[1], cv_cropped_img[1];
if((resize_h != frame.rows) || (resize_w != frame.cols))
{
cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w));
if(resize_h > height)
{
h_off = (resize_h - height) / 2;
w_off = (resize_w - width) / 2;
cv::Rect roi(w_off, h_off, height, width);
cv_cropped_img[0] = cv_img[0](roi);
}
else
cv_cropped_img[0] = cv_img[0];
}
else
{
frame.copyTo(cv_cropped_img[0]);
}
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
//float pixel;
uchar pixel;
int input_index=0;
float float_val;
short fxval;
for (int h = 0; h < height; ++h)
{
const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);//data;
int img_index = 0;
for (int w = 0; w < width; ++w)
{
//TODO : Generic for 4
for (int ch = 0; ch < 4; ++ch)
{
if(ch < img_channel)
{
//pixel = static_cast<float>(ptr[img_index++]);
pixel = ptr[img_index++];
float in_val = pixel/255.0;
float mean_val = mean_ptr[mean_idx];
int var_idx = (ch * resize_h + h + h_off) * resize_w + w + w_off;
float var_val = variance_ptr[var_idx];
in_val = (in_val - mean_val)/var_val;
short ival = (short)float_val;
fxval = ConvertToFP(float_val, ival, fbits_input);
}
else
{
float_val = 0;
fxval = 0;
in_ptr[input_index] = 0;
}
in_ptr[input_index] = fxval;
#if FILE_WRITE
float_val = ((float)fxval)/(1 << fbits_input);
fprintf(fp,"%f ", float_val);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
// loadAndPrepareImage
#endif
//int loadImage(cv::Mat &frame, char *inptr, float* mean_data, int img_w, int img_h, int img_channel, int resize_h, int resize_w, const char *mean_path, int mean_status)
int loadImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer)
{
char *in_ptr = (char *)xChangeHostInpLayer->in_ptrs[2];
float *mean_ptr = (float *)xChangeHostInpLayer->mean;
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle
int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //??
int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits;
int h_off = 0;
int w_off = 0;
cv::Mat cv_img[1], cv_cropped_img[1];
if((resize_h != frame.rows) || (resize_w != frame.cols))
{
cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w));
if(resize_h > height)
{
h_off = (resize_h - height) / 2;
w_off = (resize_w - width) / 2;
cv::Rect roi(w_off, h_off, height, width);
cv_cropped_img[0] = cv_img[0](roi);
}
else
cv_cropped_img[0] = cv_img[0];
}
else
{
frame.copyTo(cv_cropped_img[0]);
}
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
char pixel;
int input_index=0;
for (int h = 0; h < height; ++h)
{
const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);
int img_index = 0;
for (int w = 0; w < width; ++w)
{
//TODO : Generic for 4
for (int c = 0; c < 4; ++c)
{
if(c < img_channel)
{
pixel = static_cast<char>(ptr[img_index++]);
}
else
{
pixel = 0;
}
in_ptr[input_index] = pixel;
#if FILE_WRITE
fprintf(fp,"%d ", pixel);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
//loadImage
int loadImagetoBuffptr1(const char *img_path, unsigned char *buff_ptr, int height, int width, int img_channel, int resize_h, int resize_w)
{
cv::Mat frame;
frame = imread(img_path, 1);
if(!frame.data)
{
std :: cout << "[ERROR] Image read failed - " << img_path << std :: endl;
//fprintf(stderr,"image read failed\n");
//return -1;
}
int h_off = 0;
int w_off = 0;
cv::Mat cv_img[1], cv_cropped_img[1];
if((resize_h != frame.rows) || (resize_w != frame.cols))
{
cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w));
if(resize_h > height)
{
h_off = (resize_h - height) / 2;
w_off = (resize_w - width) / 2;
cv::Rect roi(w_off, h_off, height, width);
cv_cropped_img[0] = cv_img[0](roi);
}
else
cv_cropped_img[0] = cv_img[0];
}
else
{
frame.copyTo(cv_cropped_img[0]);
}
const uchar* ptr = cv_cropped_img[0].ptr<uchar>(0);
for (int ind = 0; ind < height*width*img_channel; ind++)
{
buff_ptr[ind] = ptr[ind];
}
}
//loadImage
int loadImagefromBuffptr(unsigned char *buff_ptr, xChangeLayer *xChangeHostInpLayer)
{
char *in_ptr = (char *)xChangeHostInpLayer->in_ptrs[2];
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
char pixel;
int input_index=0;
int img_index = 0;
for (int h = 0; h < height; ++h)
{
for (int w = 0; w < width; ++w)
{
//TODO : Generic for 4
for (int c = 0; c < 4; ++c)
{
if(c < img_channel)
{
pixel = buff_ptr[img_index++];
}
else
{
pixel = 0;
}
in_ptr[input_index] = pixel;
#if FILE_WRITE
fprintf(fp,"%d ", pixel);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
//loadImagefromBuffptr
int loadDatafromBuffptr(short *buff_ptr, xChangeLayer *xChangeHostInpLayer)
{
short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2];
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
params_ptr[26] = 0; //mean_sub_flag
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
short pixel;
int input_index=0;
int img_index = 0;
for (int h = 0; h < height; ++h)
{
for (int w = 0; w < width; ++w)
{
//TODO : Generic for 4
for (int c = 0; c < 4; ++c)
{
if(c < img_channel)
{
pixel = buff_ptr[img_index++];
}
else
{
pixel = 0;
}
in_ptr[input_index] = pixel;
#if FILE_WRITE
fprintf(fp,"%d ", pixel);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
//loadDatafromBuffptr
int loadData(const char *img_data_path, xChangeLayer *xChangeHostInpLayer)
{
short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2];
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
params_ptr[26] = 0; //making mean_sub_flag = 0;
FILE* fp_img = fopen(img_data_path, "r");
if(fp_img == NULL)
{
fprintf(stderr, "\n** Cannot open mean file (or) No mean file : %s **\n", img_data_path);
//return NULL;
}
int size_of_input = height*width*img_channel;
short *in_buf = (short *)malloc(size_of_input*sizeof(short));
int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;
float float_val;
short fxval;
for(int i = 0; i < height*width*img_channel; i++)
{
fscanf(fp_img, "%f ", &float_val);
short ival = (short)float_val;
fxval = ConvertToFP(float_val, ival, fbits_input);
in_buf[i] = fxval;
}
fclose(fp_img);
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
short pixel;
int input_index=0;
int img_index1 = 0;
int img_index = 0;
for (int h = 0; h < height; ++h)
{
for (int w = 0; w < width; ++w)
{
img_index1 = h*width + w;
//TODO : Generic for 4
for (int c = 0; c < 4; ++c)
{
img_index = img_index1 + c*(height*width);
if(c < img_channel)
{
pixel = in_buf[img_index];
}
else
{
pixel = 0;
}
in_ptr[input_index] = pixel;
#if FILE_WRITE
fprintf(fp,"%d ", pixel);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
//loadData
int loadDatatoBuffptr1(const char *img_data_path, float *inp_buff, int height, int width, int img_channel)
{
FILE* fp_img = fopen(img_data_path, "r");
if(fp_img == NULL)
{
fprintf(stderr, "\n** Cannot open mean file (or) No mean file : %s **\n", img_data_path);
//return NULL;
}
float float_val;
for(int i = 0; i < height*width*img_channel; i++)
{
fscanf(fp_img, "%f ", &float_val);
inp_buff[i] = float_val;
}
fclose(fp_img);
}
//loadDatatoBuffptr
int loadDatafromBuffptr1(short *inp_buff, xChangeLayer *xChangeHostInpLayer)
{
short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2];
int *params_ptr = (int *)xChangeHostInpLayer->params;
int height = params_ptr[0];
int width = params_ptr[1];
int img_channel = params_ptr[5];
params_ptr[26] = 0; //making mean_sub_flag = 0;
int size_of_input = height*width*img_channel;
#if FILE_WRITE
FILE *fp = fopen("input.txt", "w");
#endif
short pixel;
int input_index=0;
int img_index1 = 0;
int img_index = 0;
for (int h = 0; h < height; ++h)
{
for (int w = 0; w < width; ++w)
{
img_index1 = h*width + w;
//TODO : Generic for 4
for (int c = 0; c < 4; ++c)
{
img_index = img_index1 + c*(height*width);
if(c < img_channel)
{
pixel = inp_buff[img_index];
}
else
{
pixel = 0;
}
in_ptr[input_index] = pixel;
#if FILE_WRITE
fprintf(fp,"%d ", pixel);
#endif
input_index++;
}// Channels
}// Image width
#if FILE_WRITE
fprintf(fp,"\n");
#endif
}// Image Height
#if FILE_WRITE
fclose(fp);
#endif
}
//loadDatafromBuffptr
void inputImageRead(const char *img_path, xChangeLayer *xChangeHostInpLayer)
//void inputImageRead(FILE **file_list, xChangeLayer *xChangeHostInpLayer)
{
#if EN_IO_PRINT
cout<< "inputImageRead : " <<endl;
#endif
//char img_path[500];
//fscanf(*file_list, "%s", img_path);
int num_mean_values; //read from params
int status;
//xChangeLayer *xChangeHostInpLayer = &lay_obj[imgId][layerId];// = &xChangeHostLayers[0];
//xChangeHostInpLayer.in_ptrs[0] = (char*)create_sdsalloc_mem(mem_size);
//xChangeHostInpLayer.params = (char*)create_sdsalloc_mem(params_mem_size);
int *scalar_conv_args = (int *)xChangeHostInpLayer->params;
int mean_sub_flag = scalar_conv_args[26];
cv::Mat in_frame, out_frame;
out_frame = imread(img_path, 1);
if(!out_frame.data)
{
std :: cout << "[ERROR] Image read failed - " << img_path << std :: endl;
//fprintf(stderr,"image read failed\n");
//return -1;
}
if(mean_sub_flag)
{
status = loadImage(out_frame, xChangeHostInpLayer);
}
else
{
status = loadAndPrepareImage(out_frame, xChangeHostInpLayer);
}
#if EN_IO_PRINT
cout<< "inputImageRead done: " <<endl;
#endif
}
| 22.085384 | 180 | 0.636393 |
557844a4a767c4a1fe9f3add0d55c0b5b9079a2f | 3,571 | hh | C++ | include/sot/tools/kinematic-planner.hh | Rascof/sot-tools | e529611574d12fc2239bd0cfcd83749243de8bc6 | [
"BSD-2-Clause"
] | null | null | null | include/sot/tools/kinematic-planner.hh | Rascof/sot-tools | e529611574d12fc2239bd0cfcd83749243de8bc6 | [
"BSD-2-Clause"
] | 11 | 2017-02-01T19:26:29.000Z | 2021-11-03T08:25:35.000Z | include/sot/tools/kinematic-planner.hh | Rascof/sot-tools | e529611574d12fc2239bd0cfcd83749243de8bc6 | [
"BSD-2-Clause"
] | 12 | 2015-01-21T08:21:23.000Z | 2020-11-27T14:35:29.000Z | //
// Copyright (C) 2016 LAAS-CNRS
//
// Author: Rohan Budhiraja
//
#ifndef SOT_TOOLS_KINEMATIC_PLANNER_HH
#define SOT_TOOLS_KINEMATIC_PLANNER_HH
/* STD */
#include <string>
#include <sstream>
#include <list>
#include <complex>
/* dynamic-graph */
#include <dynamic-graph/entity.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/signal-base.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <dynamic-graph/linear-algebra.h>
#include <sot/core/debug.hh>
/*Eigen*/
#include <Eigen/StdVector>
#include <unsupported/Eigen/FFT>
#include <unsupported/Eigen/Splines>
#include <unsupported/Eigen/MatrixFunctions>
/* BOOST */
//#include <boost/filesystem.hpp>
namespace dynamicgraph {
namespace sot {
namespace tools {
using dynamicgraph::Entity;
class KinematicPlanner : public Entity {
public:
DYNAMIC_GRAPH_ENTITY_DECL();
typedef std::vector<Eigen::ArrayXd, Eigen::aligned_allocator<Eigen::ArrayXd> > stdVectorofArrayXd;
typedef std::vector<Eigen::ArrayXXd, Eigen::aligned_allocator<Eigen::ArrayXXd> > stdVectorofArrayXXd;
/*-----SIGNALS--------*/
typedef int Dummy;
/*
dynamicgraph::SignalPtr<double,int> distToDrawerSIN;
dynamicgraph::SignalPtr<double,int> objectPositionInDrawerSIN;
dynamicgraph::SignalTimeDependent<Dummy,int> trajectoryReadySINTERN;
dynamicgraph::SignalTimeDependent<dynamicgraph::Matrix, int> upperBodyJointPositionSOUT;
dynamicgraph::SignalTimeDependent<dynamicgraph::Matrix, int> upperBodyJointVelocitySOUT;
dynamicgraph::SignalTimeDependent<dynamicgraph::Matrix, int> freeFlyerVelocitySOUT;
*/
/* --- CONSTRUCTOR --- */
KinematicPlanner(const std::string& name);
virtual ~KinematicPlanner(void);
// Sources
Eigen::ArrayXd npSource;
Eigen::ArrayXXd pSource1;
Eigen::ArrayXXd pSource2;
stdVectorofArrayXXd pSourceDelayed1;
stdVectorofArrayXXd pSourceDelayed2;
// Delays
Eigen::ArrayXXd pDelay1;
Eigen::ArrayXXd pDelay2;
// Non Periodic Weights
Eigen::ArrayXXd wNonPeriodic; // Eigen::Array<double, 480,4>
// Periodic Weights
stdVectorofArrayXXd wPeriodic1;
stdVectorofArrayXXd wPeriodic2;
// Mean joint angles
Eigen::ArrayXXd mJointAngle;
// Number of Trajectories Created
// int nTrajectories; //30
int nJoints; // 16
int nGaitCycles; // 4
int nTimeSteps; // 160
int nSources1; // 5
int nSources2; // 4
/*! @} */
std::list<dynamicgraph::SignalBase<int>*> genericSignalRefs;
// Load Motion Capture outputs
template <typename Derived>
void read2DArray(std::string& fileName, Eigen::DenseBase<Derived>& outArr);
void setParams(const double& _distanceToDrawer, const double& _objectPositionInDrawer, const std::string& dir);
void loadSourceDelays(const std::string& dir);
void loadTrainingParams(const std::string& dir, dynamicgraph::Matrix& q, dynamicgraph::Matrix& beta3,
Eigen::ArrayXd& mwwn, double& sigma2, int& N, int& K);
dynamicgraph::Vector createSubGoals(double D, double P);
void delaySources();
void blending();
void smoothEnds(Eigen::Ref<Eigen::ArrayXd> tr);
void bSplineInterpolate(Eigen::ArrayXXd& tr, int factor);
int& runKinematicPlanner(int& dummy, int time);
void goalAdaption(dynamicgraph::Vector& goals, const std::string&);
void savitzkyGolayFilter(Eigen::Ref<Eigen::ArrayXXd> allJointTraj, int polyOrder, int frameSize);
bool parametersSet;
}; // class KinematicPlanner
} // namespace tools
} // namespace sot
} // namespace dynamicgraph
#endif // SOT_TOOLS_KINEMATIC_PLANNER_HH
| 30.262712 | 113 | 0.738169 |
5578bfbd80af35e8b15a9510717a5a0cce4ba4cf | 101 | cc | C++ | example/memcache/Item.cc | Conzxy/kanon | 3440b0966153a0b8469e90b2a52df317aa4fe723 | [
"MIT"
] | null | null | null | example/memcache/Item.cc | Conzxy/kanon | 3440b0966153a0b8469e90b2a52df317aa4fe723 | [
"MIT"
] | null | null | null | example/memcache/Item.cc | Conzxy/kanon | 3440b0966153a0b8469e90b2a52df317aa4fe723 | [
"MIT"
] | null | null | null | #include "Item.h"
namespace memcache {
std::atomic<u64> Item::s_cas_(0);
} // namespace memcache
| 12.625 | 34 | 0.683168 |
5579482f0ec6190139c6f85f8691a06d2de5ff42 | 863 | hpp | C++ | plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// 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 SGE_OPENGL_XRANDR_SET_RESOLUTION_HPP_INCLUDED
#define SGE_OPENGL_XRANDR_SET_RESOLUTION_HPP_INCLUDED
#include <sge/opengl/xrandr/configuration_fwd.hpp>
#include <sge/opengl/xrandr/mode_index.hpp>
#include <sge/opengl/xrandr/optional_refresh_rate_fwd.hpp>
#include <sge/opengl/xrandr/rotation.hpp>
#include <awl/backends/x11/window/base_fwd.hpp>
namespace sge::opengl::xrandr
{
void set_resolution(
awl::backends::x11::window::base const &,
sge::opengl::xrandr::configuration const &,
sge::opengl::xrandr::mode_index,
sge::opengl::xrandr::rotation,
sge::opengl::xrandr::optional_refresh_rate const &);
}
#endif
| 30.821429 | 61 | 0.74971 |
557a792be377471c08aeae8d211267379bea0f15 | 3,257 | hpp | C++ | tuo_units/TUO_Reg_Units_OPF_F.hpp | bc036/A3-TUO-Units | 157f4f45317a19cf90d3f28b017b43de737f5bb3 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | tuo_units/TUO_Reg_Units_OPF_F.hpp | bc036/A3-TUO-Units | 157f4f45317a19cf90d3f28b017b43de737f5bb3 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 44 | 2019-09-24T17:11:29.000Z | 2021-08-14T18:37:15.000Z | tuo_units/TUO_Reg_Units_OPF_F.hpp | bc036/A3-TUO-Units | 157f4f45317a19cf90d3f28b017b43de737f5bb3 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | class O_T_TUO_Reg_Base_F:B_T_TUO_Reg_base_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Reg_base_F:B_A_TUO_Reg_base_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Reg_Base_F:B_W_TUO_Reg_base_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Rifleman_F:B_T_TUO_Rifleman_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Rifleman_F:B_A_TUO_Rifleman_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Rifleman_F:B_W_TUO_Rifleman_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Rifleman_AT_F:B_T_TUO_Rifleman_AT_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Rifleman_AT_F:B_A_TUO_Rifleman_AT_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Rifleman_AT_F:B_W_TUO_Rifleman_AT_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Mark_F:B_T_TUO_Mark_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Mark_F:B_A_TUO_Mark_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Mark_F:B_W_TUO_Mark_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Engineer_F:B_T_TUO_Engineer_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Engineer_F:B_A_TUO_Engineer_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Engineer_F:B_W_TUO_Engineer_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Medic_F:B_T_TUO_Medic_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Medic_F:B_A_TUO_Medic_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Medic_F:B_W_TUO_Medic_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Leader_F:B_T_TUO_Leader_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Leader_F:B_A_TUO_Leader_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Leader_F:B_W_TUO_Leader_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Autorifleman_F:B_T_TUO_Autorifleman_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Autorifleman_F:B_A_TUO_Autorifleman_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Autorifleman_F:B_W_TUO_Autorifleman_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Heavy_Gunner_F:B_T_TUO_Heavy_Gunner_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_OPF_F";
};
class O_A_TUO_Heavy_Gunner_F:B_A_TUO_Heavy_Gunner_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_OPF_F";
};
class O_W_TUO_Heavy_Gunner_F:B_W_TUO_Heavy_Gunner_F
{
side=0; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_OPF_F";
};
class O_T_TUO_Grenadier_F:B_T_TUO_Grenadier_F
{
side=2; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_T_IND_F";
};
class O_A_TUO_Grenadier_F:B_A_TUO_Grenadier_F
{
side=2; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_A_IND_F";
};
class O_W_TUO_Grenadier_F:B_W_TUO_Grenadier_F
{
side=2; //OPF_F=0 BLU_F=1 IND_F=2
faction="TUO_W_IND_F";
}; | 21.713333 | 51 | 0.760823 |
557b88c28caf8c1a8e0b49aea2e46c1ae215bf71 | 1,675 | cpp | C++ | test/cli/minions_coverage_test.cpp | seqan/minions | 58339454f992264b73197f1bf8c94e8f4b1c3c2f | [
"BSD-3-Clause"
] | null | null | null | test/cli/minions_coverage_test.cpp | seqan/minions | 58339454f992264b73197f1bf8c94e8f4b1c3c2f | [
"BSD-3-Clause"
] | 16 | 2021-09-29T13:00:06.000Z | 2022-03-07T13:34:16.000Z | test/cli/minions_coverage_test.cpp | MitraDarja/Comparison | 58339454f992264b73197f1bf8c94e8f4b1c3c2f | [
"BSD-3-Clause"
] | 1 | 2022-01-09T22:36:43.000Z | 2022-01-09T22:36:43.000Z | #include "cli_test.hpp"
TEST_F(cli_test, no_options)
{
cli_test_result result = execute_app("minions coverage");
std::string expected
{
"minions-coverage\n"
"================\n"
" Try -h or --help for more information.\n"
};
EXPECT_EQ(result.exit_code, 0);
EXPECT_EQ(result.out, expected);
EXPECT_EQ(result.err, std::string{});
}
TEST_F(cli_test, minimiser)
{
cli_test_result result = execute_app("minions coverage --method minimiser -k 19 -w 19 ", data("example1.fasta"));
EXPECT_EQ(result.exit_code, 0);
EXPECT_EQ(result.out, std::string{});
EXPECT_EQ(result.err, std::string{});
}
TEST_F(cli_test, gapped_minimiser)
{
cli_test_result result = execute_app("minions coverage --method minimiser -k 19 -w 19 --shape 524223", data("example1.fasta"));
EXPECT_EQ(result.exit_code, 0);
EXPECT_EQ(result.out, std::string{});
EXPECT_EQ(result.err, std::string{});
}
TEST_F(cli_test, modmer)
{
cli_test_result result = execute_app("minions coverage --method modmer -k 19 -w 2 ", data("example1.fasta"));
EXPECT_EQ(result.exit_code, 0);
EXPECT_EQ(result.out, std::string{});
EXPECT_EQ(result.err, std::string{});
}
TEST_F(cli_test, wrong_method)
{
cli_test_result result = execute_app("minions coverage --method submer -k 19", data("example1.fasta"));
std::string expected
{
"Error. Incorrect command line input for coverage. Validation failed "
"for option --method: Value submer is not one of [kmer,minimiser,modmer].\n"
};
EXPECT_EQ(result.exit_code, 0);
EXPECT_EQ(result.err, expected);
EXPECT_EQ(result.out, std::string{});
}
| 31.018519 | 131 | 0.665672 |
5353d7e9a41855906455824ecb59c9d4b6db1312 | 2,145 | cpp | C++ | Project3/assign3.cpp | jehalladay/Theory-of-Algorithms | fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5 | [
"MIT"
] | null | null | null | Project3/assign3.cpp | jehalladay/Theory-of-Algorithms | fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5 | [
"MIT"
] | null | null | null | Project3/assign3.cpp | jehalladay/Theory-of-Algorithms | fa35ed1a3c40e45a3b97c93a44e96532b91fb1b5 | [
"MIT"
] | null | null | null | /*
Project 3 - Hashtable and Heapsort
James Halladay
Theory of Algorithms
10/9/2021
This program will render a program that expect a command line
argument being an input text file and an output text file name.
The program will read the data in the input file (strings) and write
to the output file the sorted contents of the input
We will scan the file and store the words in
the hashtable while recording their frequencies.
After the file is finished, we will input the words and their frequencies
into the heap.
The heap is a maxheap, so once the heap is full, the we will remove the root
node until it is empty into a vector.
The input file is sorted through this process and then is written to the output file specified
by the second command line argument.
*/
#include <iostream>
#include <string>
#include <fstream>
#include "hash.h"
#include "heap.h"
#include "utility.h"
using namespace std;
const string MODIFY_DATE = "10-24-21";
const string FILE_NAME = "A Scandal In Bohemia.txt";
void arg_check(int argc, char* argv[]);
void maintest();
void write_file(string file_name, vector<element>& sorted);
int main(int argc, char* argv[]) {
arg_check(argc, argv);
maintest();
Hashtable ht = read_file(argv[1], .65);
vector<element> sorted = Heap().heap_sort(ht);
write_file(argv[2], sorted);
return 0;
}
void arg_check(int argc, char* argv[]) {
if (argc < 2 || argc > 3) {
cout << "Incorrect number of arguments" << endl;
throw;
}
cout << "argc: " << argc << endl;
for(int i = 0; i < argc; i++) {
cout << "argv[" << i << "]: " << argv[i] << endl;
}
}
void write_file(string file_name, vector<element>& sorted) {
ofstream outfile;
outfile.open(file_name);
for(int i = 0; i < (int)sorted.size(); i++) {
outfile << sorted[i].entry << "\t\t" << sorted[i].frequency << endl;
}
outfile.close();
}
void maintest() {
cout << endl << "Hello, World! from inside assign3.cpp" << "\tLast Modified: " << MODIFY_DATE << endl;
}
| 26.8125 | 107 | 0.634499 |
5355b6e7c24675c87cabae20b628a3dd5351c293 | 479 | cpp | C++ | linux/cmd.cpp | Universefei/f8snippet | 408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a | [
"Apache-2.0"
] | null | null | null | linux/cmd.cpp | Universefei/f8snippet | 408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a | [
"Apache-2.0"
] | null | null | null | linux/cmd.cpp | Universefei/f8snippet | 408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a | [
"Apache-2.0"
] | null | null | null |
string exe_cmd(const string& cmd) {
int t_ret = 0;
string t_result = "";
t_result.resize(1024);
FILE* fp = popen(cmd.c_str(), "r");
fgets(&t_result[0], t_result.capacity(), fp);
pclose(fp);
return t_result;
}
string get_md5(const string& file) {
char buf[128] = {'\0'};
string cmd = "md5sum ";
cmd.append(file);
cmd.append(" | awk '{printf $1}'");
FILE* fp = popen(cmd.c_str(), "r");
fgets(buf, sizeof(buf), fp);
pclose(fp);
return string(buf);
}
| 21.772727 | 47 | 0.605428 |
535bd9c0458dc7dabf8371038d09169b5407e1f7 | 456 | hpp | C++ | net/include/HttpSecWebSocketKey.hpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 27 | 2019-04-27T00:51:22.000Z | 2022-03-30T04:05:44.000Z | net/include/HttpSecWebSocketKey.hpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 9 | 2020-05-03T12:17:50.000Z | 2021-10-15T02:18:47.000Z | net/include/HttpSecWebSocketKey.hpp | wangsun1983/Obotcha | 2464e53599305703f5150df72bf73579a39d8ef4 | [
"MIT"
] | 1 | 2019-04-16T01:45:36.000Z | 2019-04-16T01:45:36.000Z | #ifndef __OBOTCHA_HTTP_SEC_WEB_SOCKET_KEY_HPP__
#define __OBOTCHA_HTTP_SEC_WEB_SOCKET_KEY_HPP__
#include "Object.hpp"
#include "StrongPointer.hpp"
#include "String.hpp"
#include "ArrayList.hpp"
namespace obotcha {
DECLARE_CLASS(HttpSecWebSocketKey) {
public:
_HttpSecWebSocketKey();
_HttpSecWebSocketKey(String);
void import(String);
String get();
void set(String);
String toString();
private:
String key;
};
}
#endif
| 14.709677 | 47 | 0.739035 |
53613b5bf2676bb820155d844b791c3e0b582cbd | 454 | cpp | C++ | modulo arithmetic/add_mult_modulo.cpp | SAURABH2000b/Cryptography-and-network-security | 850be62ff56f7a6e180809776ace75ac165cb1c0 | [
"MIT"
] | null | null | null | modulo arithmetic/add_mult_modulo.cpp | SAURABH2000b/Cryptography-and-network-security | 850be62ff56f7a6e180809776ace75ac165cb1c0 | [
"MIT"
] | null | null | null | modulo arithmetic/add_mult_modulo.cpp | SAURABH2000b/Cryptography-and-network-security | 850be62ff56f7a6e180809776ace75ac165cb1c0 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int add_modulo(int a, int b, int N){
return (a+b)%N;
}
int mult_modulo(int a, int b, int N){
return (a*b)%N;
}
int main(){
int a=rand(), b=rand();
a=a%1000;
b=b%1000;
int add_modulo_result = add_modulo(a,b,342);
int mult_modulo_result = mult_modulo(a,b,342);
cout<<"addition modulto is: "<<add_modulo_result<<"\n";
cout<<"multiplication modulo is: "<<mult_modulo_result;
}
| 25.222222 | 59 | 0.636564 |
53660adb81cba86ca028a0122741d62a476cbbb9 | 1,342 | cpp | C++ | C++/HeapSort.cpp | patres270/AlgoLib | 8b697e1e9348c559dcabdb6665e1031264c1032a | [
"MIT"
] | 222 | 2016-07-17T17:28:19.000Z | 2022-03-27T02:57:39.000Z | C++/HeapSort.cpp | patres270/AlgoLib | 8b697e1e9348c559dcabdb6665e1031264c1032a | [
"MIT"
] | 197 | 2016-10-24T16:47:42.000Z | 2021-08-29T08:12:31.000Z | C++/HeapSort.cpp | patres270/AlgoLib | 8b697e1e9348c559dcabdb6665e1031264c1032a | [
"MIT"
] | 206 | 2016-05-18T17:08:14.000Z | 2022-01-16T04:08:47.000Z | #include<bits/stdc++.h>
using namespace std;
#define rep(i,a,b,c) for(i=a;i<b;i+=c)
#define repp(i,a,b,c) for(i=a;i>b;i+=c)
//--------------------------------------Heapify
void max_heapify(int *a, int i, int n)
{
int l=2*i+1;
int r=2*i+2;
int largest=0;
if(l<=n and a[l]>a[i])
largest=l;
else
largest=i;
if(r<=n and a[r]>a[largest])
largest=r;
if(largest!=i)
{
swap(a[largest],a[i]);
max_heapify(a,largest,n);
}
}
//---------------------------------Build max Heap
void build_maxheap(int *a, int n)
{
int i;
repp(i,n/2,-1,-1)
{
max_heapify(a,i,n);
}
}
//-----------------------------------HeapSort
void heapsort(int *a, int n)
{
int i;
build_maxheap(a,n);
repp(i,n,-1,-1)
{
swap(a[0],a[i]);
n--;
max_heapify(a,0,n);
}
}
int main()
{
int n, i, x;
cout<<"Enter no of elements of array\n";
cin>>n;
//Dynamic Memory Allocation
int *dynamic;
dynamic = new int[n];
//Input Of Elements
cout<<"Enter the elements of array :\n";
rep(i,0,n,1)
cin>>dynamic[i];
heapsort(dynamic,n-1);
//Sorted Array using heap sort
cout<< "Sorted Sequence is : " ;
rep(i,0,n,1)
cout<< dynamic[i]<<"\t";
delete []dynamic;
} | 19.449275 | 49 | 0.467213 |
5368e5f9756762633f750c5c0ff8ef6f9882060e | 1,151 | cpp | C++ | c++/zigzag_conversion.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/zigzag_conversion.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | c++/zigzag_conversion.cpp | SongZhao/leetcode | 4a2b4f554e91f6a2167b336f8a69b80fa9f3f920 | [
"Apache-2.0"
] | null | null | null | /*
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display
this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".
*/
/*
*
*/
#include "helper.h"
class Solution {
public:
string convert(string s, int nRows) {
if (nRows <= 1) {
return s;
}
vector<string> strs(nRows);
string res;
int row = 0, step = 1;
for (char c: s) {
strs[row].push_back(c);
if (row == 0) {
step = 1;
} else if (row == nRows - 1) {
step = -1;
}
row += step;
}
for (int j = 0; j < nRows; ++j) {
res.append(strs[j]);
}
return res;
}
};
int main() {
Solution s;
cout << s.convert("PAYPALISHIRING", 3) << endl;
return 0;
}
| 20.192982 | 120 | 0.529105 |
536b253989e4c9c91ccb838702940a731c4b1c28 | 4,577 | hpp | C++ | include/foonathan/lex/token.hpp | foonathan/lex | 2d0177d453f8c36afc78392065248de0b48c1e7d | [
"BSL-1.0"
] | 142 | 2018-10-16T16:41:09.000Z | 2021-12-13T20:04:50.000Z | include/foonathan/lex/token.hpp | foonathan/lex | 2d0177d453f8c36afc78392065248de0b48c1e7d | [
"BSL-1.0"
] | null | null | null | include/foonathan/lex/token.hpp | foonathan/lex | 2d0177d453f8c36afc78392065248de0b48c1e7d | [
"BSL-1.0"
] | 10 | 2018-10-16T19:08:36.000Z | 2021-03-19T14:36:29.000Z | // Copyright (C) 2018-2019 Jonathan Müller <jonathanmueller.dev@gmail.com>
// This file is subject to the license terms in the LICENSE file
// found in the top-level directory of this distribution.
#ifndef FOONATHAN_LEX_TOKEN_HPP_INCLUDED
#define FOONATHAN_LEX_TOKEN_HPP_INCLUDED
#include <foonathan/lex/spelling.hpp>
#include <foonathan/lex/token_kind.hpp>
namespace foonathan
{
namespace lex
{
template <class TokenSpec>
class tokenizer;
template <class TokenSpec>
class token
{
public:
constexpr token() noexcept : ptr_(nullptr), size_(0), kind_() {}
constexpr token_kind<TokenSpec> kind() const noexcept
{
return kind_;
}
explicit constexpr operator bool() const noexcept
{
return !!kind();
}
template <class Token>
constexpr bool is(Token token = {}) const noexcept
{
return kind_.is(token);
}
template <template <typename> class Category>
constexpr bool is_category() const noexcept
{
return kind_.template is_category<Category>();
}
constexpr const char* name() const noexcept
{
return kind_.name();
}
constexpr token_spelling spelling() const noexcept
{
return token_spelling(ptr_, size_);
}
constexpr std::size_t offset(const tokenizer<TokenSpec>& tokenizer) const noexcept
{
return static_cast<std::size_t>(ptr_ - tokenizer.begin_ptr());
}
private:
explicit constexpr token(token_kind<TokenSpec> kind, const char* ptr,
std::size_t size) noexcept
: ptr_(ptr), size_(size), kind_(kind)
{}
const char* ptr_;
std::size_t size_;
token_kind<TokenSpec> kind_;
friend tokenizer<TokenSpec>;
};
template <class Token, class Payload = void>
class static_token;
template <class Token>
class static_token<Token, void>
{
static_assert(is_token<Token>::value, "must be a token");
public:
template <class TokenSpec>
explicit constexpr static_token(const token<TokenSpec>& token) : spelling_(token.spelling())
{
FOONATHAN_LEX_PRECONDITION(token.is(Token{}), "token kind must match");
}
constexpr operator Token() const noexcept
{
return Token{};
}
template <class TokenSpec>
constexpr token_kind<TokenSpec> kind() const noexcept
{
return token_kind<TokenSpec>::template of<Token>();
}
explicit constexpr operator bool() const noexcept
{
return std::is_same<Token, error_token>::value;
}
template <class Other>
constexpr bool is(Other = {}) const noexcept
{
return std::is_same<Token, Other>::value;
}
template <template <typename> class Category>
constexpr bool is_category() const noexcept
{
return Category<Token>::value;
}
constexpr const char* name() const noexcept
{
return Token::name;
}
constexpr token_spelling spelling() const noexcept
{
return spelling_;
}
template <class TokenSpec>
constexpr std::size_t offset(const tokenizer<TokenSpec>& tokenizer) const noexcept
{
return static_cast<std::size_t>(spelling_.data() - tokenizer.begin_ptr());
}
private:
token_spelling spelling_;
};
template <class Token, class Payload>
class static_token : public static_token<Token, void>
{
public:
template <class TokenSpec>
explicit constexpr static_token(const token<TokenSpec>& token, Payload payload)
: static_token<Token, void>(token), payload_(static_cast<Payload&&>(payload))
{}
constexpr Payload& value() & noexcept
{
return payload_;
}
constexpr const Payload& value() const& noexcept
{
return payload_;
}
constexpr Payload&& value() && noexcept
{
return static_cast<Payload&&>(payload_);
}
constexpr const Payload&& value() const&& noexcept
{
return static_cast<const Payload&&>(payload_);
}
private:
Payload payload_;
};
} // namespace lex
} // namespace foonathan
#endif // FOONATHAN_LEX_TOKEN_HPP_INCLUDED
| 26.923529 | 100 | 0.59078 |
5378c2f15156a210d5184f7c0bf57ad0c60a2e74 | 195 | hpp | C++ | include/elasty/algorithm-type.hpp | yuki-koyama/elasty | 67c7a15c1483fe1979b8b3af64be4f34e110c760 | [
"MIT"
] | 176 | 2019-04-27T00:45:37.000Z | 2022-03-26T03:15:45.000Z | include/elasty/algorithm-type.hpp | yuki-koyama/elasty | 67c7a15c1483fe1979b8b3af64be4f34e110c760 | [
"MIT"
] | 28 | 2019-04-27T00:00:49.000Z | 2021-08-30T07:01:12.000Z | include/elasty/algorithm-type.hpp | yuki-koyama/elasty | 67c7a15c1483fe1979b8b3af64be4f34e110c760 | [
"MIT"
] | 15 | 2019-04-27T01:09:58.000Z | 2022-02-09T13:30:41.000Z | #ifndef ELASTY_ALGORITHM_TYPE_HPP
#define ELASTY_ALGORITHM_TYPE_HPP
namespace elasty
{
enum class AlgorithmType
{
Pbd,
Xpbd
};
}
#endif // ELASTY_ALGORITHM_TYPE_HPP
| 13.928571 | 35 | 0.697436 |
537be64c75a2acd632f61bb9e80b6d443b077e80 | 2,219 | cpp | C++ | Filesystem/Problem36/main.cpp | vegemil/ModernCppChallengeStudy | 52c2bb22c76ae3f3a883ae479cd70ac27513e78d | [
"MIT"
] | null | null | null | Filesystem/Problem36/main.cpp | vegemil/ModernCppChallengeStudy | 52c2bb22c76ae3f3a883ae479cd70ac27513e78d | [
"MIT"
] | null | null | null | Filesystem/Problem36/main.cpp | vegemil/ModernCppChallengeStudy | 52c2bb22c76ae3f3a883ae479cd70ac27513e78d | [
"MIT"
] | null | null | null | // 36. Deleting files older than a given date
// Write a function that, given the path to a directory and a duration, deletes all
// the entries (files or subdirectories) older than the specified duration, in a
// recursive manner. The duration can represent anything, such as days, hours,
// minutes, seconds, and so on, or a combination of that, such as one hour and
// twenty minutes. If the specified directory is itself older than the given duration,
// it should be deleted entirely.
// 36. 특정 날짜보다 오래된 파일들을 지우기
// 어떤 디렉토리에 대한 경로와 기간을 받아서, 정해진 기간보다 오래된 모든 것(파일들 또는 서브
// 디렉토리들)을 재귀적으로 삭제하는 함수를 작성하라. 기간은 일, 시간, 분, 초, 그외 등등, 또는
// 이 것 들의 조합인 한시간 그리고 이십분과 같이 어떤 것으로도 나타낼 수 있다. 만약에 특정 디렉
// 토리가 정해진 기간보다 오래 됐으면, 이 디렉토리 전체가 지워져야 한다
#include "gsl/gsl"
// create `main` function for catch
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
// Redirect CMake's #define to C++ constexpr string
constexpr auto TestName = PROJECT_NAME_STRING;
#include <experimental/filesystem>
#include <ctime>
bool checkModifyDate(std::tm* time, const std::experimental::filesystem::path & p)
{
auto fileTime = std::experimental::filesystem::last_write_time(p);
std::time_t cftime = decltype(fileTime)::clock::to_time_t(fileTime);
std::time_t mtime = std::mktime(time); // time_t 형식으로 변경.
std::cout << p.generic_string() << " ";
if (cftime < mtime)
{
if (std::experimental::filesystem::remove(p) == false)
{
std::cout << "ERROR REMOVE FILE!" << std::endl;
}
else
{
std::cout << "REMOVE FILE SUCCESS!" << std::endl;
}
return false;
}
else
{
std::cout << "FILE SURVIVE!" << std::endl;
return true;
}
}
void checkDirectory(std::tm* time, const std::experimental::filesystem::path & p)
{
if (std::experimental::filesystem::is_directory(p))
{
if (false == checkModifyDate(time, p))
{
return;
}
}
if (true == checkModifyDate(time, p))
{
for (auto& p : std::experimental::filesystem::recursive_directory_iterator(p))
{
checkModifyDate(time, p);
}
}
}
TEST_CASE("Deleting files older than a given date") {
std::istringstream s("2018-10-01");
std::tm x = { 0, };
s >> std::get_time(&x, "%Y-%m-%d");
checkDirectory(&x, "C:\\Users\\euna501\\Downloads\\LINE WORKS");
} | 28.448718 | 86 | 0.679585 |
537cb69b0923b19595b35018463da84a46573bfc | 472 | cpp | C++ | Engine/Source/Misc/Singleton.cpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | 2 | 2022-01-11T21:15:31.000Z | 2022-02-22T21:14:33.000Z | Engine/Source/Misc/Singleton.cpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | null | null | null | Engine/Source/Misc/Singleton.cpp | wdrDarx/DEngine3 | 27e2de3b56b6d4c8705e8a0e36f5911d8651caa2 | [
"MIT"
] | null | null | null | #include "Singleton.h"
void SingletonCache::Store(const std::type_index& type, void* ptr)
{
//return; //using auto registers breaks this whole thing
m_PointerCache[type] = ptr;
}
void* SingletonCache::Find(const std::type_index& type)
{
if(m_PointerCache.empty()) return nullptr;
for (auto& pair : m_PointerCache)
{
if (pair.first == type)
return pair.second;
}
return nullptr;
}
std::unordered_map<std::type_index, void*> SingletonCache::m_PointerCache;
| 20.521739 | 74 | 0.724576 |
537e955672b76efb287ccd96dea5e70143e09d32 | 3,574 | hpp | C++ | chapter20/uncommentedString.hpp | not-sponsored/Sams-Cpp-in-24hrs-Exercises | 2e63e2ca31f5309cc1d593f29c8b47037be150fb | [
"Fair"
] | 2 | 2022-01-08T03:31:25.000Z | 2022-03-09T01:21:54.000Z | chapter20/uncommentedString.hpp | not-sponsored/Sams-Cpp-in-24hrs-Exercises | 2e63e2ca31f5309cc1d593f29c8b47037be150fb | [
"Fair"
] | null | null | null | chapter20/uncommentedString.hpp | not-sponsored/Sams-Cpp-in-24hrs-Exercises | 2e63e2ca31f5309cc1d593f29c8b47037be150fb | [
"Fair"
] | 1 | 2022-03-09T01:26:01.000Z | 2022-03-09T01:26:01.000Z | /*********************************************************
*
* Part of the answer to exercise 1 in chapter 20
*
* Modified 20.3 from Sams Teach Yourself C++ in 24 Hours by Rogers Cadenhead
* and Jesse Liberty
*
* Compiled with g++ (GCC) 11.1.0
*
*********************************************************/
#include <iostream>
#include <string.h>
using std::cout;
using std::cin;
class String
{
public:
// constructors
String();
String(const char *const);
String(const String&);
~String();
// overloaded operators
char& operator[](int offset);
char operator[](int offset) const;
String operator+(const String&);
void operator+=(const String&);
String& operator=(const String &);
// general accessors
int getLen() const { return len; }
const char* getString() const { return value; }
static int constructorCount;
private:
String(int); // private constructor
char* value;
int len;
};
// default constructor creates 0 byte string
String::String()
{
value = new char[1];
value[0] = '\0';
len = 0;
cout << "\tDefault string constructor\n";
constructorCount++;
}
// private helper constructor only for class functions
// creates a string of required size, null filled
String::String(int len)
{
value = new char[len + 1];
int i;
for (i = 0; i < len; i++)
value[i] = '\0';
len = len;
cout << "\tString(int) constructor\n";
constructorCount++;
}
String::String(const char* const cString)
{
len = strlen(cString);
value = new char[len + 1];
int i;
for (i = 0; i < len; i++)
value[i] = cString[i];
value[len] = '\0';
cout << "\tString(char*) constructor\n";
constructorCount++;
}
String::String(const String& rhs)
{
len = rhs.getLen();
value = new char[len + 1];
int i;
for (i = 0; i < len; i++)
value[i] = rhs[i];
value[len] = '\0';
cout << "\tString(String&) constructor\n";
constructorCount++;
}
String::~String()
{
delete [] value;
len = 0;
cout << "\tString destructor\n";
}
// operator equals, frees existing memory and copies string and size
String& String::operator=(const String &rhs)
{
if (this == &rhs)
return *this;
delete [] value;
len = rhs.getLen();
value = new char[len + 1];
int i;
for (i = 0; i < len; i++)
value[i] = rhs[i];
value[len] = '\0';
return *this;
cout << "\tString operator=\n";
}
// non-constant offset operator returns reference to character to be changed
char& String::operator[](int offset)
{
if (offset > len)
return value[len - 1];
else if (offset < 0 && abs(offset) <= len)
return value[len + offset];
else if (offset < 0)
return value[0];
else
return value[offset];
}
// constant offset operator for use on const objects (see copy constructor)
char String::operator[](int offset) const
{
if (offset > len)
return value[len - 1];
else if (offset < 0 && abs(offset) <= len)
return value[len + offset];
else if (offset < 0)
return value[0];
else
return value[offset];
}
// new string by adding current string to rhs
String String::operator+(const String& rhs)
{
int totalLen = len + rhs.getLen();
int i, j;
String temp(totalLen);
for (i = 0; i < len; i++)
temp[i] = value[i];
for (j = 0; j < rhs.getLen(); j++)
temp[i] = rhs[j];
temp[totalLen] = '\0';
return temp;
}
// changes current string, returns nothing
void String::operator+=(const String& rhs)
{
int rhsLen = rhs.getLen();
int totalLen = len + rhsLen;
int i, j;
String temp(totalLen);
for (i = 0; i < len; i++)
temp[i] = value[i];
for (j = 0; j < rhs.getLen(); j++)
temp[i] = rhs[i - len];
temp[totalLen] = '\0';
*this = temp;
}
int String::constructorCount = 0;
| 21.023529 | 77 | 0.618355 |
538125a28def421e2038c7a531a082af2d91a2a8 | 4,127 | cpp | C++ | private/shell/cpls/srvwiz/dllreg.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/shell/cpls/srvwiz/dllreg.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/shell/cpls/srvwiz/dllreg.cpp | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | // dllreg.cpp -- autmatic registration and unregistration
//
#include "priv.h"
#include <advpub.h>
#include <comcat.h>
// helper macros
// ADVPACK will return E_UNEXPECTED if you try to uninstall (which does a registry restore)
// on an INF section that was never installed. We uninstall sections that may never have
// been installed, so this MACRO will quiet these errors.
#define QuietInstallNoOp(hr) ((E_UNEXPECTED == hr) ? S_OK : hr)
BOOL UnregisterTypeLibrary(const CLSID* piidLibrary)
{
TCHAR szScratch[GUIDSTR_MAX];
HKEY hk;
BOOL fResult = FALSE;
// convert the libid into a string.
//
SHStringFromGUID(*piidLibrary, szScratch, ARRAYSIZE(szScratch));
if (RegOpenKey(HKEY_CLASSES_ROOT, TEXT("TypeLib"), &hk) == ERROR_SUCCESS) {
fResult = RegDeleteKey(hk, szScratch);
RegCloseKey(hk);
}
return fResult;
}
HRESULT RegisterTypeLib(void)
{
HRESULT hr = S_OK;
ITypeLib *pTypeLib;
DWORD dwPathLen;
TCHAR szTmp[MAX_PATH];
#ifdef UNICODE
WCHAR *pwsz = szTmp;
#else
WCHAR pwsz[MAX_PATH];
#endif
// Load and register our type library.
//
dwPathLen = GetModuleFileName(HINST_THISDLL, szTmp, ARRAYSIZE(szTmp));
#ifndef UNICODE
if (SHAnsiToUnicode(szTmp, pwsz, MAX_PATH))
#endif
{
hr = LoadTypeLib(pwsz, &pTypeLib);
if (SUCCEEDED(hr))
{
// call the unregister type library as we had some old junk that
// was registered by a previous version of OleAut32, which is now causing
// the current version to not work on NT...
UnregisterTypeLibrary(&LIBID_SrvWizLib);
hr = RegisterTypeLib(pTypeLib, pwsz, NULL);
if (FAILED(hr))
{
}
pTypeLib->Release();
}
else
{
}
}
#ifndef UNICODE
else {
hr = E_FAIL;
}
#endif
return hr;
}
/*----------------------------------------------------------
Purpose: Calls the ADVPACK entry-point which executes an inf
file section.
Returns:
Cond: --
*/
HRESULT CallRegInstall(HINSTANCE hinstSrvWiz, LPSTR szSection)
{
HRESULT hr = E_FAIL;
HINSTANCE hinstAdvPack = LoadLibrary(TEXT("ADVPACK.DLL"));
if (hinstAdvPack)
{
REGINSTALL pfnri = (REGINSTALL)GetProcAddress(hinstAdvPack, "RegInstall");
if (pfnri)
{
char szThisDLL[MAX_PATH];
// Get the location of this DLL from the HINSTANCE
if ( !GetModuleFileNameA(hinstSrvWiz, szThisDLL, ARRAYSIZE(szThisDLL)) )
{
// Failed, just say "srvwiz.dll"
lstrcpyA(szThisDLL, "srvwiz.dll");
}
STRENTRY seReg[] = {
{ "THISDLL", szThisDLL },
// These two NT-specific entries must be at the end
{ "25", "%SystemRoot%" },
{ "11", "%SystemRoot%\\system32" },
};
STRTABLE stReg = { ARRAYSIZE(seReg), seReg };
hr = pfnri(g_hinst, szSection, &stReg);
}
FreeLibrary(hinstAdvPack);
}
return hr;
}
STDAPI DllRegisterServer(void)
{
HRESULT hr;
// Delete any old registration entries, then add the new ones.
// Keep ADVPACK.DLL loaded across multiple calls to RegInstall.
// (The inf engine doesn't guarantee DelReg/AddReg order, that's
// why we explicitly unreg and reg here.)
//
HINSTANCE hinstSrvWiz = GetModuleHandle(TEXT("SRVWIZ.DLL"));
hr = CallRegInstall(hinstSrvWiz, "RegDll");
RegisterTypeLib();
return hr;
}
STDAPI DllUnregisterServer(void)
{
HRESULT hr;
HINSTANCE hinstSrvWiz = GetModuleHandle(TEXT("SRVWIZ.DLL"));
// UnInstall the registry values
hr = CallRegInstall(hinstSrvWiz, "UnregDll");
UnregisterTypeLibrary(&LIBID_SrvWizLib);
return hr;
}
STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine)
{
return S_OK;
}
| 25.012121 | 92 | 0.580082 |
53830346afd4c02fa7869d8037de73ed1ec97ef6 | 11,459 | cpp | C++ | Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp | dfyzy/StealthTest | ff48d800ef073abd559048d81df7efd014c91cb7 | [
"MIT"
] | null | null | null | Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp | dfyzy/StealthTest | ff48d800ef073abd559048d81df7efd014c91cb7 | [
"MIT"
] | null | null | null | Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp | dfyzy/StealthTest | ff48d800ef073abd559048d81df7efd014c91cb7 | [
"MIT"
] | null | null | null |
#include "SmMarginCustomization.h"
#include "PropertyHandle.h"
#include "DetailLayoutBuilder.h"
#include "Widgets/Input/SNumericEntryBox.h"
#include "Editor.h"
bool FSmMarginIdentifier::IsPropertyTypeCustomized(const IPropertyHandle& PropertyHandle) const
{
return PropertyHandle.IsValidHandle() && PropertyHandle.GetMetaDataProperty()->HasMetaData("SmMargin");
}
void FSmMarginCustomization::GetSortedChildren(TSharedRef<IPropertyHandle> StructPropertyHandle, TArray<TSharedRef<IPropertyHandle>>& OutChildren)
{
OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Left")).ToSharedRef());
OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Top")).ToSharedRef());
OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Right")).ToSharedRef());
OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Bottom")).ToSharedRef());
}
TSharedRef<SWidget> FSmMarginCustomization::MakeChildWidget(TSharedRef<IPropertyHandle>& StructurePropertyHandle, TSharedRef<IPropertyHandle>& PropertyHandle)
{
TOptional<float> MinValue, MaxValue, SliderMinValue, SliderMaxValue;
float SliderExponent, Delta;
int32 ShiftMouseMovePixelPerDelta = 1;
bool SupportDynamicSliderMaxValue = false;
bool SupportDynamicSliderMinValue = false;
{
FProperty* Property = PropertyHandle->GetProperty();
const FString& MetaUIMinString = Property->GetMetaData(TEXT("UIMin"));
const FString& MetaUIMaxString = Property->GetMetaData(TEXT("UIMax"));
const FString& SliderExponentString = Property->GetMetaData(TEXT("SliderExponent"));
const FString& DeltaString = Property->GetMetaData(TEXT("Delta"));
const FString& ShiftMouseMovePixelPerDeltaString = Property->GetMetaData(TEXT("ShiftMouseMovePixelPerDelta"));
const FString& SupportDynamicSliderMaxValueString = Property->GetMetaData(TEXT("SupportDynamicSliderMaxValue"));
const FString& SupportDynamicSliderMinValueString = Property->GetMetaData(TEXT("SupportDynamicSliderMinValue"));
const FString& ClampMinString = Property->GetMetaData(TEXT("ClampMin"));
const FString& ClampMaxString = Property->GetMetaData(TEXT("ClampMax"));
// If no UIMin/Max was specified then use the clamp string
const FString& UIMinString = MetaUIMinString.Len() ? MetaUIMinString : ClampMinString;
const FString& UIMaxString = MetaUIMaxString.Len() ? MetaUIMaxString : ClampMaxString;
float ClampMin = TNumericLimits<float>::Lowest();
float ClampMax = TNumericLimits<float>::Max();
if (!ClampMinString.IsEmpty())
{
TTypeFromString<float>::FromString(ClampMin, *ClampMinString);
}
if (!ClampMaxString.IsEmpty())
{
TTypeFromString<float>::FromString(ClampMax, *ClampMaxString);
}
float UIMin = TNumericLimits<float>::Lowest();
float UIMax = TNumericLimits<float>::Max();
TTypeFromString<float>::FromString(UIMin, *UIMinString);
TTypeFromString<float>::FromString(UIMax, *UIMaxString);
SliderExponent = float(1);
if (SliderExponentString.Len())
{
TTypeFromString<float>::FromString(SliderExponent, *SliderExponentString);
}
Delta = float(0);
if (DeltaString.Len())
{
TTypeFromString<float>::FromString(Delta, *DeltaString);
}
ShiftMouseMovePixelPerDelta = 1;
if (ShiftMouseMovePixelPerDeltaString.Len())
{
TTypeFromString<int32>::FromString(ShiftMouseMovePixelPerDelta, *ShiftMouseMovePixelPerDeltaString);
//The value should be greater or equal to 1
// 1 is neutral since it is a multiplier of the mouse drag pixel
if (ShiftMouseMovePixelPerDelta < 1)
{
ShiftMouseMovePixelPerDelta = 1;
}
}
if (ClampMin >= ClampMax && (ClampMinString.Len() || ClampMaxString.Len()))
{
//UE_LOG(LogPropertyNode, Warning, TEXT("Clamp Min (%s) >= Clamp Max (%s) for Ranged Numeric"), *ClampMinString, *ClampMaxString);
}
const float ActualUIMin = FMath::Max(UIMin, ClampMin);
const float ActualUIMax = FMath::Min(UIMax, ClampMax);
MinValue = ClampMinString.Len() ? ClampMin : TOptional<float>();
MaxValue = ClampMaxString.Len() ? ClampMax : TOptional<float>();
SliderMinValue = (UIMinString.Len()) ? ActualUIMin : TOptional<float>();
SliderMaxValue = (UIMaxString.Len()) ? ActualUIMax : TOptional<float>();
if (ActualUIMin >= ActualUIMax && (MetaUIMinString.Len() || MetaUIMaxString.Len()))
{
//UE_LOG(LogPropertyNode, Warning, TEXT("UI Min (%s) >= UI Max (%s) for Ranged Numeric"), *UIMinString, *UIMaxString);
}
SupportDynamicSliderMaxValue = SupportDynamicSliderMaxValueString.Len() > 0 && SupportDynamicSliderMaxValueString.ToBool();
SupportDynamicSliderMinValue = SupportDynamicSliderMinValueString.Len() > 0 && SupportDynamicSliderMinValueString.ToBool();
}
TWeakPtr<IPropertyHandle> WeakHandlePtr = PropertyHandle;
return SNew(SNumericEntryBox<float>)
.IsEnabled(this, &FMathStructCustomization::IsValueEnabled, WeakHandlePtr)
.EditableTextBoxStyle(&FCoreStyle::Get().GetWidgetStyle<FEditableTextBoxStyle>("NormalEditableTextBox"))
.Value(this, &FSmMarginCustomization::OnGetValue, WeakHandlePtr)
.Font(IDetailLayoutBuilder::GetDetailFont())
.UndeterminedString(NSLOCTEXT("PropertyEditor", "MultipleValues", "Multiple Values"))
.OnValueCommitted(this, &FSmMarginCustomization::OnValueCommitted, WeakHandlePtr)
.OnValueChanged(this, &FSmMarginCustomization::OnValueChanged, WeakHandlePtr)
.OnBeginSliderMovement(this, &FSmMarginCustomization::OnBeginSliderMovement)
.OnEndSliderMovement(this, &FSmMarginCustomization::OnEndSliderMovement)
.LabelVAlign(VAlign_Center)
// Only allow spin on handles with one object. Otherwise it is not clear what value to spin
.AllowSpin(PropertyHandle->GetNumOuterObjects() < 2)
.ShiftMouseMovePixelPerDelta(ShiftMouseMovePixelPerDelta)
.SupportDynamicSliderMaxValue(SupportDynamicSliderMaxValue)
.SupportDynamicSliderMinValue(SupportDynamicSliderMinValue)
.OnDynamicSliderMaxValueChanged(this, &FSmMarginCustomization::OnDynamicSliderMaxValueChanged)
.OnDynamicSliderMinValueChanged(this, &FSmMarginCustomization::OnDynamicSliderMinValueChanged)
.MinValue(MinValue)
.MaxValue(MaxValue)
.MinSliderValue(SliderMinValue)
.MaxSliderValue(SliderMaxValue)
.SliderExponent(SliderExponent)
.Delta(Delta);
}
void FSmMarginCustomization::SetValue(float NewValue, EPropertyValueSetFlags::Type Flags, TWeakPtr<IPropertyHandle> WeakHandlePtr)
{
if (bPreserveScaleRatio)
{
// Get the value for each object for the modified component
TArray<FString> OldValues;
if (WeakHandlePtr.Pin()->GetPerObjectValues(OldValues) == FPropertyAccess::Success)
{
// Loop through each object and scale based on the new ratio for each object individually
for (int32 OutputIndex = 0; OutputIndex < OldValues.Num(); ++OutputIndex)
{
float OldValue;
TTypeFromString<float>::FromString(OldValue, *OldValues[OutputIndex]);
// Account for the previous scale being zero. Just set to the new value in that case?
float Ratio = OldValue == 0 ? NewValue : NewValue / OldValue;
if (Ratio == 0)
{
Ratio = NewValue;
}
// Loop through all the child handles (each component of the math struct, like X, Y, Z...etc)
for (int32 ChildIndex = 0; ChildIndex < SortedChildHandles.Num(); ++ChildIndex)
{
// Ignore scaling our selves.
TSharedRef<IPropertyHandle> ChildHandle = SortedChildHandles[ChildIndex];
if (ChildHandle != WeakHandlePtr.Pin())
{
// Get the value for each object.
TArray<FString> ObjectChildValues;
if (ChildHandle->GetPerObjectValues(ObjectChildValues) == FPropertyAccess::Success)
{
// Individually scale each object's components by the same ratio.
for (int32 ChildOutputIndex = 0; ChildOutputIndex < ObjectChildValues.Num(); ++ChildOutputIndex)
{
float ChildOldValue;
TTypeFromString<float>::FromString(ChildOldValue, *ObjectChildValues[ChildOutputIndex]);
float ChildNewValue = ChildOldValue * Ratio;
ObjectChildValues[ChildOutputIndex] = TTypeToString<float>::ToSanitizedString(ChildNewValue);
}
ChildHandle->SetPerObjectValues(ObjectChildValues);
}
}
}
}
}
}
WeakHandlePtr.Pin()->SetValue(NewValue, Flags);
}
TOptional<float> FSmMarginCustomization::OnGetValue(TWeakPtr<IPropertyHandle> WeakHandlePtr) const
{
float NumericVal = 0;
if (WeakHandlePtr.Pin()->GetValue(NumericVal) == FPropertyAccess::Success)
{
return TOptional<float>(NumericVal);
}
// Value couldn't be accessed. Return an unset value
return TOptional<float>();
}
void FSmMarginCustomization::OnValueCommitted(float NewValue, ETextCommit::Type CommitType, TWeakPtr<IPropertyHandle> WeakHandlePtr)
{
EPropertyValueSetFlags::Type Flags = EPropertyValueSetFlags::DefaultFlags;
SetValue(NewValue, Flags, WeakHandlePtr);
}
void FSmMarginCustomization::OnValueChanged(float NewValue, TWeakPtr<IPropertyHandle> WeakHandlePtr)
{
if (bIsUsingSlider)
{
EPropertyValueSetFlags::Type Flags = EPropertyValueSetFlags::InteractiveChange;
SetValue(NewValue, Flags, WeakHandlePtr);
}
}
void FSmMarginCustomization::OnBeginSliderMovement()
{
bIsUsingSlider = true;
GEditor->BeginTransaction(NSLOCTEXT("FMathStructCustomization", "SetVectorProperty", "Set Vector Property"));
}
void FSmMarginCustomization::OnEndSliderMovement(float NewValue)
{
bIsUsingSlider = false;
GEditor->EndTransaction();
}
void FSmMarginCustomization::OnDynamicSliderMaxValueChanged(float NewMaxSliderValue, TWeakPtr<SWidget> InValueChangedSourceWidget, bool IsOriginator, bool UpdateOnlyIfHigher)
{
for (TWeakPtr<SWidget>& Widget : NumericEntryBoxWidgetList)
{
TSharedPtr<SNumericEntryBox<float>> NumericBox = StaticCastSharedPtr<SNumericEntryBox<float>>(Widget.Pin());
if (NumericBox.IsValid())
{
TSharedPtr<SSpinBox<float>> SpinBox = StaticCastSharedPtr<SSpinBox<float>>(NumericBox->GetSpinBox());
if (SpinBox.IsValid())
{
if (SpinBox != InValueChangedSourceWidget)
{
if ((NewMaxSliderValue > SpinBox->GetMaxSliderValue() && UpdateOnlyIfHigher) || !UpdateOnlyIfHigher)
{
// Make sure the max slider value is not a getter otherwise we will break the link!
verifySlow(!SpinBox->IsMaxSliderValueBound());
SpinBox->SetMaxSliderValue(NewMaxSliderValue);
}
}
}
}
}
if (IsOriginator)
{
OnNumericEntryBoxDynamicSliderMaxValueChanged.Broadcast((float)NewMaxSliderValue, InValueChangedSourceWidget, false, UpdateOnlyIfHigher);
}
}
void FSmMarginCustomization::OnDynamicSliderMinValueChanged(float NewMinSliderValue, TWeakPtr<SWidget> InValueChangedSourceWidget, bool IsOriginator, bool UpdateOnlyIfLower)
{
for (TWeakPtr<SWidget>& Widget : NumericEntryBoxWidgetList)
{
TSharedPtr<SNumericEntryBox<float>> NumericBox = StaticCastSharedPtr<SNumericEntryBox<float>>(Widget.Pin());
if (NumericBox.IsValid())
{
TSharedPtr<SSpinBox<float>> SpinBox = StaticCastSharedPtr<SSpinBox<float>>(NumericBox->GetSpinBox());
if (SpinBox.IsValid())
{
if (SpinBox != InValueChangedSourceWidget)
{
if ((NewMinSliderValue < SpinBox->GetMinSliderValue() && UpdateOnlyIfLower) || !UpdateOnlyIfLower)
{
// Make sure the min slider value is not a getter otherwise we will break the link!
verifySlow(!SpinBox->IsMinSliderValueBound());
SpinBox->SetMinSliderValue(NewMinSliderValue);
}
}
}
}
}
if (IsOriginator)
{
OnNumericEntryBoxDynamicSliderMinValueChanged.Broadcast((float)NewMinSliderValue, InValueChangedSourceWidget, false, UpdateOnlyIfLower);
}
}
| 38.844068 | 174 | 0.761498 |
5384176a24be9a050c35188a1a18a9ebb667084b | 9,232 | cpp | C++ | betteryao/OTExtension/util/Miracl/zzn3.cpp | bt3ze/pcflib | c66cdc5957818cd5b3754430046cad91ce1a921d | [
"BSD-2-Clause"
] | null | null | null | betteryao/OTExtension/util/Miracl/zzn3.cpp | bt3ze/pcflib | c66cdc5957818cd5b3754430046cad91ce1a921d | [
"BSD-2-Clause"
] | null | null | null | betteryao/OTExtension/util/Miracl/zzn3.cpp | bt3ze/pcflib | c66cdc5957818cd5b3754430046cad91ce1a921d | [
"BSD-2-Clause"
] | null | null | null |
/***************************************************************************
*
Copyright 2013 CertiVox IOM Ltd. *
*
This file is part of CertiVox MIRACL Crypto SDK. *
*
The CertiVox MIRACL Crypto SDK provides developers with an *
extensive and efficient set of cryptographic functions. *
For further information about its features and functionalities please *
refer to http://www.certivox.com *
*
* The CertiVox MIRACL Crypto SDK is free software: you can *
redistribute it and/or modify it under the terms of the *
GNU Affero General Public License as published by the *
Free Software Foundation, either version 3 of the License, *
or (at your option) any later version. *
*
* The CertiVox MIRACL Crypto SDK is distributed in the hope *
that it will be useful, but WITHOUT ANY WARRANTY; without even the *
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
See the GNU Affero General Public License for more details. *
*
* You should have received a copy of the GNU Affero General Public *
License along with CertiVox MIRACL Crypto SDK. *
If not, see <http://www.gnu.org/licenses/>. *
*
You can be released from the requirements of the license by purchasing *
a commercial license. Buying such a license is mandatory as soon as you *
develop commercial activities involving the CertiVox MIRACL Crypto SDK *
without disclosing the source code of your own applications, or shipping *
the CertiVox MIRACL Crypto SDK with a closed source product. *
*
***************************************************************************/
/*
* MIRACL C++ Implementation file zzn3.cpp
*
* AUTHOR : M. Scott
*
* PURPOSE : Implementation of class ZZn3 (Arithmetic over n^3)
*
* WARNING: This class has been cobbled together for a specific use with
* the MIRACL library. It is not complete, and may not work in other
* applications
*
* Assumes p=1 mod 3 and p NOT 1 mod 8
* Irreducible is x^3+cnr (cubic non-residue)
*
*/
#include "zzn3.h"
using namespace std;
// First find a cubic non-residue cnr, which is also a quadratic non-residue
// X is precalculated sixth root of unity (cnr)^(p-1)/6
void ZZn3::get(ZZn& x,ZZn& y,ZZn& z) const
{copy(fn.a,x.getzzn()); copy(fn.b,y.getzzn()); copy(fn.c,z.getzzn());}
void ZZn3::get(ZZn& x) const
{{copy(fn.a,x.getzzn());}}
ZZn3& ZZn3::operator/=(const ZZn& x)
{
ZZn t=(ZZn)1/x;
zzn3_smul(&fn,t.getzzn(),&fn);
return *this;
}
ZZn3& ZZn3::operator/=(int i)
{
if (i==2) {zzn3_div2(&fn); return *this;}
ZZn t=one()/i;
zzn3_smul(&fn,t.getzzn(),&fn);
return *this;
}
ZZn3& ZZn3::operator/=(const ZZn3& x)
{
*this*=inverse(x);
return *this;
}
ZZn3 inverse(const ZZn3& w)
{ZZn3 i=w; zzn3_inv(&i.fn); return i;}
ZZn3 operator+(const ZZn3& x,const ZZn3& y)
{ZZn3 w=x; w+=y; return w; }
ZZn3 operator+(const ZZn3& x,const ZZn& y)
{ZZn3 w=x; w+=y; return w; }
ZZn3 operator-(const ZZn3& x,const ZZn3& y)
{ZZn3 w=x; w-=y; return w; }
ZZn3 operator-(const ZZn3& x,const ZZn& y)
{ZZn3 w=x; w-=y; return w; }
ZZn3 operator-(const ZZn3& x)
{ZZn3 w; zzn3_negate((zzn3 *)&x.fn,&w.fn); return w; }
ZZn3 operator*(const ZZn3& x,const ZZn3& y)
{
ZZn3 w=x;
if (&x==&y) w*=w;
else w*=y;
return w;
}
ZZn3 operator*(const ZZn3& x,const ZZn& y)
{ZZn3 w=x; w*=y; return w;}
ZZn3 operator*(const ZZn& y,const ZZn3& x)
{ZZn3 w=x; w*=y; return w;}
ZZn3 operator*(const ZZn3& x,int y)
{ZZn3 w=x; w*=y; return w;}
ZZn3 operator*(int y,const ZZn3& x)
{ZZn3 w=x; w*=y; return w;}
ZZn3 operator/(const ZZn3& x,const ZZn3& y)
{ZZn3 w=x; w/=y; return w;}
ZZn3 operator/(const ZZn3& x,const ZZn& y)
{ZZn3 w=x; w/=y; return w;}
ZZn3 operator/(const ZZn3& x,int i)
{ZZn3 w=x; w/=i; return w;}
#ifndef MR_NO_RAND
ZZn3 randn3(void)
{ZZn3 w; zzn3_from_zzns(randn().getzzn(),randn().getzzn(),randn().getzzn(),&w.fn); return w;}
#endif
ZZn3 rhs(const ZZn3& x)
{
ZZn3 w;
miracl *mip=get_mip();
int twist=mip->TWIST;
int qnr=mip->cnr; // the cubic non-residue is also a quadratic non-residue
w=x*x*x;
if (twist)
{
if (twist==MR_QUARTIC_M)
{
w+=tx((ZZn3)getA())*x;
}
if (twist==MR_QUARTIC_D)
{
w+=txd((ZZn3)getA())*x;
}
if (twist==MR_SEXTIC_M || twist==MR_CUBIC_M)
{
w+=tx((ZZn3)getB());
}
if (twist==MR_SEXTIC_D || twist==MR_CUBIC_D)
{
w+=txd((ZZn3)getB());
}
if (twist==MR_QUADRATIC)
{
w+=qnr*qnr*getA()*x+(qnr*qnr*qnr)*getB();
}
}
else
{
w+=getA()*x+getB();
}
return w;
}
BOOL is_on_curve(const ZZn3& x)
{
ZZn3 w;
if (qr(rhs(x))) return TRUE;
return FALSE;
}
BOOL qr(const ZZn3& x)
{
Big p=get_modulus();
ZZn3 r,t;
t=r=x;
t.powq();
r*=t;
t.powq();
r*=t;
// check x^[(p^3-1)/2] = 1
if (pow(r,(p-1)/2)==1) return TRUE;
else return FALSE;
}
ZZn3 sqrt(const ZZn3& x)
{
ZZn3 r,w,t;
Big p=get_modulus();
if (!qr(x)) return r;
// oh boy this is clever!
switch (get_mip()->pmod8)
{
case 5:
r=(x+x);
r.powq();
w=r*r; t=w*r; w*=t;
r.powq();
r*=(w*(x+x));
r=pow(r,(p-5)/8);
r*=t;
w=r*r; w*=x; w+=w;
r*=x; r*=(w-(ZZn)1);
break;
case 3:
case 7:
r=x;
r.powq();
t=r*r;
w=t*r;
r.powq();
r*=(w*x);
r=pow(r,(p-3)/4);
r*=(t*x);
break;
default: break;
}
return r;
}
ZZn3 tx(const ZZn3& w)
{
ZZn3 u=w;
zzn3_timesi(&u.fn);
return u;
}
ZZn3 tx2(const ZZn3& w)
{
ZZn3 u=w;
zzn3_timesi2(&u.fn);
return u;
}
ZZn3 txd(const ZZn3& w)
{
ZZn3 u;
ZZn wa,wb,wc;
w.get(wa,wb,wc);
u.set(wb,wc,(wa/get_mip()->cnr));
return u;
}
// regular ZZn3 powering
ZZn3 pow(const ZZn3& x,const Big& k)
{
int i,j,nb,n,nbw,nzs;
ZZn3 u,u2,t[16];
if (k==0) return (ZZn3)1;
u=x;
if (k==1) return u;
//
// Prepare table for windowing
//
u2=(u*u);
t[0]=u;
for (i=1;i<16;i++)
t[i]=u2*t[i-1];
// Left to right method - with windows
nb=bits(k);
if (nb>1) for (i=nb-2;i>=0;)
{
n=window(k,i,&nbw,&nzs,5);
for (j=0;j<nbw;j++) u*=u;
if (n>0) u*=t[n/2];
i-=nbw;
if (nzs)
{
for (j=0;j<nzs;j++) u*=u;
i-=nzs;
}
}
return u;
}
ZZn3 powl(const ZZn3& x,const Big& k)
{
ZZn3 A,B,two,y;
int j,nb;
two=(ZZn)2;
y=two*x;
// y=x;
if (k==0) return (ZZn3)two;
if (k==1) return y;
// w8=two;
// w9=y;
A=y;
B=y*y-two;
nb=bits(k);
//cout << "nb= " << nb << endl;
for (j=nb-1;j>=1;j--)
{
if (bit(k,j-1))
{
A*=B; A-=y; B*=B; B-=two;
}
else
{
B*=A; B-=y; A*=A; A-=two;
}
//cout << "1. int A= " << A << endl;
}
//cout << "1. B= " << B << endl;
return A/2;
// return (w8/2);
}
// double exponention - see Schoenmaker's method from Stam's thesis
ZZn3 powl(const ZZn3& x,const Big& n,const ZZn3& y,const Big& m,const ZZn3& a)
{
ZZn3 A,B,C,T,two,vk,vl,va;
int j,nb;
two=(ZZn)2;
vk=x+x;
vl=y+y;
va=a+a;
nb=bits(n);
if (bits(m)>nb) nb=bits(m);
//cout << "nb= " << nb << endl;
A=two; B=vk; C=vl;
/*
cout << "A= " << A << endl;
cout << "B= " << B << endl;
cout << "C= " << C << endl;
cout << "vk= " << vk << endl;
cout << "vl= " << vl << endl;
cout << "va= " << va << endl;
cout << "va*va-2= " << va*va-two << endl;
*/
for (j=nb;j>=1;j--)
{
if (bit(n,j-1)==0 && bit(m,j-1)==0)
{
B*=A; B-=vk; C*=A; C-=vl; A*=A; A-=two;
}
if (bit(n,j-1)==1 && bit(m,j-1)==0)
{
A*=B; A-=vk; C*=B; C-=va; B*=B; B-=two;
}
if (bit(n,j-1)==0 && bit(m,j-1)==1)
{
A*=C; A-=vl; B*=C; B-=va; C*=C; C-=two;
}
if (bit(n,j-1)==1 && bit(m,j-1)==1)
{
T=B*C-va; B*=A; B-=vk; C*=A; C-=vl; A=T;
T=A*vl-B; B=A*vk-C; C=T;
}
}
// return A;
return (A/2);
}
#ifndef MR_NO_STANDARD_IO
ostream& operator<<(ostream& s,const ZZn3& xx)
{
ZZn3 b=xx;
ZZn x,y,z;
b.get(x,y,z);
s << "[" << x << "," << y << "," << z << "]";
return s;
}
#endif
| 23.313131 | 93 | 0.476603 |
5388a234101dcf52c200eecd8a41f23fcd7d8291 | 843 | cpp | C++ | ThreeCharacters/CPP/main.cpp | hecate-xw/Miscellaneous | 57c5ade630f1f1af2a5aae7f2541638380fc4876 | [
"MIT"
] | null | null | null | ThreeCharacters/CPP/main.cpp | hecate-xw/Miscellaneous | 57c5ade630f1f1af2a5aae7f2541638380fc4876 | [
"MIT"
] | null | null | null | ThreeCharacters/CPP/main.cpp | hecate-xw/Miscellaneous | 57c5ade630f1f1af2a5aae7f2541638380fc4876 | [
"MIT"
] | 1 | 2020-02-13T00:48:17.000Z | 2020-02-13T00:48:17.000Z | #include <iostream>
#include "PowMatrix.h"
using namespace std;
int main() {
int n;
cin >> n;
/*
// Method 1
int dp[n][2];
dp[0][0] = 3;
dp[0][1] = 0;
for(int i = 1; i < n; i++) {
dp[i][0] = dp[i-1][0]*2 + dp[i-1][1]*2;
dp[i][1] = dp[i-1][0];
}
int sum = dp[n-1][0] + dp[n-1][1];
*/
/*
// Method 2
int dp0 = 3;
int dp1 = 0;
for(int i = 1; i < n; i++) {
int temp = dp0;
dp0 = 2*dp0 + 2*dp1;
dp1 = temp;
}
int sum = dp0+dp1;
*/
// Method 3
int dimension = 2;
int matrix[2*2] = {2,2,1,0};
PowMatrix powMatrix(dimension);
powMatrix.setMatrix(matrix);
int count = n-1;
powMatrix.pow(count);
int* result = powMatrix.getResult();
int sum = 3 * result[0] + 3 * result[2];
cout << sum << endl;
return 0;
}
| 15.327273 | 47 | 0.465006 |
538a0884ca5e025ad80b5788b0faa5f47e118860 | 10,353 | cpp | C++ | Tools/GHGUITool/GHGUITool/GTGUINavigator.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | Tools/GHGUITool/GHGUITool/GTGUINavigator.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | Tools/GHGUITool/GHGUITool/GTGUINavigator.cpp | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | // Copyright 2010 Golden Hammer Software
#include "GTGUINavigator.h"
#include "GTIdentifiers.h"
#include "GHUtils/GHEventMgr.h"
#include "GHUtils/GHMessage.h"
#include "GHGUIMgr.h"
#include "GHUtils/GHResourceFactory.h"
#include "GHXMLObjFactory.h"
#include "GHGUIPanel.h"
#include "GHXMLNode.h"
#include "GHGUIWidgetRenderer.h"
#include "GHUtils/GHPropertyContainer.h"
#include "GTChange.h"
#include "GHMath/GHRandom.h"
#include "GTUtil.h"
#include "GHUtils/GHUtilsIdentifiers.h"
#include "GTMetadataList.h"
#include "GTChangePusher.h"
#include "GTMoveType.h"
#include "GHMath/GHFloat.h"
#include "GHGUIText.h"
GTGUINavigator::GTGUINavigator(GHEventMgr& eventMgr,
GHGUIWidgetResource& topLevelGUI,
GHGUIWidgetResource*& currentSelectionPtr,
GTUtil& util,
GTMetadataList& metadataList,
GHPropertyContainer& properties,
const GHGUIRectMaker& rectMaker,
const GHScreenInfo& screenInfo)
: mEventMgr(eventMgr)
, mTopPanel(topLevelGUI)
, mCurrentPanel(currentSelectionPtr)
, mProperties(properties)
, mPosDescConverter(rectMaker, screenInfo)
, mUtil(util)
, mMetadataList(metadataList)
, mMoveType(GTMoveType::OFFSET)
{
mEventMgr.registerListener(GTIdentifiers::M_CREATEPANEL, *this);
mEventMgr.registerListener(GTIdentifiers::M_DELETEPANEL, *this);
mEventMgr.registerListener(GTIdentifiers::M_SELECTPANEL, *this);
mEventMgr.registerListener(GTIdentifiers::M_MOVEPANEL, *this);
mEventMgr.registerListener(GTIdentifiers::M_MOVEEND, *this);
mEventMgr.registerListener(GTIdentifiers::M_SETCOLOR, *this);
mEventMgr.registerListener(GTIdentifiers::M_SETTEXTURE, *this);
mEventMgr.registerListener(GTIdentifiers::M_SHIFTPRESSED, *this);
mEventMgr.registerListener(GTIdentifiers::M_SHIFTRELEASED, *this);
mEventMgr.registerListener(GTIdentifiers::M_SETMOVETYPE, *this);
}
GTGUINavigator::~GTGUINavigator(void)
{
mEventMgr.unregisterListener(GTIdentifiers::M_SETMOVETYPE, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_SHIFTRELEASED, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_SHIFTPRESSED, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_SETTEXTURE, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_SETCOLOR, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_MOVEEND, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_MOVEPANEL, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_SELECTPANEL, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_DELETEPANEL, *this);
mEventMgr.unregisterListener(GTIdentifiers::M_CREATEPANEL, *this);
}
void GTGUINavigator::handleMessage(const GHMessage& message)
{
if (message.getType() == GTIdentifiers::M_CREATEPANEL)
{
bool createAsChild = message.getPayload().getProperty(GTIdentifiers::MP_CREATEASCHILD);
createPanel(createAsChild);
}
else if (message.getType() == GTIdentifiers::M_DELETEPANEL)
{
deletePanel();
}
else if (message.getType() == GTIdentifiers::M_SELECTPANEL)
{
const GHPoint2* selectPt = (const GHPoint2*)message.getPayload().getProperty(GTIdentifiers::MP_SELECTPOINT);
if (selectPt)
{
if (!selectChildren(mTopPanel, *selectPt))
{
mCurrentPanel = 0;
}
}
bringSelectionToFront();
}
else if (message.getType() == GTIdentifiers::M_MOVEPANEL)
{
const GHPoint2* delta = (const GHPoint2*)message.getPayload().getProperty(GTIdentifiers::MP_MOVEDELTA);
if (delta) {
movePanel(*delta);
}
}
else if (message.getType() == GTIdentifiers::M_MOVEEND)
{
if (mCurrentPanel)
{
const GHGUIPosDesc& newDesc = mCurrentPanel->get()->getPosDesc();
if (newDesc != mPosBeforeMove)
{
GTChangePusher changePusher(mEventMgr, mMetadataList, mCurrentPanel);
GTMetadata* metadata = changePusher.createMetadataClone();
metadata->mPosDesc = newDesc;
changePusher.pushChange(metadata);
}
}
}
else if (message.getType() == GTIdentifiers::M_SETCOLOR)
{
GHPoint4* color = message.getPayload().getProperty(GTIdentifiers::MP_COLOR);
if (color && mCurrentPanel && mCurrentPanel->get())
{
GTChangePusher changePusher(mEventMgr, mMetadataList, mCurrentPanel);
mUtil.setColor(*mCurrentPanel, *color, &changePusher);
}
}
else if (message.getType() == GTIdentifiers::M_SETTEXTURE)
{
if (mCurrentPanel && mCurrentPanel->get())
{
const char* filename = message.getPayload().getProperty(GHUtilsIdentifiers::FILEPATH);
GTChangePusher changePusher(mEventMgr, mMetadataList, mCurrentPanel);
mUtil.setTexture(*mCurrentPanel, filename, changePusher);
}
}
else if (message.getType() == GTIdentifiers::M_SHIFTPRESSED)
{
mMoveData.shiftPressed = true;
}
else if (message.getType() == GTIdentifiers::M_SHIFTRELEASED)
{
mMoveData.shiftPressed = false;
}
else if (message.getType() == GTIdentifiers::M_SETMOVETYPE)
{
int moveType = (int)message.getPayload().getProperty(GHUtilsIdentifiers::VAL);
mMoveType = moveType;
}
}
void GTGUINavigator::createPanel(bool asChild)
{
GHGUIWidgetResource* parent = &mTopPanel;
if (asChild && mCurrentPanel) {
parent = mCurrentPanel;
}
GHGUIWidgetResource* panel = panel = mUtil.createPanel();
//default vals
GHGUIPosDesc posDesc;
posDesc.mXFill = GHFillType::FT_PIXELS;
posDesc.mYFill = GHFillType::FT_PIXELS;
posDesc.mAlign.setCoords(.5, .5);
posDesc.mOffset.setCoords(0, 0);
posDesc.mSize.setCoords(300, 67.5); //menu button
posDesc.mSizeAlign[0] = GHAlign::A_CENTER;
posDesc.mSizeAlign[1] = GHAlign::A_CENTER;
panel->get()->setPosDesc(posDesc);
//GHXMLNode* matNode = createTextureMatNode("bgrect.png", GHString::CHT_REFERENCE);
mCurrentPanel = panel;
mUtil.setRandomColor(*mCurrentPanel);
parent->get()->addChild(panel);
pushCreation(parent);
bringSelectionToFront();
}
void GTGUINavigator::deletePanel(void)
{
if (!mCurrentPanel) { return; }
GHGUIWidgetResource* parent = mUtil.findParent(mTopPanel, *mCurrentPanel);
if (parent) {
mCurrentPanel->acquire();
parent->get()->removeChild(mCurrentPanel);
pushDeletion(parent);
mCurrentPanel->release();
mCurrentPanel = 0;
}
}
void GTGUINavigator::pushCreation(GHGUIWidgetResource* parent)
{
GTChangePusher pusher(mEventMgr, mMetadataList, mCurrentPanel);
GTMetadata* newData = new GTMetadata(mCurrentPanel->get()->getId(),
parent->get()->getId(),
mCurrentPanel->get()->getPosDesc(),
0, 0);
pusher.pushChange(0, newData);
}
void GTGUINavigator::pushDeletion(GHGUIWidgetResource* parent)
{
GTChangePusher pusher(mEventMgr, mMetadataList, mCurrentPanel);
pusher.pushChange(0);
}
void GTGUINavigator::bringSelectionToFront(void)
{
if (mCurrentPanel)
{
mPosBeforeMove = mCurrentPanel->get()->getPosDesc();
GHGUIWidgetResource* parent = findCurrentParent(mTopPanel);
if (parent) {
mCurrentPanel->acquire();
parent->get()->removeChild(mCurrentPanel);
static float staticInsertionPriority = 0;
parent->get()->addChild(mCurrentPanel, ++staticInsertionPriority);
mCurrentPanel->release();
}
}
}
GHGUIWidgetResource* GTGUINavigator::findCurrentParent(GHGUIWidgetResource& potentialParent)
{
if (!mCurrentPanel) { return 0; }
return GTUtil::findParent(potentialParent, *mCurrentPanel);
}
bool GTGUINavigator::selectChildren(GHGUIWidgetResource& panel, const GHPoint2& selectPt)
{
size_t numChildren = panel.get()->getNumChildren();
for (int i = numChildren - 1; i >= 0; --i)
{
GHGUIWidgetResource* child = panel.get()->getChildAtIndex(i);
if (selectPanel(*child, selectPt))
{
return true;
}
}
return false;
}
bool GTGUINavigator::selectPanel(GHGUIWidgetResource& panel, const GHPoint2& selectPt)
{
bool ret = false;
//exclude guitext children from selection (they are not considered manipulatable panels in the tool)
if (panel.get()->getId() == mUtil.getIdForAllTexts())
{
return false;
}
const GHRect<float, 2>& rect = panel.get()->getScreenPos();
if (rect.containsPoint(selectPt))
{
const static float kLocalEps = .01f;
MoveData moveData;
if (rect.mMax[0] - selectPt[0] < kLocalEps) { moveData.edgeHeld[0] = 1; }
if (rect.mMax[1] - selectPt[1] < kLocalEps) { moveData.edgeHeld[1] = 1; }
if (selectPt[0] - rect.mMin[0] < kLocalEps) { moveData.edgeHeld[0] = -1; }
if (selectPt[1] - rect.mMin[1] < kLocalEps) { moveData.edgeHeld[1] = -1; }
mMoveData = moveData;
mCurrentPanel = &panel;
ret = true;
}
ret = selectChildren(panel, selectPt) || ret;
return ret;
}
void GTGUINavigator::movePanel(const GHPoint2& delta)
{
if (!mCurrentPanel || !mCurrentPanel->get()) { return; }
GHGUIPosDesc posDesc = mCurrentPanel->get()->getPosDesc();
//delta is always in fullscreen pct
GHPoint2 convertedDelta;
convertedDelta[0] = mPosDescConverter.convertPCTToLocalCoord(*mCurrentPanel->get(), delta[0], 0);
convertedDelta[1] = mPosDescConverter.convertPCTToLocalCoord(*mCurrentPanel->get(), delta[1], 1);
GHPoint2 localPctDelta;
localPctDelta[0] = mPosDescConverter.convertPCTToLocalPCT(*mCurrentPanel->get(), delta[0], 0);
localPctDelta[1] = mPosDescConverter.convertPCTToLocalPCT(*mCurrentPanel->get(), delta[1], 1);
if (mMoveData)
{
GHPoint2i sizeAlignDir;
sizeAlignDir[0] = posDesc.mSizeAlign[0] == GHAlign::A_LEFT ? -1 : (posDesc.mSizeAlign[0] == GHAlign::A_RIGHT ? 1 : 0);
sizeAlignDir[1] = posDesc.mSizeAlign[1] == GHAlign::A_TOP ? -1 : (posDesc.mSizeAlign[1] == GHAlign::A_BOTTOM ? 1 : 0);
for (int i = 0; i < 2; ++i)
{
if (posDesc.mSize[i] + convertedDelta[i] * mMoveData.edgeHeld[i] < 0) {
convertedDelta[i] = -posDesc.mSize[i] * mMoveData.edgeHeld[i];
}
posDesc.mSize[i] += convertedDelta[i] * mMoveData.edgeHeld[i];
localPctDelta[i] = mPosDescConverter.convertLocalCoordToLocalPCT(*mCurrentPanel->get(), convertedDelta[i], i);
GHPoint2* ptToChange = &posDesc.mOffset;
GHPoint2* deltaToRead = &convertedDelta;
if (mMoveType == GTMoveType::ALIGN) {
ptToChange = &posDesc.mAlign;
deltaToRead = &localPctDelta;
}
if (mMoveData.edgeHeld[i])
{
if (sizeAlignDir[i] == 0) {
(*ptToChange)[i] += (*deltaToRead)[i] * .5f;
}
else if (mMoveData.edgeHeld[i] != sizeAlignDir[i]) {
(*ptToChange)[i] += (*deltaToRead)[i];
}
}
}
}
else
{
if (mMoveType == GTMoveType::ALIGN) {
posDesc.mAlign += localPctDelta;
}
else {
posDesc.mOffset += convertedDelta;
}
}
mCurrentPanel->get()->setPosDesc(posDesc);
mCurrentPanel->get()->updatePosition();
}
| 30.8125 | 120 | 0.729354 |
538caf7ead7dbf6749f84be2863944b174f89479 | 8,738 | cc | C++ | be/src/runtime/row-batch.cc | wangxnhit/impala | d7a37f00a515d6942ca28bd8cd84380bc8c93c5a | [
"Apache-2.0"
] | 1 | 2016-06-08T06:22:28.000Z | 2016-06-08T06:22:28.000Z | be/src/runtime/row-batch.cc | boorad/impala | 108c5d8d39c45d49edfca98cd2d858352cd44d51 | [
"Apache-2.0"
] | null | null | null | be/src/runtime/row-batch.cc | boorad/impala | 108c5d8d39c45d49edfca98cd2d858352cd44d51 | [
"Apache-2.0"
] | null | null | null | // Copyright 2012 Cloudera Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "runtime/row-batch.h"
#include <stdint.h> // for intptr_t
#include <snappy.h>
#include "runtime/string-value.h"
#include "runtime/tuple-row.h"
#include "gen-cpp/Data_types.h"
DEFINE_bool(compress_rowbatches, true,
"if true, compresses tuple data in Serialize");
using namespace std;
namespace impala {
RowBatch::~RowBatch() {
delete [] tuple_ptrs_;
for (int i = 0; i < io_buffers_.size(); ++i) {
io_buffers_[i]->Return();
}
}
int RowBatch::Serialize(TRowBatch* output_batch) {
// why does Thrift not generate a Clear() function?
output_batch->row_tuples.clear();
output_batch->tuple_offsets.clear();
output_batch->is_compressed = false;
output_batch->num_rows = num_rows_;
row_desc_.ToThrift(&output_batch->row_tuples);
output_batch->tuple_offsets.reserve(num_rows_ * num_tuples_per_row_);
int size = TotalByteSize();
output_batch->tuple_data.resize(size);
// Copy tuple data, including strings, into output_batch (converting string
// pointers into offsets in the process)
int offset = 0; // current offset into output_batch->tuple_data
char* tuple_data = const_cast<char*>(output_batch->tuple_data.c_str());
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
if (row->GetTuple(j) == NULL) {
// NULLs are encoded as -1
output_batch->tuple_offsets.push_back(-1);
continue;
}
// Record offset before creating copy (which increments offset and tuple_data)
output_batch->tuple_offsets.push_back(offset);
row->GetTuple(j)->DeepCopy(**desc, &tuple_data, &offset, /* convert_ptrs */ true);
DCHECK_LE(offset, size);
}
}
DCHECK_EQ(offset, size);
if (FLAGS_compress_rowbatches && size > 0) {
// Try compressing tuple_data to compression_scratch_, swap if compressed data is
// smaller
int max_compressed_size = snappy::MaxCompressedLength(size);
if (compression_scratch_.size() < max_compressed_size) {
compression_scratch_.resize(max_compressed_size);
}
size_t compressed_size;
char* compressed_output = const_cast<char*>(compression_scratch_.c_str());
snappy::RawCompress(output_batch->tuple_data.c_str(), size,
compressed_output, &compressed_size);
if (LIKELY(compressed_size < size)) {
compression_scratch_.resize(compressed_size);
output_batch->tuple_data.swap(compression_scratch_);
output_batch->is_compressed = true;
}
VLOG_ROW << "uncompressed size: " << size << ", compressed size: " << compressed_size;
}
// The size output_batch would be if we didn't compress tuple_data (will be equal to
// actual batch size if tuple_data isn't compressed)
return GetBatchSize(*output_batch) - output_batch->tuple_data.size() + size;
}
// TODO: we want our input_batch's tuple_data to come from our (not yet implemented)
// global runtime memory segment; how do we get thrift to allocate it from there?
// maybe change line (in Data_types.cc generated from Data.thrift)
// xfer += iprot->readString(this->tuple_data[_i9]);
// to allocated string data in special mempool
// (change via python script that runs over Data_types.cc)
RowBatch::RowBatch(const RowDescriptor& row_desc, const TRowBatch& input_batch)
: has_in_flight_row_(false),
num_rows_(input_batch.num_rows),
capacity_(num_rows_),
num_tuples_per_row_(input_batch.row_tuples.size()),
row_desc_(row_desc),
tuple_ptrs_(new Tuple*[num_rows_ * input_batch.row_tuples.size()]),
tuple_data_pool_(new MemPool()) {
if (input_batch.is_compressed) {
// Decompress tuple data into data pool
const char* compressed_data = input_batch.tuple_data.c_str();
size_t compressed_size = input_batch.tuple_data.size();
size_t uncompressed_size;
bool success = snappy::GetUncompressedLength(compressed_data, compressed_size,
&uncompressed_size);
DCHECK(success) << "snappy::GetUncompressedLength failed";
char* data = reinterpret_cast<char*>(tuple_data_pool_->Allocate(uncompressed_size));
success = snappy::RawUncompress(compressed_data, compressed_size, data);
DCHECK(success) << "snappy::RawUncompress failed";
} else {
// Tuple data uncompressed, copy directly into data pool
uint8_t* data = tuple_data_pool_->Allocate(input_batch.tuple_data.size());
memcpy(data, input_batch.tuple_data.c_str(), input_batch.tuple_data.size());
}
// convert input_batch.tuple_offsets into pointers
int tuple_idx = 0;
for (vector<int32_t>::const_iterator offset = input_batch.tuple_offsets.begin();
offset != input_batch.tuple_offsets.end(); ++offset) {
if (*offset == -1) {
tuple_ptrs_[tuple_idx++] = NULL;
} else {
tuple_ptrs_[tuple_idx++] =
reinterpret_cast<Tuple*>(tuple_data_pool_->GetDataPtr(*offset));
}
}
// check whether we have string slots
// TODO: do that during setup (part of RowDescriptor c'tor?)
bool has_string_slots = false;
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
for (int i = 0; i < tuple_descs.size(); ++i) {
if (!tuple_descs[i]->string_slots().empty()) {
has_string_slots = true;
break;
}
}
if (!has_string_slots) return;
// convert string offsets contained in tuple data into pointers
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
if ((*desc)->string_slots().empty()) continue;
Tuple* t = row->GetTuple(j);
if (t == NULL) continue;
vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin();
for (; slot != (*desc)->string_slots().end(); ++slot) {
DCHECK_EQ((*slot)->type(), TYPE_STRING);
StringValue* string_val = t->GetStringSlot((*slot)->tuple_offset());
string_val->ptr = reinterpret_cast<char*>(
tuple_data_pool_->GetDataPtr(reinterpret_cast<intptr_t>(string_val->ptr)));
}
}
}
}
int RowBatch::GetBatchSize(const TRowBatch& batch) {
int result = batch.tuple_data.size();
result += batch.row_tuples.size() * sizeof(TTupleId);
result += batch.tuple_offsets.size() * sizeof(int32_t);
return result;
}
void RowBatch::Swap(RowBatch* other) {
DCHECK(row_desc_.Equals(other->row_desc_));
DCHECK_EQ(num_tuples_per_row_, other->num_tuples_per_row_);
DCHECK_EQ(tuple_ptrs_size_, other->tuple_ptrs_size_);
// The destination row batch should be empty.
DCHECK(!has_in_flight_row_);
DCHECK(io_buffers_.empty());
DCHECK_EQ(tuple_data_pool_->GetTotalChunkSizes(), 0);
std::swap(has_in_flight_row_, other->has_in_flight_row_);
std::swap(num_rows_, other->num_rows_);
std::swap(capacity_, other->capacity_);
std::swap(tuple_ptrs_, other->tuple_ptrs_);
std::swap(io_buffers_, other->io_buffers_);
tuple_data_pool_.swap(other->tuple_data_pool_);
}
// TODO: consider computing size of batches as they are built up
int RowBatch::TotalByteSize() {
int result = 0;
for (int i = 0; i < num_rows_; ++i) {
TupleRow* row = GetRow(i);
const vector<TupleDescriptor*>& tuple_descs = row_desc_.tuple_descriptors();
vector<TupleDescriptor*>::const_iterator desc = tuple_descs.begin();
for (int j = 0; desc != tuple_descs.end(); ++desc, ++j) {
Tuple* tuple = row->GetTuple(j);
if (tuple == NULL) continue;
result += (*desc)->byte_size();
vector<SlotDescriptor*>::const_iterator slot = (*desc)->string_slots().begin();
for (; slot != (*desc)->string_slots().end(); ++slot) {
DCHECK_EQ((*slot)->type(), TYPE_STRING);
if (tuple->IsNull((*slot)->null_indicator_offset())) continue;
StringValue* string_val = tuple->GetStringSlot((*slot)->tuple_offset());
result += string_val->len;
}
}
}
return result;
}
}
| 39.718182 | 90 | 0.690776 |
538f7a95ec0fc797cd6c48bc656ddfa4e735e33c | 2,837 | hh | C++ | deps/live555/include/MPEG2TransportStreamFramer.hh | robort-yuan/AI-EXPRESS | 56f86d03afbb09f42c21958c8cd9f2f1c6437f48 | [
"BSD-2-Clause"
] | 98 | 2020-09-11T13:52:44.000Z | 2022-03-23T11:52:02.000Z | deps/live555/include/MPEG2TransportStreamFramer.hh | robort-yuan/AI-EXPRESS | 56f86d03afbb09f42c21958c8cd9f2f1c6437f48 | [
"BSD-2-Clause"
] | 8 | 2020-10-19T14:23:30.000Z | 2022-03-16T01:00:07.000Z | deps/live555/include/MPEG2TransportStreamFramer.hh | robort-yuan/AI-EXPRESS | 56f86d03afbb09f42c21958c8cd9f2f1c6437f48 | [
"BSD-2-Clause"
] | 28 | 2020-09-17T14:20:35.000Z | 2022-01-10T16:26:00.000Z | /**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 3 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2017 Live Networks, Inc. All rights reserved.
// A filter that passes through (unchanged) chunks that contain an integral number
// of MPEG-2 Transport Stream packets, but returning (in "fDurationInMicroseconds")
// an updated estimate of the time gap between chunks.
// C++ header
#ifndef _MPEG2_TRANSPORT_STREAM_FRAMER_HH
#define _MPEG2_TRANSPORT_STREAM_FRAMER_HH
#ifndef _FRAMED_FILTER_HH
#include "FramedFilter.hh"
#endif
#ifndef _HASH_TABLE_HH
#include "HashTable.hh"
#endif
class MPEG2TransportStreamFramer: public FramedFilter {
public:
static MPEG2TransportStreamFramer*
createNew(UsageEnvironment& env, FramedSource* inputSource);
u_int64_t tsPacketCount() const { return fTSPacketCount; }
void changeInputSource(FramedSource* newInputSource) { fInputSource = newInputSource; }
void clearPIDStatusTable();
void setNumTSPacketsToStream(unsigned long numTSRecordsToStream);
void setPCRLimit(float pcrLimit);
protected:
MPEG2TransportStreamFramer(UsageEnvironment& env, FramedSource* inputSource);
// called only by createNew()
virtual ~MPEG2TransportStreamFramer();
private:
// Redefined virtual functions:
virtual void doGetNextFrame();
virtual void doStopGettingFrames();
private:
static void afterGettingFrame(void* clientData, unsigned frameSize,
unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds);
void afterGettingFrame1(unsigned frameSize,
struct timeval presentationTime);
Boolean updateTSPacketDurationEstimate(unsigned char* pkt, double timeNow);
private:
u_int64_t fTSPacketCount;
double fTSPacketDurationEstimate;
HashTable* fPIDStatusTable;
u_int64_t fTSPCRCount;
Boolean fLimitNumTSPacketsToStream;
unsigned long fNumTSPacketsToStream; // used iff "fLimitNumTSPacketsToStream" is True
Boolean fLimitTSPacketsToStreamByPCR;
float fPCRLimit; // used iff "fLimitTSPacketsToStreamByPCR" is True
};
#endif
| 35.911392 | 90 | 0.767712 |
53901f30edf43af56736ef423811ad9ee2e3fdb5 | 2,728 | cpp | C++ | uppdev/MyDbase/dbRecordSet.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | 2 | 2016-04-07T07:54:26.000Z | 2020-04-14T12:37:34.000Z | uppdev/MyDbase/dbRecordSet.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | uppdev/MyDbase/dbRecordSet.cpp | dreamsxin/ultimatepp | 41d295d999f9ff1339b34b43c99ce279b9b3991c | [
"BSD-2-Clause"
] | null | null | null | #include "dbase.h"
dbRecordSet::dbRecordSet() {
ptr = 0;
}
void dbRecordSet::Reset() {
recordSet.Clear();
ptr = 0;
}
void dbRecordSet::Add(int record, dbRecord &rec, Array<String> &orderField, Array<unsigned int> &ordStyle) {
unsigned int j, n, f, l, p, k;
k = orderField.GetCount();
#ifdef _WITH_DEBUG
RLOG("# keys: " + FormatInt(k));
#endif
// sorting the new record in the correct position with three key (field) level
bool s;
f=0; l=recordSet.GetCount(), p=l;
for(n=0; n<k; n++) {
s=true;
for(j=f; j<l; j++) {
if(ordStyle[n] == MTDB_ASC && s) {
if(IsBiggerEqual(recordSet[j].Get(orderField[n]), AsString(rec.GetValue(orderField[n])))) {
p = j;
f = j;
s = false;
}
}
if(ordStyle[n] == MTDB_DESC && s) {
if(IsSmallerEqual(recordSet[j].Get(orderField[n]), AsString(rec.GetValue(orderField[n])))) {
p = j;
f = j;
s = false;
}
}
if(!s) {
if(!IsEqual(recordSet[j].Get(orderField[n]), AsString(rec.GetValue(orderField[n])))) {
l = j;
}
}
}
if(s) {
p=l;
f=l;
}
}
recordSet.Insert((int)p, record, rec.Get());
return;
}
bool dbRecordSet::Next() {
if(recordSet.GetCount()>0 && ptr<(recordSet.GetCount()-1)) {
ptr++;
return true;
}
return false;
}
bool dbRecordSet::Previous() {
if(recordSet.GetCount()>0 && ptr>0) {
ptr--;
return true;
} return false;
}
bool dbRecordSet::GoTo(int recno) {
int q;
if((q = recordSet.Find(recno)) >= 0) {
ptr = q;
return true;
}
return false;
}
Value& dbRecordSet::GetValue(int field) {
VectorMap<String, Value> &rec = recordSet[ptr];
Value &res = rec[field];
return res;
}
Value dbRecordSet::GetValue(const String &field) {
VectorMap<String, Value> &rec = recordSet[ptr];
int q = rec.Find(field);
if(q >= 0) {
Value res = rec[q];
return res;
}
else return Nuller();
}
const Value dbRecordSet::GetValue(const String &field) const {
return GetValue(field);
}
Value dbRecordSet::GetValue(int record, const String &field) {
VectorMap<String, Value> &rec = recordSet.Get(record);
int q = rec.Find(field);
Value res = rec[q];
return res;
}
const Value dbRecordSet::GetValue(int record, const String &field) const {
return GetValue(record, field);
}
Value& dbRecordSet::GetValue(int record, int field) {
//VectorMap<String, Value> &rec = recordSet.Get(record);
//return rec[field];
int q = recordSet.Find(record);
if(q < 0) {
VectorMap<String, Value> r;
recordSet.GetAdd(record, r);
q = recordSet.GetCount()-1;
}
VectorMap<String, Value> &rec = recordSet[q];
return rec[field];
}
| 22.360656 | 109 | 0.595674 |
5393b719ef0294534bff4c75e8f68335bc127ddb | 5,424 | cpp | C++ | SmallWorld/LibCpp/Graph.cpp | pchaigno/smallworld | 8a22099753166b4fea0bf93a1a7298fed51fef8c | [
"MIT"
] | 1 | 2018-11-08T17:20:56.000Z | 2018-11-08T17:20:56.000Z | SmallWorld/LibCpp/Graph.cpp | pchaigno/smallworld | 8a22099753166b4fea0bf93a1a7298fed51fef8c | [
"MIT"
] | null | null | null | SmallWorld/LibCpp/Graph.cpp | pchaigno/smallworld | 8a22099753166b4fea0bf93a1a7298fed51fef8c | [
"MIT"
] | null | null | null | #include "Graph.h"
/**
* @returns The size of the graph.
*/
int Graph::size() const {
return this->succs.size();
}
/**
* Checks if an unit can go from one point to all others of the map.
* @param map The map.
* @param size The size of the map.
* @returns True if all squares of the map are accessible from one.
*/
bool Graph::isConnectedGraph(Tile** map, int size) {
Graph graph = Graph(map, size);
vector<Point> composant = graph.getConnectedComposant(graph.getKeys()[0]);
return composant.size() == graph.size();
}
/**
* Converts the map to a graph.
* Squares are vertices if they're not sea.
* Two squares are connected if they're adjacent (an unit can go from one to the other in one move).
* Note: Sea is represented by 1.
* @param map The map randomly generated.
* @param size The size of the map.
* @returns The graph as a map of adjacent vertices by vertex.
*/
Graph::Graph(Tile** map, int size) {
for(int i=0; i<size; i++) {
for(int j=0; j<size; j++) {
Point pos = Point(i, j);
if(!pos.isSea(map)) {
vector<Point> adjacents;
Point adjacent;
for(int x=i-1; x<=i+1; x+=2) {
adjacent = Point(x, j);
if(x>=0 && x<size && !adjacent.isSea(map)) {
adjacents.push_back(adjacent);
}
}
for(int y=j-1; y<=j+1; y+=2) {
adjacent = Point(i, y);
if(y>=0 && y<size && !adjacent.isSea(map)) {
adjacents.push_back(adjacent);
}
}
this->succs.insert(make_pair(pos, adjacents));
}
}
}
}
/**
* Tarjan algorithm to find a connected composant from a starting vertex.
* @param vertex The vertex to start.
* @returns The connected composant containing vertex.
*/
vector<Point> Graph::getConnectedComposant(const Point& vertex) const {
// Attributes integers to each vertex:
Point* vertices = new Point[this->size()];
int j=0;
for(map<Point, vector<Point>>::const_iterator it = this->succs.begin(); it!=this->succs.end(); ++it) {
vertices[j] = it->first;
j++;
}
// Initialization:
int* p = new int[this->succs.size()];
int* d = new int[this->succs.size()];
int* n = new int[this->succs.size()];
int* num = new int[this->succs.size()];
int numA = -1;
for(int i=0; i<this->succs.size(); i++) {
num[i] = -1;
p[i] = -1;
d[i] = this->succs.at(vertices[i]).size();
n[i] = -1;
if(vertices[i] == vertex) {
numA = i;
}
}
int index = numA;
int k = 0;
num[numA] = 0;
p[numA] = numA;
// Core of the algorithm:
while(n[index]+1!=d[index] || index!=numA) {
if(n[index]+1 == d[index]) {
index = p[index];
} else {
n[index]++;
Point pt = this->succs.at(vertices[index])[n[index]];
j = Graph::getIndex(pt, vertices, this->size());
if(p[j] == -1) {
p[j] = index;
index = j;
k++;
num[index] = k;
}
}
}
// Check if the graph is connected:
if(k+1 == this->size()) {
return this->getKeys();
}
vector<Point> connectedVertices;
for(int i=0; i<this->size(); i++) {
if(num[i]<=k && num[i]!=-1) {
connectedVertices.push_back(vertices[i]);
}
}
return connectedVertices;
}
/**
* @returns The keys of the graph object.
*/
vector<Point> Graph::getKeys() const {
vector<Point> keys;
for(map<Point, vector<Point>>::const_iterator it = this->succs.begin(); it!=this->succs.end(); ++it) {
keys.push_back(it->first);
}
return keys;
}
/**
* @returns The keys of the graph object.
*/
Point* Graph::getKeysAsArray() const {
Point* keys = new Point[this->size()];
int i = 0;
for(map<Point, vector<Point>>::const_iterator it = this->succs.begin(); it!=this->succs.end(); ++it) {
keys[i] = it->first;
i++;
}
return keys;
}
/**
* Roy-Marshall algorithm to find the best cost routing in a graph.
* @param vertices The vertices as an array (to associate a Point to a number).
* @returns The matrix with the best cost for each origin-destination couple.
*/
int** Graph::getBestCostRouting(Point* vertices) const {
// Initialization:
int** routes = new int*[this->size()];
int** costs = new int*[this->size()];
for(int i=0; i<this->size(); i++) {
routes[i] = new int[this->size()];
costs[i] = new int[this->size()];
for(int j=0; j<this->size(); j++) {
if(inArray(vertices[j], this->succs.at(vertices[i]))) {
routes[i][j] = j;
costs[i][j] = 1;
} else {
routes[i][j] = -1;
costs[i][j] = INT_MAX;
}
}
}
// Roy-Marshall's algorithm:
for(int i=0; i<this->size(); i++) {
for(int x=0; x<this->size(); x++) {
if(routes[x][i] != -1) {
for(int y=0; y<this->size(); y++) {
if(routes[i][y] != -1) {
if(costs[x][y] > costs[x][i]+costs[i][y]) {
costs[x][y] = costs[x][i] + costs[i][y];
routes[x][y] = routes[x][i];
}
}
}
}
}
}
return costs;
}
/**
* Checks if a point if in a vector of points.
* @param pt The point.
* @param points The vector of points.
* @returns True if pt is in points.
*/
bool Graph::inArray(const Point& pt, const vector<Point>& points) {
for(int i=0; i<points.size(); i++) {
if(pt == points[i]) {
return true;
}
}
return false;
}
/**
* Checks if a point if in a vector of points.
* @param pt The point.
* @param points The array of points.
* @param nbPoints The number of points in the array.
* @returns The index of pt in points or -1 if pt is not in points.
*/
int Graph::getIndex(const Point& pt, Point* points, int nbPoints) {
for(int i=0; i<nbPoints; i++) {
if(pt == points[i]) {
return i;
}
}
return -1;
} | 25.111111 | 103 | 0.599558 |
5396350bb63761ed2223415e6eb90979556befc4 | 45,917 | cxx | C++ | main/sal/qa/osl/socket/osl_Socket2.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/sal/qa/osl/socket/osl_Socket2.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/sal/qa/osl/socket/osl_Socket2.cxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sal.hxx"
/** test coder preface:
1. the BSD socket function will meet "unresolved external symbol error" on Windows platform
if you are not including ws2_32.lib in makefile.mk, the including format will be like this:
.IF "$(GUI)" == "WNT"
SHL1STDLIBS += $(SOLARLIBDIR)$/cppunit.lib
SHL1STDLIBS += ws2_32.lib
.ENDIF
likewise on Solaris platform.
.IF "$(GUI)" == "UNX"
SHL1STDLIBS+=$(SOLARLIBDIR)$/libcppunit$(DLLPOSTFIX).a
SHL1STDLIBS += -lsocket -ldl -lnsl
.ENDIF
2. since the Socket implementation of osl is only IPv4 oriented, our test are mainly focus on IPv4
category.
3. some fragment of Socket source implementation are lack of comment so it is hard for testers
guess what the exact functionality or usage of a member. Hope the Socket section's comment
will be added.
4. following functions are declared but not implemented:
inline sal_Bool SAL_CALL operator== (const SocketAddr & Addr) const;
*/
//------------------------------------------------------------------------
// include files
//------------------------------------------------------------------------
#include "gtest/gtest.h"
//#include "osl_Socket_Const.h"
#include "sockethelper.hxx"
using namespace osl;
using namespace rtl;
#define IP_PORT_FTP 21
#define IP_PORT_TELNET 23
#define IP_PORT_HTTP2 8080
#define IP_PORT_INVAL 99999
#define IP_PORT_POP3 110
#define IP_PORT_NETBIOS 139
#define IP_PORT_MYPORT 8881
#define IP_PORT_MYPORT1 8882
#define IP_PORT_MYPORT5 8886
#define IP_PORT_MYPORT6 8887
#define IP_PORT_MYPORT7 8895
#define IP_PORT_MYPORT8 8896
#define IP_PORT_MYPORT9 8897
//------------------------------------------------------------------------
// helper functions
//------------------------------------------------------------------------
// just used to test socket::close() when accepting
class AcceptorThread : public Thread
{
::osl::AcceptorSocket asAcceptorSocket;
::rtl::OUString aHostIP;
sal_Bool bOK;
protected:
void SAL_CALL run( )
{
::osl::SocketAddr saLocalSocketAddr( aHostIP, IP_PORT_MYPORT9 );
::osl::StreamSocket ssStreamConnection;
asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //integer not sal_Bool : sal_True);
sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
if ( sal_True != bOK1 )
{
printf("# AcceptorSocket bind address failed.\n" ) ;
return;
}
sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
if ( sal_True != bOK2 )
{
printf("# AcceptorSocket listen address failed.\n" ) ;
return;
}
asAcceptorSocket.enableNonBlockingMode( sal_False );
oslSocketResult eResult = asAcceptorSocket.acceptConnection( ssStreamConnection );
if (eResult != osl_Socket_Ok )
{
bOK = sal_True;
printf("AcceptorThread: acceptConnection failed! \n");
}
}
public:
AcceptorThread(::osl::AcceptorSocket & asSocket, ::rtl::OUString const& aBindIP )
: asAcceptorSocket( asSocket ), aHostIP( aBindIP )
{
bOK = sal_False;
}
sal_Bool isOK() { return bOK; }
~AcceptorThread( )
{
if ( isRunning( ) )
{
asAcceptorSocket.shutdown();
printf("# error: Acceptor thread not terminated.\n" );
}
}
};
namespace osl_Socket
{
/** testing the methods:
inline Socket( );
inline Socket( const Socket & socket );
inline Socket( oslSocket socketHandle );
inline Socket( oslSocket socketHandle, __sal_NoAcquire noacquire );
*/
/** test writer's comment:
class Socket can not be initialized by its protected constructor, though the protected
constructor is the most convenient way to create a new socket.
it only allow the method of C function osl_createSocket like:
::osl::Socket sSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream,
osl_Socket_ProtocolIp ) );
the use of C method lost some of the transparent of tester using C++ wrapper.
*/
class ctors : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class ctors
TEST_F(ctors, ctors_none)
{
/// Socket constructor.
// ::osl::Socket sSocket();
ASSERT_TRUE(1 == 1) << "test for ctors_none constructor function: check if the socket was created successfully, if no exception occurred";
}
TEST_F(ctors, ctors_acquire)
{
/// Socket constructor.
::osl::Socket sSocket( sHandle );
ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << "test for ctors_acquire constructor function: check if the socket was created successfully";
}
TEST_F(ctors, ctors_no_acquire)
{
/// Socket constructor.
::osl::Socket sSocket( sHandle, SAL_NO_ACQUIRE );
ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << " test for ctors_no_acquire constructor function: check if the socket was created successfully";
}
TEST_F(ctors, ctors_copy_ctor)
{
::osl::Socket sSocket( sHandle );
/// Socket copy constructor.
::osl::Socket copySocket( sSocket );
ASSERT_TRUE(osl_Socket_TypeStream == copySocket.getType( )) << " test for ctors_copy_ctor constructor function: create new Socket instance using copy constructor";
}
TEST_F(ctors, ctors_TypeRaw)
{
#ifdef WNT
oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp );
// LLA: ? ::osl::Socket sSocket( sHandleRaw );
ASSERT_TRUE(sHandleRaw != NULL) << " type osl_Socket_TypeRaw socket create failed on UNX ";
#else
oslSocket sHandleRaw = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp );
ASSERT_TRUE(sHandleRaw == NULL) << " can't create socket with type osl_Socket_TypeRaw within UNX is ok.";
#endif
}
TEST_F(ctors, ctors_family_Ipx)
{
oslSocket sHandleIpx = osl_createSocket( osl_Socket_FamilyIpx, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
ASSERT_TRUE(sHandleIpx != NULL) << " family osl_Socket_FamilyIpx socket create failed! ";
::osl::Socket sSocket( sHandleIpx ); //, SAL_NO_ACQUIRE );
printf("#Type is %d \n", sSocket.getType( ) );
ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << " test for create new Socket instance that family is osl_Socket_FamilyIpx";
}
/** testing the methods:
inline Socket& SAL_CALL operator= ( oslSocket socketHandle);
inline Socket& SAL_CALL operator= (const Socket& sock);
inline sal_Bool SAL_CALL operator==( const Socket& rSocket ) const ;
inline sal_Bool SAL_CALL operator==( const oslSocket socketHandle ) const;
*/
class operators : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class operators
/** test writer's comment:
the assignment operator does not support direct assinment like:
::osl::Socket sSocket = sHandle.
*/
TEST_F(operators, operators_assignment_handle)
{
::osl::Socket sSocket(sHandle);
::osl::Socket assignSocket = sSocket.getHandle();
ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment_handle function: test the assignment operator.";
}
TEST_F(operators, operators_assignment)
{
::osl::Socket sSocket( sHandle );
::osl::Socket assignSocket = sSocket;
ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment function: assignment operator";
}
TEST_F(operators, operators_equal_handle_001)
{
/// Socket constructor.
::osl::Socket sSocket( sHandle );
::osl::Socket equalSocket = sSocket;
ASSERT_TRUE(equalSocket == sHandle) << " test for operators_equal_handle_001 function: check equal.";
}
TEST_F(operators, operators_equal_handle_002)
{
/// Socket constructor.
::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) );
ASSERT_TRUE(!( equalSocket == sHandle )) << " test for operators_equal_handle_001 function: check unequal.";
}
TEST_F(operators, operators_equal_001)
{
::osl::Socket sSocket( sHandle );
/// Socket copy constructor.
::osl::Socket equalSocket( sSocket );
ASSERT_TRUE(equalSocket == sSocket) << " test for operators_equal function: check equal.";
}
TEST_F(operators, operators_equal_002)
{
::osl::Socket sSocket( sHandle );
/// Socket copy constructor.
::osl::Socket equalSocket( osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp ) );
ASSERT_TRUE(!( equalSocket == sSocket )) << " test for operators_equal_002 function: check unequal.";
}
/** testing the methods:
inline void SAL_CALL shutdown( oslSocketDirection Direction = osl_Socket_DirReadWrite );
inline void SAL_CALL close();
*/
class close : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class close
TEST_F(close, close_001)
{
::osl::Socket sSocket(sHandle);
sSocket.close();
ASSERT_TRUE(sSocket.getHandle() == sHandle) << "test for close_001 function: this function is reserved for test.";
}
TEST_F(close, close_002)
{
// This blocks forever on FreeBSD
#if defined(LINUX)
::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
AcceptorThread myAcceptorThread( asSocket, rtl::OUString::createFromAscii("127.0.0.1") );
myAcceptorThread.create();
thread_sleep( 1 );
//when accepting, close the socket, the thread will not block for accepting
//man close:Any locks held on the file it was associated with, and owned by the process, are removed
asSocket.close();
//thread_sleep( 2 );
myAcceptorThread.join();
ASSERT_TRUE(myAcceptorThread.isOK() == sal_True) << "test for close when is accepting: the socket will quit accepting status.";
#endif
}
// to cover "if ( pSockAddrIn->sin_addr.s_addr == htonl(INADDR_ANY) )" in osl_closeSocket( )
TEST_F(close, close_003)
{
// This blocks forever on FreeBSD
#if defined(LINUX)
::osl::AcceptorSocket asSocket( osl_Socket_FamilyInet, osl_Socket_ProtocolIp, osl_Socket_TypeStream );
AcceptorThread myAcceptorThread( asSocket, rtl::OUString::createFromAscii("0.0.0.0") );
myAcceptorThread.create();
thread_sleep( 1 );
asSocket.close();
myAcceptorThread.join();
ASSERT_TRUE(myAcceptorThread.isOK() == sal_True) << "test for close when is accepting: the socket will quit accepting status.";
#endif
}
/** testing the method:
inline void SAL_CALL getLocalAddr( SocketAddr &Addr ) const;
*/
class getLocalAddr : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getLocalAddr
// get the Address of the local end of the socket
TEST_F(getLocalAddr, getLocalAddr_001)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT8 );
::osl::SocketAddr saLocalSocketAddr;
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = sSocket.bind( saBindSocketAddr );
::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString();
ASSERT_TRUE(sal_True == bOK1) << suError1.pData;
sSocket.getLocalAddr( saLocalSocketAddr );
sal_Bool bOK = compareUString( saLocalSocketAddr.getHostname( 0 ), sSocket.getLocalHost() ) ;
ASSERT_TRUE(sal_True == bOK) << "test for getLocalAddr function: first create a new socket, then a socket address, bind them, and check the address.";
}
/** testing the method:
inline sal_Int32 SAL_CALL getLocalPort() const;
*/
class getLocalPort : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getLocalPort
TEST_F(getLocalPort, getLocalPort_001)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT7 ); // aHostIp1 localhost
::osl::SocketAddr saLocalSocketAddr;
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = sSocket.bind( saBindSocketAddr );
::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString();
ASSERT_TRUE(sal_True == bOK1) << suError1.pData;
sal_Bool bOK = ( IP_PORT_MYPORT7 == sSocket.getLocalPort( ) );
ASSERT_TRUE(sal_True == bOK) << "test for getLocalPort function: first create a new socket, then a socket address, bind them, and check the port.";
}
/** test writer's comment:
the invalid port number can not be set by giving invalid port number
such as 99999 or -1, it will convert to ( x mod 65535 ), so it will always be
valid, the only instance that the getLocalPort returns OSL_INVALID_PORT
is when saSocketAddr itself is an invalid one, that is , the IP or host name
can not be found, then the created socket address is not valid.
*/
TEST_F(getLocalPort, getLocalPort_002)
{
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_TELNET);
#ifdef WNT
::osl::Socket sSocket(sHandle);
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True);
sSocket.bind( saBindSocketAddr );
//Invalid IP, so bind should fail
::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )),
::rtl::OUString::valueOf((sal_Int32)OSL_INVALID_PORT),
"test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned.");
sal_Bool bOK = ( OSL_INVALID_PORT == sSocket.getLocalPort( ) );
(void)bOK;
#else
//on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT
::rtl::OUString suError = ::rtl::OUString::createFromAscii( "on Unix, if Addr is not an address of type osl_Socket_FamilyInet, it returns OSL_INVALID_PORT, but can not create Addr of that case");
#endif
ASSERT_TRUE(sal_False) << suError.pData;
}
TEST_F(getLocalPort, getLocalPort_003)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_INVAL);
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = sSocket.bind( saBindSocketAddr );
::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString();
ASSERT_TRUE(sal_True == bOK1) << suError1.pData;
::rtl::OUString suError = outputError(::rtl::OUString::valueOf(sSocket.getLocalPort( )),
::rtl::OUString::createFromAscii("34463"),
"test for getLocalPort function: first create a new socket, then an invalid socket address, bind them, and check the port assigned");
sal_Bool bOK = ( sSocket.getLocalPort( ) >= 1 && sSocket.getLocalPort( ) <= 65535);
ASSERT_TRUE(sal_True == bOK) << suError.pData;
}
/** testing the method:
inline ::rtl::OUString SAL_CALL getLocalHost() const;
Mindyliu: on Linux, at first it will check the binded in /etc/hosts, if it has the binded IP, it will return the hostname in it;
else if the binded IP is "127.0.0.1", it will return "localhost", if it's the machine's ethernet ip such as "129.158.217.90", it
will return hostname of current processor such as "aegean.PRC.Sun.COM"
*/
class getLocalHost : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getLocalHost
TEST_F(getLocalHost, getLocalHost_001)
{
::osl::Socket sSocket(sHandle);
//port number from IP_PORT_HTTP1 to IP_PORT_MYPORT6, mindyliu
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT6 );
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = sSocket.bind( saBindSocketAddr );
::rtl::OUString suError1 = ::rtl::OUString::createFromAscii("Socket bind fail:") + sSocket.getErrorAsString();
ASSERT_TRUE(sal_True == bOK1) << suError1.pData;
sal_Bool bOK;
::rtl::OUString suError;
#ifdef WNT
bOK = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ;
suError = outputError(sSocket.getLocalHost( ), getThisHostname( ),
"test for getLocalHost function: create localhost socket and check name");
#else
::rtl::OUString aUString = ::rtl::OUString::createFromAscii( (const sal_Char *) "localhost" );
sal_Bool bRes1, bRes2;
bRes1 = compareUString( sSocket.getLocalHost( ), aUString ) ;
bRes2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname(0) ) ;
bOK = bRes1 || bRes2;
suError = outputError(sSocket.getLocalHost( ), aUString, "test for getLocalHost function: create localhost socket and check name");
#endif
ASSERT_TRUE(sal_True == bOK) << suError.pData;
}
TEST_F(getLocalHost, getLocalHost_002)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_POP3);
::osl::SocketAddr saLocalSocketAddr;
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sSocket.bind( saBindSocketAddr );
//Invalid IP, so bind should fail
sal_Bool bOK = compareUString( sSocket.getLocalHost( ), rtl::OUString::createFromAscii("") ) ;
::rtl::OUString suError = outputError(sSocket.getLocalHost( ), rtl::OUString::createFromAscii(""), "test for getLocalHost function: getLocalHost with invalid SocketAddr");
ASSERT_TRUE(sal_True == bOK) << suError.pData;
}
/** testing the methods:
inline void SAL_CALL getPeerAddr( SocketAddr & Addr) const;
inline sal_Int32 SAL_CALL getPeerPort() const;
inline ::rtl::OUString SAL_CALL getPeerHost() const;
*/
class getPeer : public ::testing::Test
{
public:
oslSocket sHandle;
TimeValue *pTimeout;
::osl::AcceptorSocket asAcceptorSocket;
::osl::ConnectorSocket csConnectorSocket;
// initialization
void SetUp( )
{
pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
pTimeout->Seconds = 3;
pTimeout->Nanosec = 0;
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
free( pTimeout );
sHandle = NULL;
asAcceptorSocket.close( );
csConnectorSocket.close( );
}
}; // class getPeer
TEST_F(getPeer, getPeer_001)
{
::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT );
::osl::SocketAddr saTargetSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT );
::osl::SocketAddr saPeerSocketAddr( rtl::OUString::createFromAscii("129.158.217.202"), IP_PORT_FTP );
::osl::StreamSocket ssConnection;
asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
/// launch server socket
sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind '127.0.0.1' address failed.";
sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed.";
asAcceptorSocket.enableNonBlockingMode( sal_True );
asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection...
/// launch client socket
csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server...
/// get peer information
csConnectorSocket.getPeerAddr( saPeerSocketAddr );/// connected.
sal_Int32 peerPort = csConnectorSocket.getPeerPort( );
::rtl::OUString peerHost = csConnectorSocket.getPeerHost( );
ASSERT_TRUE(( sal_True == compareSocketAddr( saPeerSocketAddr, saLocalSocketAddr ) )&&
( sal_True == compareUString( peerHost, saLocalSocketAddr.getHostname( 0 ) ) ) &&
( peerPort == saLocalSocketAddr.getPort( ) )) << "test for getPeer function: setup a connection and then get the peer address, port and host from client side.";
}
/** testing the methods:
inline sal_Bool SAL_CALL bind(const SocketAddr& LocalInterface);
*/
class bind : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class bind
TEST_F(bind, bind_001)
{
::osl::Socket sSocket(sHandle);
//bind must use local IP address ---mindyliu
::osl::SocketAddr saBindSocketAddr( getLocalIP(), IP_PORT_MYPORT5 );
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = sSocket.bind( saBindSocketAddr );
ASSERT_TRUE(sal_True == bOK1) << "Socket bind fail.";
sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), saBindSocketAddr.getHostname( ) ) ;
sSocket.close();
ASSERT_TRUE(sal_True == bOK2) << "test for bind function: bind a valid address.";
}
TEST_F(bind, bind_002)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_NETBIOS );
::osl::SocketAddr saLocalSocketAddr;
sSocket.setOption( osl_Socket_OptionReuseAddr, 1); // sal_True);
sal_Bool bOK1 = sSocket.bind( saBindSocketAddr );
sal_Bool bOK2 = compareUString( sSocket.getLocalHost( ), getThisHostname( ) ) ;
ASSERT_TRUE(( sal_False == bOK1 ) && ( sal_False == bOK2 )) << "test for bind function: bind a valid address.";
}
/** testing the methods:
inline sal_Bool SAL_CALL isRecvReady(const TimeValue *pTimeout = 0) const;
*/
class isRecvReady : public ::testing::Test
{
public:
oslSocket sHandle;
TimeValue *pTimeout;
::osl::AcceptorSocket asAcceptorSocket;
::osl::ConnectorSocket csConnectorSocket;
// initialization
void SetUp( )
{
pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
pTimeout->Seconds = 3;
pTimeout->Nanosec = 0;
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
free( pTimeout );
sHandle = NULL;
asAcceptorSocket.close( );
csConnectorSocket.close( );
}
}; // class isRecvReady
TEST_F(isRecvReady, isRecvReady_001)
{
::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT1 );
::osl::SocketAddr saTargetSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT1 );
::osl::SocketAddr saPeerSocketAddr( rtl::OUString::createFromAscii("129.158.217.202"), IP_PORT_FTP );
::osl::StreamSocket ssConnection;
/// launch server socket
asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True);
sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed.";
sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed.";
asAcceptorSocket.enableNonBlockingMode( sal_True );
asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection...
/// launch client socket
csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server...
/// is receive ready?
sal_Bool bOK3 = asAcceptorSocket.isRecvReady( pTimeout );
ASSERT_TRUE(( sal_True == bOK3 )) << "test for isRecvReady function: setup a connection and then check if it can transmit data.";
}
/** testing the methods:
inline sal_Bool SAL_CALL isSendReady(const TimeValue *pTimeout = 0) const;
*/
class isSendReady : public ::testing::Test
{
public:
oslSocket sHandle;
TimeValue *pTimeout;
::osl::AcceptorSocket asAcceptorSocket;
::osl::ConnectorSocket csConnectorSocket;
// initialization
void SetUp( )
{
pTimeout = ( TimeValue* )malloc( sizeof( TimeValue ) );
pTimeout->Seconds = 3;
pTimeout->Nanosec = 0;
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
free( pTimeout );
sHandle = NULL;
asAcceptorSocket.close( );
csConnectorSocket.close( );
}
}; // class isSendReady
TEST_F(isSendReady, isSendReady_001)
{
::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT );
::osl::SocketAddr saTargetSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT );
::osl::SocketAddr saPeerSocketAddr( rtl::OUString::createFromAscii("129.158.217.202"), IP_PORT_FTP );
::osl::StreamSocket ssConnection;
/// launch server socket
asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed.";
sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed.";
asAcceptorSocket.enableNonBlockingMode( sal_True );
asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection...
/// launch client socket
csConnectorSocket.connect( saTargetSocketAddr, pTimeout ); /// connecting to server...
/// is send ready?
sal_Bool bOK3 = csConnectorSocket.isSendReady( pTimeout );
ASSERT_TRUE(( sal_True == bOK3 )) << "test for isSendReady function: setup a connection and then check if it can transmit data.";
}
/** testing the methods:
inline oslSocketType SAL_CALL getType() const;
*/
class getType : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getType
TEST_F(getType, getType_001)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
ASSERT_TRUE(osl_Socket_TypeStream == sSocket.getType( )) << "test for getType function: get type of socket.";
}
TEST_F(getType, getType_002)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
ASSERT_TRUE(osl_Socket_TypeDgram == sSocket.getType( )) << "test for getType function: get type of socket.";
}
#ifdef UNX
// mindy: since on LINUX and SOLARIS, Raw type socket can not be created, so do not test getType() here
// mindy: and add one test case to test creating Raw type socket--> ctors_TypeRaw()
TEST_F(getType, getType_003)
{
ASSERT_TRUE(sal_True) << "test for getType function: get type of socket.this is not passed in (LINUX, SOLARIS), the osl_Socket_TypeRaw, type socket can not be created.";
}
#else
TEST_F(getType, getType_003)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeRaw, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
ASSERT_TRUE(osl_Socket_TypeRaw == sSocket.getType( )) << "test for getType function: get type of socket.";
}
#endif
/** testing the methods:
inline sal_Int32 SAL_CALL getOption(
oslSocketOption Option,
void* pBuffer,
sal_uInt32 BufferLen,
oslSocketOptionLevel Level= osl_Socket_LevelSocket) const;
inline sal_Int32 getOption( oslSocketOption option ) const;
*/
class getOption : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getOption
/** test writer's comment:
in oslSocketOption, the osl_Socket_OptionType denote 1 as osl_Socket_TypeStream.
2 as osl_Socket_TypeDgram, etc which is not mapping the oslSocketType enum. differ
in 1.
*/
TEST_F(getOption, getOption_001)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
sal_Int32 * pType = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) );
*pType = 0;
sSocket.getOption( osl_Socket_OptionType, pType, sizeof ( sal_Int32 ) );
sal_Bool bOK = ( SOCK_STREAM == *pType );
// there is a TypeMap(socket.c) which map osl_Socket_TypeStream to SOCK_STREAM on UNX, and SOCK_STREAM != osl_Socket_TypeStream
//sal_Bool bOK = ( TYPE_TO_NATIVE(osl_Socket_TypeStream) == *pType );
free( pType );
ASSERT_TRUE(sal_True == bOK) << "test for getOption function: get type option of socket.";
}
// getsockopt error
TEST_F(getOption, getOption_004)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
sal_Bool * pbDontRoute = ( sal_Bool * )malloc( sizeof ( sal_Bool ) );
sal_Int32 nRes = sSocket.getOption( osl_Socket_OptionInvalid, pbDontRoute, sizeof ( sal_Bool ) );
free( pbDontRoute );
ASSERT_TRUE(nRes == -1) << "test for getOption function: get invalid option of socket, should return -1.";
}
TEST_F(getOption, getOption_simple_001)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDontRoute ) );
ASSERT_TRUE(sal_True == bOK) << "test for getOption function: get debug option of socket.";
}
TEST_F(getOption, getOption_simple_002)
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeDgram, osl_Socket_ProtocolIp );
::osl::Socket sSocket(sHandle);
sal_Bool bOK = ( sal_False == sSocket.getOption( osl_Socket_OptionDebug ) );
ASSERT_TRUE(sal_True == bOK) << "test for getOption function: get debug option of socket.";
}
/** testing the methods:
inline sal_Bool SAL_CALL setOption( oslSocketOption Option,
void* pBuffer,
sal_uInt32 BufferLen,
oslSocketOptionLevel Level= osl_Socket_LevelSocket ) const;
*/
class setOption : public ::testing::Test
{
public:
TimeValue *pTimeout;
// LLA: maybe there is an error in the source,
// as long as I remember, if a derived class do not overload all ctors there is a problem.
::osl::AcceptorSocket asAcceptorSocket;
void SetUp( )
{
}
void TearDown( )
{
asAcceptorSocket.close( );
}
}; // class setOption
// LLA:
// getSocketOption returns BufferLen, or -1 if something failed
// setSocketOption returns sal_True, if option could stored
// else sal_False
TEST_F(setOption, setOption_001)
{
/// set and get option.
int nBufferLen = sizeof ( sal_Int32);
// LLA: SO_DONTROUTE expect an integer boolean, what ever it is, it's not sal_Bool!
sal_Int32 * pbDontRouteSet = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) );
*pbDontRouteSet = 1; // sal_True;
sal_Int32 * pGetBuffer = ( sal_Int32 * )malloc( sizeof ( sal_Int32 ) );
*pGetBuffer = 0;
// maybe asAcceptorSocket is not right initialized
sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, nBufferLen );
ASSERT_TRUE(( sal_True == b1 )) << "setOption function failed.";
sal_Int32 n2 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen );
ASSERT_TRUE(( n2 == nBufferLen )) << "getOption function failed.";
// on Linux, the value of option is 1, on Solaris, it's 16, but it's not important the exact value,
// just judge it is zero or not!
sal_Bool bOK = ( 0 != *pGetBuffer );
printf("#setOption_001: getOption is %d \n", *pGetBuffer);
// toggle check, set to 0
*pbDontRouteSet = 0;
sal_Bool b3 = asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontRouteSet, sizeof ( sal_Int32 ) );
ASSERT_TRUE(( sal_True == b3 )) << "setOption function failed.";
sal_Int32 n4 = asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pGetBuffer, nBufferLen );
ASSERT_TRUE(( n4 == nBufferLen )) << "getOption (DONTROUTE) function failed.";
sal_Bool bOK2 = ( 0 == *pGetBuffer );
printf("#setOption_001: getOption is %d \n", *pGetBuffer);
// LLA: sal_Bool * pbDontTouteSet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) );
// LLA: *pbDontTouteSet = sal_True;
// LLA: sal_Bool * pbDontTouteGet = ( sal_Bool * )malloc( sizeof ( sal_Bool ) );
// LLA: *pbDontTouteGet = sal_False;
// LLA: asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, pbDontTouteSet, sizeof ( sal_Bool ) );
// LLA: asAcceptorSocket.getOption( osl_Socket_OptionDontRoute, pbDontTouteGet, sizeof ( sal_Bool ) );
// LLA: ::rtl::OUString suError = outputError(::rtl::OUString::valueOf((sal_Int32)*pbDontTouteGet),
// LLA: ::rtl::OUString::valueOf((sal_Int32)*pbDontTouteSet),
// LLA: "test for setOption function: set osl_Socket_OptionDontRoute and then check");
// LLA:
// LLA: sal_Bool bOK = ( sal_True == *pbDontTouteGet );
// LLA: free( pbDontTouteSet );
// LLA: free( pbDontTouteGet );
ASSERT_TRUE(( sal_True == bOK ) && (sal_True == bOK2)) << "test for setOption function: set option of a socket and then check.";
free( pbDontRouteSet );
free( pGetBuffer );
// LLA: ASSERT_TRUE(sal_True == bOK) << suError;
}
TEST_F(setOption, setOption_002)
{
/// set and get option.
// sal_Int32 * pbLingerSet = ( sal_Int32 * )malloc( nBufferLen );
// *pbLingerSet = 7;
// sal_Int32 * pbLingerGet = ( sal_Int32 * )malloc( nBufferLen );
/* struct */linger aLingerSet;
sal_Int32 nBufferLen = sizeof( struct linger );
aLingerSet.l_onoff = 1;
aLingerSet.l_linger = 7;
linger aLingerGet;
asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, nBufferLen );
sal_Int32 n1 = asAcceptorSocket.getOption( osl_Socket_OptionLinger, &aLingerGet, nBufferLen );
ASSERT_TRUE(( n1 == nBufferLen )) << "getOption (SO_LINGER) function failed.";
//printf("#setOption_002: getOption is %d \n", aLingerGet.l_linger);
sal_Bool bOK = ( 7 == aLingerGet.l_linger );
ASSERT_TRUE(sal_True == bOK) << "test for setOption function: set option of a socket and then check. ";
}
TEST_F(setOption, setOption_003)
{
linger aLingerSet;
aLingerSet.l_onoff = 1;
aLingerSet.l_linger = 7;
sal_Bool b1 = asAcceptorSocket.setOption( osl_Socket_OptionLinger, &aLingerSet, 0 );
printUString( asAcceptorSocket.getErrorAsString( ) );
ASSERT_TRUE(( b1 == sal_False )) << "setOption (SO_LINGER) function failed for optlen is 0.";
}
TEST_F(setOption, setOption_simple_001)
{
/// set and get option.
asAcceptorSocket.setOption( osl_Socket_OptionDontRoute, 1 ); //sal_True );
sal_Bool bOK = ( 0 != asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) );
printf("setOption_simple_001(): getoption is %d \n", asAcceptorSocket.getOption( osl_Socket_OptionDontRoute ) );
ASSERT_TRUE(( sal_True == bOK )) << "test for setOption function: set option of a socket and then check.";
}
TEST_F(setOption, setOption_simple_002)
{
/// set and get option.
// LLA: this does not work, due to the fact that SO_LINGER is a structure
// LLA: asAcceptorSocket.setOption( osl_Socket_OptionLinger, 7 );
// LLA: sal_Bool bOK = ( 7 == asAcceptorSocket.getOption( osl_Socket_OptionLinger ) );
// LLA: ASSERT_TRUE(// LLA: ( sal_True == bOK )) << "test for setOption function: set option of a socket and then check.";
}
/** testing the method:
inline sal_Bool SAL_CALL enableNonBlockingMode( sal_Bool bNonBlockingMode);
*/
class enableNonBlockingMode : public ::testing::Test
{
public:
::osl::AcceptorSocket asAcceptorSocket;
}; // class enableNonBlockingMode
TEST_F(enableNonBlockingMode, enableNonBlockingMode_001)
{
::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT );
::osl::StreamSocket ssConnection;
/// launch server socket
asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed.";
sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed.";
asAcceptorSocket.enableNonBlockingMode( sal_True );
asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection...
/// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default.
sal_Bool bOK = sal_True;
asAcceptorSocket.close( );
ASSERT_TRUE(( sal_True == bOK )) << "test for enableNonBlockingMode function: launch a server socket and make it non blocking. if it can pass the acceptConnection statement, it is non-blocking";
}
/** testing the method:
inline sal_Bool SAL_CALL isNonBlockingMode() const;
*/
class isNonBlockingMode : public ::testing::Test
{
public:
::osl::AcceptorSocket asAcceptorSocket;
}; // class isNonBlockingMode
TEST_F(isNonBlockingMode, isNonBlockingMode_001)
{
::osl::SocketAddr saLocalSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_MYPORT );
::osl::StreamSocket ssConnection;
/// launch server socket
asAcceptorSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); // sal_True);
sal_Bool bOK1 = asAcceptorSocket.bind( saLocalSocketAddr );
ASSERT_TRUE(sal_True == bOK1) << "AcceptorSocket bind address failed.";
sal_Bool bOK2 = asAcceptorSocket.listen( 1 );
ASSERT_TRUE(sal_True == bOK2) << "AcceptorSocket listen failed.";
sal_Bool bOK3 = asAcceptorSocket.isNonBlockingMode( );
asAcceptorSocket.enableNonBlockingMode( sal_True );
asAcceptorSocket.acceptConnection(ssConnection); /// waiting for incoming connection...
/// if reach this statement, it is non-blocking mode, since acceptConnection will blocked by default.
sal_Bool bOK4 = asAcceptorSocket.isNonBlockingMode( );
asAcceptorSocket.close( );
ASSERT_TRUE(( sal_False == bOK3 ) && ( sal_True == bOK4 )) << "test for isNonBlockingMode function: launch a server socket and make it non blocking. it is expected to change from blocking mode to non-blocking mode.";
}
/** testing the method:
inline void SAL_CALL clearError() const;
*/
class clearError : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class clearError
TEST_F(clearError, clearError_001)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_HTTP2 );
::osl::SocketAddr saLocalSocketAddr;
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail"
oslSocketError seBind = sSocket.getError( );
sSocket.clearError( );
ASSERT_TRUE(osl_Socket_E_None == sSocket.getError( ) && seBind != osl_Socket_E_None) << "test for clearError function: trick an error called sSocket.getError( ), and then clear the error states, check the result.";
}
/** testing the methods:
inline oslSocketError getError() const;
inline ::rtl::OUString getErrorAsString( ) const;
*/
class getError : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getError
TEST_F(getError, getError_001)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("127.0.0.1"), IP_PORT_FTP );
::osl::SocketAddr saLocalSocketAddr;
ASSERT_TRUE(osl_Socket_E_None == sSocket.getError( )) << "test for getError function: should get no error.";
}
TEST_F(getError, getError_002)
{
::osl::Socket sSocket(sHandle);
::osl::SocketAddr saBindSocketAddr( rtl::OUString::createFromAscii("123.45.67.89"), IP_PORT_FTP );
::osl::SocketAddr saLocalSocketAddr;
sSocket.setOption( osl_Socket_OptionReuseAddr, 1 ); //sal_True);
sSocket.bind( saBindSocketAddr );//build an error "osl_Socket_E_AddrNotAvail"
//on Solaris, the error no is EACCES, but it has no mapped value, so getError() returned osl_Socket_E_InvalidError.
#if defined(SOLARIS)
ASSERT_TRUE(osl_Socket_E_InvalidError == sSocket.getError( )) << "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. ";
#else
//while on Linux & Win32, the errno is EADDRNOTAVAIL, getError returned osl_Socket_E_AddrNotAvail.
ASSERT_TRUE(osl_Socket_E_AddrNotAvail == sSocket.getError( )) << "trick an error called sSocket.getError( ), check the getError result.Failed on Solaris, returned osl_Socket_E_InvalidError because no entry to map the errno EACCES. Passed on Linux & Win32";
#endif
}
/** testing the methods:
inline oslSocket getHandle() const;
*/
class getHandle : public ::testing::Test
{
public:
oslSocket sHandle;
// initialization
void SetUp( )
{
sHandle = osl_createSocket( osl_Socket_FamilyInet, osl_Socket_TypeStream, osl_Socket_ProtocolIp );
}
void TearDown( )
{
sHandle = NULL;
}
}; // class getHandle
TEST_F(getHandle, getHandle_001)
{
::osl::Socket sSocket(sHandle);
::osl::Socket assignSocket = sSocket.getHandle();
ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment_handle function: test the assignment operator.";
}
TEST_F(getHandle, getHandle_002)
{
::osl::Socket sSocket( sHandle );
::osl::Socket assignSocket ( sSocket.getHandle( ) );
ASSERT_TRUE(osl_Socket_TypeStream == assignSocket.getType( )) << "test for operators_assignment function: assignment operator";
}
} // namespace osl_Socket
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 36.616427 | 264 | 0.673106 |
53988aa7ba416ddd19afa84395af5a3fae8bd86d | 1,714 | cpp | C++ | test/quiver/disjoint_set.cpp | Fytch/Quiver | 572c59bbc7aaef0e61318d6d0feaf5771b38cfdb | [
"MIT"
] | null | null | null | test/quiver/disjoint_set.cpp | Fytch/Quiver | 572c59bbc7aaef0e61318d6d0feaf5771b38cfdb | [
"MIT"
] | 1 | 2018-11-28T12:55:50.000Z | 2018-11-28T12:55:50.000Z | test/quiver/disjoint_set.cpp | Fytch/Quiver | 572c59bbc7aaef0e61318d6d0feaf5771b38cfdb | [
"MIT"
] | 1 | 2018-08-19T16:48:23.000Z | 2018-08-19T16:48:23.000Z | /*
* Quiver - A graph theory library
* Copyright (C) 2018 Josua Rieder (josua.rieder1996@gmail.com)
* Distributed under the MIT License.
* See the enclosed file LICENSE.txt for further information.
*/
#include <catch2/catch.hpp>
#include <quiver.hpp>
using namespace quiver;
TEST_CASE("disjoint_set", "[quiver][fundamentals]")
{
const std::size_t N = 10;
disjoint_set<> set(N);
CHECK(set.sets() == N);
for(std::size_t i = 0; i < N; ++i) {
CHECK(set.find(i) == i);
CHECK(set.cardinality(i) == 1);
}
set.unite(1, 2);
set.unite(2, 3);
set.unite(7, 6);
set.unite(5, 6);
CHECK(set.sets() == N - 4);
CHECK(set.cardinality(0) == 1);
CHECK(set.cardinality(1) == 3);
CHECK(set.cardinality(2) == 3);
CHECK(set.cardinality(3) == 3);
CHECK(set.find(1) == set.find(2));
CHECK(set.find(1) == set.find(3));
CHECK(set.cardinality(4) == 1);
CHECK(set.cardinality(5) == 3);
CHECK(set.cardinality(6) == 3);
CHECK(set.cardinality(7) == 3);
CHECK(set.find(5) == set.find(6));
CHECK(set.find(5) == set.find(7));
CHECK(set.cardinality(8) == 1);
CHECK(set.cardinality(9) == 1);
set.unite(7, 2);
set.unite(3, 9);
CHECK(set.sets() == N - 6);
CHECK(set.cardinality(0) == 1);
CHECK(set.cardinality(4) == 1);
CHECK(set.cardinality(8) == 1);
CHECK(set.cardinality(1) == 7);
CHECK(set.cardinality(2) == 7);
CHECK(set.cardinality(3) == 7);
CHECK(set.cardinality(5) == 7);
CHECK(set.cardinality(6) == 7);
CHECK(set.cardinality(7) == 7);
CHECK(set.cardinality(9) == 7);
CHECK(set.find(1) == set.find(2));
CHECK(set.find(1) == set.find(3));
CHECK(set.find(1) == set.find(5));
CHECK(set.find(1) == set.find(6));
CHECK(set.find(1) == set.find(7));
CHECK(set.find(1) == set.find(9));
}
| 23.805556 | 63 | 0.620187 |
5398b26338a516064b89ca836a8e8e18f2bf5567 | 2,366 | hpp | C++ | include/xtr/detail/align.hpp | uilianries/xtr | b1dccc51b024369e6c1a2f6d3fcf5f405735289b | [
"MIT"
] | 10 | 2021-09-25T10:40:55.000Z | 2022-03-19T01:05:05.000Z | include/xtr/detail/align.hpp | uilianries/xtr | b1dccc51b024369e6c1a2f6d3fcf5f405735289b | [
"MIT"
] | 2 | 2021-09-24T12:59:08.000Z | 2021-09-24T19:17:47.000Z | include/xtr/detail/align.hpp | uilianries/xtr | b1dccc51b024369e6c1a2f6d3fcf5f405735289b | [
"MIT"
] | 1 | 2021-09-24T13:45:29.000Z | 2021-09-24T13:45:29.000Z | // Copyright 2014, 2019 Chris E. Holloway
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#ifndef XTR_DETAIL_ALIGN_HPP
#define XTR_DETAIL_ALIGN_HPP
#include <bit>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include <type_traits>
namespace xtr::detail
{
// value is unchanged if it is already aligned
template<typename T>
constexpr T align(T value, T alignment) noexcept
{
static_assert(std::is_unsigned_v<T>, "value must be unsigned");
assert(std::has_single_bit(alignment));
return (value + (alignment - 1)) & ~(alignment - 1);
}
// Align is only a template argument to allow it to be used with
// assume_aligned. Improvement: Make Align a plain argument if it is
// possible to do so while still marking the return value as aligned.
template<std::size_t Align, typename T>
__attribute__((assume_aligned(Align))) T* align(T* ptr) noexcept
{
static_assert(
std::is_same_v<std::remove_cv_t<T>, std::byte> ||
std::is_same_v<std::remove_cv_t<T>, char> ||
std::is_same_v<std::remove_cv_t<T>, unsigned char> ||
std::is_same_v<std::remove_cv_t<T>, signed char>,
"value must be a char or byte pointer");
return reinterpret_cast<T*>(align(std::uintptr_t(ptr), Align));
}
}
#endif
| 40.793103 | 81 | 0.707946 |
539a24d2037b6ea2b2309ec0dd0fdbb5473e839d | 1,118 | cpp | C++ | src/gmp_integer_vector.cpp | dhruvdcoder/poly-metic | c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac | [
"Apache-2.0"
] | 1 | 2021-12-14T16:16:12.000Z | 2021-12-14T16:16:12.000Z | src/gmp_integer_vector.cpp | dhruvdcoder/poly-metic | c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac | [
"Apache-2.0"
] | 3 | 2018-09-02T04:38:52.000Z | 2018-09-09T20:14:16.000Z | src/gmp_integer_vector.cpp | dhruvdcoder/poly-metic | c8ec0ba30dd052c6b41a0cdeb58318d063cf9eac | [
"Apache-2.0"
] | null | null | null | // Copyright 2018 Dhruvesh Nikhilkumar Patel
//
// 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 <gmpxx.h>
#include <iostream>
#include <vector>
int main()
{
std::vector<std::vector<mpz_class>> Integers {{1,2},{34,45}};
// Integers.push_back(1);
// Integers.push_back(2);
// Integers.push_back(34);
// Integers.push_back(45);
std::cout<<"Integers = (";
size_t i =0;
for (;i<2;i++) {
std::cout<< "(";
for(size_t j=0;j<2;j++) {
std::cout<<Integers[i][j]<<",";
}
std::cout<<")";
}
std::cout<<")"<<std::endl;
return 0;
}
| 29.421053 | 77 | 0.635957 |
539b28bd3fd509a516e0026b76ec38fb73d66154 | 795 | cpp | C++ | demo/ref_object.cpp | bianc2018/Sim | 8c37f65d28b99598c1c75a650e4da36a460cf600 | [
"MIT"
] | 1 | 2021-01-19T15:25:25.000Z | 2021-01-19T15:25:25.000Z | demo/ref_object.cpp | bianc2018/Sim | 8c37f65d28b99598c1c75a650e4da36a460cf600 | [
"MIT"
] | null | null | null | demo/ref_object.cpp | bianc2018/Sim | 8c37f65d28b99598c1c75a650e4da36a460cf600 | [
"MIT"
] | null | null | null | #include "Logger.hpp"
#include "TaskPool.hpp"
#include "RefObject.hpp"
class faketype
{
public:
faketype()
{
SIM_LINFO("faketype() "<<SIM_HEX(this));
}
~faketype()
{
SIM_LINFO("~faketype " << SIM_HEX(this));
}
};
sim::RefObject<faketype> temp;
void* run(void* pd)
{
sim::RefObject<faketype> ref = temp;
SIM_LINFO("ref count=" << ref.getcount());
return NULL;
}
int main(int argc, char* argv[])
{
SIM_LOG_CONSOLE(sim::LInfo);
SIM_FUNC_DEBUG();
sim::RefObject<faketype> ref(new faketype());
SIM_LINFO("ref count=" << ref.getcount());
sim::RefObject<faketype> ref1 = ref;
temp = ref1;
sim::TaskPool pool(8);
for (int i = 0; i < 10000; ++i)
pool.Post(run, NULL, NULL);
while (ref.getcount() >3)
{
SIM_LINFO("ref count=" << ref.getcount());
}
getchar();
return 0;
}
| 17.666667 | 46 | 0.642767 |
539cff1c13cce4d0f9acdc2c642e1c8ccd143bf2 | 1,294 | cc | C++ | examples/RC/baseline/test_RC.cc | donghao2nanjing/PIDControl_and_RC | e5a96e834d41f8151e9a213f6d7797b2e71dbc07 | [
"MIT"
] | 11 | 2018-10-31T02:15:28.000Z | 2021-02-26T04:14:33.000Z | examples/RC/baseline/test_RC.cc | donghao2nanjing/PIDControl_and_RC | e5a96e834d41f8151e9a213f6d7797b2e71dbc07 | [
"MIT"
] | null | null | null | examples/RC/baseline/test_RC.cc | donghao2nanjing/PIDControl_and_RC | e5a96e834d41f8151e9a213f6d7797b2e71dbc07 | [
"MIT"
] | 12 | 2019-01-03T09:44:06.000Z | 2021-02-26T04:14:39.000Z | #include <rc.h>
#include <filter.h>
#include <stdio.h>
#include <math.h>
#define TS 1e-4 // 100us control period
#define NUM_ITERATIONS 20000 // 2 seconds
float rc_buffer1[200];
float rc_buffer2[200];
float rc_buffer3[200];
Filter_t compensator;
float filter_num[3] = {0, 0.00726436941467171, 0.00668055316076471};
float filter_den[3] = {1, -1.76382275659635, 0.777767679171789};
float x_buffer[3];
float y_buffer[3];
int main(){
RC_t rc1;
RC_t rc2;
RC_t rc3;
float output1 = 0.0f ;
float output2 = 0.0f ;
float output3 = 0.0f ;
float sin_wave = 0.0f ;
rc_init(&rc1, 0.9f, rc_buffer1, 200, 0, 1.0, NULL);
rc_init(&rc2, 0.9f, rc_buffer2, 200, 25, 0.5, NULL);
filter_init(&compensator, 2, filter_num, filter_den, x_buffer, y_buffer);
rc_init(&rc3, 0.9f, rc_buffer3, 200, 50, 1.0, &compensator);
FILE *fp = fopen("test_rc_output.txt", "w");
if(fp == NULL){
return -1;
}
for(int i = 0; i < NUM_ITERATIONS; i ++ ){
sin_wave = sin( 2 * 3.1415926f * 50 * i * TS) ;
output1 = rc_calc(&rc1, sin_wave) ;
output2 = rc_calc(&rc2, sin_wave) ;
output3 = rc_calc(&rc3, sin_wave) ;
fprintf(fp, "%f\t%f\t%f\t%f\n", TS * i, output1, output2, output3);
}
fclose(fp) ;
return 0 ;
}
| 24.415094 | 77 | 0.613601 |
53a00aa768d7073cafbf71f51d524ea23faded2c | 669 | cpp | C++ | RapyutaTest.cpp | abhis2007/Algorithms-1 | 7637209c5aa52c1afd8be1884d018673d26f5c1f | [
"MIT"
] | 26 | 2019-04-05T07:10:15.000Z | 2022-01-08T02:35:19.000Z | RapyutaTest.cpp | abhis2007/Algorithms-1 | 7637209c5aa52c1afd8be1884d018673d26f5c1f | [
"MIT"
] | 2 | 2019-04-25T15:47:54.000Z | 2019-09-03T06:46:05.000Z | RapyutaTest.cpp | abhis2007/Algorithms-1 | 7637209c5aa52c1afd8be1884d018673d26f5c1f | [
"MIT"
] | 8 | 2019-04-05T08:58:50.000Z | 2020-07-03T01:53:58.000Z | #include <bits/stdc++.h>
using namespace std;
int main() {
int n;
cin >> n;
int arr[n + 1];
for (int i = 1; i <= n; ++i) {
cin >> arr[i];
}
int dp[n + 1][n + 1];
memset(dp, sizeof(dp), 0);
int res = INT_MIN;
dp[1][0] = 0;
dp[1][1] = arr[1];
for (int i = 2; i <= n; ++i) {
for (int j = 0; j <= i; ++j) {
if(j == 0){
dp[i][j] = 0;
continue;
}
if(j == i) {
dp[i][j] = arr[i] * j + dp[i - 1][j - 1];
}
else {
dp[i][j] = max(dp[i - 1][j], arr[i] * j + dp[i - 1][j - 1]);
}
res = max(res, dp[i][j]);
}
}
cout << res;
return 0;
}
| 19.114286 | 73 | 0.355755 |
53a23198e743b9d58184647433429dd85d8499a8 | 5,867 | cpp | C++ | cpgf/src/scriptbind/gscriptbind.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | null | null | null | cpgf/src/scriptbind/gscriptbind.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | null | null | null | cpgf/src/scriptbind/gscriptbind.cpp | mousepawmedia/libdeps | b004d58d5b395ceaf9fdc993cfb00e91334a5d36 | [
"BSD-3-Clause"
] | null | null | null | #include "cpgf/scriptbind/gscriptbind.h"
#include "cpgf/gglobal.h"
#include "../pinclude/gbindcommon.h"
#include "../pinclude/gscriptbindapiimpl.h"
namespace cpgf {
GScriptObject::GScriptObject(const GScriptConfig & config)
: config(config), owner(nullptr)
{
}
GScriptObject::GScriptObject(const GScriptObject & other)
: config(other.config), owner(nullptr)
{
}
GScriptObject::~GScriptObject()
{
}
GScriptValue GScriptObject::getValue(const char * name)
{
return this->doGetValue(name);
}
extern int Error_ScriptBinding_CantSetScriptValue;
void GScriptObject::setValue(const char * name, const GScriptValue & value)
{
switch(value.getType()) {
// We can't set any script object back to script engine,
// otherwise, cross module portability will be broken.
case GScriptValue::typeScriptObject:
case GScriptValue::typeScriptFunction:
case GScriptValue::typeScriptArray:
raiseCoreException(Error_ScriptBinding_CantSetScriptValue);
break;
default:
this->doSetValue(name, value);
break;
}
}
void GScriptObject::bindClass(const char * name, IMetaClass * metaClass)
{
this->setValue(name, GScriptValue::fromClass(metaClass));
}
void GScriptObject::bindEnum(const char * name, IMetaEnum * metaEnum)
{
this->setValue(name, GScriptValue::fromEnum(metaEnum));
}
void GScriptObject::bindFundamental(const char * name, const GVariant & value)
{
this->setValue(name, GScriptValue::fromFundamental(value));
}
void GScriptObject::bindAccessible(const char * name, void * instance, IMetaAccessible * accessible)
{
this->setValue(name, GScriptValue::fromAccessible(instance, accessible));
}
void GScriptObject::bindString(const char * stringName, const char * s)
{
this->setValue(stringName, GScriptValue::fromString(s));
}
void GScriptObject::bindObject(const char * objectName, void * instance, IMetaClass * type, bool transferOwnership)
{
this->setValue(objectName, GScriptValue::fromObject(instance, type, transferOwnership));
}
void GScriptObject::bindRaw(const char * name, const GVariant & value)
{
this->setValue(name, GScriptValue::fromRaw(value));
}
void GScriptObject::bindMethod(const char * name, void * instance, IMetaMethod * method)
{
this->setValue(name, GScriptValue::fromMethod(instance, method));
}
void GScriptObject::bindMethodList(const char * name, IMetaList * methodList)
{
this->setValue(name, GScriptValue::fromOverloadedMethods(methodList));
}
void GScriptObject::bindCoreService(const char * name, IScriptLibraryLoader * libraryLoader)
{
this->doBindCoreService(name, libraryLoader);
}
IMetaClass * GScriptObject::getClass(const char * className)
{
return this->getValue(className).toClass();
}
IMetaEnum * GScriptObject::getEnum(const char * enumName)
{
return this->getValue(enumName).toEnum();
}
GVariant GScriptObject::getFundamental(const char * name)
{
return this->getValue(name).toFundamental();
}
std::string GScriptObject::getString(const char * stringName)
{
return this->getValue(stringName).toString();
}
void * GScriptObject::getObject(const char * objectName)
{
return this->getValue(objectName).toObjectAddress(nullptr, nullptr);
}
GVariant GScriptObject::getRaw(const char * name)
{
return this->getValue(name).toRaw();
}
IMetaMethod * GScriptObject::getMethod(const char * methodName, void ** outInstance)
{
return this->getValue(methodName).toMethod(outInstance);
}
IMetaList * GScriptObject::getMethodList(const char * methodName)
{
return this->getValue(methodName).toOverloadedMethods();
}
GScriptValue::Type GScriptObject::getType(const char * name, IMetaTypedItem ** outMetaTypeItem)
{
GScriptValue value(this->getValue(name));
if(outMetaTypeItem != nullptr) {
*outMetaTypeItem = getTypedItemFromScriptValue(value);
}
return value.getType();
}
bool GScriptObject::valueIsNull(const char * name)
{
return this->getValue(name).isNull();
}
void GScriptObject::nullifyValue(const char * name)
{
this->setValue(name, GScriptValue::fromNull());
}
const GScriptConfig & GScriptObject::getConfig() const
{
return this->config;
}
GScriptObject * GScriptObject::getOwner() const
{
return this->owner;
}
void GScriptObject::setOwner(GScriptObject * newOwner)
{
this->owner = newOwner;
}
bool GScriptObject::isGlobal() const
{
return this->owner == nullptr;
}
const char * GScriptObject::getName() const
{
return this->name.c_str();
}
void GScriptObject::setName(const std::string & newName)
{
this->name = newName;
}
GScriptValue GScriptObject::createScriptObject(const char * name)
{
GScriptObject * object = nullptr;
const int delimiter = '.';
if(strchr(name, delimiter) == nullptr) {
object = this->doCreateScriptObject(name);
}
else {
size_t len = strlen(name);
GScopedArray<char> tempName(new char[len + 1]);
memmove(tempName.get(), name, len + 1);
char * next;
char * head = tempName.get();
GScopedPointer<GScriptObject> scriptObject;
for(;;) {
next = strchr(head, delimiter);
if(next != nullptr) {
*next = '\0';
}
GScriptObject * obj = scriptObject.get();
if(obj == nullptr) {
obj = this;
}
scriptObject.reset(obj->doCreateScriptObject(head));
if(! scriptObject) {
break;
}
if(next == nullptr) {
break;
}
++next;
head = next;
}
object = scriptObject.take();
}
if(object == nullptr) {
return GScriptValue();
}
else {
GScopedInterface<IScriptObject> scriptObject(new ImplScriptObject(object, true));
return GScriptValue::fromScriptObject(scriptObject.get());
}
}
void GScriptObject::holdObject(IObject * object)
{
this->objectHolder.push_back(GSharedInterface<IObject>(object));
}
} // namespace cpgf
| 24.344398 | 116 | 0.705642 |
53a33854d47f89f9ee86688a4019783b5cf36ffc | 569 | cpp | C++ | qt-creator-opensource-src-4.6.1/src/shared/qbs/tests/auto/blackbox/testdata-qt/auto-qrc/main.cpp | kevinlq/Qt-Creator-Opensource-Study | b8cadff1f33f25a5d4ef33ed93f661b788b1ba0f | [
"MIT"
] | 5 | 2018-12-22T14:49:13.000Z | 2022-01-13T07:21:46.000Z | Src/shared/qbs/tests/auto/blackbox/testdata-qt/auto-qrc/main.cpp | kevinlq/QSD | b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a | [
"MIT"
] | null | null | null | Src/shared/qbs/tests/auto/blackbox/testdata-qt/auto-qrc/main.cpp | kevinlq/QSD | b618fc63dc3aa5a18701c5b23e3ea3cdd253e89a | [
"MIT"
] | 8 | 2018-07-17T03:55:48.000Z | 2021-12-22T06:37:53.000Z | #include <QFile>
#include <iostream>
int main()
{
QFile resource1(":/thePrefix/resource1.txt");
if (!resource1.open(QIODevice::ReadOnly))
return 1;
QFile resource2(":/thePrefix/resource2.txt");
if (!resource2.open(QIODevice::ReadOnly))
return 2;
QFile resource3(":/theOtherPrefix/resource3.txt");
if (!resource3.open(QIODevice::ReadOnly))
return 3;
std::cout << "resource data: " << resource1.readAll().constData()
<< resource2.readAll().constData() << resource3.readAll().constData() << std::endl;
}
| 29.947368 | 97 | 0.636204 |
53a6d540c52e63dc58070a971baff80f27fd0f77 | 2,388 | cpp | C++ | client/include/game/CCheckpoints.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 368 | 2015-01-01T21:42:00.000Z | 2022-03-29T06:22:22.000Z | client/include/game/CCheckpoints.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 92 | 2019-01-23T23:02:31.000Z | 2022-03-23T19:59:40.000Z | client/include/game/CCheckpoints.cpp | MayconFelipeA/sampvoiceatt | 3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff | [
"MIT"
] | 179 | 2015-02-03T23:41:17.000Z | 2022-03-26T08:27:16.000Z | /*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CCheckpoints.h"
unsigned int MAX_NUM_CHECKPOINTS = 32;
unsigned int &CCheckpoints::NumActiveCPts = *(unsigned int *)0xC7C6D4;
CCheckpoint *CCheckpoints::m_aCheckPtArray = (CCheckpoint *)0xC7F158;
// Converted from cdecl void CCheckpoints::DeleteCP(uint id,ushort type) 0x722FC0
void CCheckpoints::DeleteCP(unsigned int id, unsigned short type) {
plugin::Call<0x722FC0, unsigned int, unsigned short>(id, type);
}
// Converted from cdecl void CCheckpoints::Init(void) 0x722880
void CCheckpoints::Init() {
plugin::Call<0x722880>();
}
// Converted from cdecl CCheckpoint* CCheckpoints::PlaceMarker(uint id,ushort type,CVector &posn,CVector &direction,float size,uchar red,uchar green,uchar blue,uchar alpha,ushort pulsePeriod,float pulseFraction,short rotateRate) 0x722C40
CCheckpoint* CCheckpoints::PlaceMarker(unsigned int id, unsigned short type, CVector& posn, CVector& direction, float size, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha, unsigned short pulsePeriod, float pulseFraction, short rotateRate) {
return plugin::CallAndReturn<CCheckpoint*, 0x722C40, unsigned int, unsigned short, CVector&, CVector&, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned short, float, short>(id, type, posn, direction, size, red, green, blue, alpha, pulsePeriod, pulseFraction, rotateRate);
}
// Converted from cdecl void CCheckpoints::Render(void) 0x726060
void CCheckpoints::Render() {
plugin::Call<0x726060>();
}
// Converted from cdecl void CCheckpoints::SetHeading(uint id,float angle) 0x722970
void CCheckpoints::SetHeading(unsigned int id, float angle) {
plugin::Call<0x722970, unsigned int, float>(id, angle);
}
// Converted from cdecl void CCheckpoints::Shutdown(void) 0x7228F0
void CCheckpoints::Shutdown() {
plugin::Call<0x7228F0>();
}
// Converted from cdecl void CCheckpoints::Update(void) 0x7229C0
void CCheckpoints::Update() {
plugin::Call<0x7229C0>();
}
// Converted from cdecl void CCheckpoints::UpdatePos(uint id,CVector &posn) 0x722900
void CCheckpoints::UpdatePos(unsigned int id, CVector& posn) {
plugin::Call<0x722900, unsigned int, CVector&>(id, posn);
} | 45.923077 | 302 | 0.760888 |
53b09b21c521c6d5830ca64f950aa53d5bd17b6e | 4,064 | cc | C++ | airec/src/model/ListItemsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | airec/src/model/ListItemsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | airec/src/model/ListItemsResult.cc | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/airec/model/ListItemsResult.h>
#include <json/json.h>
using namespace AlibabaCloud::Airec;
using namespace AlibabaCloud::Airec::Model;
ListItemsResult::ListItemsResult() :
ServiceResult()
{}
ListItemsResult::ListItemsResult(const std::string &payload) :
ServiceResult()
{
parse(payload);
}
ListItemsResult::~ListItemsResult()
{}
void ListItemsResult::parse(const std::string &payload)
{
Json::Reader reader;
Json::Value value;
reader.parse(payload, value);
setRequestId(value["RequestId"].asString());
auto resultNode = value["result"];
auto alldetailNode = resultNode["detail"]["detailItem"];
for (auto resultNodedetaildetailItem : alldetailNode)
{
Result::DetailItem detailItemObject;
if(!resultNodedetaildetailItem["author"].isNull())
detailItemObject.author = resultNodedetaildetailItem["author"].asString();
if(!resultNodedetaildetailItem["brandId"].isNull())
detailItemObject.brandId = resultNodedetaildetailItem["brandId"].asString();
if(!resultNodedetaildetailItem["categoryPath"].isNull())
detailItemObject.categoryPath = resultNodedetaildetailItem["categoryPath"].asString();
if(!resultNodedetaildetailItem["channel"].isNull())
detailItemObject.channel = resultNodedetaildetailItem["channel"].asString();
if(!resultNodedetaildetailItem["duration"].isNull())
detailItemObject.duration = resultNodedetaildetailItem["duration"].asString();
if(!resultNodedetaildetailItem["expireTime"].isNull())
detailItemObject.expireTime = resultNodedetaildetailItem["expireTime"].asString();
if(!resultNodedetaildetailItem["itemId"].isNull())
detailItemObject.itemId = resultNodedetaildetailItem["itemId"].asString();
if(!resultNodedetaildetailItem["itemType"].isNull())
detailItemObject.itemType = resultNodedetaildetailItem["itemType"].asString();
if(!resultNodedetaildetailItem["pubTime"].isNull())
detailItemObject.pubTime = resultNodedetaildetailItem["pubTime"].asString();
if(!resultNodedetaildetailItem["shopId"].isNull())
detailItemObject.shopId = resultNodedetaildetailItem["shopId"].asString();
if(!resultNodedetaildetailItem["status"].isNull())
detailItemObject.status = resultNodedetaildetailItem["status"].asString();
if(!resultNodedetaildetailItem["title"].isNull())
detailItemObject.title = resultNodedetaildetailItem["title"].asString();
result_.detail.push_back(detailItemObject);
}
auto totalNode = resultNode["total"];
if(!totalNode["instanceRecommendItem"].isNull())
result_.total.instanceRecommendItem = std::stol(totalNode["instanceRecommendItem"].asString());
if(!totalNode["queryCount"].isNull())
result_.total.queryCount = std::stol(totalNode["queryCount"].asString());
if(!totalNode["sceneRecommendItem"].isNull())
result_.total.sceneRecommendItem = std::stol(totalNode["sceneRecommendItem"].asString());
if(!totalNode["sceneWeightItem"].isNull())
result_.total.sceneWeightItem = std::stol(totalNode["sceneWeightItem"].asString());
if(!totalNode["totalCount"].isNull())
result_.total.totalCount = std::stol(totalNode["totalCount"].asString());
if(!totalNode["weightItem"].isNull())
result_.total.weightItem = std::stol(totalNode["weightItem"].asString());
if(!value["requestId"].isNull())
requestId_ = value["requestId"].asString();
}
std::string ListItemsResult::getRequestId()const
{
return requestId_;
}
ListItemsResult::Result ListItemsResult::getResult()const
{
return result_;
}
| 40.237624 | 97 | 0.762549 |
53b778497d67824a758b505d8509133ac53883c4 | 5,833 | hpp | C++ | include/RavEngine/unordered_vector.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 48 | 2020-11-18T23:14:25.000Z | 2022-03-11T09:13:42.000Z | include/RavEngine/unordered_vector.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 1 | 2020-11-17T20:53:10.000Z | 2020-12-01T20:27:36.000Z | include/RavEngine/unordered_vector.hpp | Ravbug/RavEngine | 73249827cb2cd3c938bb59447e9edbf7b6f0defc | [
"Apache-2.0"
] | 3 | 2020-12-22T02:40:39.000Z | 2021-10-08T02:54:22.000Z | #pragma once
#include <vector>
#include <phmap.h>
#include <functional>
namespace RavEngine {
/**
The Unordered Vector provides:
- O(1) erase by iterator
All other complexities for valid behaviors are identical to a regular vector. Elements must be moveable.
Note that the order of elements cannot be guareneed.
*/
template<typename T, typename vec = std::vector<T>>
class unordered_vector{
vec underlying;
public:
typedef typename decltype(underlying)::iterator iterator_type;
typedef typename decltype(underlying)::const_iterator const_iterator_type;
typedef typename decltype(underlying)::size_type index_type;
typedef typename decltype(underlying)::size_type size_type;
/**
Erase by iterator. Complexity is O(1).
@param it the iterator to erase
*/
inline const_iterator_type erase(iterator_type it){
*it = std::move(underlying.back());
underlying.pop_back();
return it;
}
/**
@return the underlying vector. Do not modify!
*/
inline const decltype(underlying)& get_underlying() const{
return underlying;
}
/**
Erase by iterator. Complexity is O(n)
@param value the data to erase
*/
inline const_iterator_type erase(const T& value){
auto it = std::find(underlying.begin(),underlying.end(),value);
underlying.erase(it);
return it;
}
/**
Add an item to the container
@param value the data to add
@return a reference to the pushed item
@note references may become invalid if an item is erased from the container
*/
inline T& insert(const T& value){
underlying.push_back(value);
return underlying.back();
}
/**
Add an item to the container
@param value the data to add
@return a reference to the emplaced item
@note references may become invalid if an item is erased from the container
*/
template<typename ... A>
inline T& emplace(A ... args){
underlying.emplace_back(args...);
return underlying.back();
}
inline T& operator[](index_type idx){
return underlying[idx];
}
const inline T& operator[](index_type idx) const{
return underlying[idx];
}
inline T& at(index_type idx){
return underlying.at(idx);
}
const inline T& at(index_type idx) const{
return underlying.at(idx);
}
inline const_iterator_type begin() const{
return underlying.begin();
}
inline const_iterator_type end() const{
return underlying.end();
}
inline iterator_type end(){
return underlying.end();
}
inline iterator_type begin(){
return underlying.begin();
}
inline size_type size() const{
return underlying.size();
}
inline void reserve(size_t num){
underlying.reserve(num);
}
inline void resize(size_t num){
underlying.resize(num);
}
inline bool empty() const{
return underlying.empty();
}
inline void clear(){
underlying.clear();
}
};
/**
The Unordered Contiguous Set provides:
- O(1) erase by value
- O(1) erase by iterator
All other complexities are identical to a regular vector. Elements must be moveable and hashable. Hashes must not have collisions. An imperfect hash will result in unpredictable behavior.
Note that the order of elements cannot be guareneed.
*/
template<typename T,typename vec = std::vector<T>, typename _hash = std::hash<T>>
class unordered_contiguous_set : public unordered_vector<T,vec>{
protected:
phmap::flat_hash_map<size_t, typename unordered_vector<T,vec>::size_type> offsets;
public:
typedef typename unordered_vector<T,vec>::iterator_type iterator_type;
typedef typename unordered_vector<T,vec>::iterator_type iterator;
typedef typename unordered_vector<T,vec>::const_iterator_type const_iterator_type;
typedef typename unordered_vector<T,vec>::const_iterator_type const_iterator; // for redundancy
typedef typename unordered_vector<T,vec>::size_type index_type;
typedef typename unordered_vector<T,vec>::size_type size_type;
/**
@return the hash for an element. This container does not need to include the element
*/
inline constexpr size_t hash_for(const T& value) const{
auto hasher = _hash();
return hasher(value);
}
/**
Erase by iterator
@param it the iterator to remove
*/
inline void erase(const typename unordered_vector<T,vec>::iterator_type& it){
// remove from the offset cache
auto hasher = _hash();
auto hash = hasher(*it);
if (offsets.contains(hash)) { // only erase if the container has the value
offsets.erase(hash);
// pop from back
auto i = unordered_vector<T,vec>::erase(it);
// update offset cache
hash = hasher(*i);
offsets[hash] = std::distance(this->begin(), it);
}
}
/**
Erase by element hash
@param size_t hash the hash of the element to remove
*/
constexpr inline void erase_by_hash(size_t hash){
auto it = this->begin() + offsets[hash];
erase(it);
}
/**
Erase by value
@param value item to remove
*/
inline void erase(const T& value){
auto valuehash = _hash()(value);
if (offsets.contains(valuehash)) {
auto it = this->begin() + offsets[valuehash];
erase(it);
}
}
inline void insert(const T& value){
auto hashcode = _hash()(value);
if (!this->offsets.contains(hashcode)){
offsets.emplace(hashcode,this->size());
unordered_vector<T,vec>::insert(value);
}
}
inline void contains(const T& value){
auto valuehash = _hash()(value);
return offsets.contains(valuehash);
}
};
}
| 27.64455 | 188 | 0.652323 |
53ba76c61e98337aadf73ebd3e280e4db93c4c91 | 1,827 | cpp | C++ | book/CH02/S16_Presenting_an_image.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 5 | 2019-03-02T16:29:15.000Z | 2021-11-07T11:07:53.000Z | book/CH02/S16_Presenting_an_image.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | null | null | null | book/CH02/S16_Presenting_an_image.cpp | THISISAGOODNAME/vkCookBook | d022b4151a02c33e5c58534dc53ca39610eee7b5 | [
"MIT"
] | 2 | 2018-07-10T18:15:40.000Z | 2020-01-03T04:02:32.000Z | //
// Created by aicdg on 2017/6/19.
//
//
// Chapter: 02 Image Presentation
// Recipe: 16 Presenting an image
#include "S16_Presenting_an_image.h"
namespace VKCookbook {
bool PresentImage(VkQueue queue,
std::vector<VkSemaphore> rendering_semaphores,
std::vector<PresentInfo> images_to_present) {
VkResult result;
std::vector<VkSwapchainKHR> swapchains;
std::vector<uint32_t> image_indices;
for( auto & image_to_present : images_to_present ) {
swapchains.emplace_back( image_to_present.Swapchain );
image_indices.emplace_back( image_to_present.ImageIndex );
}
VkPresentInfoKHR present_info = {
VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // VkStructureType sType
nullptr, // const void* pNext
static_cast<uint32_t>(rendering_semaphores.size()), // uint32_t waitSemaphoreCount
rendering_semaphores.data(), // const VkSemaphore * pWaitSemaphores
static_cast<uint32_t>(swapchains.size()), // uint32_t swapchainCount
swapchains.data(), // const VkSwapchainKHR * pSwapchains
image_indices.data(), // const uint32_t * pImageIndices
nullptr // VkResult* pResults
};
result = vkQueuePresentKHR( queue, &present_info );
switch( result ) {
case VK_SUCCESS:
return true;
default:
return false;
}
}
} | 41.522727 | 116 | 0.509031 |
53bf0759144880c94ad882e74dd18a42bbed8403 | 910 | cpp | C++ | lab2/Q1.cpp | jasonsie88/OOP-and-DS | fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28 | [
"MIT"
] | null | null | null | lab2/Q1.cpp | jasonsie88/OOP-and-DS | fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28 | [
"MIT"
] | null | null | null | lab2/Q1.cpp | jasonsie88/OOP-and-DS | fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
class Student {
private:
string name;
string studentID;
int score;
public:
Student(){
}
Student(string name, string studentID, int score){
Student:: name=name;
Student:: studentID=studentID;
Student:: score=score;
}
string getName(){
return Student:: name;
}
string getStudentID(){
return Student:: studentID;
}
int getScore(){
return Student:: score;
}
};
int main() {
string name;
string studentID;
int score;
Student mStudent;
cin >> name >> studentID >> score;
mStudent = Student(name, studentID, score);
cout << mStudent.getName() << "'s studentID is " << mStudent.getStudentID()
<< " and score is " << mStudent.getScore() << "." << endl;
return 0;
}
| 21.162791 | 80 | 0.552747 |
53c1d1bfbc4f270184ff9e72daeba7920a071150 | 5,895 | cpp | C++ | source/QtCore/QFutureWatcherBaseSlots.cpp | kenny1818/qt4xhb | f62f40d8b17acb93761014317b52da9f919707d0 | [
"MIT"
] | 1 | 2021-03-07T10:44:03.000Z | 2021-03-07T10:44:03.000Z | source/QtCore/QFutureWatcherBaseSlots.cpp | kenny1818/qt4xhb | f62f40d8b17acb93761014317b52da9f919707d0 | [
"MIT"
] | null | null | null | source/QtCore/QFutureWatcherBaseSlots.cpp | kenny1818/qt4xhb | f62f40d8b17acb93761014317b52da9f919707d0 | [
"MIT"
] | 2 | 2020-07-19T03:28:08.000Z | 2021-03-05T18:07:20.000Z | /*
Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4
Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>
*/
/*
DO NOT EDIT THIS FILE - the content was created using a source code generator
*/
#include "QFutureWatcherBaseSlots.h"
QFutureWatcherBaseSlots::QFutureWatcherBaseSlots( QObject * parent ) : QObject( parent )
{
}
QFutureWatcherBaseSlots::~QFutureWatcherBaseSlots()
{
}
void QFutureWatcherBaseSlots::started()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "started()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QFutureWatcherBaseSlots::finished()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "finished()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QFutureWatcherBaseSlots::canceled()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "canceled()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QFutureWatcherBaseSlots::paused()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "paused()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QFutureWatcherBaseSlots::resumed()
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resumed()" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
hb_vmEvalBlockV( cb, 1, pSender );
hb_itemRelease( pSender );
}
}
void QFutureWatcherBaseSlots::resultReadyAt( int resultIndex )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resultReadyAt(int)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
PHB_ITEM pResultIndex = hb_itemPutNI( NULL, resultIndex );
hb_vmEvalBlockV( cb, 2, pSender, pResultIndex );
hb_itemRelease( pSender );
hb_itemRelease( pResultIndex );
}
}
void QFutureWatcherBaseSlots::resultsReadyAt( int beginIndex, int endIndex )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resultsReadyAt(int,int)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
PHB_ITEM pBeginIndex = hb_itemPutNI( NULL, beginIndex );
PHB_ITEM pEndIndex = hb_itemPutNI( NULL, endIndex );
hb_vmEvalBlockV( cb, 3, pSender, pBeginIndex, pEndIndex );
hb_itemRelease( pSender );
hb_itemRelease( pBeginIndex );
hb_itemRelease( pEndIndex );
}
}
void QFutureWatcherBaseSlots::progressRangeChanged( int minimum, int maximum )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressRangeChanged(int,int)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
PHB_ITEM pMinimum = hb_itemPutNI( NULL, minimum );
PHB_ITEM pMaximum = hb_itemPutNI( NULL, maximum );
hb_vmEvalBlockV( cb, 3, pSender, pMinimum, pMaximum );
hb_itemRelease( pSender );
hb_itemRelease( pMinimum );
hb_itemRelease( pMaximum );
}
}
void QFutureWatcherBaseSlots::progressValueChanged( int progressValue )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressValueChanged(int)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
PHB_ITEM pProgressValue = hb_itemPutNI( NULL, progressValue );
hb_vmEvalBlockV( cb, 2, pSender, pProgressValue );
hb_itemRelease( pSender );
hb_itemRelease( pProgressValue );
}
}
void QFutureWatcherBaseSlots::progressTextChanged( const QString & progressText )
{
QObject * object = qobject_cast< QObject * >( sender() );
PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressTextChanged(QString)" );
if( cb )
{
PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" );
PHB_ITEM pProgressText = hb_itemPutC( NULL, QSTRINGTOSTRING( progressText ) );
hb_vmEvalBlockV( cb, 2, pSender, pProgressText );
hb_itemRelease( pSender );
hb_itemRelease( pProgressText );
}
}
void QFutureWatcherBaseSlots_connect_signal( const QString & signal, const QString & slot )
{
QFutureWatcherBase * obj = qobject_cast< QFutureWatcherBase * >( Qt4xHb::getQObjectPointerFromSelfItem() );
if( obj )
{
QFutureWatcherBaseSlots * s = QCoreApplication::instance()->findChild<QFutureWatcherBaseSlots *>();
if( s == NULL )
{
s = new QFutureWatcherBaseSlots();
s->moveToThread( QCoreApplication::instance()->thread() );
s->setParent( QCoreApplication::instance() );
}
hb_retl( Qt4xHb::Signals_connection_disconnection( s, signal, slot ) );
}
else
{
hb_retl( false );
}
}
| 26.917808 | 110 | 0.674979 |
53c3ed79cdbaac28d59dd1e13c36a9e10713d41b | 6,671 | cc | C++ | alljoyn_js/jni/ScriptableObject.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 33 | 2018-01-12T00:37:43.000Z | 2022-03-24T02:31:36.000Z | alljoyn_js/jni/ScriptableObject.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 1 | 2020-01-05T05:51:27.000Z | 2020-01-05T05:51:27.000Z | alljoyn_js/jni/ScriptableObject.cc | liuxiang88/core-alljoyn | 549c966482d9b89da84aa528117584e7049916cb | [
"Apache-2.0"
] | 30 | 2017-12-13T23:24:00.000Z | 2022-01-25T02:11:19.000Z | /*
* Copyright (c) Open Connectivity Foundation (OCF), AllJoyn Open Source
* Project (AJOSP) Contributors and others.
*
* SPDX-License-Identifier: Apache-2.0
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Apache License, Version 2.0
* which accompanies this distribution, and is available at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Copyright (c) Open Connectivity Foundation and Contributors to AllSeen
* Alliance. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all
* copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
* WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
* AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
* TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
#include "ScriptableObject.h"
#include "NativeObject.h"
#include "npn.h"
#include <assert.h>
#include <qcc/Debug.h>
#include <string.h>
#define QCC_MODULE "ALLJOYN_JS"
#define CALL_MEMBER(o, m) ((*o).*(m))
std::map<qcc::String, int32_t> ScriptableObject::noConstants;
ScriptableObject::ScriptableObject(Plugin& plugin) :
plugin(plugin),
getter(0),
setter(0),
deleter(0),
enumerator(0),
caller(0),
constants(noConstants)
{
QCC_DbgTrace(("%s", __FUNCTION__));
}
ScriptableObject::ScriptableObject(Plugin& plugin, std::map<qcc::String, int32_t>& constants) :
plugin(plugin),
getter(0),
setter(0),
deleter(0),
enumerator(0),
caller(0),
constants(constants)
{
QCC_DbgTrace(("%s", __FUNCTION__));
}
ScriptableObject::~ScriptableObject()
{
QCC_DbgTrace(("%s", __FUNCTION__));
}
void ScriptableObject::Invalidate()
{
QCC_DbgTrace(("%s", __FUNCTION__));
}
bool ScriptableObject::HasMethod(const qcc::String& name)
{
QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str()));
std::map<qcc::String, Operation>::iterator it = operations.find(name);
return (it != operations.end());
}
bool ScriptableObject::Invoke(const qcc::String& name, const NPVariant* args, uint32_t argCount, NPVariant* result)
{
QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str()));
std::map<qcc::String, Operation>::iterator it = operations.find(name);
if (it != operations.end()) {
assert(it->second.call);
return CALL_MEMBER(this, it->second.call) (args, argCount, result);
}
return false;
}
bool ScriptableObject::InvokeDefault(const NPVariant* args, uint32_t argCount, NPVariant* result)
{
QCC_DbgTrace(("%s", __FUNCTION__));
if (caller) {
return CALL_MEMBER(this, caller) (args, argCount, result);
}
return false;
}
bool ScriptableObject::HasProperty(const qcc::String& name)
{
QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str()));
std::map<qcc::String, int32_t>::iterator cit = constants.find(name);
if (cit != constants.end()) {
return true;
}
std::map<qcc::String, Attribute>::iterator ait = attributes.find(name);
return (ait != attributes.end());
}
bool ScriptableObject::GetProperty(const qcc::String& name, NPVariant* result)
{
QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str()));
std::map<qcc::String, int32_t>::iterator cit = constants.find(name);
if (cit != constants.end()) {
INT32_TO_NPVARIANT(cit->second, *result);
return true;
}
std::map<qcc::String, Attribute>::iterator ait = attributes.find(name);
if (ait != attributes.end()) {
assert(ait->second.get);
return CALL_MEMBER(this, ait->second.get) (result);
}
if (getter) {
return CALL_MEMBER(this, getter) (name, result);
}
return false;
}
bool ScriptableObject::SetProperty(const qcc::String& name, const NPVariant* value)
{
QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str()));
/*
* Workaround for WebKit browsers. "delete obj.property" doesn't call RemoveProperty, so allow
* "obj.property = undefined" to do the same thing.
*/
if (NPVARIANT_IS_VOID(*value)) {
return RemoveProperty(name);
}
std::map<qcc::String, Attribute>::iterator it = attributes.find(name);
if ((it != attributes.end()) && it->second.set) {
return CALL_MEMBER(this, it->second.set) (value);
}
if (setter) {
return CALL_MEMBER(this, setter) (name, value);
}
return false;
}
bool ScriptableObject::RemoveProperty(const qcc::String& name)
{
QCC_DbgTrace(("%s(name=%s)", __FUNCTION__, name.c_str()));
if (deleter) {
return CALL_MEMBER(this, deleter) (name);
}
return false;
}
bool ScriptableObject::Enumerate(NPIdentifier** value, uint32_t* count)
{
QCC_DbgTrace(("%s", __FUNCTION__));
*value = NULL;
*count = 0;
NPIdentifier* enumeratorValue = NULL;
uint32_t enumeratorCount = 0;
if (enumerator) {
CALL_MEMBER(this, enumerator) (&enumeratorValue, &enumeratorCount);
}
*count = enumeratorCount + constants.size() + attributes.size() + operations.size();
if (*count) {
*value = reinterpret_cast<NPIdentifier*>(NPN_MemAlloc(*count * sizeof(NPIdentifier)));
NPIdentifier* v = *value;
for (uint32_t i = 0; i < enumeratorCount; ++i) {
*v++ = enumeratorValue[i];
}
if (enumeratorValue) {
NPN_MemFree(enumeratorValue);
}
for (std::map<qcc::String, int32_t>::iterator it = constants.begin(); it != constants.end(); ++it) {
*v++ = NPN_GetStringIdentifier(it->first.c_str());
}
for (std::map<qcc::String, Attribute>::iterator it = attributes.begin(); it != attributes.end(); ++it) {
*v++ = NPN_GetStringIdentifier(it->first.c_str());
}
for (std::map<qcc::String, Operation>::iterator it = operations.begin(); it != operations.end(); ++it) {
*v++ = NPN_GetStringIdentifier(it->first.c_str());
}
}
return true;
}
bool ScriptableObject::Construct(const NPVariant* args, uint32_t argCount, NPVariant* result)
{
QCC_UNUSED(args);
QCC_UNUSED(argCount);
QCC_UNUSED(result);
QCC_DbgTrace(("%s", __FUNCTION__));
return false;
}
| 32.227053 | 115 | 0.653275 |
53cc3cee63f5e72f8f8ef2ed867e47459b546d2b | 8,973 | cpp | C++ | CGALib/src/Model.cpp | jorge-jcc/MarioCraftv2 | f0870721685452b2b39df1004f4be26f2dfb3629 | [
"Xnet",
"X11"
] | null | null | null | CGALib/src/Model.cpp | jorge-jcc/MarioCraftv2 | f0870721685452b2b39df1004f4be26f2dfb3629 | [
"Xnet",
"X11"
] | null | null | null | CGALib/src/Model.cpp | jorge-jcc/MarioCraftv2 | f0870721685452b2b39df1004f4be26f2dfb3629 | [
"Xnet",
"X11"
] | null | null | null | /*
* Model.cpp
*
* Created on: 13/09/2016
* Author: rey
*/
#include "Headers/Model.h"
#include "Headers/TimeManager.h"
#include "Headers/mathUtil.h"
Model::Model() {
this->aabb.mins.x = FLT_MAX;
this->aabb.mins.y = FLT_MAX;
this->aabb.mins.z = FLT_MAX;
this->aabb.maxs.x = -FLT_MAX;
this->aabb.maxs.y = -FLT_MAX;
this->aabb.maxs.z = -FLT_MAX;
this->animationIndex = 0;
}
Model::~Model() {
for (GLuint i = 0; i < this->meshes.size(); i++){
delete this->meshes[i]->bones;
delete this->meshes[i];
}
for (int i = 0; i < this->textureLoaded.size(); i++)
delete this->textureLoaded[i];
}
void Model::render(glm::mat4 parentTrans) {
float runningTime = TimeManager::Instance().GetRunningTime();
//float runningTime = TimeManager::Instance().DeltaTime;
for (GLuint i = 0; i < this->meshes.size(); i++) {
this->meshes[i]->setShader(this->getShader());
this->meshes[i]->setPosition(this->getPosition());
this->meshes[i]->setScale(this->getScale());
this->meshes[i]->setOrientation(this->getOrientation());
if(scene->mNumAnimations > 0){
this->meshes[i]->bones->setAnimationIndex(this->animationIndex);
if(this->meshes[i]->bones != nullptr){
shader_ptr->setInt("numBones", this->meshes[i]->bones->getNumBones());
std::vector<glm::mat4> transforms;
this->meshes[i]->bones->bonesTransform(runningTime, transforms, scene);
for (unsigned int j = 0; j < transforms.size(); j++) {
std::stringstream ss;
ss << "bones[" << j << "]";
shader_ptr->setMatrix4(ss.str(), 1, GL_FALSE,
glm::value_ptr(m_GlobalInverseTransform * transforms[j]));
}
}
else
parentTrans = m_GlobalInverseTransform * parentTrans;
}
this->meshes[i]->render(parentTrans);
glActiveTexture(GL_TEXTURE0);
shader_ptr->setInt("numBones", 0);
}
}
void Model::loadModel(const std::string & path) {
// Lee el archivo via ASSIMP
scene = importer.ReadFile(path.c_str(),
aiProcess_Triangulate | aiProcess_FlipUVs
| aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace);
// Revisa errores
if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE
|| !scene->mRootNode) // if is Not Zero
{
std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString()
<< std::endl;
return;
}
CopyMat(scene->mRootNode->mTransformation, this->m_GlobalInverseTransform);
this->m_GlobalInverseTransform = glm::inverse(
this->m_GlobalInverseTransform);
// Recupera el path del directorio del archivo.
this->directory = path.substr(0, path.find_last_of('/'));
// Se procesa el nodo raiz recursivamente.
this->processNode(scene->mRootNode, scene);
// Se crea la SBB
this->sbb.c = glm::vec3((this->aabb.mins.x + this->aabb.maxs.x) / 2.0f,
(this->aabb.mins.y + this->aabb.maxs.y) / 2.0f,
(this->aabb.mins.z + this->aabb.maxs.z) / 2.0f);
/*this->sbb.ratio = sqrt(
pow(this->aabb.mins.x - this->aabb.maxs.x, 2)
+ pow(this->aabb.mins.y - this->aabb.maxs.y, 2)
+ pow(this->aabb.mins.z - this->aabb.maxs.z, 2)) / 2.0f;*/
float disX = fabs(this->aabb.mins.x - this->aabb.maxs.x);
float disY = fabs(this->aabb.mins.y - this->aabb.maxs.y);
float disZ = fabs(this->aabb.mins.z - this->aabb.maxs.z);
float rtmp = std::max(disX, disY);
rtmp = std::max(rtmp, disZ);
this->sbb.ratio = rtmp / 2.f;
// Se crea la obb
this->obb.c = this->sbb.c;
/*this->obb.e.x = aabb.maxs.x - aabb.mins.x;
this->obb.e.y = aabb.maxs.y - aabb.mins.y;
this->obb.e.z = aabb.maxs.z - aabb.mins.z;*/
this->obb.e = (aabb.maxs - aabb.mins) / 2.0f;
this->obb.u = glm::quat(0.0, 0.0, 0.0, 1);
}
void Model::processNode(aiNode* node, const aiScene* scene) {
// Procesa cada maya del nodo actual
for (GLuint i = 0; i < node->mNumMeshes; i++) {
aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
Mesh * meshModel = this->processMesh(mesh, scene);
Bones * bones = new Bones(meshModel->getVAO(), mesh->mNumVertices);
bones->loadBones(i, mesh);
meshModel->bones = bones;
this->meshes.push_back(meshModel);
}
for (GLuint i = 0; i < node->mNumChildren; i++) {
this->processNode(node->mChildren[i], scene);
}
}
Mesh * Model::processMesh(aiMesh* mesh, const aiScene* scene) {
std::vector<AbstractModel::Vertex> vertices;
std::vector<GLuint> indices;
std::vector<Texture*> textures;
// Recorre los vertices de cada maya
for (GLuint i = 0; i < mesh->mNumVertices; i++) {
AbstractModel::Vertex vertex;
glm::vec3 vector;
// Compute the AABB
if (mesh->mVertices[i].x < aabb.mins.x)
aabb.mins.x = mesh->mVertices[i].x;
if (mesh->mVertices[i].x > aabb.maxs.x)
aabb.maxs.x = mesh->mVertices[i].x;
if (mesh->mVertices[i].y < aabb.mins.y)
aabb.mins.y = mesh->mVertices[i].y;
if (mesh->mVertices[i].y > aabb.maxs.y)
aabb.maxs.y = mesh->mVertices[i].y;
if (mesh->mVertices[i].z < aabb.mins.z)
aabb.mins.z = mesh->mVertices[i].z;
if (mesh->mVertices[i].z > aabb.maxs.z)
aabb.maxs.z = mesh->mVertices[i].z;
// Positions
vector.x = mesh->mVertices[i].x;
vector.y = mesh->mVertices[i].y;
vector.z = mesh->mVertices[i].z;
vertex.m_pos = vector;
// Normals
vector.x = mesh->mNormals[i].x;
vector.y = mesh->mNormals[i].y;
vector.z = mesh->mNormals[i].z;
vertex.m_normal = vector;
// Texture Coordinates
if (mesh->mTextureCoords[0]) // Esto se ejecuta si la maya contiene texturas.
{
glm::vec2 vec;
// Un vertice puede contener hasta 8 diferentes coordenadas de textura, unicamente se considera
// que los modelos tiene una coordenada de textura por vertice, y corresponde a la primera en el arreglo.
vec.x = mesh->mTextureCoords[0][i].x;
vec.y = mesh->mTextureCoords[0][i].y;
vertex.m_tex = vec;
} else
vertex.m_tex = glm::vec2(0.0f, 0.0f);
vertices.push_back(vertex);
}
// Se recorre cada cara de la maya (una cara es un triangulo en la maya) y recupera su correspondiente indice del vertice.
for (GLuint i = 0; i < mesh->mNumFaces; i++) {
aiFace face = mesh->mFaces[i];
// Recupera todos los indices de la cara y los almacena en el vector de indices
for (GLuint j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
// Process materials
if (mesh->mMaterialIndex >= 0) {
aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];
// We assume a convention for sampler names in the shaders. Each diffuse texture should be named
// as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER.
// Same applies to other texture as the following list summarizes:
// Diffuse: texture_diffuseN
// Specular: texture_specularN
// Normal: texture_normalN
// 1. Diffuse maps
std::vector<Texture*> diffuseMaps = this->loadMaterialTextures(material,
aiTextureType_DIFFUSE, "texture_diffuse");
textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end());
// 2. Specular maps
std::vector<Texture*> specularMaps = this->loadMaterialTextures(material,
aiTextureType_SPECULAR, "texture_specular");
textures.insert(textures.end(), specularMaps.begin(),
specularMaps.end());
// 3. Normal maps
std::vector<Texture*> normalMaps = this->loadMaterialTextures(material,
aiTextureType_NORMALS, "texture_normal");
textures.insert(textures.end(), normalMaps.begin(), normalMaps.end());
// 4. Height maps
std::vector<Texture*> heightMaps = this->loadMaterialTextures(material,
aiTextureType_HEIGHT, "texture_height");
textures.insert(textures.end(), heightMaps.begin(), heightMaps.end());
}
Mesh * meshModel = new Mesh(vertices, indices, textures);
// Regresa la maya de un objeto creado de los datos extraidos.
return meshModel;
}
std::vector<Texture*> Model::loadMaterialTextures(aiMaterial* mat,
aiTextureType type, std::string typeName) {
std::vector<Texture*> textures;
for (GLuint i = 0; i < mat->GetTextureCount(type); i++) {
aiString str;
mat->GetTexture(type, i, &str);
// Verifica si la textura fue cargada antes y si es as�, continua con la siguiente iteracion: en caso controaio se salta la carga
GLboolean skip = false;
for (GLuint j = 0; j < textureLoaded.size(); j++) {
if (textureLoaded[j]->getFileName() == str.C_Str()) {
textures.push_back(textureLoaded[j]);
skip = true;
break;
}
}
if (!skip) {
std::string filename = std::string(str.C_Str());
filename = this->directory + '/' + filename;
Texture * texture = new Texture(GL_TEXTURE_2D, filename);
texture->load();
texture->setType(typeName);
textures.push_back(texture);
this->textureLoaded.push_back(texture); // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
}
}
return textures;
}
bool Model::rayPicking(glm::vec3 init, glm::vec3 end, glm::vec3 &intersection) {
return false;
}
| 36.77459 | 146 | 0.657528 |
53cffcce8f6c207095d511f4629668bd41857bb6 | 10,689 | cpp | C++ | iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | iOS/G3MApp/G3MApp/G3MHUDDemoScene.cpp | AeroGlass/g3m | a21a9e70a6205f1f37046ae85dafc6e3bfaeb917 | [
"BSD-2-Clause"
] | null | null | null | //
// G3MHUDDemoScene.cpp
// G3MApp
//
// Created by Diego Gomez Deck on 12/2/14.
// Copyright (c) 2014 Igo Software SL. All rights reserved.
//
#include "G3MHUDDemoScene.hpp"
//#include <G3MiOSSDK/G3MWidget.hpp>
#include <G3MiOSSDK/MapBoxLayer.hpp>
#include <G3MiOSSDK/LayerSet.hpp>
#include <G3MiOSSDK/CanvasImageBuilder.hpp>
#include <G3MiOSSDK/ICanvas.hpp>
#include <G3MiOSSDK/Color.hpp>
#include <G3MiOSSDK/IStringUtils.hpp>
#include <G3MiOSSDK/GFont.hpp>
#include <G3MiOSSDK/Context.hpp>
#include <G3MiOSSDK/HUDQuadWidget.hpp>
#include <G3MiOSSDK/HUDRenderer.hpp>
#include <G3MiOSSDK/HUDRelativePosition.hpp>
#include <G3MiOSSDK/HUDRelativeSize.hpp>
#include <G3MiOSSDK/LabelImageBuilder.hpp>
#include <G3MiOSSDK/DownloaderImageBuilder.hpp>
#include <G3MiOSSDK/HUDAbsolutePosition.hpp>
#include <G3MiOSSDK/GTask.hpp>
#include <G3MiOSSDK/G3MWidget.hpp>
#include <G3MiOSSDK/PeriodicalTask.hpp>
#include "G3MDemoModel.hpp"
class AltimeterCanvasImageBuilder : public CanvasImageBuilder {
private:
float _altitude = 38500;
float _step = 100;
protected:
void buildOnCanvas(const G3MContext* context,
ICanvas* canvas) {
const float width = canvas->getWidth();
const float height = canvas->getHeight();
canvas->setFillColor(Color::fromRGBA(0, 0, 0, 0.5));
canvas->fillRectangle(0, 0, width, height);
canvas->setFillColor(Color::white());
const IStringUtils* su = context->getStringUtils();
int altitude = _altitude;
canvas->setFont(GFont::monospaced(32));
for (int y = 0; y <= height; y += 16) {
if ((y % 80) == 0) {
canvas->fillRectangle(0, y-1.5f, width/6.0f, 3);
const std::string label = su->toString(altitude);
const Vector2F labelExtent = canvas->textExtent(label);
canvas->fillText(label,
width/6.0f * 1.25f,
y - labelExtent._y/2);
altitude -= 100;
}
else {
canvas->fillRectangle(0, y-0.5f, width/8.0f, 1);
}
}
canvas->setLineColor(Color::white());
canvas->setLineWidth(8);
canvas->strokeRectangle(0, 0, width, height);
}
public:
AltimeterCanvasImageBuilder() :
CanvasImageBuilder(256, 256*3)
{
}
bool isMutable() const {
return true;
}
void step() {
_altitude += _step;
if (_altitude > 40000) {
_altitude = 40000;
_step *= -1;
}
if (_altitude < 0) {
_altitude = 0;
_step *= -1;
}
changed();
}
};
class AnimateHUDWidgetsTask : public GTask {
private:
HUDQuadWidget* _compass1;
HUDQuadWidget* _compass2;
HUDQuadWidget* _ruler;
LabelImageBuilder* _labelBuilder;
AltimeterCanvasImageBuilder* _altimeterCanvasImageBuilder;
double _angleInRadians;
float _translationV;
float _translationStep;
public:
AnimateHUDWidgetsTask(HUDQuadWidget* compass1,
HUDQuadWidget* compass2,
HUDQuadWidget* ruler,
LabelImageBuilder* labelBuilder,
AltimeterCanvasImageBuilder* altimeterCanvasImageBuilder) :
_compass1(compass1),
_compass2(compass2),
_ruler(ruler),
_labelBuilder(labelBuilder),
_altimeterCanvasImageBuilder(altimeterCanvasImageBuilder),
_angleInRadians(0),
_translationV(0),
_translationStep(0.002)
{
}
void run(const G3MContext* context) {
_angleInRadians += Angle::fromDegrees(2)._radians;
// _labelBuilder->setText( Angle::fromRadians(_angleInRadians).description() );
double degrees = Angle::fromRadians(_angleInRadians)._degrees;
while (degrees > 360) {
degrees -= 360;
}
const std::string degreesText = IStringUtils::instance()->toString( IMathUtils::instance()->round( degrees ) );
_labelBuilder->setText( " " + degreesText );
// _compass1->setTexCoordsRotation(_angleInRadians,
// 0.5f, 0.5f);
_compass2->setTexCoordsRotation(-_angleInRadians,
0.5f, 0.5f);
// _compass3->setTexCoordsRotation(Angle::fromRadians(_angle),
// 0.5f, 0.5f);
if (_translationV > 0.5 || _translationV < 0) {
_translationStep *= -1;
}
_translationV += _translationStep;
_ruler->setTexCoordsTranslation(0, _translationV);
_altimeterCanvasImageBuilder->step();
}
};
void G3MHUDDemoScene::rawActivate(const G3MContext *context) {
G3MDemoModel* model = getModel();
G3MWidget* g3mWidget = model->getG3MWidget();
MapBoxLayer* layer = new MapBoxLayer("examples.map-m0t0lrpu",
TimeInterval::fromDays(30),
true,
2);
model->getLayerSet()->addLayer(layer);
HUDRenderer* hudRenderer = model->getHUDRenderer();
AltimeterCanvasImageBuilder* altimeterCanvasImageBuilder = new AltimeterCanvasImageBuilder();
HUDQuadWidget* test = new HUDQuadWidget(altimeterCanvasImageBuilder,
new HUDRelativePosition(0,
HUDRelativePosition::VIEWPORT_WIDTH,
HUDRelativePosition::RIGHT,
10),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_HEIGHT,
HUDRelativePosition::MIDDLE),
new HUDRelativeSize(0.22,
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new HUDRelativeSize(0.66,
HUDRelativeSize::VIEWPORT_MIN_AXIS)
);
hudRenderer->addWidget(test);
LabelImageBuilder* labelBuilder = new LabelImageBuilder("glob3", // text
GFont::monospaced(38), // font
6, // margin
Color::yellow(), // color
Color::black(), // shadowColor
3, // shadowBlur
1, // shadowOffsetX
-1, // shadowOffsetY
Color::red(), // backgroundColor
4, // cornerRadius
true // mutable
);
HUDQuadWidget* label = new HUDQuadWidget(labelBuilder,
new HUDAbsolutePosition(10),
new HUDAbsolutePosition(10),
new HUDRelativeSize(1, HUDRelativeSize::BITMAP_WIDTH),
new HUDRelativeSize(1, HUDRelativeSize::BITMAP_HEIGHT) );
hudRenderer->addWidget(label);
HUDQuadWidget* compass2 = new HUDQuadWidget(new DownloaderImageBuilder(URL("file:///CompassHeadings.png")),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_WIDTH,
HUDRelativePosition::CENTER),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_HEIGHT,
HUDRelativePosition::MIDDLE),
new HUDRelativeSize(0.25,
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new HUDRelativeSize(0.125,
HUDRelativeSize::VIEWPORT_MIN_AXIS));
compass2->setTexCoordsRotation(Angle::fromDegrees(30),
0.5f, 0.5f);
compass2->setTexCoordsScale(1, 0.5f);
hudRenderer->addWidget(compass2);
float visibleFactor = 3;
HUDQuadWidget* ruler = new HUDQuadWidget(new DownloaderImageBuilder(URL("file:///altimeter-ruler-1536x113.png")),
new HUDRelativePosition(1,
HUDRelativePosition::VIEWPORT_WIDTH,
HUDRelativePosition::LEFT,
10),
new HUDRelativePosition(0.5,
HUDRelativePosition::VIEWPORT_HEIGHT,
HUDRelativePosition::MIDDLE),
new HUDRelativeSize(2 * (113.0 / 1536.0),
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new HUDRelativeSize(2 / visibleFactor,
HUDRelativeSize::VIEWPORT_MIN_AXIS),
new DownloaderImageBuilder(URL("file:///widget-background.png")));
ruler->setTexCoordsScale(1 , 1.0f / visibleFactor);
hudRenderer->addWidget(ruler);
g3mWidget->addPeriodicalTask(new PeriodicalTask(TimeInterval::fromMilliseconds(50),
new AnimateHUDWidgetsTask(label,
compass2,
ruler,
labelBuilder,
altimeterCanvasImageBuilder)));
}
| 41.27027 | 116 | 0.477874 |
53d1654bd095104482205740dbd1d2022d6be557 | 1,346 | hpp | C++ | Hardware/src/hard/rpi_gpio.hpp | torunxxx001/BookCollectionSystem | cce2942e30c460949ba729db432f0efdd66f8465 | [
"MIT"
] | null | null | null | Hardware/src/hard/rpi_gpio.hpp | torunxxx001/BookCollectionSystem | cce2942e30c460949ba729db432f0efdd66f8465 | [
"MIT"
] | null | null | null | Hardware/src/hard/rpi_gpio.hpp | torunxxx001/BookCollectionSystem | cce2942e30c460949ba729db432f0efdd66f8465 | [
"MIT"
] | null | null | null | /* 参考PDF[BCM2835-ARM-Peripherals.pdf] */
/* RaspberryPI用GPIO操作プログラム */
/*
対応表
PIN NAME
0 GPIO 2(SDA)
1 GPIO 3(SCL)
2 GPIO 4(GPCLK0)
3 GPIO 7(CE1)
4 GPIO 8(CE0)
5 GPIO 9(MISO)
6 GPIO 10(MOSI)
7 GPIO 11(SCLK)
8 GPIO 14(TXD)
9 GPIO 15(RXD)
10 GPIO 17
11 GPIO 18(PCM_CLK)
12 GPIO 22
13 GPIO 23
14 GPIO 24
15 GPIO 25
16 GPIO 27(PCM_DOUT)
17 GPIO 28
18 GPIO 29
19 GPIO 30
20 GPIO 31
*/
#ifndef __RPI_GPIO_HPP__
#define __RPI_GPIO_HPP__
/* バスアクセス用物理アドレス(Page.6 - 1.2.3) */
#define PHADDR_OFFSET 0x20000000
/* GPIOコントロールレジスタへのオフセット(Page.90 - 6.1) */
#define GPIO_CONTROL_OFFSET (PHADDR_OFFSET + 0x200000)
/* GPFSEL0からGPLEVまでのサイズ */
#define GPCONT_SIZE 0x3C
/* 各レジスタへのオフセット */
#define GPFSEL_OFFSET 0x00
#define GPSET_OFFSET 0x1C
#define GPCLR_OFFSET 0x28
#define GPLEV_OFFSET 0x34
/* モード定義 */
#define GPIO_INPUT 0
#define GPIO_OUTPUT 1
#define GPIO_ALT0 4
#define GPIO_ALT1 5
#define GPIO_ALT2 6
#define GPIO_ALT3 7
#define GPIO_ALT4 3
#define GPIO_ALT5 2
#define HIGH 1
#define LOW 0
extern const char* PINtoNAME[];
//GPIOコントロール用クラス
class gpio {
private:
//GPIOマッピング用ポインタ
static volatile unsigned int* gpio_control;
static int instance_count;
public:
gpio();
~gpio();
void mode_write(int pin, int mode);
void mode_read(int pin, int* mode);
void data_write(int pin, int data);
void data_read(int pin, int* data);
};
#endif
| 16.02381 | 54 | 0.732541 |
53d19d2e5ac46e190dc814d6c6e9592c5831fbe9 | 1,137 | cpp | C++ | src/query_tatami.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/query_tatami.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | src/query_tatami.cpp | LTLA/diet.scran | c274bf058e10c174a06a409af50fcad225d40f0d | [
"MIT"
] | null | null | null | #include "tatami/tatami.h"
#include "Rcpp.h"
#include "tatamize.h"
//[[Rcpp::export(rng=false)]]
Rcpp::IntegerVector tatami_dim(SEXP x) {
auto ptr = extract_NumericMatrix(x);
return Rcpp::IntegerVector::create(ptr->nrow(), ptr->ncol());
}
//[[Rcpp::export(rng=false)]]
Rcpp::NumericMatrix tatami_rows(SEXP x, Rcpp::IntegerVector rows, int first, int last) {
auto ptr = extract_NumericMatrix(x);
size_t nc = last - first;
Rcpp::NumericMatrix output(nc, rows.size());
double* optr = output.begin();
auto wrk = ptr->new_workspace(true);
for (auto r : rows) {
ptr->row_copy(r, optr, first, last, wrk.get());
}
return Rcpp::transpose(output);
}
//[[Rcpp::export(rng=false)]]
Rcpp::NumericMatrix tatami_columns(SEXP x, Rcpp::IntegerVector columns, int first, int last) {
auto ptr = extract_NumericMatrix(x);
size_t nr = last - first;
Rcpp::NumericMatrix output(nr, columns.size());
double* optr = output.begin();
auto wrk = ptr->new_workspace(false);
for (auto c : columns) {
ptr->column_copy(c, optr, first, last, wrk.get());
}
return output;
}
| 27.071429 | 94 | 0.648197 |
53d3d8fbf496c15a7e0b017d0d78183d4f70afc5 | 1,256 | cpp | C++ | Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | Bit Manipulation/1835. Find XOR Sum of All Pairs Bitwise AND.cpp | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z | /*
We all know the distributive property that (a1+a2)*(b1+b2) = a1*b1 + a1*b2 + a2*b1 + a2*b2
Explanation
Distributive property is similar for AND and XOR here.
(a1^a2) & (b1^b2) = (a1&b1) ^ (a1&b2) ^ (a2&b1) ^ (a2&b2)
(I wasn't aware of this at first either)
另一种思路, 如果所有arr2 中的数 第一个bit 是奇数个(求所有数第一位bit的xor),if arr1[0] 第一个bit 为 1, 那么第一个 bit 可以留下来
如果所有arr2 中的数 第二个bit 是奇数个(求所有数第二位bit的xor),if arr1[0] 第二个bit 为 1, 那么第二个 bit 可以留下来
: : : : : : : : : : : : : : : : : : : :
如果所有arr2 中的数 第n个bit 是奇数个(求所有数第n位bit的xor),if arr1[0] 第n个bit 为 1, 那么第二个 bit 可以留下来
把这n 个 bit 结合到一起(xorb),就是 (arr1[0] & arr2 [0]) ^ (arr1[0] & arr2[1]) ... (arr1[0] & arr2[n2-1])
*/
class Solution {
public:
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int xora = 0, xorb = 0;
for (int& a: arr1)
xora ^= a;
for (int& b: arr2)
xorb ^= b;
return xora & xorb;
}
};
class Solution {
public:
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int xorb = 0;
for (int& b: arr2)
xorb ^= b;
int ret = 0;
for (int& a: arr1)
ret ^= (xorb & a);
return ret;
}
};
| 26.723404 | 104 | 0.514331 |
53d43ebb01cd7590624edbe6e9033bcf44f6d4ad | 291 | cpp | C++ | Graph/DSU.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | 1 | 2021-07-20T06:08:26.000Z | 2021-07-20T06:08:26.000Z | Graph/DSU.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | Graph/DSU.cpp | scortier/DSA-Complete-Sheet | 925a5cb148d9addcb32192fe676be76bfb2915c7 | [
"MIT"
] | null | null | null | #define MAX 20001
int par[MAX], sz[MAX];
void init(int v) {
par[v] = v;
sz[v] = 1;
}
int find(int v) {
return v == par[v] ? v : par[v] = find(par[v]);
}
void join(int u, int v) {
u = find(u), v = find(v);
if(u != v) {
if(sz[u] < sz[v]) swap(u, v);
par[v] = u;
sz[u] += sz[v];
}
} | 17.117647 | 48 | 0.484536 |
53d6db547db42be009f19c81dd2f8ad1d67d5f6a | 1,070 | cpp | C++ | Pm2Service/Pm2Helper.cpp | thebecwar/PM2Service | 594fdc39f734a425ccd61fd6132755f32882afb6 | [
"MIT"
] | null | null | null | Pm2Service/Pm2Helper.cpp | thebecwar/PM2Service | 594fdc39f734a425ccd61fd6132755f32882afb6 | [
"MIT"
] | null | null | null | Pm2Service/Pm2Helper.cpp | thebecwar/PM2Service | 594fdc39f734a425ccd61fd6132755f32882afb6 | [
"MIT"
] | null | null | null | #include "Pm2Helper.h"
#include "Process.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <PathCch.h>
#include <locale>
#include <codecvt>
#include <string>
#include <sstream>
void ConvertNarrowToWide(std::string& narrow, std::wstring& wide)
{
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
wide = converter.from_bytes(narrow);
}
void FindPm2Path(std::wstring& path)
{
std::wstring command(L"node -e \"process.stdout.write(require.resolve('pm2/bin/pm2'))\"");
wchar_t buf[MAX_PATH];
GetModuleFileNameW(NULL, buf, MAX_PATH);
PathCchRemoveFileSpec(buf, MAX_PATH);
std::wstring programPath(buf);
Process proc(command);
proc.SetWorkingDir(programPath);
proc.StartProcess();
std::string pm2path;
proc.ReadStdOut(pm2path);
ConvertNarrowToWide(pm2path, path);
}
void BuildPm2Command(std::wstring& args, std::wstring& target)
{
std::wstring pm2path;
FindPm2Path(pm2path);
std::wstringstream ss;
ss << L"node.exe \"" << pm2path << L"\" " << args;
target = ss.str();
}
| 23.777778 | 94 | 0.692523 |
53d7aa80fd1ff968638b54548a45f3b42086a965 | 517 | cpp | C++ | unittest/tests/JsonTest/source/Application.cpp | Hurleyworks/Ketone | 97c0c730a6e3155154a0ccb87a535e109dfa3c7d | [
"Apache-2.0"
] | 1 | 2021-04-01T01:16:33.000Z | 2021-04-01T01:16:33.000Z | unittest/tests/JsonTest/source/Application.cpp | Hurleyworks/Ketone | 97c0c730a6e3155154a0ccb87a535e109dfa3c7d | [
"Apache-2.0"
] | null | null | null | unittest/tests/JsonTest/source/Application.cpp | Hurleyworks/Ketone | 97c0c730a6e3155154a0ccb87a535e109dfa3c7d | [
"Apache-2.0"
] | null | null | null | #include "Jahley.h"
#include <json.hpp>
const std::string APP_NAME = "JsonTest";
#ifdef CHECK
#undef CHECK
#endif
#define DOCTEST_CONFIG_IMPLEMENT
#include "doctest.h"
using json = nlohmann::json;
class Application : public Jahley::App
{
public:
Application(DesktopWindowSettings settings = DesktopWindowSettings(), bool windowApp = false) :
Jahley::App(settings, windowApp)
{
doctest::Context().run();
}
private:
};
Jahley::App* Jahley::CreateApplication()
{
return new Application();
}
| 14.771429 | 98 | 0.709865 |
53d7f6e0454d6351e2ae3cdadf79ee85ae0b982e | 265 | cpp | C++ | 1480 Running Sum of 1d Array.cpp | akash2099/LeetCode-Problems | 74c346146ca5ba2336d1e8d6dc26e3cd8920cb25 | [
"MIT"
] | 1 | 2021-11-14T01:06:38.000Z | 2021-11-14T01:06:38.000Z | 1480 Running Sum of 1d Array.cpp | akash2099/LeetCode-Problems | 74c346146ca5ba2336d1e8d6dc26e3cd8920cb25 | [
"MIT"
] | null | null | null | 1480 Running Sum of 1d Array.cpp | akash2099/LeetCode-Problems | 74c346146ca5ba2336d1e8d6dc26e3cd8920cb25 | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> runningSum(vector<int>& nums) {
// input: nums array nums = [1,2,3,4]
for(int i=1;i<nums.size();i++){
nums[i]=nums[i-1]+nums[i];
}
return nums;
}
};
| 18.928571 | 47 | 0.441509 |
53d82a58d6860797fcbbc6ec091433cc8d8e9769 | 1,402 | cpp | C++ | FERMIONS/WILSON/LoopMacros.cpp | markmace/OVERLAP | 2d26366aa862cbd36182db8ee3165d9fe4d3e704 | [
"MIT"
] | 1 | 2020-12-13T03:11:03.000Z | 2020-12-13T03:11:03.000Z | FERMIONS/WILSON/LoopMacros.cpp | markmace/OVERLAP | 2d26366aa862cbd36182db8ee3165d9fe4d3e704 | [
"MIT"
] | null | null | null | FERMIONS/WILSON/LoopMacros.cpp | markmace/OVERLAP | 2d26366aa862cbd36182db8ee3165d9fe4d3e704 | [
"MIT"
] | null | null | null | #ifndef __LOOP_MACROS_CPP__
#define __LOOP_MACROS_CPP__
#define START_FERMION_LOOP(gMatrixCoupling) \
\
for(INT i=0;i<Nc;i++){ \
for(INT j=0;j<Nc;j++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0){ \
#define END_FERMION_LOOP \
}\
}\
}\
}\
}
#define START_FERMION_LOOP_2(gMatrixCoupling,gMatrixCoupling2) \
\
for(INT i=0;i<Nc;i++){ \
for(INT j=0;j<Nc;j++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0 || gMatrixCoupling2[alpha][beta]!=0.0){ \
#define END_FERMION_LOOP \
}\
}\
}\
}\
}
#define START_LOCAL_FERMION_LOOP(gMatrixCoupling) \
\
for(INT i=0;i<Nc;i++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0){ \
#define END_LOCAL_FERMION_LOOP \
}\
}\
}\
}
#define START_LOCAL_FERMION_LOOP_2(gMatrixCoupling,gMatrixCoupling2) \
\
for(INT i=0;i<Nc;i++){ \
\
for(INT alpha=0;alpha<DiracAlgebra::SpinorComponents;alpha++){\
for(INT beta=0;beta<DiracAlgebra::SpinorComponents;beta++){ \
\
if(gMatrixCoupling[alpha][beta]!=0.0 || gMatrixCoupling2[alpha][beta]!=0.0){ \
#define END_LOCAL_FERMION_LOOP \
}\
}\
}\
}
#endif | 18.207792 | 78 | 0.702568 |
53dbaa396bff25abf48fc6ac3065b6f56a0bcd80 | 2,156 | cpp | C++ | sources/thelib/src/mediaformats/readers/mp4/atomhdlr.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 3 | 2020-07-30T19:41:00.000Z | 2020-10-28T12:52:37.000Z | sources/thelib/src/mediaformats/readers/mp4/atomhdlr.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | null | null | null | sources/thelib/src/mediaformats/readers/mp4/atomhdlr.cpp | rdkcmf/rdkc-rms | 65ab1efcee9e3de46a888c125f591cd48b815601 | [
"Apache-2.0"
] | 2 | 2020-05-11T03:19:00.000Z | 2021-07-07T17:40:47.000Z | /**
##########################################################################
# If not stated otherwise in this file or this component's LICENSE
# file the following copyright and licenses apply:
#
# Copyright 2019 RDK Management
#
# 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.
##########################################################################
**/
#ifdef HAS_MEDIA_MP4
#include "mediaformats/readers/mp4/atomhdlr.h"
AtomHDLR::AtomHDLR(MP4Document *pDocument, uint32_t type, uint64_t size, uint64_t start)
: VersionedAtom(pDocument, type, size, start) {
_componentType = 0;
_componentSubType = 0;
_componentManufacturer = 0;
_componentFlags = 0;
_componentFlagsMask = 0;
_componentName = "";
}
AtomHDLR::~AtomHDLR() {
}
uint32_t AtomHDLR::GetComponentSubType() {
return _componentSubType;
}
bool AtomHDLR::ReadData() {
if (!ReadUInt32(_componentType)) {
FATAL("Unable to read component type");
return false;
}
if (!ReadUInt32(_componentSubType)) {
FATAL("Unable to read component sub type");
return false;
}
if (!ReadUInt32(_componentManufacturer)) {
FATAL("Unable to read component manufacturer");
return false;
}
if (!ReadUInt32(_componentFlags)) {
FATAL("Unable to read component flags");
return false;
}
if (!ReadUInt32(_componentFlagsMask)) {
FATAL("Unable to read component flags mask");
return false;
}
if (!ReadString(_componentName, _size - 32)) {
FATAL("Unable to read component name");
return false;
}
return true;
}
string AtomHDLR::Hierarchy(uint32_t indent) {
return string(4 * indent, ' ') + GetTypeString() + "(" + U32TOS(_componentSubType) + ")";
}
#endif /* HAS_MEDIA_MP4 */
| 25.975904 | 90 | 0.678571 |
53dbd15883fca8e4fb9012fbe7b16ae78429f8df | 1,255 | cpp | C++ | ansi-c/fix_symbol.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | ansi-c/fix_symbol.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | ansi-c/fix_symbol.cpp | holao09/esbmc | 659c006a45e9aaf8539b12484e2ec2b093cc6f02 | [
"BSD-3-Clause"
] | null | null | null | /*******************************************************************\
Module: ANSI-C Linking
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include "fix_symbol.h"
/*******************************************************************\
Function: fix_symbolt::fix_symbol
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void fix_symbolt::fix_symbol(symbolt &symbol)
{
type_mapt::const_iterator it=
type_map.find(symbol.name);
if(it!=type_map.end())
symbol.name=it->second.id();
replace(symbol.type);
replace(symbol.value);
}
/*******************************************************************\
Function: fix_symbolt::fix_context
Inputs:
Outputs:
Purpose:
\*******************************************************************/
void fix_symbolt::fix_context(contextt &context)
{
for(type_mapt::const_iterator
t_it=type_map.begin();
t_it!=type_map.end();
t_it++)
{
symbolt* symb = context.find_symbol(t_it->first);
assert(symb != nullptr);
symbolt s = *symb;
s.name = t_it->second.identifier();
context.erase_symbol(t_it->first);
context.move(s);
}
}
| 19.920635 | 69 | 0.449402 |
53de116229cda7fec51a86c23c78b472d07a9197 | 1,214 | cc | C++ | src/leaderboard.cc | CS126SP20/final-project-teresa622 | 38b1e943383fe9e71cfffb42460f855444754820 | [
"MIT"
] | null | null | null | src/leaderboard.cc | CS126SP20/final-project-teresa622 | 38b1e943383fe9e71cfffb42460f855444754820 | [
"MIT"
] | null | null | null | src/leaderboard.cc | CS126SP20/final-project-teresa622 | 38b1e943383fe9e71cfffb42460f855444754820 | [
"MIT"
] | null | null | null | //
// Created by Teresa Dong on 4/17/20.
//
#include <string>
#include "mylibrary/leaderboard.h"
#include "mylibrary/player.h"
namespace tetris {
LeaderBoard::LeaderBoard(const std::string& db_path) : db_{db_path} {
db_ << "CREATE TABLE if not exists leaderboard (\n"
" name TEXT NOT NULL,\n"
" score INTEGER NOT NULL\n"
");";
}
void LeaderBoard::AddScoreToLeaderBoard(const Player& player) {
db_ << u"insert into leaderboard (name,score) values (?,?);"
<< player.name
<< player.score;
}
std::vector<Player> GetPlayers(sqlite::database_binder* rows) {
std::vector<Player> players;
for (auto&& row : *rows) {
std::string name;
size_t score;
row >> name >> score;
Player player = {name, score};
players.push_back(player);
}
return players;
}
std::vector<Player> LeaderBoard::RetrieveHighScores(const size_t limit) {
try {
auto rows = db_<< "SELECT name,score FROM "
"leaderboard ORDER BY score DESC LIMIT (?);"
<< limit;
return GetPlayers(&rows);
} catch (const std::exception& e) {
std::cerr << "Query error at retrieve universal high scores";
}
}
} //namespace tetris
| 23.346154 | 73 | 0.623558 |
53de483523e0636452f358b5f0779fb78869303d | 628 | cpp | C++ | LuoguOJ/Luogu 2661.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | 1 | 2018-02-11T09:41:54.000Z | 2018-02-11T09:41:54.000Z | LuoguOJ/Luogu 2661.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | LuoguOJ/Luogu 2661.cpp | tico88612/Solution-Note | 31a9d220fd633c6920760707a07c9a153c2f76cc | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define _ ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
const int MAXN=2e6+10;
int disjoint[MAXN],dis[MAXN]={0},ans=2e6+10;
int getjoint(int s){
if(disjoint[s]!=s){
int last=disjoint[s];
disjoint[s]=getjoint(disjoint[s]);
dis[s]+=dis[last];
}
return disjoint[s];
}
void link(int s,int t){
int x=getjoint(s),y=getjoint(t);
if(x!=y){
disjoint[x]=y;
dis[s]=dis[t]+1;
}
else
ans=min(ans,dis[s]+dis[t]+1);
}
int main(){
int N;
cin>>N;
for(int i=1;i<=N;i++)
disjoint[i]=i;
for(int i=1;i<=N;i++){
int k;
cin>>k;
link(i,k);
}
cout<<ans<<'\n';
return 0;
} | 17.942857 | 57 | 0.600318 |
53debfd17bffc22006b3728f7979ccc1a195d383 | 2,701 | cpp | C++ | graph-source-code/118-E/745508.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/118-E/745508.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/118-E/745508.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <map>
#include <set>
#include <list>
#include <stack>
#include <cmath>
#include <queue>
#include <ctime>
#include <cfloat>
#include <vector>
#include <string>
#include <cstdio>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <iomanip>
#include <sstream>
#include <utility>
#include <iostream>
#include <algorithm>
#define INF 0x3F3F3F3F
#define LINF 0x3F3F3F3FFFFFFFFFLL
#define FILL(X, V) memset( X, V, sizeof(X) )
#define TI(X) __typeof((X).begin())
#define ALL(V) V.begin(), V.end()
#define SIZE(V) int((V).size())
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define RFOR(i, b, a) for(int i = b; i >= a; --i)
#define REP(i, N) for(int i = 0; i < N; ++i)
#define RREP(i, N) for(int i = N-1; i >= 0; --i)
#define FORIT(i, a) for( TI(a) i = a.begin(); i != a.end(); i++ )
#define PB push_back
#define MP make_pair
template<typename T> T inline SQR( const T &a ){ return a*a; }
template<typename T> T inline ABS( const T &a ){ return a < 0 ? -a : a; }
template<typename T> T inline MIN( const T& a, const T& b){ if( a < b ) return a; return b; }
template<typename T> T inline MAX( const T& a, const T& b){ if( a > b ) return a; return b; }
const double EPS = 1e-9;
inline int SGN( double a ){ return ((a > EPS) ? (1) : ((a < -EPS) ? (-1) : (0))); }
inline int CMP( double a, double b ){ return SGN(a - b); }
typedef long long int64;
typedef unsigned long long uint64;
using namespace std;
#define MAXN 100000
vector< vector<int> > gr;
int parent[MAXN], low[MAXN], lbl[MAXN];
int dfsnum, bridges;
void dfs( int u ){
lbl[u] = low[u] = dfsnum++;
for( size_t i = 0, sz = gr[u].size(); i < sz; i++ ){
int v = gr[u][i];
if( lbl[v] == -1 ){
parent[v] = u;
dfs( v );
if( low[u] > low[v] ) low[u] = low[v];
if( low[v] == lbl[v] ) bridges++;
} else if( v != parent[u] ) low[u] = min( low[u], lbl[v] );
}
}
set< pair<int,int> > seen;
void show( int u ){
lbl[u] = 0;
for( size_t i = 0, sz = gr[u].size(); i < sz; i++ ){
int v = gr[u][i];
if( lbl[v] == -1 ){
cout << u+1 << " " << v+1 << "\n";
seen.insert( MP(min(u,v), max(u,v)) );
show( v );
} else if( seen.insert( MP(min(u,v),max(u,v))).second ) cout << u+1 << " " << v+1 << "\n";
}
}
int main( int argc, char* argv[] ){
ios::sync_with_stdio( false );
int n, m, u, v;
cin >> n >> m;
gr.resize(n);
REP( i, n ){ gr[i].clear(); lbl[i] = low[i] = -1; parent[i] = -1; }
REP( i, m ){
cin >> u >> v; u--, v--;
gr[u].PB( v );
gr[v].PB( u );
}
dfsnum = 0, bridges = 0; dfs( 0 );
if( bridges ) cout << "0" << "\n";
else{ REP( i, n ) lbl[i] = -1; show( 0 ); }
return 0;
}
| 20.007407 | 93 | 0.546835 |
53e19c7e9a43f973ed26aea01b09b554f826fbff | 2,162 | hpp | C++ | src/camera.hpp | mvorbrodt/engine | 0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c | [
"0BSD"
] | 3 | 2019-04-25T11:39:13.000Z | 2022-01-30T22:24:08.000Z | src/camera.hpp | mvorbrodt/engine | 0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c | [
"0BSD"
] | null | null | null | src/camera.hpp | mvorbrodt/engine | 0b9c5c1f6d293e98ea8bea3db3bfb67fee84b73c | [
"0BSD"
] | 1 | 2019-11-20T07:58:38.000Z | 2019-11-20T07:58:38.000Z | #pragma once
#include <cassert>
#include "types.hpp"
#include "vector.hpp"
#include "point.hpp"
#include "matrix.hpp"
#include "transforms.hpp"
#define MIN_FOV 10.0f
#define MAX_FOV 90.0f
namespace engine
{
class camera
{
public:
camera(real aspect, real fov = 60.0f, real _near = 1.0f, real _far = 100.0f, const point& origin = ORIGIN, const vector& direction = -UNIT_Z, const vector& up = UNIT_Y)
: m_aspect{ aspect }, m_fov{ fov }, m_near{ _near }, m_far{ _far }, m_origin{ origin }, m_direction{ direction }, m_up{ up }
{
assert(aspect != 0.0f && aspect > 0.0f);
assert(m_fov >= MIN_FOV && m_fov <= MAX_FOV);
assert(m_near >= 1.0f && m_far >= 1.0f && m_near < m_far);
m_direction.normalize();
m_up.normalize();
}
real get_aspect() const { return m_aspect; }
void set_aspect(real aspect) { m_aspect = aspect; }
real get_fov() const { return m_fov; }
void set_fov(real fov)
{
if(fov < MIN_FOV) fov = MIN_FOV;
if(fov > MAX_FOV) fov = MAX_FOV;
m_fov = fov;
}
real get_near() const { return m_near; }
void set_near(real _near)
{
if(_near < 1.0f) _near = 1.0f;
if(_near > m_far) _near = m_far - 1.0f;
m_near = _near;
}
real get_far() const { return m_far; }
void set_far(real _far)
{
if(_far < 1.0f) _far = 1.0f;
if(_far < m_near) _far = m_near + 1.0f;
m_far = _far;
}
void move(real forward, real side)
{
auto v = (m_up ^ m_direction).normal();
m_origin += forward * m_direction + side * v;
}
void turn(real angle)
{
auto m = engine::rotate(angle, m_up);
m_direction *= m;
}
void look(real angle)
{
auto side = (m_up ^ m_direction).normal();
auto m = engine::rotate(angle, side);
m_direction *= m;
}
void roll(real angle)
{
auto m = engine::rotate(angle, m_direction);
m_up *= m;
}
matrix view_matrix() const
{
auto at = m_origin + m_direction;
return look_at(m_origin, at, m_up);
}
matrix projection_matrix()
{
return projection(m_fov, m_aspect, m_near, m_far);
}
private:
real m_aspect;
real m_fov;
real m_near;
real m_far;
point m_origin;
vector m_direction;
vector m_up;
};
}
| 21.405941 | 170 | 0.630897 |
53e2799cb3b28afcb8ae8d1a833700671f0aa9e3 | 1,177 | cc | C++ | debian/modules/ngx_pagespeed/src/ngx_list_iterator.cc | yosefadi/nginx | 38840f728310017aefb1fb9e6ac4531e7ce01921 | [
"BSD-2-Clause"
] | 2 | 2015-05-19T08:13:20.000Z | 2016-01-09T05:42:54.000Z | debian/modules/ngx_pagespeed/src/ngx_list_iterator.cc | yosefadi/nginx | 38840f728310017aefb1fb9e6ac4531e7ce01921 | [
"BSD-2-Clause"
] | null | null | null | debian/modules/ngx_pagespeed/src/ngx_list_iterator.cc | yosefadi/nginx | 38840f728310017aefb1fb9e6ac4531e7ce01921 | [
"BSD-2-Clause"
] | 5 | 2015-01-20T20:20:47.000Z | 2020-05-19T12:01:43.000Z | /*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Author: jefftk@google.com (Jeff Kaufman)
#include "ngx_list_iterator.h"
namespace net_instaweb {
NgxListIterator::NgxListIterator(ngx_list_part_t* part) :
part_(part),
index_within_part_(0) {}
ngx_table_elt_t* NgxListIterator::Next() {
if (index_within_part_ >= part_->nelts) {
if (part_->next == NULL) {
return NULL;
}
part_ = part_->next;
index_within_part_ = 0;
}
ngx_table_elt_t* elts = static_cast<ngx_table_elt_t*>(part_->elts);
return &elts[index_within_part_++]; // Intentional post-increment.
}
} // namespace net_instaweb
| 29.425 | 75 | 0.715378 |
53e769523deb7262b5987220848f596dd26ee00d | 906 | cpp | C++ | BLEConstantCharacteristic.cpp | femtoduino/arduino-BLEPeripheral | eaedd3b9279f09f21e8c8db153af7c76096f754b | [
"MIT"
] | 2 | 2015-05-27T00:37:37.000Z | 2017-01-31T06:41:52.000Z | BLEConstantCharacteristic.cpp | femtoduino/arduino-BLEPeripheral | eaedd3b9279f09f21e8c8db153af7c76096f754b | [
"MIT"
] | null | null | null | BLEConstantCharacteristic.cpp | femtoduino/arduino-BLEPeripheral | eaedd3b9279f09f21e8c8db153af7c76096f754b | [
"MIT"
] | null | null | null | #include "BLEConstantCharacteristic.h"
BLEConstantCharacteristic::BLEConstantCharacteristic(const char* uuid, const unsigned char value[], unsigned char length) :
BLEFixedLengthCharacteristic(uuid, BLERead, (unsigned char)0)
{
this->_valueLength = this->_valueSize = length;
this->_value = (unsigned char*)value;
}
BLEConstantCharacteristic::BLEConstantCharacteristic(const char* uuid, const char* value) :
BLEFixedLengthCharacteristic(uuid, BLERead, (unsigned char)0)
{
this->_valueLength = this->_valueSize = strlen(value);
this->_value = (unsigned char*)value;
}
BLEConstantCharacteristic::~BLEConstantCharacteristic() {
this->_value = NULL; // null so super destructor doesn't try to free
}
bool BLEConstantCharacteristic::setValue(const unsigned char value[], unsigned char length) {
return false;
}
bool BLEConstantCharacteristic::setValue(const char* value) {
return false;
}
| 32.357143 | 123 | 0.770419 |
53e8532ad79bf9a0704c56fe0263f884d7dc31cc | 446 | cpp | C++ | 643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | 643-maximum-average-subarray-i/643-maximum-average-subarray-i.cpp | SouvikChan/-Leetcode_Souvik | cc4b72cb4a14a1c6b8be8bd8390de047443fe008 | [
"MIT"
] | null | null | null | class Solution {
public:
double findMaxAverage(vector<int>& nums, int k) {
int sum=0;
for(int i=0;i<k;i++){
sum+=nums[i];
}
double avg=(double)sum/k;
int i=0, j=k;
while(j<nums.size()){
sum -= nums[i];
sum += nums[j];
double a = (double)sum/k;
avg = max(avg,a);
i++;
j++;
}
return avg;
}
}; | 22.3 | 53 | 0.394619 |
53f20407d36b640aa7b0d498a7d180d06e7ac743 | 1,477 | cpp | C++ | linked-list/merge-sort-doublyLL.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | linked-list/merge-sort-doublyLL.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | linked-list/merge-sort-doublyLL.cpp | Strider-7/code | e096c0d0633b53a07bf3f295cb3bd685b694d4ce | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
struct Node *next, *prev;
};
Node *merge(Node *a, Node *b)
{
// Base cases
if (!a)
return b;
if (!b)
return a;
if (a->data <= b->data)
{
a->next = merge(a->next, b);
a->next->prev = a;
a->prev = NULL;
return a;
}
else
{
b->next = merge(a, b->next);
b->next->prev = b;
b->prev = NULL;
return b;
}
}
pair<Node *, Node *> FrontBackSplit(Node *source)
{
Node *frontRef = nullptr, *backRef = nullptr;
if (source == nullptr || source->next == nullptr)
{
frontRef = source;
backRef = nullptr;
return make_pair(frontRef, backRef);
}
struct Node *slow = source;
struct Node *fast = source->next;
while (fast != NULL)
{
fast = fast->next;
if (fast != NULL)
{
slow = slow->next;
fast = fast->next;
}
}
frontRef = source;
backRef = slow->next;
slow->next = NULL;
return make_pair(frontRef, backRef);
}
struct Node *sortDoubly(struct Node *head)
{
if (!head || !head->next)
return head;
pair<Node *, Node *> P = FrontBackSplit(head);
Node *p = P.first, *q = P.second;
p = sortDoubly(p);
q = sortDoubly(q);
head = merge(p, q);
return head;
} | 19.181818 | 54 | 0.475288 |
53f50c53640f4dc2d832d2b71c9dd5101573236f | 168 | cpp | C++ | vm/mterp/c/OP_DISPATCH_FF.cpp | ThirdProject/android_dalvik | 6a9739380c73a0256f2484f2bcd0b8f908a2db52 | [
"Apache-2.0"
] | null | null | null | vm/mterp/c/OP_DISPATCH_FF.cpp | ThirdProject/android_dalvik | 6a9739380c73a0256f2484f2bcd0b8f908a2db52 | [
"Apache-2.0"
] | null | null | null | vm/mterp/c/OP_DISPATCH_FF.cpp | ThirdProject/android_dalvik | 6a9739380c73a0256f2484f2bcd0b8f908a2db52 | [
"Apache-2.0"
] | null | null | null | HANDLE_OPCODE(OP_DISPATCH_FF)
/*
* Indicates extended opcode. Use next 8 bits to choose where to branch.
*/
DISPATCH_EXTENDED(INST_AA(inst));
OP_END
| 24 | 77 | 0.696429 |
53fa031c22b8eed150594efa271ddde6a8d2a68e | 9,895 | cpp | C++ | src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 13 | 2018-02-09T22:59:39.000Z | 2021-11-29T06:33:22.000Z | src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 17 | 2018-01-26T11:36:07.000Z | 2022-02-03T18:48:43.000Z | src/c++/lib/alignment/matchSelector/BinningFragmentStorage.cpp | Illumina/Isaac4 | 0924fba8b467868da92e1c48323b15d7cbca17dd | [
"BSD-3-Clause"
] | 4 | 2018-10-19T20:00:00.000Z | 2020-10-29T14:44:06.000Z | /**
** Isaac Genome Alignment Software
** Copyright (c) 2010-2017 Illumina, Inc.
** All rights reserved.
**
** This software is provided under the terms and conditions of the
** GNU GENERAL PUBLIC LICENSE Version 3
**
** You should have received a copy of the GNU GENERAL PUBLIC LICENSE Version 3
** along with this program. If not, see
** <https://github.com/illumina/licenses/>.
**
** \file BinningFragmentStorage.cpp
**
** \author Roman Petrovski
**/
#include <cerrno>
#include <fstream>
#include "common/Debug.hh"
#include "common/Exceptions.hh"
#include "alignment/BinMetadata.hh"
#include "alignment/matchSelector/BinningFragmentStorage.hh"
namespace isaac
{
namespace alignment
{
namespace matchSelector
{
/**
* \brief creates bin data files at regular genomic intervals.
*
* \param contigsPerBinMax maximum number of different contigs to be associated with the
* same data file path
*/
static boost::filesystem::path makeDataFilePath(
std::size_t genomicOffset,
const uint64_t targetBinLength,
unsigned binIndex,
const reference::ReferencePosition& binStartPos,
const unsigned contigsPerBinMax,
const reference::SortedReferenceMetadata::Contigs& contigs,
const bfs::path& binDirectory,
unsigned &lastBinLastContig,
uint64_t& lastBinRoundedGenomicOffset,
unsigned & lastBinContigs,
uint64_t& lastFileNameGenomicOffset)
{
reference::ReferencePosition fileNameReferencePosition;
uint64_t roundedGenomicOffset = (genomicOffset / targetBinLength) * targetBinLength;
uint64_t fileNameGenomicOffset = roundedGenomicOffset;
if (binIndex && lastBinRoundedGenomicOffset == roundedGenomicOffset)
{
if (lastBinLastContig != binStartPos.getContigId())
{
++lastBinContigs;
}
if (contigsPerBinMax < lastBinContigs)
{
fileNameGenomicOffset = genomicOffset;
lastFileNameGenomicOffset = genomicOffset;
lastBinContigs = 0;
}
else
{
fileNameGenomicOffset = lastFileNameGenomicOffset;
}
}
else
{
lastBinRoundedGenomicOffset = roundedGenomicOffset;
lastFileNameGenomicOffset = fileNameGenomicOffset;
lastBinContigs = 0;
}
lastBinLastContig = binIndex ? binStartPos.getContigId() : 0;
fileNameReferencePosition = reference::genomicOffsetToPosition(fileNameGenomicOffset, contigs);
// ISAAC_THREAD_CERR << "roundedGenomicOffset:" << roundedGenomicOffset << std::endl;
// ISAAC_THREAD_CERR << "fileNameReferencePosition:" << fileNameReferencePosition << std::endl;
boost::filesystem::path binPath =
// Pad file names well, so that we don't have to worry about them becoming of different length.
// This is important for memory reservation to be stable
binDirectory / (boost::format("bin-%08d-%09d.dat")
% (binIndex ? (fileNameReferencePosition.getContigId() + 1) : 0)
% (binIndex ? fileNameReferencePosition.getPosition() : 0)).str();
return binPath;
}
static void buildBinPathList(
const alignment::matchSelector::BinIndexMap &binIndexMap,
const bfs::path &binDirectory,
const flowcell::BarcodeMetadataList &barcodeMetadataList,
const reference::SortedReferenceMetadata::Contigs &contigs,
const uint64_t targetBinLength,
alignment::BinMetadataList &ret)
{
ISAAC_TRACE_STAT("before buildBinPathList");
ISAAC_ASSERT_MSG(!binIndexMap.empty(), "Empty binIndexMap is illegal");
ISAAC_ASSERT_MSG(!binIndexMap.back().empty(), "Empty binIndexMap entry is illegal" << binIndexMap);
reference::SortedReferenceMetadata::Contigs offsetOderedContigs = contigs;
std::sort(offsetOderedContigs.begin(), offsetOderedContigs.end(),
[](const reference::SortedReferenceMetadata::Contig &left,
const reference::SortedReferenceMetadata::Contig &right)
{return left.genomicPosition_ < right.genomicPosition_;});
std::size_t genomicOffset = 0;
static const unsigned CONTIGS_PER_BIN_MAX = 16;
unsigned lastBinContigs = 0;
unsigned lastBinLastContig = -1;
uint64_t lastBinRoundedGenomicOffset = uint64_t(0) - 1;
uint64_t lastFileNameGenomicOffset = uint64_t(0) - 1;
BOOST_FOREACH(const std::vector<unsigned> &contigBins, binIndexMap)
{
ISAAC_ASSERT_MSG(!contigBins.empty(), "Unexpected empty contigBins");
// this offset goes in bin length increments. They don't sum up to the real contig length
std::size_t binGenomicOffset = genomicOffset;
for (unsigned i = contigBins.front(); contigBins.back() >= i; ++i)
{
const reference::ReferencePosition binStartPos = binIndexMap.getBinFirstPos(i);
// binIndexMap contig 0 is unaligned bin
ISAAC_ASSERT_MSG(!i || binIndexMap.getBinIndex(binStartPos) == i, "BinIndexMap is broken");
const boost::filesystem::path binPath =
makeDataFilePath(
binGenomicOffset, targetBinLength, i, binStartPos,
CONTIGS_PER_BIN_MAX, offsetOderedContigs, binDirectory,
lastBinLastContig, lastBinRoundedGenomicOffset,
lastBinContigs, lastFileNameGenomicOffset);
const uint64_t binLength = i ? binIndexMap.getBinFirstInvalidPos(i) - binStartPos : 0;
ret.push_back(
alignment::BinMetadata(barcodeMetadataList.size(), ret.size(), binStartPos, binLength, binPath));
// ISAAC_THREAD_CERR << "binPathList.back():" << binPathList.back() << std::endl;
binGenomicOffset += binLength;
}
// ISAAC_THREAD_CERR << "contigBins.front():" << contigBins.front() << std::endl;
if (!ret.back().isUnalignedBin())
{
genomicOffset += contigs.at(ret.back().getBinStart().getContigId()).totalBases_;
}
}
}
BinningFragmentStorage::BinningFragmentStorage(
const boost::filesystem::path &tempDirectory,
const bool keepUnaligned,
const BinIndexMap &binIndexMap,
const reference::SortedReferenceMetadata::Contigs& contigs,
const flowcell::BarcodeMetadataList &barcodeMetadataList,
const bool preAllocateBins,
const uint64_t expectedBinSize,
const uint64_t targetBinLength,
const unsigned threads,
alignment::BinMetadataList &binMetadataList):
FragmentBinner(keepUnaligned, binIndexMap, preAllocateBins ? expectedBinSize : 0, threads),
binIndexMap_(binIndexMap),
expectedBinSize_(expectedBinSize),
binMetadataList_(binMetadataList)
{
buildBinPathList(
binIndexMap, tempDirectory, barcodeMetadataList, contigs, targetBinLength, binMetadataList_);
const std::size_t worstCaseEstimatedUnalignedBins =
// This assumes that none of the data will align and we will need to
// make as many unaligned bins as we expect the aligned ones to be there
// This is both bad and weak. Bad because we allocate pile of memory
// that will never be used with proper aligning data.
// Weak because if in fact nothing will align, we might need more unaligned bins than we expect.
// Keeping this here because we're talking about a few thousands relatively small structures,
// so pile is not large enough to worry about, and the reallocation will occur while no other threads
// are using the list, so it should not invalidate any references.
binMetadataList_.size() * binIndexMap.getBinLength() / targetBinLength +
// in case the above math returns 0, we'll have room for at least one unaligned bin
1;
binMetadataList_.reserve(binMetadataList_.size() + worstCaseEstimatedUnalignedBins);
unalignedBinMetadataReserve_.resize(worstCaseEstimatedUnalignedBins, binMetadataList_.back());
FragmentBinner::open(binMetadataList_.begin(), binMetadataList_.end());
}
BinningFragmentStorage::~BinningFragmentStorage()
{
}
void BinningFragmentStorage::store(
const BamTemplate &bamTemplate,
const unsigned barcodeIdx,
const unsigned threadNumber)
{
common::StaticVector<char, READS_MAX * (sizeof(io::FragmentHeader) + FRAGMENT_BYTES_MAX)> buffer;
if (2 == bamTemplate.getFragmentCount())
{
packPairedFragment(bamTemplate, 0, barcodeIdx, binIndexMap_, std::back_inserter(buffer));
const io::FragmentAccessor &fragment0 = reinterpret_cast<const io::FragmentAccessor&>(buffer.front());
packPairedFragment(bamTemplate, 1, barcodeIdx, binIndexMap_, std::back_inserter(buffer));
const io::FragmentAccessor &fragment1 = *reinterpret_cast<const io::FragmentAccessor*>(&buffer.front() + fragment0.getTotalLength());
storePaired(fragment0, fragment1, binMetadataList_, threadNumber);
}
else
{
packSingleFragment(bamTemplate, barcodeIdx, std::back_inserter(buffer));
const io::FragmentAccessor &fragment = reinterpret_cast<const io::FragmentAccessor&>(buffer.front());
storeSingle(fragment, binMetadataList_, threadNumber);
}
}
void BinningFragmentStorage::prepareFlush() noexcept
{
if (binMetadataList_.front().getDataSize() > expectedBinSize_)
{
ISAAC_ASSERT_MSG(!unalignedBinMetadataReserve_.empty(), "Unexpectedly ran out of reserved BinMetadata when extending the unaligned bin");
// does not cause memory allocation because of reserve in constructor
binMetadataList_.resize(binMetadataList_.size() + 1);
using std::swap;
swap(binMetadataList_.back(), unalignedBinMetadataReserve_.back());
unalignedBinMetadataReserve_.pop_back();
binMetadataList_.back() = binMetadataList_.front();
binMetadataList_.front().startNew();
}
}
} //namespace matchSelector
} // namespace alignment
} // namespace isaac
| 41.57563 | 145 | 0.703183 |
53fb4768f41b00844adfb9ec51edd9b7f4b37bdf | 3,036 | hpp | C++ | src/OpenAnalysis/CallGraph/ManagerCallGraph.hpp | sriharikrishna/OpenAnalysis | 0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc | [
"BSD-3-Clause"
] | null | null | null | src/OpenAnalysis/CallGraph/ManagerCallGraph.hpp | sriharikrishna/OpenAnalysis | 0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc | [
"BSD-3-Clause"
] | null | null | null | src/OpenAnalysis/CallGraph/ManagerCallGraph.hpp | sriharikrishna/OpenAnalysis | 0d0c3819bd091cc0c83db5555cc20bfbc07ecbdc | [
"BSD-3-Clause"
] | null | null | null | /*! \file
\brief Declarations of the AnnotationManager that generates a CallGraphStandard.
\authors Arun Chauhan (2001 as part of Mint), Nathan Tallent, Michelle Strout, Priyadarshini Malusare
\version $Id: ManagerCallGraphStandard.hpp,v 1.6 2004/11/19 19:21:50 mstrout Exp $
Copyright (c) 2002-2005, Rice University <br>
Copyright (c) 2004-2005, University of Chicago <br>
Copyright (c) 2006, Contributors <br>
All rights reserved. <br>
See ../../../Copyright.txt for details. <br>
*/
/*!
#ifndef CallGraphMANAGERSTANDARD_H
#define CallGraphMANAGERSTANDARD_H
*/
#ifndef ManagerCallGraph_H
#define ManagerCallGraph_H
//--------------------------------------------------------------------
// standard headers
#ifdef NO_STD_CHEADERS
# include <string.h>
#else
# include <cstring>
#endif
// STL headers
#include <list>
#include <set>
#include <map>
// OpenAnalysis headers
#include <OpenAnalysis/Utils/OA_ptr.hpp>
#include <OpenAnalysis/Utils/Util.hpp>
#include <OpenAnalysis/Location/Locations.hpp>
#include <OpenAnalysis/CallGraph/CallGraph.hpp>
#include <OpenAnalysis/Alias/InterAliasInterface.hpp>
#include <OpenAnalysis/IRInterface/CallGraphIRInterface.hpp>
namespace OA {
namespace CallGraph {
//--------------------------------------------------------------------
/*!
The AnnotationManager for a CallGraphStandard Annotation. Knows how to
build a CallGraphStandard, read one in from a file, and write one out to a file.
*/
class ManagerCallGraphStandard { //??? eventually public OA::AnnotationManager
public:
ManagerCallGraphStandard(OA_ptr<CallGraphIRInterface> _ir);
virtual ~ManagerCallGraphStandard () {}
//??? don't think this guy need AQM, but will eventually have
//to have one so is standard with other AnnotationManagers
//what type of handle are we going to attach the CallGraph to?
virtual OA_ptr<CallGraph>
performAnalysis(OA_ptr<IRProcIterator> procIter,
OA_ptr<Alias::InterAliasInterface> interAlias );
//-------------------------------------
// information access
//-------------------------------------
OA_ptr<CallGraphIRInterface> getIRInterface() { return mIR; }
//------------------------------------------------------------------
// Exceptions
//------------------------------------------------------------------
/*! COMMENTED OUT BY plm 08/18/06
class CallGraphException : public Exception {
public:
void report (std::ostream& os) const { os << "E! Unexpected." << std::endl; }
};
*/
private:
//------------------------------------------------------------------
// Methods that build CallGraphStandard
//------------------------------------------------------------------
void build_graph(OA_ptr<IRProcIterator> funcIter);
private:
OA_ptr<CallGraphIRInterface> mIR;
OA_ptr<CallGraph> mCallGraph;
OA_ptr<Alias::InterAliasInterface> mInterAlias;
};
//--------------------------------------------------------------------
} // end of CallGraph namespace
} // end of OA namespace
#endif
| 30.979592 | 103 | 0.600132 |
53fc218fdcd65dc427360ddb202a4d1c73c959e3 | 3,611 | cpp | C++ | geometry/src/capsule.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 10 | 2016-06-01T12:54:45.000Z | 2021-09-07T17:34:37.000Z | geometry/src/capsule.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | null | null | null | geometry/src/capsule.cpp | Ludophonic/JigLib | 541ec63b345ccf01e58cce49eb2f73c21eaf6aa6 | [
"Zlib"
] | 4 | 2017-05-03T14:03:03.000Z | 2021-01-04T04:31:15.000Z | //==============================================================
// Copyright (C) 2004 Danny Chapman
// danny@rowlhouse.freeserve.co.uk
//--------------------------------------------------------------
//
/// @file capsule.cpp
//
//==============================================================
#include "capsule.hpp"
#include "intersection.hpp"
using namespace JigLib;
//==============================================================
// Clone
//==============================================================
tPrimitive* tCapsule::Clone() const
{
return new tCapsule(*this);
}
//==============================================================
// SegmentIntersect
//==============================================================
bool tCapsule::SegmentIntersect(tScalar &frac, tVector3 &pos, tVector3 &normal, const class tSegment &seg) const
{
bool result;
if (result = SegmentCapsuleIntersection(&frac, seg, *this))
{
pos = seg.GetPoint(frac);
normal = pos - mTransform.position;
normal -= Dot(normal, mTransform.orientation.GetLook()) * mTransform.orientation.GetLook();
normal.NormaliseSafe();
}
return result;
}
//==============================================================
// GetMassProperties
//==============================================================
void tCapsule::GetMassProperties(const tPrimitiveProperties &primitiveProperties,
tScalar &mass,
tVector3 ¢erOfMass,
tMatrix33 &inertiaTensor) const
{
if (primitiveProperties.mMassType == tPrimitiveProperties::MASS)
{
mass = primitiveProperties.mMassOrDensity;
}
else
{
if (primitiveProperties.mMassDistribution == tPrimitiveProperties::SOLID)
mass = GetVolume() * primitiveProperties.mMassOrDensity;
else
mass = GetSurfaceArea() * primitiveProperties.mMassOrDensity;
}
centerOfMass = GetPos() + 0.5f * GetLength() * GetOrient().GetLook();
/// todo check solid/shell
// first cylinder
tScalar cylinderMass = mass * PI * Sq(mRadius) * mLength / GetVolume();
tScalar Ixx = 0.5f * cylinderMass * Sq(mRadius);
tScalar Iyy = 0.25f * cylinderMass * Sq(mRadius) + (1.0f / 12.0f) * cylinderMass * Sq(mLength);
tScalar Izz = Iyy;
// add ends
tScalar endMass = mass - cylinderMass;
Ixx += 0.2f * endMass * Sq(mRadius);
Iyy += 0.4f * endMass * Sq(mRadius) + endMass * Sq(0.5f * mLength);
Izz += 0.4f * endMass * Sq(mRadius) + endMass * Sq(0.5f * mLength);
inertiaTensor.Set(Ixx, 0.0f, 0.0f,
0.0f, Iyy, 0.0f,
0.0f, 0.0f, Izz);
// transform - e.g. see p664 of Physics-Based Animation
// todo is the order correct here? Does it matter?
// Calculate the tensor in a frame at the CoM, but aligned with the world axes
inertiaTensor = mTransform.orientation * inertiaTensor * mTransform.orientation.GetTranspose();
// Transfer of axe theorem
inertiaTensor(0, 0) = inertiaTensor(0, 0) + mass * (Sq(centerOfMass.y) + Sq(centerOfMass.z));
inertiaTensor(1, 1) = inertiaTensor(1, 1) + mass * (Sq(centerOfMass.z) + Sq(centerOfMass.x));
inertiaTensor(2, 2) = inertiaTensor(2, 2) + mass * (Sq(centerOfMass.x) + Sq(centerOfMass.y));
inertiaTensor(0, 1) = inertiaTensor(1, 0) = inertiaTensor(0, 1) - mass * centerOfMass.x * centerOfMass.y;
inertiaTensor(1, 2) = inertiaTensor(2, 1) = inertiaTensor(1, 2) - mass * centerOfMass.y * centerOfMass.z;
inertiaTensor(2, 0) = inertiaTensor(0, 2) = inertiaTensor(2, 0) - mass * centerOfMass.z * centerOfMass.x;
}
| 39.681319 | 112 | 0.546109 |
53fdbadfaa6215e4b01d0233392fe1f15fd914eb | 244 | cpp | C++ | lib/cards/expansion_card.cpp | BioBoost/home_automator | acc77023003110bc18f376c5305dd26912b26a9a | [
"MIT"
] | null | null | null | lib/cards/expansion_card.cpp | BioBoost/home_automator | acc77023003110bc18f376c5305dd26912b26a9a | [
"MIT"
] | 14 | 2018-08-19T09:03:06.000Z | 2018-09-22T21:08:36.000Z | lib/cards/expansion_card.cpp | BioBoost/home_automator | acc77023003110bc18f376c5305dd26912b26a9a | [
"MIT"
] | null | null | null | #include "expansion_card.h"
namespace BiosHomeAutomator {
ExpansionCard::ExpansionCard(unsigned int id) {
this->id = id;
}
ExpansionCard::~ExpansionCard(void) { }
unsigned int ExpansionCard::get_id(void) {
return id;
}
}; | 16.266667 | 49 | 0.684426 |
d87cc8d47fa687a1a4fa586a5d626144557df6fb | 850 | hpp | C++ | poet/detail/utility.hpp | fmhess/libpoet | ca6a168a772a1452ac39745a851ba390e86fad30 | [
"BSL-1.0"
] | 1 | 2017-04-03T11:53:20.000Z | 2017-04-03T11:53:20.000Z | poet/detail/utility.hpp | fmhess/libpoet | ca6a168a772a1452ac39745a851ba390e86fad30 | [
"BSL-1.0"
] | null | null | null | poet/detail/utility.hpp | fmhess/libpoet | ca6a168a772a1452ac39745a851ba390e86fad30 | [
"BSL-1.0"
] | null | null | null | // copyright (c) Frank Mori Hess <fmhess@users.sourceforge.net> 2008-04-13
// 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 _POET_DETAIL_UTILITY_HPP
#define _POET_DETAIL_UTILITY_HPP
#include <boost/weak_ptr.hpp>
namespace poet
{
namespace detail
{
// deadlock-free locking of a pair of locks with arbitrary locking order
template<typename LockT, typename LockU>
void lock_pair(LockT &a, LockU &b)
{
while(true)
{
a.lock();
if(b.try_lock()) return;
a.unlock();
b.lock();
if(a.try_lock()) return;
b.unlock();
}
}
template<typename T>
boost::weak_ptr<T> make_weak(const boost::shared_ptr<T> &sp)
{
return boost::weak_ptr<T>(sp);
}
}
}
#endif // _POET_DETAIL_UTILITY_HPP
| 21.25 | 75 | 0.685882 |
d886b626bba54bf7c1acdaf6800e7e362c9ca320 | 1,378 | hpp | C++ | GLSL-Pipeline/Toolkits/include/System/Func.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Func.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | GLSL-Pipeline/Toolkits/include/System/Func.hpp | GilFerraz/GLSL-Pipeline | d2fd965a4324e85b6144682f8104c306034057d6 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "DLL.hpp"
#include <functional>
namespace System
{
/**
* \brief Encapsulates a method that has specified parameters and returns a value of the type specified by the TResult
* parameter. Unlike in other .NET languages, the first paramenter correspondes to TResult.
* \tparam TResult The type of the return value of the method that this delegate encapsulates.
* \tparam Args The parameters of the method that this delegate encapsulates.
*/
template<typename TResult, typename ...Args>
class DLLExport Func final
{
public:
typedef std::function<TResult(Args...)> FuncType;
Func(FuncType func);
~Func();
#pragma region Public Instance Methods
TResult Invoke(Args&&... args);
#pragma endregion
private:
FuncType func;
};
template <typename TResult, typename ... Args>
Func<TResult, Args...>::Func(FuncType func)
{
this->func = func;
}
template <typename TResult, typename ... Args>
Func<TResult, Args...>::~Func()
{
}
#pragma region Public Instance Methods
template <typename TResult, typename ... Args>
TResult Func<TResult, Args...>::Invoke(Args&&... args)
{
if (&func != nullptr)
{
return func(args...);
}
return nullptr;
}
#pragma endregion
}
| 23.758621 | 122 | 0.624819 |
d88756cddfe30e47e7f80e2cfebaaa7174008521 | 493 | cc | C++ | endo/module_wrap.cc | Qard/endo | 6e3241b12e58344524711d4db4ed44d115fa8175 | [
"MIT"
] | null | null | null | endo/module_wrap.cc | Qard/endo | 6e3241b12e58344524711d4db4ed44d115fa8175 | [
"MIT"
] | null | null | null | endo/module_wrap.cc | Qard/endo | 6e3241b12e58344524711d4db4ed44d115fa8175 | [
"MIT"
] | null | null | null | #include "module_wrap.h"
namespace endo {
ModuleWrap::ModuleWrap(Isolate* isolate, Local<Module> module, Local<String> url)
: module_(isolate, module),
url_(isolate, url) {};
bool ModuleWrap::operator==(Local<Module>& mod) {
return module_.Get(Isolate::GetCurrent())->GetIdentityHash() == mod->GetIdentityHash();
}
Local<Module> ModuleWrap::module() {
return module_.Get(Isolate::GetCurrent());
}
Local<String> ModuleWrap::url() {
return url_.Get(Isolate::GetCurrent());
}
}
| 22.409091 | 89 | 0.703854 |
d88790b0562948b7fa957ebf6c42c2c0eea6b303 | 2,542 | cp | C++ | Sources_Common/Application/Preferences/CSearchStyle.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 12 | 2015-04-21T16:10:43.000Z | 2021-11-05T13:41:46.000Z | Sources_Common/Application/Preferences/CSearchStyle.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2015-11-02T13:32:11.000Z | 2019-07-10T21:11:21.000Z | Sources_Common/Application/Preferences/CSearchStyle.cp | mulberry-mail/mulberry4-client | cdaae15c51dd759110b4fbdb2063d0e3d5202103 | [
"ECL-2.0",
"Apache-2.0"
] | 6 | 2015-01-12T08:49:12.000Z | 2021-03-27T09:11:10.000Z | /*
Copyright (c) 2007 Cyrus Daboo. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Search style data object
// Stores hierarchical search criteria that can be saved in prefs or applied as filter
#include "CSearchStyle.h"
#include "char_stream.h"
#pragma mark ____________________________CSearchStyle
extern const char* cSpace;
// Copy construct
CSearchStyle::CSearchStyle(const CSearchStyle& copy)
{
mItem = nil;
_copy(copy);
}
// Assignment with same type
CSearchStyle& CSearchStyle::operator=(const CSearchStyle& copy)
{
if (this != ©)
{
_tidy();
_copy(copy);
}
return *this;
}
// Compare with same type
int CSearchStyle::operator==(const CSearchStyle& other) const
{
// Just compare names
return mName == other.mName;
}
void CSearchStyle::_copy(const CSearchStyle& copy)
{
mName = copy.mName;
mItem = new CSearchItem(*copy.mItem);
}
// Parse S-Expression element
bool CSearchStyle::SetInfo(char_stream& txt, NumVersion vers_prefs)
{
bool result = true;
txt.get(mName, true);
mItem = new CSearchItem;
mItem->SetInfo(txt);
return result;
}
// Create S_Expression element
cdstring CSearchStyle::GetInfo(void) const
{
cdstring all;
cdstring temp = mName;
temp.quote();
temp.ConvertFromOS();
all += temp;
all += cSpace;
all += mItem->GetInfo();
return all;
}
#pragma mark ____________________________CSearchStyleList
// Find named style
const CSearchStyle* CSearchStyleList::FindStyle(const cdstring& name) const
{
CSearchStyle temp(name);
CSearchStyleList::const_iterator found = begin();
for(; found != end(); found++)
{
if (**found == temp)
break;
}
if (found != end())
return *found;
else
return nil;
}
// Find index of named style
long CSearchStyleList::FindIndexOf(const cdstring& name) const
{
CSearchStyle temp(name);
CSearchStyleList::const_iterator found = begin();
for(; found != end(); found++)
{
if (**found == temp)
break;
}
if (found != end())
return found - begin();
else
return -1;
}
| 20.336 | 86 | 0.709284 |
d88b09f7941ed97b33f164ff59b9cd7a0be36365 | 606 | hpp | C++ | Helios/src/Game.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | Helios/src/Game.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | Helios/src/Game.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <SDL.h>
#include <memory>
#include "Texture.hpp"
#include "Sprite.hpp"
#include "Clock.hpp"
#include "Input.hpp"
#include "Event.hpp"
#include "SceneStateMachine.hpp"
#include "scenes/SceneSplashScreen.hpp"
#include "scenes/SceneGame.hpp"
namespace Helio
{
class Game
{
private:
Event event;
Clock clock;
double deltaTime;
SceneStateMachine sceneStateMachine;
public:
Game();
void CaptureEvent();
//void CaptureInput();
void ProcessInput();
void Update();
void LateUpdate();
void Draw();
void CalculateDeltaTime();
bool IsRunning();
~Game();
};
} | 15.947368 | 39 | 0.70132 |
d88f5accbe4168ea1013c8b0dca216ac0573e7fd | 29,740 | hpp | C++ | include/CameraModels/CameraModelUtils.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | 34 | 2016-11-13T22:17:50.000Z | 2021-01-20T19:59:25.000Z | include/CameraModels/CameraModelUtils.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | null | null | null | include/CameraModels/CameraModelUtils.hpp | lukier/camera_models | 90196141fa4749148b6a7b0adc7af19cb1971039 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T00:45:56.000Z | 2019-04-02T11:56:50.000Z | /**
* ****************************************************************************
* Copyright (c) 2015, Robert Lukierski.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ****************************************************************************
* Common types and functions.
* ****************************************************************************
*/
#ifndef CAMERA_MODEL_UTILS_HPP
#define CAMERA_MODEL_UTILS_HPP
#include <Eigen/Core>
#include <Eigen/Dense>
#include <Eigen/Geometry>
#include <unsupported/Eigen/AutoDiff>
#include <sophus/so2.hpp>
#include <sophus/se2.hpp>
#include <sophus/so3.hpp>
#include <sophus/se3.hpp>
// For future Eigen + CUDA
#ifndef EIGEN_DEVICE_FUNC
#define EIGEN_DEVICE_FUNC
#endif // EIGEN_DEVICE_FUNC
// If Cereal serializer is preferred
#ifdef CAMERA_MODELS_SERIALIZER_CEREAL
#define CAMERA_MODELS_HAVE_SERIALIZER
#define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE(cereal::make_nvp(NAME,VAR))
#endif // CAMERA_MODELS_SERIALIZER_CEREAL
// If Boost serializer is preferred
#ifdef CAMERA_MODELS_SERIALIZER_BOOST
#define CAMERA_MODELS_HAVE_SERIALIZER
#define CAMERA_MODELS_SERIALIZE(ARCHIVE,NAME,VAR) ARCHIVE & boost::serialization::make_nvp(NAME,VAR)
#endif // CAMERA_MODELS_SERIALIZER_BOOST
#ifndef VISIONCORE_EIGEN_MISSING_BITS_HPP
#define VISIONCORE_EIGEN_MISSING_BITS_HPP
namespace Eigen
{
namespace numext
{
template<typename T>
EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
T atan2(const T& y, const T &x) {
EIGEN_USING_STD_MATH(atan2);
return atan2(y,x);
}
#ifdef __CUDACC__
template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
float atan2(const float& y, const float &x) { return ::atan2f(y,x); }
template<> EIGEN_DEVICE_FUNC EIGEN_ALWAYS_INLINE
double atan2(const double& y, const double &x) { return ::atan2(y,x); }
#endif
}
template<typename DerType>
inline const Eigen::AutoDiffScalar<EIGEN_EXPR_BINARYOP_SCALAR_RETURN_TYPE(typename Eigen::internal::remove_all<DerType>::type, typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar, product)>
atan(const Eigen::AutoDiffScalar<DerType>& x)
{
using namespace Eigen;
EIGEN_UNUSED typedef typename Eigen::internal::traits<typename Eigen::internal::remove_all<DerType>::type>::Scalar Scalar;
using numext::atan;
return Eigen::MakeAutoDiffScalar(atan(x.value()),x.derivatives() * ( Scalar(1) / (Scalar(1) + x.value() * x.value()) ));
}
}
#endif // VISIONCORE_EIGEN_MISSING_BITS_HPP
namespace cammod
{
/**
* Camera Models
*/
enum class CameraModelType
{
PinholeDistance = 0,
PinholeDistanceDistorted,
PinholeDisparity,
PinholeDisparityDistorted,
Generic,
GenericDistorted,
Spherical,
SphericalPovRay,
Fisheye,
FisheyeDistorted,
PinholeDisparityBrownConrady
};
template<CameraModelType cmt>
struct CameraModelToTypeAndName;
/**
* Collection of common 2D/3D types.
*/
template<typename T>
struct ComplexTypes
{
typedef Sophus::SO3<T> RotationT;
typedef Sophus::SE3<T> TransformT;
typedef Eigen::Map<TransformT> TransformMapT;
typedef Eigen::Map<const TransformT> ConstTransformMapT;
typedef Eigen::Map<RotationT> RotationMapT;
typedef Eigen::Map<const RotationT> ConstRotationMapT;
typedef Sophus::SO2<T> Rotation2DT;
typedef Sophus::SE2<T> Transform2DT;
typedef Eigen::Map<Transform2DT> Transform2DMapT;
typedef Eigen::Map<const Transform2DT> ConstTransform2DMapT;
typedef Eigen::Map<Rotation2DT> Rotation2DMapT;
typedef Eigen::Map<const Rotation2DT> ConstRotation2DMapT;
typedef typename Sophus::SE3<T>::Tangent TangentTransformT;
typedef Eigen::Map<typename Sophus::SE3<T>::Tangent> TangentTransformMapT;
typedef Eigen::Map<const typename Sophus::SE3<T>::Tangent> ConstTangentTransformMapT;
typedef typename Sophus::SE2<T>::Tangent TangentTransform2DT;
typedef Eigen::Map<typename Sophus::SE2<T>::Tangent> TangentTransform2DMapT;
typedef Eigen::Map<const typename Sophus::SE2<T>::Tangent> ConstTangentTransform2DMapT;
typedef typename Sophus::SO3<T>::Tangent TangentRotationT;
typedef Eigen::Map<typename Sophus::SO3<T>::Tangent> TangentRotationMapT;
typedef Eigen::Map<const typename Sophus::SO3<T>::Tangent> ConstTangentRotationMapT;
typedef typename Sophus::SO2<T>::Tangent TangentRotation2DT;
typedef Eigen::Map<typename Sophus::SO2<T>::Tangent> TangentRotation2DMapT;
typedef Eigen::Map<const typename Sophus::SO2<T>::Tangent> ConstTangentRotation2DMapT;
typedef Eigen::Matrix<T,2,1> PixelT;
typedef Eigen::Map<PixelT> PixelMapT;
typedef Eigen::Map<const PixelT> ConstPixelMapT;
typedef typename TransformT::Point PointT;
typedef Eigen::Map<PointT> PointMapT;
typedef Eigen::Map<const PointT> ConstPointMapT;
typedef typename Transform2DT::Point Point2DT;
typedef Eigen::Map<Point2DT> Point2DMapT;
typedef Eigen::Map<const Point2DT> ConstPoint2DMapT;
typedef Eigen::Quaternion<T> QuaternionT;
typedef Eigen::Map<QuaternionT> QuaternionMapT;
typedef Eigen::Map<const QuaternionT> ConstQuaternionMapT;
typedef Eigen::Matrix<T,2,3> ForwardPointJacobianT;
typedef Eigen::Map<ForwardPointJacobianT> ForwardPointJacobianMapT;
typedef Eigen::Map<const ForwardPointJacobianT> ConstForwardPointJacobianMapT;
typedef Eigen::Matrix<T,3,2> InversePointJacobianT;
typedef Eigen::Map<InversePointJacobianT> InversePointJacobianMapT;
typedef Eigen::Map<const InversePointJacobianT> ConstInversePointJacobianMapT;
typedef Eigen::Matrix<T,2,2> DistortionJacobianT;
typedef Eigen::Map<DistortionJacobianT> DistortionJacobianMapT;
typedef Eigen::Map<const DistortionJacobianT> ConstDistortionJacobianMapT;
template<int ParametersToOptimize>
using ForwardParametersJacobianT = Eigen::Matrix<T,2,ParametersToOptimize>;
template<int ParametersToOptimize>
using ForwardParametersJacobianMapT = Eigen::Map<ForwardParametersJacobianT<ParametersToOptimize>>;
template<int ParametersToOptimize>
using ConstForwardParametersJacobianMapT = Eigen::Map<const ForwardParametersJacobianT<ParametersToOptimize>>;
};
template<typename T>
EIGEN_DEVICE_FUNC static inline T getFieldOfView(T focal, T width)
{
using Eigen::numext::atan;
return T(2.0) * atan(width / (T(2.0) * focal));
}
template<typename T>
EIGEN_DEVICE_FUNC static inline T getFocalLength(T fov, T width)
{
using Eigen::numext::tan;
return width / (T(2.0) * tan(fov / T(2.0)));
}
/**
* Runtime polymorphic interface if one prefers that.
*/
template<typename T>
class CameraInterface
{
public:
virtual ~CameraInterface() { }
virtual CameraModelType getModelType() const = 0;
virtual const char* getModelName() const = 0;
virtual bool pointValid(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0;
virtual bool pixelValid(T x, T y) const = 0;
virtual bool pixelValidSquare(T x, T y) const = 0;
virtual bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const = 0;
virtual bool pixelValidCircular(T x, T y) const = 0;
virtual bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const = 0;
virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const = 0;
virtual typename ComplexTypes<T>::PointT inverse(T x, T y) const = 0;
virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PointT& pt) const = 0;
virtual typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose,
const typename ComplexTypes<T>::PointT& pt) const = 0;
virtual typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PixelT& pix, T dist) const = 0;
virtual typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose,
T x, T y, T dist) const = 0;
virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1,
const typename ComplexTypes<T>::PixelT& pix, T dist,
const typename ComplexTypes<T>::TransformT& pose2) const = 0;
virtual typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1,
T x, T y, T dist, const typename ComplexTypes<T>::TransformT& pose2) const = 0;
};
/**
* Functions / methods shared by all the camera models.
*/
template<typename Derived>
class CameraFunctions
{
static constexpr unsigned int ParametersToOptimize = Eigen::internal::traits<Derived>::ParametersToOptimize;
static constexpr bool HasForwardPointJacobian = Eigen::internal::traits<Derived>::HasForwardPointJacobian;
static constexpr bool HasForwardParametersJacobian = Eigen::internal::traits<Derived>::HasForwardParametersJacobian;
static constexpr bool HasInversePointJacobian = Eigen::internal::traits<Derived>::HasInversePointJacobian;
static constexpr bool HasInverseParametersJacobian = Eigen::internal::traits<Derived>::HasInverseParametersJacobian;
public:
typedef typename Eigen::internal::traits<Derived>::Scalar Scalar;
// ------------------- statics ---------------------
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose.inverse() * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT worldToCamera(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose.inverse() * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT cameraToWorld(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt)
{
return pose * pt; // why!
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
return Derived::template pixelValidCircular<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
return Derived::template pixelValidSquare<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(Derived& ccd, const typename ComplexTypes<T>::PixelT& pt)
{
Derived::template resizeViewport<T>(ccd, pt(0), pt(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PointT& pt)
{
return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const Derived& ccd,
const typename ComplexTypes<T>::RotationT& pose,
const typename ComplexTypes<T>::PointT& pt)
{
return Derived::template forward<T>(ccd, worldToCamera<T>(pose, pt));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const Derived& ccd,
const typename ComplexTypes<T>::PixelT& pix)
{
return Derived::template inverse<T>(ccd, pix(0), pix(1));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, const typename ComplexTypes<T>::PixelT& pix, T dist)
{
return Derived::template inverse<T>(ccd, pix(0), pix(1)) * dist;
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd, T x, T y, T dist)
{
return Derived::template inverse<T>(ccd, x, y) * dist;
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PixelT& pix, T dist)
{
return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,pix)) * dist));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose,
T x, T y, T dist)
{
return cameraToWorld<T>(pose, ((Derived::template inverse<T>(ccd,x,y)) * dist));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose1,
const typename ComplexTypes<T>::PixelT& pix,
T dist,
const typename ComplexTypes<T>::TransformT& pose2)
{
return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, pix, dist));
}
template<typename T = Scalar>
static EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const Derived& ccd,
const typename ComplexTypes<T>::TransformT& pose1,
T x, T y, T dist,
const typename ComplexTypes<T>::TransformT& pose2)
{
return forward<T>(ccd, pose2, inverseAtDistance<T>(ccd, pose1, x, y, dist));
}
// ------------------- non statics ---------------------
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(T x, T y)
{
Derived::template resizeViewport<T>(*static_cast<Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE void resizeViewport(const typename ComplexTypes<T>::PixelT& pt)
{
Derived::template resizeViewport<T>(*static_cast<Derived*>(this), pt(0), pt(1));
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pointValid(const typename ComplexTypes<T>::PointT& pt) const
{
return Derived::template pointValid<T>(*static_cast<const Derived*>(this), pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValid(T x, T y) const
{
return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(T x, T y) const
{
return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidSquare(const typename ComplexTypes<T>::PixelT& pt) const
{
return Derived::template pixelValidSquare<T>(*static_cast<const Derived*>(this), pt(0), pt(1));
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(T x, T y) const
{
return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE bool pixelValidCircular(const typename ComplexTypes<T>::PixelT& pt) const
{
return Derived::template pixelValidCircular<T>(*static_cast<const Derived*>(this), pt(0), pt(1));
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::PointT& tmp_pt) const
{
return Derived::template forward<T>(*static_cast<const Derived*>(this), tmp_pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(T x, T y) const
{
return Derived::template inverse<T>(*static_cast<const Derived*>(this), x, y);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::TransformT& pose, const typename ComplexTypes<T>::PointT& pt) const
{
return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT forward(const typename ComplexTypes<T>::RotationT& pose, const typename ComplexTypes<T>::PointT& pt) const
{
return CameraFunctions::forward<T>(*static_cast<const Derived*>(this), pose, pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardPointJacobian, typename ComplexTypes<T>::ForwardPointJacobianT>::type forwardPointJacobian(const typename ComplexTypes<T>::PointT& pt) const
{
return Derived::template forwardPointJacobian<T>(*static_cast<const Derived*>(this), pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename std::enable_if<HasForwardParametersJacobian, typename ComplexTypes<T>::template ForwardParametersJacobianT<ParametersToOptimize> >::type forwardParametersJacobian(const typename ComplexTypes<T>::PointT& pt) const
{
return Derived::template forwardParametersJacobian<T>(*static_cast<const Derived*>(this), pt);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverse(const typename ComplexTypes<T>::PixelT& pix) const
{
return CameraFunctions::inverse<T>(*static_cast<const Derived*>(this), pix);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::PixelT& pix, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pix, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(T x, T y, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), x, y, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose,
const typename ComplexTypes<T>::PixelT& pix, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, pix, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PointT inverseAtDistance(const typename ComplexTypes<T>::TransformT& pose, T x, T y, T dist) const
{
return CameraFunctions::inverseAtDistance<T>(*static_cast<const Derived*>(this), pose, x, y, dist);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, const typename ComplexTypes<T>::PixelT& pix, T dist,
const typename ComplexTypes<T>::TransformT& pose2) const
{
return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, pix, dist, pose2);
}
template<typename T = Scalar>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE typename ComplexTypes<T>::PixelT twoFrameProject(const typename ComplexTypes<T>::TransformT& pose1, T x, T y, T dist,
const typename ComplexTypes<T>::TransformT& pose2) const
{
return CameraFunctions::twoFrameProject<T>(*static_cast<const Derived*>(this), pose1, x, y, dist, pose2);
}
};
/**
* Wraps templated typed camera model into a polymorphic class.
*/
template <typename ModelT>
class CameraFromCRTP : public ModelT, public CameraInterface<typename ModelT::Scalar>
{
public:
typedef ModelT Derived;
typedef typename Derived::Scalar Scalar;
CameraFromCRTP() = default;
CameraFromCRTP(const Derived& d) : Derived(d) { }
CameraFromCRTP(const CameraFromCRTP& other) = default;
virtual ~CameraFromCRTP() { }
virtual CameraModelType getModelType() const
{
return Derived::ModelType;
}
virtual const char* getModelName() const
{
return CameraModelToTypeAndName<Derived::ModelType>::Name;
}
virtual bool pointValid(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const
{
return Derived::template pointValid<Scalar>(tmp_pt);
}
virtual bool pixelValid(Scalar x, Scalar y) const
{
return Derived::template pixelValid<Scalar>(x,y);
}
virtual bool pixelValidSquare(Scalar x, Scalar y) const
{
return Derived::template pixelValidSquare<Scalar>(x,y);
}
virtual bool pixelValidSquare(const typename ComplexTypes<Scalar>::PixelT& pt) const
{
return Derived::template pixelValidSquare<Scalar>(pt);
}
virtual bool pixelValidCircular(Scalar x, Scalar y) const
{
return Derived::template pixelValidCircular<Scalar>(x,y);
}
virtual bool pixelValidCircular(const typename ComplexTypes<Scalar>::PixelT& pt) const
{
return Derived::template pixelValidCircular<Scalar>(pt);
}
virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::PointT& tmp_pt) const
{
return Derived::template forward<Scalar>(tmp_pt);
}
virtual typename ComplexTypes<Scalar>::PointT inverse(Scalar x, Scalar y) const
{
return Derived::template inverse<Scalar>(x,y);
}
virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::TransformT& pose,
const typename ComplexTypes<Scalar>::PointT& pt) const
{
return Derived::template forward<Scalar>(pose, pt);
}
virtual typename ComplexTypes<Scalar>::PixelT forward(const typename ComplexTypes<Scalar>::RotationT& pose,
const typename ComplexTypes<Scalar>::PointT& pt) const
{
return Derived::template forward<Scalar>(pose, pt);
}
virtual typename ComplexTypes<Scalar>::PointT inverse(const typename ComplexTypes<Scalar>::PixelT& pix) const
{
return Derived::template inverse<Scalar>(pix);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::PixelT& pix,
Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(pix,dist);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(Scalar x, Scalar y, Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(x,y,dist);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose,
const typename ComplexTypes<Scalar>::PixelT& pix,
Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(pose,pix,dist);
}
virtual typename ComplexTypes<Scalar>::PointT inverseAtDistance(const typename ComplexTypes<Scalar>::TransformT& pose,
Scalar x, Scalar y, Scalar dist) const
{
return Derived::template inverseAtDistance<Scalar>(pose,x,y,dist);
}
virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1,
const typename ComplexTypes<Scalar>::PixelT& pix,
Scalar dist,
const typename ComplexTypes<Scalar>::TransformT& pose2) const
{
return Derived::template twoFrameProject<Scalar>(pose1,pix,dist,pose2);
}
virtual typename ComplexTypes<Scalar>::PixelT twoFrameProject(const typename ComplexTypes<Scalar>::TransformT& pose1,
Scalar x, Scalar y, Scalar dist,
const typename ComplexTypes<Scalar>::TransformT& pose2) const
{
return Derived::template twoFrameProject<Scalar>(pose1,x,y,dist,pose2);
}
};
}
#endif // CAMERA_MODEL_UTILS_HPP
| 46.323988 | 263 | 0.648857 |
d8918e5ce4cd1348ab24b3521eb4ec70ebe62e0a | 2,657 | cc | C++ | euler/core/kernels/sample_edge_op.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 2,829 | 2019-01-12T09:16:03.000Z | 2022-03-29T14:00:58.000Z | euler/core/kernels/sample_edge_op.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 331 | 2019-01-17T21:07:49.000Z | 2022-03-30T06:38:17.000Z | euler/core/kernels/sample_edge_op.cc | HuangLED/euler | a56b5fe3fe56123af062317ca0b4160ce3b3ace9 | [
"Apache-2.0"
] | 578 | 2019-01-16T10:48:53.000Z | 2022-03-21T13:41:34.000Z | /* Copyright 2020 Alibaba Group Holding Limited. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <string>
#include "euler/core/framework/op_kernel.h"
#include "euler/core/framework/dag_node.pb.h"
#include "euler/common/logging.h"
#include "euler/core/api/api.h"
namespace euler {
class SampleEdgeOp: public OpKernel {
public:
explicit SampleEdgeOp(const std::string& name): OpKernel(name) { }
void Compute(const DAGNodeProto& node_def, OpKernelContext* ctx);
};
void SampleEdgeOp::Compute(const DAGNodeProto& node_def, OpKernelContext* ctx) {
if (node_def.inputs_size() != 2) {
EULER_LOG(ERROR) << "Invalid input arguments";
return;
}
Tensor* edge_type_t = nullptr;
auto s = ctx->tensor(node_def.inputs(0), &edge_type_t);
if (!s.ok()) {
EULER_LOG(ERROR) << "Retrieve edge_type input failed!";
return;
}
Tensor* count_t = nullptr;
s = ctx->tensor(node_def.inputs(1), &count_t);
if (!s.ok()) {
EULER_LOG(ERROR) << "Retrieve count input failed!";
return;
}
std::vector<int> edge_types(edge_type_t->NumElements());
std::copy(edge_type_t->Raw<int32_t>(),
edge_type_t->Raw<int32_t>() + edge_type_t->NumElements(),
edge_types.begin());
int count = *count_t->Raw<int32_t>();
auto edge_id_vec = euler::SampleEdge(edge_types, count);
if (edge_id_vec.size() != static_cast<size_t>(count)) {
EULER_LOG(ERROR) << "Expect sample count: " << count
<< ", real got:" << edge_id_vec.size();
return;
}
std::string output_name = OutputName(node_def, 0);
TensorShape shape({ static_cast<size_t>(count), 3ul });
Tensor* output = nullptr;
s = ctx->Allocate(output_name, shape, DataType::kInt64, &output);
if (!s.ok()) {
EULER_LOG(ERROR) << "Allocate output tensor failed!";
return;
}
auto data = output->Raw<int64_t>();
for (auto& edge_id : edge_id_vec) {
*data++ = std::get<0>(edge_id);
*data++ = std::get<1>(edge_id);
*data++ = std::get<2>(edge_id);
}
}
REGISTER_OP_KERNEL("API_SAMPLE_EDGE", SampleEdgeOp);
} // namespace euler
| 31.630952 | 80 | 0.666165 |
d894316a3388b78f662dc89b069e5ff4a9bf42f4 | 1,339 | cpp | C++ | src/lighting.cpp | armedturret/GlassWall | 1ff438987d32be154ce81488a8f2729eaaf563ee | [
"MIT"
] | null | null | null | src/lighting.cpp | armedturret/GlassWall | 1ff438987d32be154ce81488a8f2729eaaf563ee | [
"MIT"
] | null | null | null | src/lighting.cpp | armedturret/GlassWall | 1ff438987d32be154ce81488a8f2729eaaf563ee | [
"MIT"
] | 1 | 2018-12-23T01:46:41.000Z | 2018-12-23T01:46:41.000Z | #include <lighting.h>
GW::RenderEngine::Lighting::Lighting()
{
}
GW::RenderEngine::Lighting::~Lighting()
{
}
void GW::RenderEngine::Lighting::setDirectionalLight(const DirectionalLight & light)
{
m_directionalLight = light;
}
void GW::RenderEngine::Lighting::addPointLight(const PointLight & light)
{
m_pointLights.push_back(light);
}
void GW::RenderEngine::Lighting::addSpotLight(const SpotLight & light)
{
m_spotLights.push_back(light);
}
void GW::RenderEngine::Lighting::setPointLight(unsigned int index, const PointLight & light)
{
if (index < m_pointLights.size()) {
m_pointLights[index] = light;
}
}
void GW::RenderEngine::Lighting::setSpotLight(unsigned int index, const SpotLight & light)
{
if (index < m_spotLights.size()) {
m_spotLights[index] = light;
}
}
GW::RenderEngine::PointLight GW::RenderEngine::Lighting::getPointLight(unsigned int index)
{
if (index < m_pointLights.size()) {
return m_pointLights[index];
}
return GW::RenderEngine::PointLight();
}
std::vector<GW::RenderEngine::PointLight> GW::RenderEngine::Lighting::getPointLights()
{
return m_pointLights;
}
std::vector<GW::RenderEngine::SpotLight> GW::RenderEngine::Lighting::getSpotLights()
{
return m_spotLights;
}
GW::RenderEngine::DirectionalLight GW::RenderEngine::Lighting::getDirectionalLight()
{
return m_directionalLight;
}
| 21.253968 | 92 | 0.746826 |
d894353cd687d3ce761962c40144ad58c01ad041 | 1,234 | cpp | C++ | EngineAttempt0/project/src/engine/general/Transform.cpp | MEEMEEMAN/EngineAttempt0 | 2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6 | [
"MIT"
] | null | null | null | EngineAttempt0/project/src/engine/general/Transform.cpp | MEEMEEMAN/EngineAttempt0 | 2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6 | [
"MIT"
] | null | null | null | EngineAttempt0/project/src/engine/general/Transform.cpp | MEEMEEMAN/EngineAttempt0 | 2d470af8d19b8f90c03b1bcdee9ae64f3cddd7b6 | [
"MIT"
] | null | null | null | #include "Transform.h"
void Transform::UpdateTRS()
{
mat4 modelMatrix = mat4(1);
modelMatrix = glm::translate(modelMatrix, position);
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.x), vec3(1, 0, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.y), vec3(0, 1, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.z), vec3(0, 0, 1));
modelMatrix = glm::scale(modelMatrix, scale);
mModelMatrix = modelMatrix;
CalcDirections();
}
void Transform::UpdateSRT()
{
mat4 modelMatrix = mat4(1);
modelMatrix = glm::scale(modelMatrix, scale);
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.x), vec3(1, 0, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.y), vec3(0, 1, 0));
modelMatrix = glm::rotate(modelMatrix, glm::radians(rotaiton.z), vec3(0, 0, 1));
modelMatrix = glm::translate(modelMatrix, position);
mModelMatrix = modelMatrix;
CalcDirections();
}
void Transform::CalcDirections()
{
mat4 inverse = glm::inverse(mModelMatrix);
mForward = glm::normalize(glm::vec3(inverse[2]));
vec3 right = glm::normalize(glm::cross(mForward, vec3(0, 1, 0)));
mRight = right;
vec3 top = glm::normalize(glm::cross(mForward, mRight));
mUp = top;
}
| 26.826087 | 81 | 0.703404 |
d89886f2c4165e5ace2f8f6e9b07abdfd2d5d458 | 233 | cpp | C++ | library/src/ButtonMatrix.cpp | StratifyLabs/LvglAPI | c869d5b38ad3aa148fa0801d12271f2d9a6043c5 | [
"MIT"
] | 1 | 2022-01-03T19:16:58.000Z | 2022-01-03T19:16:58.000Z | library/src/ButtonMatrix.cpp | StratifyLabs/LvglAPI | c869d5b38ad3aa148fa0801d12271f2d9a6043c5 | [
"MIT"
] | null | null | null | library/src/ButtonMatrix.cpp | StratifyLabs/LvglAPI | c869d5b38ad3aa148fa0801d12271f2d9a6043c5 | [
"MIT"
] | null | null | null | #include "lvgl/ButtonMatrix.hpp"
using namespace lvgl;
LVGL_OBJECT_ASSERT_SIZE(ButtonMatrix);
ButtonMatrix::ButtonMatrix(const char * name){
m_object = api()->btnmatrix_create(screen_object());
set_user_data(m_object,name);
}
| 21.181818 | 54 | 0.776824 |
d8989ee0c5f697d49473166919b635c30401a505 | 15,067 | cpp | C++ | 3rdparty/GPSTk/ext/apps/geomatics/relposition/ProcessRawData.cpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/ext/apps/geomatics/relposition/ProcessRawData.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/ext/apps/geomatics/relposition/ProcessRawData.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | 14 | 2019-11-05T01:50:29.000Z | 2021-08-06T06:23:44.000Z | //============================================================================
//
// This file is part of GPSTk, the GPS Toolkit.
//
// The GPSTk is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 3.0 of the License, or
// any later version.
//
// The GPSTk is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with GPSTk; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
//
// Copyright 2004, The University of Texas at Austin
//
//============================================================================
//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
// release, distribution is unlimited.
//
//=============================================================================
/**
* @file ProcessRawData.cpp
* Process raw data, including editing, buffering and computation of a pseudorange
* solution using RAIM algorithm, part of program DDBase.
*/
//------------------------------------------------------------------------------------
// TD ProcessRawData put back EOP mean of date
// TD ProcessRawData user input pseudorange limits in EditRawData(ObsFile& obsfile)
//------------------------------------------------------------------------------------
// system includes
// GPSTk
#include "EphemerisRange.hpp"
#include "TimeString.hpp"
// DDBase
//#include "PreciseRange.hpp"
#include "DDBase.hpp"
#include "index.hpp"
//------------------------------------------------------------------------------------
using namespace std;
using namespace gpstk;
//------------------------------------------------------------------------------------
// local data
static vector<SatID> Sats; // used by RAIM, bad ones come back marked (id < 0)
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
// prototypes -- this module only
// ComputeRAIMSolution.cpp :
int ComputeRAIMSolution(ObsFile& of,CommonTime& tt,vector<SatID>& Sats,ofstream *pofs)
throw(Exception);
void RAIMedit(ObsFile& of, vector<SatID>& Sats) throw(Exception);
// those defined here
void FillRawData(ObsFile& of) throw(Exception);
void GetEphemerisRange(ObsFile& obsfile, CommonTime& timetag) throw(Exception);
void EditRawData(ObsFile& of) throw(Exception);
int BufferRawData(ObsFile& of) throw(Exception);
//------------------------------------------------------------------------------------
int ProcessRawData(ObsFile& obsfile, CommonTime& timetag, ofstream *pofs)
throw(Exception)
{
try {
int iret;
// fill RawDataMap for Station
FillRawData(obsfile);
// compute nominal elevation and ephemeris range; RecomputeFromEphemeris
// will re-do after synchronization and before differencing
GetEphemerisRange(obsfile,timetag);
// Edit raw data for this station
EditRawData(obsfile);
// fill RawDataMap for Station, and compute pseudorange solution
// return Sats, with bad satellites marked with (id < 0)
iret = ComputeRAIMSolution(obsfile,timetag,Sats,pofs);
if(iret) {
if(CI.Verbose) oflog
<< " Warning - ProcessRawData for station " << obsfile.label
<< ", at time "
<< printTime(timetag,"%Y/%02m/%02d %2H:%02M:%6.3f=%F/%10.3g,")
<< " failed with code " << iret
<< (iret == 2 ? " (large RMS residual)" :
(iret == 1 ? " (large slope)" :
(iret == -1 ? " (no convergence)" :
(iret == -2 ? " (singular)" :
(iret == -3 ? " (not enough satellites)" :
(iret == -4 ? " (no ephemeris)" :
(iret == -5 ? " (invalid solution)" :
" (unknown)")))))))
<< endl;
// TD change this -- or user input ?
//if(iret > 0) iret = 0; // suspect solution
if(iret) {
Stations[obsfile.label].PRS.Valid = false; // remove data in RAIMedit
}
}
// save statistics on PR solution
Station& st=Stations[obsfile.label];
if(st.PRS.Valid) {
st.PRSXstats.Add(st.PRS.Solution(0));
st.PRSYstats.Add(st.PRS.Solution(1));
st.PRSZstats.Add(st.PRS.Solution(2));
}
// if user wants PRSolution2 as a priori, update it here so that the
// elevation can be computed - this serves to eliminate the low-elevation
// data from the raw data buffers and simplifies processing.
// it does not seem to affect the final estimation processing at all...
if(st.usePRS && st.PRSXstats.N() >= 10) {
Position prs;
prs.setECEF(st.PRSXstats.Average(),
st.PRSYstats.Average(),
st.PRSZstats.Average());
st.pos = prs;
if(CI.Debug) oflog << "Update apriori=PR solution for " << obsfile.label
<< " at " << printTime(timetag,"%Y/%02m/%02d %2H:%02M:%6.3f=%F/%10.3g")
<< fixed << setprecision(5)
<< " " << setw(15) << st.PRSXstats.Average()
<< " " << setw(15) << st.PRSYstats.Average()
<< " " << setw(15) << st.PRSZstats.Average()
<< endl;
}
// edit based on RAIM, using Sats
RAIMedit(obsfile,Sats);
// buffer raw data, including ER(==0), EL and clock
iret = BufferRawData(obsfile);
if(iret) return iret; // always returns 0
return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
} // end ProcessRawData
//------------------------------------------------------------------------------------
void FillRawData(ObsFile& of) throw(Exception)
{
try {
//int nsvs;
//double C1;
GSatID sat;
RinexObsData::RinexSatMap::const_iterator it;
RinexObsData::RinexObsTypeMap otmap;
RinexObsData::RinexObsTypeMap::const_iterator jt;
Station& st=Stations[of.label];
st.RawDataMap.clear(); // assumes one file per site at each epoch
// loop over sat=it->first, ObsTypeMap=it->second
// fill DataStruct
// Don't include L2 when user has specified --Freq L1 -- there have been
// cases where L2 is present but bad, and user had no recourse but to edit
// the RINEX file to remove L2 before processing
//nsvs = 0;
for(it=of.Robs.obs.begin(); it != of.Robs.obs.end(); ++it) {
sat = it->first;
otmap = it->second;
// ignore non-GPS satellites
if(sat.system != SatID::systemGPS) continue;
// is the satellite excluded?
if(index(CI.ExSV,sat) != -1) continue;
// pull out the data
DataStruct D;
D.P1 = D.P2 = D.L1 = D.L2 = D.D1 = D.D2 = D.S1 = D.S2 = 0;
if(of.inP1 > -1 && CI.Frequency != 2 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inP1])) != otmap.end())
D.P1 = jt->second.data;
if(of.inP2 > -1 && CI.Frequency != 1 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inP2])) != otmap.end())
D.P2 = jt->second.data;
if(of.inL1 > -1 && CI.Frequency != 2 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inL1])) != otmap.end())
D.L1 = jt->second.data;
if(of.inL2 > -1 && CI.Frequency != 1 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inL2])) != otmap.end())
D.L2 = jt->second.data;
if(of.inD1 > -1 && CI.Frequency != 2 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inD1])) != otmap.end())
D.D1 = jt->second.data;
if(of.inD2 > -1 && CI.Frequency != 1 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inD2])) != otmap.end())
D.D2 = jt->second.data;
if(of.inS1 > -1 && CI.Frequency != 2 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inS1])) != otmap.end())
D.S1 = jt->second.data;
if(of.inS2 > -1 && CI.Frequency != 1 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inS2])) != otmap.end())
D.S2 = jt->second.data;
//if(of.inC1 > -1 && CI.Frequency != 2 &&
// (jt=otmap.find(of.Rhead.obsTypeList[of.inC1])) != otmap.end())
// C1 = jt->second.data;
// if P1 is not available, but C1 is, use C1 in place of P1
if((of.inP1 == -1 || D.P1 == 0) &&
of.inC1 > -1 && CI.Frequency != 2 &&
(jt=otmap.find(of.Rhead.obsTypeList[of.inC1])) != otmap.end())
D.P1 = jt->second.data;
// temp - round L1 and L2 to 1/256 cycle
//{
// double dL1 = D.L1 - long(D.L1);
// double cL1 = double(long(256.*dL1))/256.;
// D.L1 -= dL1 - cL1;
//}
st.RawDataMap[sat] = D;
st.time = SolutionEpoch;
//nsvs++;
} // end loop over sats
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
} // end FillRawData()
//------------------------------------------------------------------------------------
void GetEphemerisRange(ObsFile& obsfile, CommonTime& timetag) throw(Exception)
{
try {
CorrectedEphemerisRange CER; // temp
//PreciseRange CER;
Station& st=Stations[obsfile.label];
map<GSatID,DataStruct>::iterator it;
for(it=st.RawDataMap.begin(); it != st.RawDataMap.end(); it++) {
// ER cannot be used until the a priori positions are computed --
// because user may want the PRSolution2 as the a priori, we must wait.
// This will be updated in RecomputeFromEphemeris(), after Synchronization()
it->second.ER = 0.0;
// this will happen when user has chosen to use the PRSolution2 as the a priori
// and the st.pos has not yet been updated
if(st.pos.getCoordinateSystem() == Position::Unknown) {
it->second.elev = 90.0; // include it in the PRS
it->second.az = 0.0;
continue;
}
// TD why did PreciseRange not throw here?
// catch NoEphemerisFound and set elevation -90 --> edited out later
try {
//it->second.ER =
CER.ComputeAtReceiveTime(timetag, st.pos, it->first, *pEph);
it->second.elev = CER.elevation; // this will be compared to PRS elev Limit
it->second.az = CER.azimuth;
}
catch(InvalidRequest& e) {
if(CI.Verbose)
oflog << "No ephemeris found for sat " << it->first << " at time "
<< printTime(timetag,"%Y/%02m/%02d %2H:%02M:%6.3f=%F/%10.3g") << endl;
//it->second.ER = 0.0;
it->second.elev = -90.0; // do not include it in the PRS
it->second.az = 0.0;
}
}
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
//------------------------------------------------------------------------------------
void EditRawData(ObsFile& obsfile) throw(Exception)
{
try {
size_t i;
Station& st=Stations[obsfile.label];
vector<GSatID> BadSVs;
map<GSatID,DataStruct>::iterator it;
for(it=st.RawDataMap.begin(); it != st.RawDataMap.end(); it++) {
if(
// DON'T DO THIS - clock may get large and negative, leading to negative PR
// bad pseudorange
// (CI.Frequency != 2 && it->second.P1 < 1000.0) || // TD
// (CI.Frequency != 1 && it->second.P2 < 1000.0) ||
// below elevation cutoff (for PRS)
(it->second.elev < CI.PRSMinElevation)
) { //end if
BadSVs.push_back(it->first);
}
}
// delete the bad satellites
for(i=0; i<BadSVs.size(); i++) {
st.RawDataMap.erase(BadSVs[i]);
}
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
} // end EditRawData()
//------------------------------------------------------------------------------------
// add good raw data in RawDataMap to RawDataBuffers for the appropriate station
// and satellite. Also buffer the clock solution and sigma.
// NB these buffers must remain parallel.
int BufferRawData(ObsFile& obsfile) throw(Exception)
{
try {
Station& st=Stations[obsfile.label];
map<GSatID,DataStruct>::iterator it;
map<GSatID,RawData>::iterator jt;
// loop over satellites
for(it=st.RawDataMap.begin(); it != st.RawDataMap.end(); it++) {
// find iterator for this sat in Buffers map
jt = st.RawDataBuffers.find(it->first);
if(jt == st.RawDataBuffers.end()) {
RawData rd;
st.RawDataBuffers[it->first] = rd;
jt = st.RawDataBuffers.find(it->first);
}
// buffer the data -- keep parallel with count
jt->second.count.push_back(Count);
jt->second.L1.push_back(it->second.L1);
jt->second.L2.push_back(it->second.L2);
jt->second.P1.push_back(it->second.P1);
jt->second.P2.push_back(it->second.P2);
jt->second.ER.push_back(it->second.ER);
jt->second.S1.push_back(it->second.S1);
jt->second.S2.push_back(it->second.S2);
jt->second.elev.push_back(it->second.elev);
jt->second.az.push_back(it->second.az);
}
// buffer the clock solution and the timetag offset, and
// buffer the (Station) count in parallel.
// NB these are NOT necessarily parallel to raw data buffers
if(st.PRS.isValid()) {
st.ClockBuffer.push_back(st.PRS.Solution(3));
st.ClkSigBuffer.push_back(st.PRS.Covariance(3,3));
st.RxTimeOffset.push_back(SolutionEpoch - obsfile.Robs.time);
}
else {
st.ClockBuffer.push_back(0.0);
st.ClkSigBuffer.push_back(0.0);
st.RxTimeOffset.push_back(0.0);
}
st.CountBuffer.push_back(Count);
return 0;
}
catch(Exception& e) { GPSTK_RETHROW(e); }
catch(std::exception& e) { Exception E("std except: "+string(e.what())); GPSTK_THROW(E); }
catch(...) { Exception e("Unknown exception"); GPSTK_THROW(e); }
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
| 38.338422 | 90 | 0.553727 |
d89a1419d316000ed182f6a183475ebeb0a06af7 | 23,275 | cpp | C++ | codecparsers/vp9parser.cpp | genisysram/libyami | 08d3ecbbfe1f5d23d433523f747a7093a0b3a13a | [
"Apache-2.0"
] | 89 | 2015-01-09T10:31:13.000Z | 2018-01-18T12:48:21.000Z | codecparsers/vp9parser.cpp | genisysram/libyami | 08d3ecbbfe1f5d23d433523f747a7093a0b3a13a | [
"Apache-2.0"
] | 626 | 2015-01-12T00:01:26.000Z | 2018-01-23T18:58:58.000Z | codecparsers/vp9parser.cpp | genisysram/libyami | 08d3ecbbfe1f5d23d433523f747a7093a0b3a13a | [
"Apache-2.0"
] | 104 | 2015-01-12T04:02:09.000Z | 2017-12-28T08:27:42.000Z | /*
* Copyright 2016 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.
*/
/**
* SECTION:vp9parser
* @short_description: Convenience library for parsing vp9 video bitstream.
*
* For more details about the structures, you can refer to the
* specifications:
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "bitReader.h"
#include "vp9quant.h"
#include "vp9parser.h"
#include <string.h>
#include <stdlib.h>
#include "common/log.h"
using YamiParser::BitReader;
#define MAX_LOOP_FILTER 63
#define MAX_PROB 255
typedef struct _ReferenceSize {
uint32_t width;
uint32_t height;
} ReferenceSize;
typedef struct _Vp9ParserPrivate {
BOOL subsampling_x;
BOOL subsampling_y;
VP9_COLOR_SPACE color_space;
int8_t y_dc_delta_q;
int8_t uv_dc_delta_q;
int8_t uv_ac_delta_q;
int16_t y_dequant[QINDEX_RANGE][2];
int16_t uv_dequant[QINDEX_RANGE][2];
/* for loop filters */
int8_t ref_deltas[VP9_MAX_REF_LF_DELTAS];
int8_t mode_deltas[VP9_MAX_MODE_LF_DELTAS];
BOOL segmentation_abs_delta;
Vp9SegmentationInfoData segmentation[VP9_MAX_SEGMENTS];
ReferenceSize reference[VP9_REF_FRAMES];
} Vp9ParserPrivate;
void init_dequantizer(Vp9Parser* parser);
static void init_vp9_parser(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr)
{
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
memset(parser, 0, sizeof(Vp9Parser));
memset(priv, 0, sizeof(Vp9ParserPrivate));
parser->priv = priv;
parser->bit_depth = frame_hdr->bit_depth;
init_dequantizer(parser);
}
Vp9Parser* vp9_parser_new()
{
Vp9Parser* parser = (Vp9Parser*)malloc(sizeof(Vp9Parser));
if (!parser)
return NULL;
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)malloc(sizeof(Vp9ParserPrivate));
if (!priv) {
free(parser);
return NULL;
}
parser->priv = priv;
return parser;
}
void vp9_parser_free(Vp9Parser* parser)
{
if (parser) {
if (parser->priv)
free(parser->priv);
free(parser);
}
}
#define vp9_read_bit(br) br->read(1)
#define vp9_read_bits(br, bits) br->read(bits)
static int32_t vp9_read_signed_bits(BitReader* br, int bits)
{
assert(bits < 32);
const int32_t value = vp9_read_bits(br, bits);
return vp9_read_bit(br) ? -value : value;
}
static BOOL verify_frame_marker(BitReader* br)
{
#define VP9_FRAME_MARKER 2
uint8_t frame_marker = vp9_read_bits(br, 2);
if (frame_marker != VP9_FRAME_MARKER)
return FALSE;
return TRUE;
}
static BOOL verify_sync_code(BitReader* const br)
{
#define VP9_SYNC_CODE_0 0x49
#define VP9_SYNC_CODE_1 0x83
#define VP9_SYNC_CODE_2 0x42
return vp9_read_bits(br, 8) == VP9_SYNC_CODE_0 && vp9_read_bits(br, 8) == VP9_SYNC_CODE_1 && vp9_read_bits(br, 8) == VP9_SYNC_CODE_2;
}
static VP9_PROFILE read_profile(BitReader* br)
{
uint8_t profile = vp9_read_bit(br);
profile |= vp9_read_bit(br) << 1;
if (profile > 2)
profile += vp9_read_bit(br);
return (VP9_PROFILE)profile;
}
static void read_frame_size(BitReader* br,
uint32_t* width, uint32_t* height)
{
const uint32_t w = vp9_read_bits(br, 16) + 1;
const uint32_t h = vp9_read_bits(br, 16) + 1;
*width = w;
*height = h;
}
static void read_display_frame_size(Vp9FrameHdr* frame_hdr, BitReader* br)
{
frame_hdr->display_size_enabled = vp9_read_bit(br);
if (frame_hdr->display_size_enabled) {
read_frame_size(br, &frame_hdr->display_width, &frame_hdr->display_height);
}
}
static void read_frame_size_from_refs(const Vp9Parser* parser, Vp9FrameHdr* frame_hdr, BitReader* br)
{
BOOL found = FALSE;
int i;
const Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
for (i = 0; i < VP9_REFS_PER_FRAME; i++) {
found = vp9_read_bit(br);
if (found) {
uint8_t idx = frame_hdr->ref_frame_indices[i];
frame_hdr->size_from_ref[i] = TRUE;
frame_hdr->width = priv->reference[idx].width;
frame_hdr->height = priv->reference[idx].height;
break;
}
}
if (!found) {
read_frame_size(br, &frame_hdr->width, &frame_hdr->height);
}
}
static VP9_INTERP_FILTER read_interp_filter(BitReader* br)
{
const VP9_INTERP_FILTER filter_map[] = { VP9_EIGHTTAP_SMOOTH,
VP9_EIGHTTAP,
VP9_EIGHTTAP_SHARP,
VP9_BILINEAR };
return vp9_read_bit(br) ? VP9_SWITCHABLE
: filter_map[vp9_read_bits(br, 2)];
}
static void read_loopfilter(Vp9LoopFilter* lf, BitReader* br)
{
lf->filter_level = vp9_read_bits(br, 6);
lf->sharpness_level = vp9_read_bits(br, 3);
lf->mode_ref_delta_update = 0;
lf->mode_ref_delta_enabled = vp9_read_bit(br);
if (lf->mode_ref_delta_enabled) {
lf->mode_ref_delta_update = vp9_read_bit(br);
if (lf->mode_ref_delta_update) {
int i;
for (i = 0; i < VP9_MAX_REF_LF_DELTAS; i++) {
lf->update_ref_deltas[i] = vp9_read_bit(br);
if (lf->update_ref_deltas[i])
lf->ref_deltas[i] = vp9_read_signed_bits(br, 6);
}
for (i = 0; i < VP9_MAX_MODE_LF_DELTAS; i++) {
lf->update_mode_deltas[i] = vp9_read_bit(br);
if (lf->update_mode_deltas[i])
lf->mode_deltas[i] = vp9_read_signed_bits(br, 6);
}
}
}
}
static int8_t read_delta_q(BitReader* br)
{
return vp9_read_bit(br) ? vp9_read_signed_bits(br, 4) : 0;
}
static void read_quantization(Vp9FrameHdr* frame_hdr, BitReader* br)
{
frame_hdr->base_qindex = vp9_read_bits(br, QINDEX_BITS);
frame_hdr->y_dc_delta_q = read_delta_q(br);
frame_hdr->uv_dc_delta_q = read_delta_q(br);
frame_hdr->uv_ac_delta_q = read_delta_q(br);
}
static void read_segmentation(Vp9SegmentationInfo* seg, BitReader* br)
{
int i;
seg->update_map = FALSE;
seg->update_data = FALSE;
seg->enabled = vp9_read_bit(br);
if (!seg->enabled)
return;
seg->update_map = vp9_read_bit(br);
if (seg->update_map) {
for (i = 0; i < VP9_SEG_TREE_PROBS; i++) {
seg->update_tree_probs[i] = vp9_read_bit(br);
seg->tree_probs[i] = seg->update_tree_probs[i] ? vp9_read_bits(br, 8) : MAX_PROB;
}
seg->temporal_update = vp9_read_bit(br);
if (seg->temporal_update) {
for (i = 0; i < VP9_PREDICTION_PROBS; i++) {
seg->update_pred_probs[i] = vp9_read_bit(br);
seg->pred_probs[i] = seg->update_pred_probs[i] ? vp9_read_bits(br, 8) : MAX_PROB;
}
}
else {
for (i = 0; i < VP9_PREDICTION_PROBS; i++) {
seg->pred_probs[i] = MAX_PROB;
}
}
}
seg->update_data = vp9_read_bit(br);
if (seg->update_data) {
/* clear all features */
memset(seg->data, 0, sizeof(seg->data));
seg->abs_delta = vp9_read_bit(br);
for (i = 0; i < VP9_MAX_SEGMENTS; i++) {
Vp9SegmentationInfoData* seg_data = seg->data + i;
uint8_t data;
/* SEG_LVL_ALT_Q */
seg_data->alternate_quantizer_enabled = vp9_read_bit(br);
if (seg_data->alternate_quantizer_enabled) {
data = vp9_read_bits(br, 8);
seg_data->alternate_quantizer = vp9_read_bit(br) ? -data : data;
}
/* SEG_LVL_ALT_LF */
seg_data->alternate_loop_filter_enabled = vp9_read_bit(br);
if (seg_data->alternate_loop_filter_enabled) {
data = vp9_read_bits(br, 6);
seg_data->alternate_loop_filter = vp9_read_bit(br) ? -data : data;
}
/* SEG_LVL_REF_FRAME */
seg_data->reference_frame_enabled = vp9_read_bit(br);
if (seg_data->reference_frame_enabled) {
seg_data->reference_frame = vp9_read_bits(br, 2);
}
seg_data->reference_skip = vp9_read_bit(br);
}
}
}
#define MIN_TILE_WIDTH_B64 4
#define MAX_TILE_WIDTH_B64 64
uint32_t get_max_lb_tile_cols(uint32_t sb_cols)
{
int log2 = 0;
while ((sb_cols >> log2) >= MIN_TILE_WIDTH_B64)
++log2;
if (log2)
log2--;
return log2;
}
uint32_t get_min_lb_tile_cols(uint32_t sb_cols)
{
uint32_t log2 = 0;
while ((uint64_t)(MAX_TILE_WIDTH_B64 << log2) < sb_cols)
++log2;
return log2;
}
/* align to 64, follow specification 6.2.6 Compute image size syntax */
#define SB_ALIGN(w) (((w) + 63) >> 6)
static BOOL read_tile_info(Vp9FrameHdr* frame_hdr, BitReader* br)
{
const uint32_t sb_cols = SB_ALIGN(frame_hdr->width);
uint32_t min_lb_tile_cols = get_min_lb_tile_cols(sb_cols);
uint32_t max_lb_tile_cols = get_max_lb_tile_cols(sb_cols);
uint32_t max_ones = max_lb_tile_cols - min_lb_tile_cols;
/* columns */
frame_hdr->log2_tile_columns = min_lb_tile_cols;
while (max_ones-- && vp9_read_bit(br))
frame_hdr->log2_tile_columns++;
/* row */
frame_hdr->log2_tile_rows = vp9_read_bit(br);
if (frame_hdr->log2_tile_rows)
frame_hdr->log2_tile_rows += vp9_read_bit(br);
return TRUE;
}
static void loop_filter_update(Vp9Parser* parser, const Vp9LoopFilter* lf)
{
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
int i;
for (i = 0; i < VP9_MAX_REF_LF_DELTAS; i++) {
if (lf->update_ref_deltas[i])
priv->ref_deltas[i] = lf->ref_deltas[i];
}
for (i = 0; i < VP9_MAX_MODE_LF_DELTAS; i++) {
if (lf->update_mode_deltas[i])
priv->mode_deltas[i] = lf->mode_deltas[i];
}
}
BOOL compare_and_set(int8_t* dest, const int8_t src)
{
const int8_t old = *dest;
*dest = src;
return old != src;
}
void init_dequantizer(Vp9Parser* parser)
{
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
int q;
for (q = 0; q < QINDEX_RANGE; q++) {
priv->y_dequant[q][0] = vp9_dc_quant(parser->bit_depth, q, priv->y_dc_delta_q);
priv->y_dequant[q][1] = vp9_ac_quant(parser->bit_depth, q, 0);
priv->uv_dequant[q][0] = vp9_dc_quant(parser->bit_depth, q, priv->uv_dc_delta_q);
priv->uv_dequant[q][1] = vp9_ac_quant(parser->bit_depth, q, priv->uv_ac_delta_q);
}
}
static void quantization_update(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr)
{
BOOL update = FALSE;
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
update |= compare_and_set(&priv->y_dc_delta_q, frame_hdr->y_dc_delta_q);
update |= compare_and_set(&priv->uv_dc_delta_q, frame_hdr->uv_dc_delta_q);
update |= compare_and_set(&priv->uv_ac_delta_q, frame_hdr->uv_ac_delta_q);
if (update) {
init_dequantizer(parser);
}
parser->lossless_flag = frame_hdr->base_qindex == 0 && frame_hdr->y_dc_delta_q == 0 && frame_hdr->uv_dc_delta_q == 0 && frame_hdr->uv_ac_delta_q == 0;
}
uint8_t seg_get_base_qindex(const Vp9Parser* parser, const Vp9FrameHdr* frame_hdr, int segid)
{
int seg_base = frame_hdr->base_qindex;
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
const Vp9SegmentationInfoData* seg = priv->segmentation + segid;
/* DEBUG("id = %d, seg_base = %d, seg enable = %d, alt eanble = %d, abs = %d, alt= %d\n",segid,
seg_base, frame_hdr->segmentation.enabled, seg->alternate_quantizer_enabled, priv->segmentation_abs_delta, seg->alternate_quantizer);
*/
if (frame_hdr->segmentation.enabled && seg->alternate_quantizer_enabled) {
if (priv->segmentation_abs_delta)
seg_base = seg->alternate_quantizer;
else
seg_base += seg->alternate_quantizer;
}
return clamp(seg_base, 0, MAXQ);
}
uint8_t seg_get_filter_level(const Vp9Parser* parser, const Vp9FrameHdr* frame_hdr, int segid)
{
int seg_filter = frame_hdr->loopfilter.filter_level;
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
const Vp9SegmentationInfoData* seg = priv->segmentation + segid;
if (frame_hdr->segmentation.enabled && seg->alternate_loop_filter_enabled) {
if (priv->segmentation_abs_delta)
seg_filter = seg->alternate_loop_filter;
else
seg_filter += seg->alternate_loop_filter;
}
return clamp(seg_filter, 0, MAX_LOOP_FILTER);
}
/*save segmentation info from frame header to parser*/
static void segmentation_save(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr)
{
const Vp9SegmentationInfo* info = &frame_hdr->segmentation;
if (!info->enabled)
return;
if (info->update_map) {
ASSERT(sizeof(parser->mb_segment_tree_probs) == sizeof(info->tree_probs));
ASSERT(sizeof(parser->segment_pred_probs) == sizeof(info->pred_probs));
memcpy(parser->mb_segment_tree_probs, info->tree_probs, sizeof(info->tree_probs));
memcpy(parser->segment_pred_probs, info->pred_probs, sizeof(info->pred_probs));
}
if (info->update_data) {
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
priv->segmentation_abs_delta = info->abs_delta;
ASSERT(sizeof(priv->segmentation) == sizeof(info->data));
memcpy(priv->segmentation, info->data, sizeof(info->data));
}
}
static void segmentation_update(Vp9Parser* parser, const Vp9FrameHdr* frame_hdr)
{
int i = 0;
const Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
const Vp9LoopFilter* lf = &frame_hdr->loopfilter;
int default_filter = lf->filter_level;
const int scale = 1 << (default_filter >> 5);
segmentation_save(parser, frame_hdr);
for (i = 0; i < VP9_MAX_SEGMENTS; i++) {
uint8_t q = seg_get_base_qindex(parser, frame_hdr, i);
Vp9Segmentation* seg = parser->segmentation + i;
const Vp9SegmentationInfoData* info = priv->segmentation + i;
seg->luma_dc_quant_scale = priv->y_dequant[q][0];
seg->luma_ac_quant_scale = priv->y_dequant[q][1];
seg->chroma_dc_quant_scale = priv->uv_dequant[q][0];
seg->chroma_ac_quant_scale = priv->uv_dequant[q][1];
if (lf->filter_level) {
uint8_t filter = seg_get_filter_level(parser, frame_hdr, i);
if (!lf->mode_ref_delta_enabled) {
memset(seg->filter_level, filter, sizeof(seg->filter_level));
}
else {
int ref, mode;
const int intra_filter = filter + priv->ref_deltas[VP9_INTRA_FRAME] * scale;
seg->filter_level[VP9_INTRA_FRAME][0] = clamp(intra_filter, 0, MAX_LOOP_FILTER);
for (ref = VP9_LAST_FRAME; ref < VP9_MAX_REF_FRAMES; ++ref) {
for (mode = 0; mode < VP9_MAX_MODE_LF_DELTAS; ++mode) {
const int inter_filter = filter + priv->ref_deltas[ref] * scale
+ priv->mode_deltas[mode] * scale;
seg->filter_level[ref][mode] = clamp(inter_filter, 0, MAX_LOOP_FILTER);
}
}
}
}
seg->reference_frame_enabled = info->reference_frame_enabled;
;
seg->reference_frame = info->reference_frame;
seg->reference_skip = info->reference_skip;
}
}
static void reference_update(Vp9Parser* parser, const Vp9FrameHdr* const frame_hdr)
{
uint8_t flag = 1;
uint8_t refresh_frame_flags;
int i;
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
ReferenceSize* reference = priv->reference;
if (frame_hdr->frame_type == VP9_KEY_FRAME) {
refresh_frame_flags = 0xff;
}
else {
refresh_frame_flags = frame_hdr->refresh_frame_flags;
}
for (i = 0; i < VP9_REF_FRAMES; i++) {
if (refresh_frame_flags & flag) {
reference[i].width = frame_hdr->width;
reference[i].height = frame_hdr->height;
}
flag <<= 1;
}
}
static inline int key_or_intra_only(const Vp9FrameHdr* frame_hdr)
{
return frame_hdr->frame_type == VP9_KEY_FRAME || frame_hdr->intra_only;
}
static void set_default_lf_deltas(Vp9Parser* parser)
{
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
priv->ref_deltas[VP9_INTRA_FRAME] = 1;
priv->ref_deltas[VP9_LAST_FRAME] = 0;
priv->ref_deltas[VP9_GOLDEN_FRAME] = -1;
priv->ref_deltas[VP9_ALTREF_FRAME] = -1;
priv->mode_deltas[0] = 0;
priv->mode_deltas[1] = 0;
}
static void set_default_segmentation_info(Vp9Parser* parser)
{
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
memset(priv->segmentation, 0, sizeof(priv->segmentation));
priv->segmentation_abs_delta = FALSE;
}
static void setup_past_independence(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr)
{
set_default_lf_deltas(parser);
set_default_segmentation_info(parser);
memset(frame_hdr->ref_frame_sign_bias, 0, sizeof(frame_hdr->ref_frame_sign_bias));
}
static void color_config_update(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr)
{
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
priv->color_space = frame_hdr->color_space;
priv->subsampling_x = frame_hdr->subsampling_x;
priv->subsampling_y = frame_hdr->subsampling_y;
}
static Vp9ParseResult vp9_parser_update(Vp9Parser* parser, Vp9FrameHdr* const frame_hdr)
{
if (key_or_intra_only(frame_hdr) || frame_hdr->error_resilient_mode) {
setup_past_independence(parser, frame_hdr);
}
color_config_update(parser, frame_hdr);
loop_filter_update(parser, &frame_hdr->loopfilter);
quantization_update(parser, frame_hdr);
segmentation_update(parser, frame_hdr);
reference_update(parser, frame_hdr);
return VP9_PARSER_OK;
}
static Vp9ParseResult vp9_color_config(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, BitReader* br)
{
if (frame_hdr->profile >= VP9_PROFILE_2) {
frame_hdr->bit_depth = vp9_read_bit(br) ? VP9_BITS_12 : VP9_BITS_10;
if (VP9_BITS_12 == frame_hdr->bit_depth) {
ERROR("vp9 12 bits-depth is unsupported by now!");
return VP9_PARSER_UNSUPPORTED;
}
}
else {
frame_hdr->bit_depth = VP9_BITS_8;
}
frame_hdr->color_space = (VP9_COLOR_SPACE)vp9_read_bits(br, 3);
if (frame_hdr->color_space != VP9_SRGB) {
vp9_read_bit(br); //color_range
if (frame_hdr->profile == VP9_PROFILE_1 || frame_hdr->profile == VP9_PROFILE_3) {
frame_hdr->subsampling_x = vp9_read_bit(br);
frame_hdr->subsampling_y = vp9_read_bit(br);
if (vp9_read_bit(br)) { //reserved_zero
ERROR("reserved bit");
return VP9_PARSER_ERROR;
}
}
else {
frame_hdr->subsampling_y = frame_hdr->subsampling_x = 1;
}
}
else {
ERROR("do not support SRGB");
return VP9_PARSER_UNSUPPORTED;
}
return VP9_PARSER_OK;
}
Vp9ParseResult
vp9_parse_frame_header(Vp9Parser* parser, Vp9FrameHdr* frame_hdr, const uint8_t* data, uint32_t size)
{
#define FRAME_CONTEXTS_BITS 2
Vp9ParserPrivate* priv = (Vp9ParserPrivate*)parser->priv;
BitReader bit_reader(data, size);
BitReader* br = &bit_reader;
memset(frame_hdr, 0, sizeof(*frame_hdr));
/* Uncompressed Data Chunk */
if (!verify_frame_marker(br))
goto error;
frame_hdr->profile = read_profile(br);
if (frame_hdr->profile > MAX_VP9_PROFILES)
goto error;
frame_hdr->show_existing_frame = vp9_read_bit(br);
if (frame_hdr->show_existing_frame) {
frame_hdr->frame_to_show = vp9_read_bits(br, VP9_REF_FRAMES_LOG2);
return VP9_PARSER_OK;
}
frame_hdr->frame_type = (VP9_FRAME_TYPE)vp9_read_bit(br);
frame_hdr->show_frame = vp9_read_bit(br);
frame_hdr->error_resilient_mode = vp9_read_bit(br);
if (frame_hdr->frame_type == VP9_KEY_FRAME) {
if (!verify_sync_code(br))
goto error;
if (vp9_color_config(parser, frame_hdr, br) != VP9_PARSER_OK)
goto error;
init_vp9_parser(parser, frame_hdr);
read_frame_size(br, &frame_hdr->width, &frame_hdr->height);
read_display_frame_size(frame_hdr, br);
}
else {
frame_hdr->intra_only = frame_hdr->show_frame ? 0 : vp9_read_bit(br);
frame_hdr->reset_frame_context = frame_hdr->error_resilient_mode ? 0 : vp9_read_bits(br, 2);
if (frame_hdr->intra_only) {
if (!verify_sync_code(br))
goto error;
if (frame_hdr->profile > VP9_PROFILE_0) {
if (vp9_color_config(parser, frame_hdr, br) != VP9_PARSER_OK)
goto error;
}
else {
frame_hdr->color_space = VP9_BT_601;
frame_hdr->subsampling_y = frame_hdr->subsampling_x = 1;
frame_hdr->bit_depth = VP9_BITS_8;
}
if (frame_hdr->bit_depth != parser->bit_depth) {
parser->bit_depth = frame_hdr->bit_depth;
init_dequantizer(parser);
}
frame_hdr->refresh_frame_flags = vp9_read_bits(br, VP9_REF_FRAMES);
read_frame_size(br, &frame_hdr->width, &frame_hdr->height);
read_display_frame_size(frame_hdr, br);
}
else {
int i;
//copy color config
frame_hdr->color_space = priv->color_space;
frame_hdr->subsampling_x = priv->subsampling_x;
frame_hdr->subsampling_y = priv->subsampling_y;
frame_hdr->refresh_frame_flags = vp9_read_bits(br, VP9_REF_FRAMES);
for (i = 0; i < VP9_REFS_PER_FRAME; i++) {
frame_hdr->ref_frame_indices[i] = vp9_read_bits(br, VP9_REF_FRAMES_LOG2);
frame_hdr->ref_frame_sign_bias[i] = vp9_read_bit(br);
}
read_frame_size_from_refs(parser, frame_hdr, br);
read_display_frame_size(frame_hdr, br);
frame_hdr->allow_high_precision_mv = vp9_read_bit(br);
frame_hdr->mcomp_filter_type = read_interp_filter(br);
}
}
if (!frame_hdr->error_resilient_mode) {
frame_hdr->refresh_frame_context = vp9_read_bit(br);
frame_hdr->frame_parallel_decoding_mode = vp9_read_bit(br);
}
else {
frame_hdr->frame_parallel_decoding_mode = TRUE;
}
frame_hdr->frame_context_idx = vp9_read_bits(br, FRAME_CONTEXTS_BITS);
read_loopfilter(&frame_hdr->loopfilter, br);
read_quantization(frame_hdr, br);
read_segmentation(&frame_hdr->segmentation, br);
if (!read_tile_info(frame_hdr, br))
goto error;
frame_hdr->first_partition_size = vp9_read_bits(br, 16);
if (!frame_hdr->first_partition_size)
goto error;
frame_hdr->frame_header_length_in_bytes = (br->getPos() + 7) / 8;
return vp9_parser_update(parser, frame_hdr);
error:
return VP9_PARSER_ERROR;
}
| 34.17768 | 154 | 0.653792 |
d89c9b95521a33dca025ff45cb1e46b31018c3f0 | 2,137 | cc | C++ | design-pattern/creational/factory_method.cc | curoky/my-own-x | 825273af2d73dff76562422ca87a077635ee870b | [
"Apache-2.0"
] | null | null | null | design-pattern/creational/factory_method.cc | curoky/my-own-x | 825273af2d73dff76562422ca87a077635ee870b | [
"Apache-2.0"
] | null | null | null | design-pattern/creational/factory_method.cc | curoky/my-own-x | 825273af2d73dff76562422ca87a077635ee870b | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2018-2022 curoky(cccuroky@gmail.com).
*
* This file is part of my-own-x.
* See https://github.com/curoky/my-own-x for further info.
*
* 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 <catch2/catch.hpp> // for SourceLineInfo, StringRef, TEST_CASE
#include <iostream> // for operator<<, endl, basic_ostream, cout, ostream
namespace {
class Interviewer {
public:
virtual void ask_questions() = 0;
virtual ~Interviewer() = default;
};
class Developer : public Interviewer {
public:
void ask_questions() override { std::cout << "Asking about design patterns!" << std::endl; }
};
class CommunityExecutive : public Interviewer {
public:
void ask_questions() override { std::cout << "Asking about community building" << std::endl; }
};
class HiringManager {
public:
void takeInterview() {
auto iv = make_interviewer();
iv->ask_questions();
delete iv;
}
virtual ~HiringManager() = default;
private:
virtual Interviewer* make_interviewer() = 0;
};
class DevelopmentManager : public HiringManager {
public:
Interviewer* make_interviewer() override { return new Developer(); }
};
class MarketingManager : public HiringManager {
public:
Interviewer* make_interviewer() override { return new CommunityExecutive(); }
};
} // namespace
TEST_CASE("", "[FactoryMethod]") {
auto dev_manager = new DevelopmentManager();
dev_manager->takeInterview(); // Output: Asking about design patterns
auto mk_manager = new MarketingManager();
mk_manager->takeInterview(); // Output: Asking about community building.
delete dev_manager;
delete mk_manager;
}
| 28.493333 | 96 | 0.718297 |
d89f410ee574765481e3a36294c4bdb915b9e62a | 2,261 | cpp | C++ | main.cpp | paramsingh/gameboy | b6e57d14e975975fb1cdb85634682918c54cdb43 | [
"MIT"
] | 31 | 2016-08-31T10:19:06.000Z | 2022-01-11T00:04:21.000Z | main.cpp | paramsingh/gameboy | b6e57d14e975975fb1cdb85634682918c54cdb43 | [
"MIT"
] | null | null | null | main.cpp | paramsingh/gameboy | b6e57d14e975975fb1cdb85634682918c54cdb43 | [
"MIT"
] | 18 | 2016-08-19T07:21:44.000Z | 2022-03-19T14:35:45.000Z | #include <bits/stdc++.h>
#include <SDL2/SDL.h>
using namespace std;
#include "cpu/cpu.hpp"
#include "cpu/cpu.cpp"
#include "ops/ops.hpp"
#include "ops/ops.cpp"
#include "gui/gui.hpp"
#include "gui/gui.cpp"
#include "gpu/gpu.hpp"
#include "gpu/gpu.cpp"
const int fps = 60;
const int ticks_per_frame = 1000 / 60;
// TODO: Get this stuff into a gameboy class maybe
cpu c;
gui screen;
gpu g(&c, &screen);
int flag = 0;
inline void execute_instruction() {
int extended = 0;
uint16_t opcode = c.read(c.pc);
if (flag == 1) {
printf("opcode = %02x, pc = %04x\n", opcode, c.pc);
}
// if opcode is 0xcb then we have to execute the next byte
// from the extended instruction set
if (opcode == 0xcb)
{
extended = 1;
opcode = c.read(c.pc + 1) + 0xff;
c.pc += 1;
}
int executed = inst_set[opcode].func(&c);
if (executed == 0)
{
if (extended)
printf("extended instruction\n");
c.status();
exit(0);
}
else if (executed == 1)
{
c.pc += inst_set[opcode].size;
//if (opcode == 0xf3)
//printf("size = %d\n", inst_set[opcode].size);
}
c.time += c.t;
if (c.pc == 0x0463) {
//flag = 1;
}
if (flag == 1)
{
printf("%04x %02x %s\n", c.pc, opcode,inst_set[opcode].name.c_str());
c.status();
getchar();
}
}
int fc = 0;
void emulate() {
//int max_cycles = 69905; // frequency of gameboy / 60
int cycles = 0;
execute_instruction();
if (c.pending_enable == 1 && c.read(c.pc - 1) != 0xfb)
{
c.interrupts_enabled = 1;
c.pending_enable = 0;
}
if (c.pending_disable == 1 && c.read(c.pc - 1) != 0xf3)
{
c.interrupts_enabled = 0;
c.pending_disable = 0;
}
g.step();
c.update_timers();
c.do_interrupts();
cycles += c.t;
fc++;
//printf("fc = %d\n", fc);
}
int main()
{
screen.init();
int quit = 0;
SDL_Event e;
//LTimer fps;
while (!quit)
{
while(SDL_PollEvent(&e) != 0)
{
//User requests quit
if(e.type == SDL_QUIT)
{
quit = 1;
}
}
emulate();
}
return 0;
}
| 21.330189 | 77 | 0.513047 |
d8a38e5258811eb165bc3e3898308603f0c05dfd | 174 | cpp | C++ | node2/src/init.cpp | eirikeve/ttk4155-byggern | 07f33b70ed5e02214705f81d2537371b538716eb | [
"MIT"
] | null | null | null | node2/src/init.cpp | eirikeve/ttk4155-byggern | 07f33b70ed5e02214705f81d2537371b538716eb | [
"MIT"
] | null | null | null | node2/src/init.cpp | eirikeve/ttk4155-byggern | 07f33b70ed5e02214705f81d2537371b538716eb | [
"MIT"
] | null | null | null | #include "../include/init.h"
// void init() {
// init_timer();
// init_uart();
// can_init();
// ADC_internal& adc_internal = ADC_internal::getInstance();
// } | 19.333333 | 64 | 0.58046 |
d8a4014bf20f395ce43b7168392b63d604bc2586 | 346 | cpp | C++ | C++/sum-of-digits-in-the-minimum-number.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/sum-of-digits-in-the-minimum-number.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/sum-of-digits-in-the-minimum-number.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n * l), l is the max length of numbers
// Space: O(l)
class Solution {
public:
int sumOfDigits(vector<int>& A) {
int min_num = *min_element(A.begin(),A.end());
int total = 0;
while (min_num) {
total += min_num % 10;
min_num /= 10;
}
return total % 2 == 0;
}
};
| 21.625 | 54 | 0.488439 |
d8ad75d32fe936031a6c65bbb6bc7d6318b204cc | 4,244 | cpp | C++ | src/platform/lpc17xx/power.cpp | wangyanjunmsn/vi-firmware | a5940ab6c773457d4c41e80273ae0ce327164d60 | [
"BSD-3-Clause"
] | 148 | 2015-01-01T18:32:25.000Z | 2022-03-05T12:02:24.000Z | src/platform/lpc17xx/power.cpp | wangyanjunmsn/vi-firmware | a5940ab6c773457d4c41e80273ae0ce327164d60 | [
"BSD-3-Clause"
] | 109 | 2015-02-11T16:33:49.000Z | 2021-01-04T16:14:00.000Z | src/platform/lpc17xx/power.cpp | wangyanjunmsn/vi-firmware | a5940ab6c773457d4c41e80273ae0ce327164d60 | [
"BSD-3-Clause"
] | 89 | 2015-02-04T00:39:29.000Z | 2021-10-03T00:01:17.000Z | #include "power.h"
#include "util/log.h"
#include "gpio.h"
#include "lpc17xx_pinsel.h"
#include "lpc17xx_clkpwr.h"
#include "lpc17xx_wdt.h"
#define POWER_CONTROL_PORT 2
#define POWER_CONTROL_PIN 13
#define PROGRAM_BUTTON_PORT 2
#define PROGRAM_BUTTON_PIN 12
namespace gpio = openxc::gpio;
using openxc::gpio::GPIO_VALUE_HIGH;
using openxc::gpio::GPIO_VALUE_LOW;
using openxc::gpio::GPIO_DIRECTION_OUTPUT;
using openxc::util::log::debug;
const uint32_t DISABLED_PERIPHERALS[] = {
CLKPWR_PCONP_PCTIM0,
CLKPWR_PCONP_PCTIM1,
CLKPWR_PCONP_PCSPI,
CLKPWR_PCONP_PCI2C0,
CLKPWR_PCONP_PCRTC,
CLKPWR_PCONP_PCSSP1,
CLKPWR_PCONP_PCI2C1,
CLKPWR_PCONP_PCSSP0,
CLKPWR_PCONP_PCI2C2,
};
void setPowerPassthroughStatus(bool enabled) {
int pinStatus;
debug("Switching 12v power passthrough ");
if(enabled) {
debug("on");
pinStatus = 0;
} else {
debug("off");
pinStatus = 1;
}
gpio::setValue(POWER_CONTROL_PORT, POWER_CONTROL_PIN,
pinStatus ? GPIO_VALUE_HIGH : GPIO_VALUE_LOW);
}
void openxc::power::initialize() {
// Configure 12v passthrough control as a digital output
PINSEL_CFG_Type powerPassthroughPinConfig;
powerPassthroughPinConfig.OpenDrain = 0;
powerPassthroughPinConfig.Pinmode = 1;
powerPassthroughPinConfig.Funcnum = 0;
powerPassthroughPinConfig.Portnum = POWER_CONTROL_PORT;
powerPassthroughPinConfig.Pinnum = POWER_CONTROL_PIN;
PINSEL_ConfigPin(&powerPassthroughPinConfig);
gpio::setDirection(POWER_CONTROL_PORT, POWER_CONTROL_PIN, GPIO_DIRECTION_OUTPUT);
setPowerPassthroughStatus(true);
debug("Turning off unused peripherals");
for(unsigned int i = 0; i < sizeof(DISABLED_PERIPHERALS) /
sizeof(DISABLED_PERIPHERALS[0]); i++) {
CLKPWR_ConfigPPWR(DISABLED_PERIPHERALS[i], DISABLE);
}
PINSEL_CFG_Type programButtonPinConfig;
programButtonPinConfig.OpenDrain = 0;
programButtonPinConfig.Pinmode = 1;
programButtonPinConfig.Funcnum = 1;
programButtonPinConfig.Portnum = PROGRAM_BUTTON_PORT;
programButtonPinConfig.Pinnum = PROGRAM_BUTTON_PIN;
PINSEL_ConfigPin(&programButtonPinConfig);
}
void openxc::power::handleWake() {
// This isn't especially graceful, we just reset the device after a
// wakeup. Then again, it makes the code a hell of a lot simpler because we
// only have to worry about initialization of core peripherals in one spot,
// setup() in vi_firmware.cpp and main.cpp. I'll leave this for now and we
// can revisit it if there is some reason we need to keep state between CAN
// wakeup events (e.g. fine_odometer_since_restart could be more persistant,
// but then it actually might be more confusing since it'd be
// fine_odometer_since_we_lost_power)
NVIC_SystemReset();
}
void openxc::power::suspend() {
debug("Going to low power mode");
NVIC_EnableIRQ(CANActivity_IRQn);
NVIC_EnableIRQ(EINT2_IRQn);
setPowerPassthroughStatus(false);
// Disable brown-out detection when we go into lower power
LPC_SC->PCON |= (1 << 2);
// TODO do we need to disable and disconnect the main PLL0 before ending
// deep sleep, accoridn gto errata lpc1768-16.march2010? it's in some
// example code from NXP.
CLKPWR_DeepSleep();
}
void openxc::power::enableWatchdogTimer(int microseconds) {
WDT_Init(WDT_CLKSRC_IRC, WDT_MODE_RESET);
WDT_Start(microseconds);
}
void openxc::power::disableWatchdogTimer() {
// TODO this is nuts, but you can't change the WDMOD register until after
// the WDT times out. But...we are using a RESET with the WDT, so the whole
// board will reset and then we don't have any idea if the WDT should be
// disabled or not! This makes it really difficult to use the WDT for both
// normal runtime hard freeze protection and periodic wakeup from sleep (to
// check if CAN is active via OBD-II). I have to disable the regular WDT for
// now for this reason.
LPC_WDT->WDMOD = 0x0;
}
void openxc::power::feedWatchdog() {
WDT_Feed();
}
extern "C" {
void CANActivity_IRQHandler(void) {
openxc::power::handleWake();
}
void EINT2_IRQHandler(void) {
openxc::power::handleWake();
}
}
| 31.671642 | 85 | 0.723139 |
d8ad9b57ba96684e2d202bffd040cf4b8cd25d22 | 2,228 | cpp | C++ | src/time.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/time.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/time.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | //
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 06 Jun 2011 Brian Frank Creation
// 19 Aug 2014 Radu Racariu<radur@2inn.com> Ported to C++
//
#include "time.hpp"
#include <sstream>
#include <ctime>
////////////////////////////////////////////////
// Time
////////////////////////////////////////////////
using namespace haystack;
////////////////////////////////////////////////
// to zinc
////////////////////////////////////////////////
// Encode as "hh:mm:ss.FFF"
const std::string Time::to_zinc() const
{
std::stringstream os;
if (hour < 10) os << '0'; os << hour << ':';
if (minutes < 10) os << '0'; os << minutes << ':';
if (sec < 10) os << '0'; os << sec;
if (ms != 0)
{
os << '.';
if (ms < 10) os << '0';
if (ms < 100) os << '0';
os << ms;
}
return os.str();
}
const Time& Time::MIDNIGHT = *new Time(0, 0, 0);
////////////////////////////////////////////////
// Equal
////////////////////////////////////////////////
bool Time::operator ==(const Time &other) const
{
return (hour == other.hour && minutes == other.minutes && sec == other.sec && ms == other.ms);
}
bool Time::operator==(const Val &other) const
{
if (type() != other.type())
return false;
return *this == static_cast<const Time&>(other);
}
////////////////////////////////////////////////
// Comparators
////////////////////////////////////////////////
bool Time::operator <(const Val &other) const
{
return type() == other.type() && compareTo(((Time&)other)) < 0;
}
bool Time::operator >(const Val &other) const
{
return type() == other.type() && compareTo(((Time&)other)) > 0;
}
Time::auto_ptr_t Time::clone() const
{
return auto_ptr_t(new Time(*this));
}
int Time::compareTo(const Time &other) const
{
if (hour < other.hour) return -1; else if (hour > other.hour) return 1;
if (minutes < other.minutes) return -1; else if (minutes > other.minutes) return 1;
if (sec < other.sec) return -1; else if (sec > other.sec) return 1;
if (ms < other.ms) return -1; else if (ms > other.ms) return 1;
return 0;
}
| 26.211765 | 98 | 0.480251 |
d8b3a99a7dacc8d1ee20bd5a58d8d53b7dd355e3 | 40,105 | cpp | C++ | geometrictools/utils/image_cpu.cpp | eth-sri/transformation-smoothing | 12a653e881a6d61c5c63a3e16d58292435486cbd | [
"Apache-2.0"
] | 3 | 2020-11-07T18:12:50.000Z | 2021-06-11T22:56:09.000Z | geometrictools/utils/image_cpu.cpp | eth-sri/transformation-smoothing | 12a653e881a6d61c5c63a3e16d58292435486cbd | [
"Apache-2.0"
] | null | null | null | geometrictools/utils/image_cpu.cpp | eth-sri/transformation-smoothing | 12a653e881a6d61c5c63a3e16d58292435486cbd | [
"Apache-2.0"
] | null | null | null | #include "image.h"
#include "image_cpu.h"
#include "transforms/interpolation.h"
#include "utils/utilities.h"
using namespace std;
Interval roundIntervalToInt(const Interval& i) {
Interval in = i.meet({0, 1});
float inf = in.inf * 255.0f;
int inf_lower = floorf(inf);
if (inf_lower == roundf(inf)) {
inf = pixelVals[inf_lower];
} else {
inf = pixelVals[min(255, inf_lower + 1)];
}
float sup = in.sup * 255.0f;
int sup_lower = floorf(sup);
if (sup_lower == roundf(sup)) {
sup = pixelVals[sup_lower];
} else {
sup = pixelVals[min(255, sup_lower + 1)];
}
assert(inf <= sup);
return {inf, sup};
}
/*** constuctors and friends ***/
//empty
ImageImpl::ImageImpl() {};
// from torch
// ImageImpl(const torch::Tensor &img) {
// assert(img.dim() == 3);
// this->nRows = img.size(1);
// this->nCols = img.size(2);
// this->nChannels = img.size(0);
// const size_t s = nRows * nCols * nChannels;
// auto acc = img.accessor<float, 3>();
// this->a = new Interval[s];
// float _min = 0;
// float _max = 0;
// for(size_t i = 0; i < nRows; ++i)
// for(size_t j = 0; j < nCols; ++j)
// for(size_t k = 0; k < nChannels; ++k)
// {
// const size_t m = rcc_to_idx(i, j, k);
// const float v = acc[k][i][j];
// a[m] = {v, v};
// _min = min(_min, v);
// _max = max(_max, v);
// }
// cout << _min << " " << _max << endl;
// }
//from numpy
ImageImpl::ImageImpl(PyArrayObject* np) {
int dims = PyArray_NDIM(np);
assert(dims == 2 || dims == 3);
this->nRows = PyArray_DIM(np, 0);
this->nCols = PyArray_DIM(np, 1);
if (dims == 2) {
this->nChannels = 1;
} else {
this->nChannels = PyArray_DIM(np, 2);
}
int image_typ = PyArray_TYPE(np);
if (image_typ == NPY_UINT8) {
const size_t s = nRows * nCols * nChannels;
uint8_t* acc = (uint8_t*)PyArray_DATA(np);
this->a = new Interval[s];
for(size_t i = 0; i < nRows; ++i)
for(size_t j = 0; j < nCols; ++j)
for(size_t k = 0; k < nChannels; ++k)
{
const uint8_t v = acc[i * nCols * nChannels + j * nChannels + k ];
const float vv = v / 255.0f;
const size_t m = rcc_to_idx(i, j, k);
a[m] = {vv, vv};
}
} else if (image_typ == NPY_FLOAT32) {
const size_t s = nRows * nCols * nChannels;
float* acc = (float*)PyArray_DATA(np);
this->a = new Interval[s];
for(size_t i = 0; i < nRows; ++i)
for(size_t j = 0; j < nCols; ++j)
for(size_t k = 0; k < nChannels; ++k)
{
const float v = acc[i * nCols * nChannels + j * nChannels + k ];
assert(v >= 0.0f);
assert(v <= 255.0f);
const size_t m = rcc_to_idx(i, j, k);
a[m] = {v, v};
}
} else {
assert(false);
}
}
//copy
ImageImpl::ImageImpl(const ImageImpl &other) {
this->nRows = other.nRows;
this->nCols = other.nCols;
this->nChannels = other.nChannels;
const size_t s = nRows * nCols * nChannels;
this->a = new Interval[s];
for(size_t i = 0; i < s; ++i)
a[i] = other.a[i];
}
//empty fixed size
ImageImpl::ImageImpl(size_t nRows, size_t nCols, size_t nChannels) {
this->nRows = nRows;
this->nCols = nCols;
this->nChannels = nChannels;
this->a = new Interval[nRows * nCols * nChannels];
}
// from string
ImageImpl::ImageImpl(size_t nRows, size_t nCols, size_t nChannels, string line) {
this->nRows = nRows;
this->nCols = nCols;
this->nChannels = nChannels;
this->a = new Interval[nRows * nCols * nChannels];
string curr = "";
// Label of the image is the first digit
size_t offset = 0;
while (line[offset] != ',') {
curr += line[offset++];
}
// we currently don't need this
// this->label = stoi(curr);
curr = "";
// ImageImpl
vector<Interval> its;
for (size_t i = offset+1; i < line.size(); ++i) {
if (line[i] == ',') {
its.push_back({stof(curr), stof(curr)});
curr = "";
} else {
curr += line[i];
}
}
its.push_back({stof(curr), stof(curr)});
assert((size_t)its.size() == nRows * nCols * nChannels);
size_t nxt = 0;
for (size_t r = 0; r < nRows; ++r) {
for (size_t c = 0; c < nCols; ++c) {
for (size_t i = 0; i < nChannels; ++i) {
this->a[rcc_to_idx(r, c, i)] = its[nxt++];
}
}
}
}
// assignment
ImageImpl& ImageImpl::operator = (const ImageImpl &other)
{
this->nRows = other.nRows;
this->nCols = other.nCols;
this->nChannels = other.nChannels;
const size_t s = nRows * nCols * nChannels;
// delete old pointer before changing to prevent memory leak
if (this->a != 0)
{
delete[] this->a;
this->a = 0;
}
this->a = new Interval[s];
for(size_t i = 0; i < s; ++i)
a[i] = other.a[i];
return *this;
}
// destructor
ImageImpl::~ImageImpl() {
if (this->a != 0)
{
delete[] this->a;
this->a = 0;
}
};
/*** other ***/
ImageImpl* ImageImpl::operator + (const ImageImpl& other) const {
assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels);
ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
ret->a[m] = a[m] + other.a[m];
}
}
}
return ret;
}
ImageImpl* ImageImpl::operator | (const ImageImpl& other) const {
assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels);
ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
if (a[m].inf > 0 || other.a[m].inf > 0)
ret->a[m] = {1, 1};
else
ret->a[m] = {0, 0};
}
}
}
return ret;
}
ImageImpl* ImageImpl::operator & (const ImageImpl& other) const {
assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels);
ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
if (a[m].inf > 0 && other.a[m].inf > 0)
ret->a[m] = {1, 1};
else
ret->a[m] = {0, 0};
}
}
}
return ret;
}
ImageImpl* ImageImpl::operator - (const ImageImpl& other) const {
assert(nRows==other.nRows && nCols==other.nCols && nChannels==other.nChannels);
ImageImpl *ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
ret->a[m] = a[m] - other.a[m];
}
}
}
return ret;
}
// Remark: works for even and odd image sizes
Interval ImageImpl::valueAt(int x, int y, size_t i, Interval default_value) const {
assert(unsigned(x % 2) != nCols % 2 && unsigned(y % 2) != nRows % 2 && "Off grid coordinates");
const int c = (x + (nCols - 1)) / 2;
const int r = (y + (nRows - 1)) / 2;
if (r < 0 || r >= signed(nRows) || c < 0 || c >= signed(nCols)) {
return default_value;
}
size_t m = rcc_to_idx(r, c, i);
assert(a != 0);
return a[m];
}
Interval ImageImpl::valueAt(int x, int y, size_t i) const {
return valueAt(x, y, i, {0, 0});
}
// Input:
// 0 <= r <= nRows - 1
// 0 <= c <= nCols - 1
// Output: coordinates on the odd integer grid
//
// Remark: works for even and odd image sizes
Coordinate<float> ImageImpl::getCoordinate(float r, float c, size_t channel) const {
return {2 * c - (nCols - 1), 2 * r - (nRows - 1), channel};
}
// Coordinate to rcc inex
std::tuple<int, int> ImageImpl::getRc(float x, float y) const {
int c = int(int(x + (nCols - 1)) / 2);
int r = int(int(y + (nRows - 1)) / 2);
return {r, c};
}
float ImageImpl::l2norm() const {
Interval sum_squared(0,0);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
sum_squared += a[m].square();
}
}
}
return sqrt(sum_squared.sup);
}
std::tuple<float, float, float> ImageImpl::l2norm_channelwise() const {
Interval sum_squared_0(0,0), sum_squared_1(0,0), sum_squared_2(0,0);
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
sum_squared_0 += a[rcc_to_idx(i, j, 0)].square();
sum_squared_1 += a[rcc_to_idx(i, j, 1)].square();
sum_squared_2 += a[rcc_to_idx(i, j, 2)].square();
}
}
return {sqrt(sum_squared_0.sup), sqrt(sum_squared_1.sup), sqrt(sum_squared_2.sup)};
}
float* ImageImpl::getFilter(float sigma, size_t filter_size) const {
const size_t c = filter_size / 2;
// use symmetry to only store 1 quarter of the filter
float *G = new float[(c+1) * (c+1)];
getGaussianFilter(G, filter_size, sigma);
return G;
}
void ImageImpl::delFilter(float *f) const {
if (f != 0)
delete[] f;
}
void ImageImpl::rect_vignetting(size_t filter_size) {
for (size_t chan = 0; chan < nChannels; ++chan) {
for (size_t i = 0; i < min(nRows, filter_size); ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, chan);
a[m] = {0, 0};
}
}
for (size_t i = max(nRows-filter_size, (size_t)0); i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, chan);
a[m] = {0, 0};
}
}
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < min(nCols, filter_size); ++j) {
size_t m = rcc_to_idx(i, j, chan);
a[m] = {0, 0};
}
for (size_t j = max(nRows-filter_size, (size_t)0); j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, chan);
a[m] = {0, 0};
}
}
}
}
ImageImpl* ImageImpl::filter_vignetting(const float* filter, size_t filter_size, float radiusDecrease) const {
assert(nRows == nCols);
assert(filter_size % 2 == 1); // odd filter so we can correctly center it
const size_t c = filter_size / 2;
const bool do_radius = radiusDecrease >= 0;
const bool do_filter = filter != 0;
const float radius = do_radius ? min(nRows, nCols) - 1 - 2 * radiusDecrease : numeric_limits<float>::infinity();
const float radiusSq = radius*radius;
ImageImpl *ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t chan = 0; chan < nChannels; ++chan) {
for (size_t row = 0; row < nRows; ++row){
for (size_t col = 0; col < nCols; ++col) {
const int x = 2 * col - (nCols - 1);
const int y = 2 * row - (nRows - 1);
//cout << do_filter << " " << x << " " << y << endl;
if(x*x + y*y <= radiusSq) {
if (do_filter) {
Interval out = {0, 0};
for (int i = -c; i <= signed(c); ++i)
for (int j = -c; j <= signed(c); ++j) {
const int r_ = row + i;
const int c_ = col + j;
const int x_ = 2 * c_ - (nCols - 1);
const int y_ = 2 * r_ - (nRows - 1);
//cout << "a" << endl << flush;
//cout << x_*x_ << " " << y_*y_ << " " << radiusSq << endl;
if (r_ > 0 && r_ < signed(nRows) && c_ > 0 && c_ < signed(nCols)
&& (x_*x_ + y_*y_ <= radiusSq)
) {
out += filter[abs(i) * (c+1) + abs(j)] * this->a[rcc_to_idx(r_, c_, chan)];
}
}
ret->a[rcc_to_idx(row, col, chan)] = out;
} else {
ret->a[rcc_to_idx(row, col, chan)] = a[rcc_to_idx(row, col, chan)];
}
} else {
ret->a[rcc_to_idx(row, col, chan)] = {0,0};
}
//cout << rcc_to_idx(row, col, chan) << " " << ret->a[rcc_to_idx(row, col, chan)] << endl;
}
}
}
return ret;
}
void ImageImpl::saveBMP(string fn, bool inf) const {
assert(nChannels == 1 || nChannels == 3);
// based on https://stackoverflow.com/a/18675807
unsigned char file[14] = {
'B','M', // magic
0,0,0,0, // size in bytes
0,0, // app data
0,0, // app data
40+14,0,0,0 // start of data offset
};
unsigned char info[40] = {
40,0,0,0, // info hd size
0,0,0,0, // width
0,0,0,0, // heigth
1,0, // number color planes
24,0, // bits per pixel
0,0,0,0, // compression is none
0,0,0,0, // image bits size
0x13,0x0B,0,0, // horz resoluition in pixel / m
0x13,0x0B,0,0, // vert resolutions (0x03C3 = 96 dpi, 0x0B13 = 72 dpi)
0,0,0,0, // #colors in pallete
0,0,0,0, // #important colors
};
const size_t w = nCols;
const size_t h = nRows;
int padSize = (4-(w*3)%4)%4;
int sizeData = w*h*3 + h*padSize;
int sizeAll = sizeData + sizeof(file) + sizeof(info);
file[ 2] = (unsigned char)( sizeAll );
file[ 3] = (unsigned char)( sizeAll>> 8);
file[ 4] = (unsigned char)( sizeAll>>16);
file[ 5] = (unsigned char)( sizeAll>>24);
info[ 4] = (unsigned char)( w );
info[ 5] = (unsigned char)( w>> 8);
info[ 6] = (unsigned char)( w>>16);
info[ 7] = (unsigned char)( w>>24);
info[ 8] = (unsigned char)( h );
info[ 9] = (unsigned char)( h>> 8);
info[10] = (unsigned char)( h>>16);
info[11] = (unsigned char)( h>>24);
info[20] = (unsigned char)( sizeData );
info[21] = (unsigned char)( sizeData>> 8);
info[22] = (unsigned char)( sizeData>>16);
info[23] = (unsigned char)( sizeData>>24);
ofstream stream;
stream.open (fn);
stream.write( (char*)file, sizeof(file) );
stream.write( (char*)info, sizeof(info) );
unsigned char pad[3] = {0,0,0};
for(size_t i = 0; i < h; i++) {
size_t k = h-1-i;
for(size_t j = 0; j < w; j++ ) {
unsigned char pixel[3];
if (nChannels == 3) {
if (inf) {
assert( 0 <= a[rcc_to_idx(k, j, 0)].inf && a[rcc_to_idx(k, j, 0)].inf <= 1 );
assert( 0 <= a[rcc_to_idx(k, j, 1)].inf && a[rcc_to_idx(k, j, 1)].inf <= 1 );
assert( 0 <= a[rcc_to_idx(k, j, 2)].inf && a[rcc_to_idx(k, j, 2)].inf <= 1 );
pixel[2] = (unsigned char) round(a[rcc_to_idx(k, j, 0)].inf * 255);
pixel[1] = (unsigned char) round(a[rcc_to_idx(k, j, 1)].inf * 255);
pixel[0] = (unsigned char) round(a[rcc_to_idx(k, j, 2)].inf * 255);
} else {
assert( 0 <= a[rcc_to_idx(k, j, 0)].sup && a[rcc_to_idx(k, j, 0)].sup <= 1 );
assert( 0 <= a[rcc_to_idx(k, j, 1)].sup && a[rcc_to_idx(k, j, 1)].sup <= 1 );
assert( 0 <= a[rcc_to_idx(k, j, 2)].sup && a[rcc_to_idx(k, j, 2)].sup <= 1 );
pixel[2] = (unsigned char) round(a[rcc_to_idx(k, j, 0)].sup * 255);
pixel[1] = (unsigned char) round(a[rcc_to_idx(k, j, 1)].sup * 255);
pixel[0] = (unsigned char) round(a[rcc_to_idx(k, j, 2)].sup * 255);
}
} else {
size_t m = rcc_to_idx(k, j, 0);
if (inf) {
if (!(0 <= a[rcc_to_idx(k, j, 0)].inf && a[rcc_to_idx(k, j, 0)].inf <= 1)) {
cout << k << " " << j << " " << a[rcc_to_idx(k, j, 0)].inf << endl;
}
assert( 0 <= a[rcc_to_idx(k, j, 0)].inf && a[rcc_to_idx(k, j, 0)].inf <= 1 );
pixel[2] = (unsigned char) round(a[m].inf * 255);
pixel[1] = (unsigned char) round(a[m].inf * 255);
pixel[0] = (unsigned char) round(a[m].inf * 255);
} else {
if (!(0 <= a[rcc_to_idx(k, j, 0)].sup && a[rcc_to_idx(k, j, 0)].sup <= 1)) {
cout << k << " " << j << " " << a[rcc_to_idx(k, j, 0)].sup << endl;
}
assert( 0 <= a[rcc_to_idx(k, j, 0)].sup && a[rcc_to_idx(k, j, 0)].sup <= 1 );
pixel[2] = (unsigned char) round(a[m].sup * 255);
pixel[1] = (unsigned char) round(a[m].sup * 255);
pixel[0] = (unsigned char) round(a[m].sup * 255);
}
}
stream.write((char*)pixel, 3);
}
stream.write((char*)pad, padSize);
}
}
void ImageImpl::zero() {
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
a[m] = {0,0};
}
}
}
}
void ImageImpl::roundToInt() {
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
if (!a[m].is_empty()) {
cout << m << endl;
a[m] = roundIntervalToInt(a[m]);
}
}
}
}
}
void ImageImpl::clip(const float min_val, const float max_val) {
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
if (!a[m].is_empty()) {
a[m] = {min(max(min_val, a[m].inf), max_val), min(max(min_val, a[m].sup), max_val)};
}
}
}
}
}
ImageImpl* ImageImpl::threshold(const float val) {
ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
if (!a[m].is_empty() && a[m].inf >= val) {
ret->a[m] = {1, 1};
} else {
ret->a[m] = {0, 0};
}
}
}
}
return ret;
}
ImageImpl* ImageImpl::center_crop(const size_t size) const {
assert(size % 2 == 0);
assert(this->nCols % 2 == 0);
assert(this->nRows % 2 == 0);
assert(this->nCols >= size);
assert(this->nRows >= size);
const size_t diffCols = this->nCols - size;
const size_t diffRows = this->nRows - size;
ImageImpl *ret = new ImageImpl(size, size, this->nChannels);
for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) {
for (size_t nRow = 0; nRow < size; ++nRow) {
for (size_t nCol = 0; nCol < size; ++nCol) {
const size_t r = nRow + diffRows / 2;
const size_t c = nCol + diffCols / 2;
const size_t m = ret->rcc_to_idx(nRow, nCol, nChannel);
const size_t n = this->rcc_to_idx(r, c, nChannel);
//cout << m << " " << n << endl;
ret->a[m] = this->a[n];
}
}
}
// cout << " not here" << endl;
return ret;
}
ImageImpl* ImageImpl::resize(const size_t new_nRows, const size_t new_nCols, const bool roundToInt) const {
ImageImpl *ret = new ImageImpl(new_nRows, new_nCols, this->nChannels);
for (size_t nChannel = 0; nChannel < ret->nChannels; ++nChannel) {
for (size_t nRow = 0; nRow < ret->nRows; ++nRow) {
for (size_t nCol = 0; nCol < ret->nCols; ++nCol) {
Coordinate<float> new_coord = getCoordinate(nRow * this->nRows / (float) ret->nRows,
nCol * this->nCols / (float) ret->nCols,
nChannel);
size_t m = ret->rcc_to_idx(nRow, nCol, nChannel);
Interval out = BilinearInterpolation(new_coord, *this);
if (roundToInt) {
out = roundIntervalToInt(out);
}
ret->a[m] = out;
//cout << m << " "<< nRow << " " << nCol << " " << nChannel<< " " << ret->a[m] << endl;
}
}
}
return ret;
}
ImageImpl* ImageImpl::resize(const size_t new_nRows, const size_t new_nCols, const bool roundToInt, const size_t size) const {
assert(size % 2 == 0);
//assert(this->nCols % 2 == 0);
//assert(this->nRows % 2 == 0);
assert(new_nRows >= size);
assert(new_nCols >= size);
const size_t diffCols = new_nCols - size;
const size_t diffRows = new_nRows - size;
ImageImpl *ret = new ImageImpl(size, size, this->nChannels);
for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) {
for (size_t nRow = 0; nRow < size; ++nRow) {
for (size_t nCol = 0; nCol < size; ++nCol) {
const size_t r = nRow + diffRows / 2;
const size_t c = nCol + diffCols / 2;
const size_t m = ret->rcc_to_idx(nRow, nCol, nChannel);
Coordinate<float> new_coord = getCoordinate(r * this->nRows / (float) new_nRows,
c * this->nCols / (float) new_nCols,
nChannel);
Interval out = BilinearInterpolation(new_coord, *this);
if (roundToInt) {
out = roundIntervalToInt(out);
}
ret->a[m] = out;
}
}
}
return ret;
}
vector<ImageImpl*> ImageImpl::split_color_channels() const {
vector<ImageImpl*> channels(nChannels);
if (nChannels == 1) {
channels[0] = new ImageImpl(*this);
} else {
for (size_t nChannel = 0; nChannel < nChannels; ++nChannel) {
ImageImpl *im = new ImageImpl(nRows, nCols, 1);
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = im->rcc_to_idx(i, j, 0);
size_t n = rcc_to_idx(i, j, nChannel);
im->a[m] = a[n];
}
}
channels[nChannel] = im;
}
}
return channels;
}
ImageImpl* ImageImpl::customVingette(const ImageImpl* vingette) const {
ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels);
assert(vingette->nRows == nRows);
assert(vingette->nCols == nCols);
assert(vingette->nChannels == nChannels);
for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) {
for (size_t nRow = 0; nRow < this->nRows; ++nRow) {
for (size_t nCol = 0; nCol < this->nCols; ++nCol) {
const size_t m = rcc_to_idx(nRow, nCol, nChannel);
if (vingette->a[m].sup == 0)
ret->a[m] = a[m];
else
ret->a[m] = {0, 0};
}
}
}
return ret;
};
ImageImpl* ImageImpl::widthVingette(const ImageImpl* vingette, const float treshold) const {
ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels);
assert(vingette->nRows == nRows);
assert(vingette->nCols == nCols);
assert(vingette->nChannels == nChannels);
for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) {
for (size_t nRow = 0; nRow < this->nRows; ++nRow) {
for (size_t nCol = 0; nCol < this->nCols; ++nCol) {
const size_t m = rcc_to_idx(nRow, nCol, nChannel);
if ((vingette->a[m].sup - vingette->a[m].inf) <= treshold)
ret->a[m] = a[m];
else
ret->a[m] = {0, 0};
}
}
}
return ret;
};
ImageImpl* ImageImpl::transform(std::function<Coordinate<Interval>(const Coordinate<float>)> T,
const bool roundToInt) const {
ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels);
for (size_t nChannel = 0; nChannel < this->nChannels; ++nChannel) {
for (size_t nRow = 0; nRow < this->nRows; ++nRow) {
for (size_t nCol = 0; nCol < this->nCols; ++nCol) {
Interval out = BilinearInterpolation(T(this->getCoordinate(nRow, nCol, nChannel)), *this);
if (roundToInt) {
out = roundIntervalToInt(out);
}
ret->a[ret->rcc_to_idx(nRow, nCol, nChannel)] = out;
}
}
}
return ret;
};
ImageImpl* ImageImpl::rotate(const Interval& params, const bool roundToInt) const {
auto T = [&](const Coordinate<float> it) -> Coordinate<Interval>{
return Rotation(it, params);
};
return transform(T, roundToInt);
};
ImageImpl* ImageImpl::translate(const Interval& dx, const Interval& dy, const bool roundToInt) const {
auto T = [&](const Coordinate<float> it) -> Coordinate<Interval>{
return Translation(it, dx, dy);
};
return transform(T, roundToInt);
};
vector<float> ImageImpl::bilinear_coefficients(int x_iter, int y_iter, float x, float y) const {
assert(x_iter <= x && x <= x_iter + 2 && y_iter <= y && y <= y_iter + 2);
float a_alpha = (x_iter + 2 - x) * (y_iter + 2 - y) / 4;
float a_beta = (x_iter + 2 - x) * (y - y_iter) / 4;
float a_gamma = (x - x_iter) * (y_iter + 2 - y) / 4;
float a_delta = (x - x_iter) * (y - y_iter) / 4;
return {a_alpha, a_beta, a_gamma, a_delta};
}
bool ImageImpl::inverseRot(ImageImpl** out_ret,
ImageImpl** out_vingette,
const Interval gamma,
const size_t refinements,
const bool addIntegerError,
const bool toIntegerValues,
const bool computeVingette) const {
auto T = [&](Coordinate<Interval> coord){
Coordinate<Interval> coord_out = Rotation(coord, gamma);
return coord_out;
};
auto Tinv = [&](Coordinate<Interval> coord){
Coordinate<Interval> coord_out = Rotation(coord, -gamma);
return coord_out;
};
assert(out_ret != 0);
if(computeVingette) assert(out_vingette != 0);
bool isEmpty = inverse(out_ret,
out_vingette,
T,
Tinv,
addIntegerError,
toIntegerValues,
refinements,
computeVingette);
assert(out_ret != 0);
assert(*out_ret != 0);
if(computeVingette) {
assert(out_vingette != 0);
assert(*out_vingette != 0);
}
return isEmpty;
}
bool ImageImpl::inverseTranslation(ImageImpl** out_ret,
ImageImpl** out_vingette,
const Interval dx,
const Interval dy,
const size_t refinements,
const bool addIntegerError,
const bool toIntegerValues,
const bool computeVingette) const {
auto T = [&](Coordinate<Interval> coord){
Coordinate<Interval> coord_out = Translation(coord, dx, dy);
return coord_out;
};
auto Tinv = [&](Coordinate<Interval> coord){
Coordinate<Interval> coord_out = Translation(coord, -dx, -dy);
return coord_out;
};
assert(out_ret != 0);
if(computeVingette) assert(out_vingette != 0);
bool isEmpty = inverse(out_ret,
out_vingette,
T,
Tinv,
addIntegerError,
toIntegerValues,
refinements,
computeVingette);
assert(out_ret != 0);
assert(*out_ret != 0);
if(computeVingette) {
assert(out_vingette != 0);
assert(*out_vingette != 0);
}
return isEmpty;
}
ostream& operator<<(ostream& os, const ImageImpl& img)
{
for (size_t k = 0; k < img.nChannels; ++k) {
os << "Channel " << k << ":" << endl;
for (size_t i = 0; i < img.nRows; ++i) {
for (size_t j = 0; j < img.nCols; ++j) {
size_t m = img.rcc_to_idx(i, j, k);
os << img.a[m] << " ";
}
os << endl;
}
os << endl;
}
return os;
}
bool ImageImpl::inverse(ImageImpl **out,
ImageImpl **vingette,
const std::function<Coordinate<Interval>(Coordinate<Interval>)> T,
const std::function<Coordinate<Interval>(Coordinate<Interval>)> invT,
const bool addIntegerError,
const bool toIntegerValues,
const size_t nrRefinements,
const bool computeVingette) const {
ImageImpl *ret = new ImageImpl(this->nRows, this->nCols, this->nChannels);
ImageImpl *constraints = 0;
bool isEmpty = false;
assert(out != 0);
if (computeVingette) {
assert(vingette != 0);
*vingette = new ImageImpl(this->nRows, this->nCols, this->nChannels);
}
for(size_t it = 0; it < (1 + nrRefinements); ++it) {
bool refine = it > 0;
bool lastIt = (it == nrRefinements);
if (refine) {
ImageImpl *tmp = ret;
ret = constraints;
constraints = tmp;
if (ret == 0) ret = new ImageImpl(this->nRows, this->nCols, this->nChannels);
}
for (size_t nRow = 0; nRow < this->nRows; ++nRow)
for (size_t nCol = 0; nCol < this->nCols; ++nCol) {
bool e = invert_pixel_on_bounding_box(nRow,
nCol,
ret,
refine,
constraints,
T,
invT,
addIntegerError,
lastIt && toIntegerValues,
lastIt && computeVingette,
(lastIt && computeVingette) ? *vingette : 0);
isEmpty = isEmpty || e;
if (isEmpty) {nRow = this->nRows; nCol=this->nCols;} // break loops
}
if (isEmpty) break;
}
if (constraints != 0) delete constraints;
*out = ret;
return isEmpty;
}
bool ImageImpl::invert_pixel_on_bounding_box(const size_t nRow,
const size_t nCol,
ImageImpl *ret,
const bool refine,
const ImageImpl *constraints,
const std::function<Coordinate<Interval>(Coordinate<Interval>)> T,
const std::function<Coordinate<Interval>(Coordinate<Interval>)> invT,
const bool addIntegerError,
const bool toIntegerValues,
const bool computeVingette,
ImageImpl *vingette) const {
assert(ret != 0);
if (refine) assert(constraints != 0);
Coordinate<float> coord = getCoordinate(nRow, nCol, 0);
Coordinate<Interval> coordI({coord.x-2, coord.x+2}, {coord.y-2, coord.y+2}, 0);
Coordinate<Interval> coordI_pre = invT(coordI);
// pixels to consider
size_t parity_x = (nCols - 1) % 2;
size_t parity_y = (nRows - 1) % 2;
int lo_x, hi_x, lo_y, hi_y;
tie(lo_x, hi_x, lo_y, hi_y) = calculateBoundingBox(coordI_pre.x, coordI_pre.y, parity_x, parity_y);
//size_t m = rcc_to_idx(nRow, nCol, 0);
//printf("%ld %ld %f %f %f %f %f %f %d %d %d %d\n", nRow, nCol, coordI_pre.x.inf, coordI_pre.x.sup, coordI_pre.y.inf, coordI_pre.y.sup, a[m].inf, a[m].sup, lo_x, hi_x, lo_y, hi_y);
Interval inv_p[nChannels];
for (size_t chan = 0; chan < this->nChannels; ++chan)
inv_p[chan] = Interval(0, 1);
for (int x_iter = lo_x; x_iter <= hi_x; x_iter += 2)
for (int y_iter = lo_y; y_iter <= hi_y; y_iter += 2) {
Coordinate<Interval> coord_iter({(float)x_iter, (float)x_iter}, {(float)y_iter, (float)y_iter}, 0.0f );
Coordinate<Interval> coord_iterT = T(coord_iter);
if (coord_iterT.x.meet(coordI.x).is_empty() || coord_iterT.y.meet(coordI.y).is_empty()) continue;
Interval p[nChannels];
int r_iter, c_iter;
tie(r_iter, c_iter) = getRc(x_iter, y_iter);
if (0 <= r_iter && r_iter < signed(nRows) &&
0 <= c_iter && c_iter < signed(nCols)) {
for (size_t chan = 0; chan < this->nChannels; ++chan) {
p[chan] = valueAt(x_iter, y_iter, chan, Interval(0, 1));
if (addIntegerError) {
//this assumes that the pixel_values * 255 are integers in [0, 255]
//and that the rounding mode is arithmetic rounding (and not for example floorfing)
assert(p[chan].inf == p[chan].sup);
float deltaUp = (0.5f - Constants::EPS)/255.0f;
float deltaDown = 0.5f / 255.0f;
p[chan] = Interval(p[chan].inf - deltaDown, p[chan].sup + deltaUp).meet({0, 1});
}
}
} else {
for (size_t chan = 0; chan < this->nChannels; ++chan)
p[chan] = Interval(0, 1);
}
Interval inv_corners[nChannels];
for (Corner c : {Corner::upper_left, Corner::lower_left, Corner::upper_right, Corner::lower_right}) {
Interval inv_corner[nChannels];
invert_pixel(c,
coord,
coord_iterT,
inv_corner,
p,
constraints,
refine,
false); // debug
for (size_t chan = 0; chan < this->nChannels; ++chan) {
inv_corners[chan] = inv_corners[chan].join(inv_corner[chan]);
}
}
for (size_t chan = 0; chan < this->nChannels; ++chan) {
// printf("%d %d %d %d %d [%f %f] [%f %f] [%f %f]\n", (int)nRow, (int)nCol, x_iter, y_iter, (int)chan, inv_p[chan].inf, inv_p[chan].sup,
// inv_corners[chan].inf, inv_corners[chan].sup,
// (inv_p[chan].meet(inv_corners[chan])).inf,
// (inv_p[chan].meet(inv_corners[chan])).sup);
inv_p[chan] = inv_p[chan].meet(inv_corners[chan]);
}
}
bool isEmpty = false;
for (size_t chan = 0; chan < this->nChannels; ++chan) {
size_t m = rcc_to_idx(nRow, nCol, chan);
if (toIntegerValues && !inv_p[chan].is_empty()) {
float lower = inv_p[chan].inf;
float upper = inv_p[chan].sup;
if (lower > 0) {
for(size_t k = 0; k < 255; k ++) {
if(pixelVals[k] < lower && lower <= pixelVals[k+1] ) {
lower = pixelVals[k+1];
break;
}
}
}
assert(lower >= inv_p[chan].inf);
if(upper < 1) {
for(size_t k = 256; k >= 1; k--) {
if(pixelVals[k] > upper && upper >= pixelVals[k]) {
upper = pixelVals[k];
break;
}
}
}
assert(upper <= inv_p[chan].sup);
if (lower > upper) {
inv_p[chan] = Interval();
} else {
inv_p[chan] = Interval(lower, upper);
}
}
ret->a[m] = inv_p[chan];
if (computeVingette) {
if ((ret->a[m].sup - ret->a[m].inf) > 0.3f)
vingette->a[m] = Interval(1, 1);
else
vingette->a[m] = Interval(0, 0);
}
isEmpty = isEmpty || ret->a[m].is_empty();
}
return isEmpty;
}
void ImageImpl::invert_pixel(const Corner center,
const Coordinate<float>& coord,
const Coordinate<Interval>& coord_iterT,
Interval* out,
const Interval* pixel_values,
const ImageImpl* constraints,
const bool refine,
const bool debug) const {
Interval x_box, y_box;
float x_ll, y_ll;
vector<tuple<float, float>> corners;
switch(center) {
case lower_right:
x_ll = coord.x;
y_ll = coord.y;
x_box = coord_iterT.x.meet(Interval(coord.x, coord.x+2));
y_box = coord_iterT.y.meet(Interval(coord.y, coord.y+2));
if (!refine) corners.push_back({x_box.sup, y_box.sup});
break;
case upper_right:
x_ll = coord.x;
y_ll = coord.y - 2;
x_box = coord_iterT.x.meet(Interval(coord.x, coord.x+2));
y_box = coord_iterT.y.meet(Interval(coord.y-2, coord.y));
if (!refine) corners.push_back({x_box.sup, y_box.inf});
break;
case lower_left:
x_ll = coord.x - 2;
y_ll = coord.y;
x_box = coord_iterT.x.meet(Interval(coord.x-2, coord.x));
y_box = coord_iterT.y.meet(Interval(coord.y, coord.y+2));
if (!refine) corners.push_back({x_box.inf, y_box.sup});
break;
case upper_left:
x_ll = coord.x - 2;
y_ll = coord.y - 2;
x_box = coord_iterT.x.meet(Interval(coord.x-2, coord.x));
y_box = coord_iterT.y.meet(Interval(coord.y-2, coord.y));
if (!refine) corners.push_back({x_box.inf, y_box.inf});
break;
default:
assert(false);
};
if (debug) printf("%f %f %f %f %f %f %f %f %f %f\n", x_ll, y_ll, x_box.inf, x_box.sup, y_box.inf, y_box.sup, coord_iterT.x.inf, coord_iterT.x.sup, coord_iterT.y.inf, coord_iterT.y.sup);
assert(out != 0);
for (size_t chan = 0; chan < this->nChannels; ++chan)
out[chan] = Interval();
if (x_box.is_empty() || y_box.is_empty()) {
return;
}
assert(pixel_values != 0);
if (refine) {
assert(constraints != 0);
corners.push_back({x_box.inf, y_box.inf});
corners.push_back({x_box.sup, y_box.inf});
corners.push_back({x_box.inf, y_box.sup});
corners.push_back({x_box.sup, y_box.sup});
}
for (auto c : corners) {
float x_coord = get<0>(c), y_coord = get<1>(c);
Interval ret[nChannels];
//printf("%f %f %f\n", x_ll, x_coord, x_ll + 2);
vector<float> coef = bilinear_coefficients(x_ll, y_ll, x_coord, y_coord);
if (debug) printf("coefs %f %f %f %f\n", coef[0], coef[1], coef[2], coef[3]);
if (coef[center] == 0) {
for (size_t chan = 0; chan < this->nChannels; ++chan)
ret[chan] = Interval(0, 1);
} else {
for (size_t chan = 0; chan < this->nChannels; ++chan) {
ret[chan] = pixel_values[chan];
if (debug) printf("[%f %f]", ret[chan].inf, ret[chan].sup);
}
if (debug) printf("\n");
if(refine) {
for(size_t k = 0; k < 4; ++k) {
if (k == center) continue;
float x_ = 0, y_ = 0;
switch(k) {
case 0:
x_ = x_ll;
y_ = y_ll;
break;
case 1:
x_ = x_ll;
y_ = y_ll + 2;
break;
case 2:
x_ = x_ll + 2;
y_ = y_ll;
break;
case 3:
x_ = x_ll + 2;
y_ = y_ll + 2;
break;
}
for (size_t chan = 0; chan < this->nChannels; ++chan) {
Interval con = constraints->valueAt(x_, y_, chan, {0, 1});
if (debug) printf("con [%f %f] %d \n", con.inf, con.sup, con.is_empty());
ret[chan] = ret[chan] - coef[k] * con;
if (debug) printf("%d [%f %f]\n", (int)k, ret[chan].inf, ret[chan].sup);
}
}
} else {
float f = 0;
for(size_t k = 0; k < 4; ++k) {
if (k == center) continue;
f += coef[k];
}
Interval tmp = f * Interval(0,1);
for (size_t chan = 0; chan < this->nChannels; ++chan) {
ret[chan] = ret[chan] - tmp;
if (debug) printf("[%f %f]\n", ret[chan].inf, ret[chan].sup);
}
}
for (size_t chan = 0; chan < this->nChannels; ++chan) {
ret[chan] = ret[chan] / coef[center];
if (debug) printf("%f [%f %f]\n", coef[center], ret[chan].inf, ret[chan].sup);
}
}
for (size_t chan = 0; chan < this->nChannels; ++chan) {
out[chan] = out[chan].join(ret[chan]);
}
}
}
ImageImpl* ImageImpl::erode() {
ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
const size_t m = rcc_to_idx(i, j, k);
Interval val = a[m];
for(int di=-1; di <= 1; ++di)
for(int dj=-1; dj <= 1; ++dj) {
int ii = (signed)i + di;
int jj = (signed)j + dj;
if (0 <= ii && ii < nRows && 0 <= jj && jj < nCols) {
const size_t mm = rcc_to_idx((unsigned)ii, (unsigned)jj, k);
Interval other = a[mm];
if (other.inf <= val.inf && other.sup <= val.sup)
val = other;
}
}
ret->a[m] = val;
}
}
}
}
ImageImpl* ImageImpl::fill (const float value) const {
ImageImpl* ret = new ImageImpl(nRows, nCols, nChannels);
for (size_t k = 0; k < nChannels; ++k) {
for (size_t i = 0; i < nRows; ++i) {
for (size_t j = 0; j < nCols; ++j) {
size_t m = rcc_to_idx(i, j, k);
ret->a[m] = {value, value};
}
}
}
return ret;
}
| 32.792314 | 187 | 0.522279 |
d8b48ddfbda489b7b393ff79497c2ac72d382948 | 2,095 | cpp | C++ | simulation/Rendering/Window.cpp | Terae/3D_Langton_Ant | 017dadbe2962018db043bf50e8a6dcd49ade0eac | [
"MIT"
] | null | null | null | simulation/Rendering/Window.cpp | Terae/3D_Langton_Ant | 017dadbe2962018db043bf50e8a6dcd49ade0eac | [
"MIT"
] | null | null | null | simulation/Rendering/Window.cpp | Terae/3D_Langton_Ant | 017dadbe2962018db043bf50e8a6dcd49ade0eac | [
"MIT"
] | null | null | null | //
// Created by benji on 10/11/16.
//
#include "Window.h"
#include "Context.h"
void glfwErrorCallback(int error, const char* description) {
std::cerr << _RED("There was a glfw error : ") << description << _RED(" (" + std::to_string(error) + ")") << std::endl;
}
Window::Window(std::string title) {
std::cout << "Starting GLFW" << std::endl;
// Init GLFW
if(!glfwInit()) {
std::cerr << "Error during glfw initializing" << std::endl;
return;
}
glfwSetErrorCallback(glfwErrorCallback);
// Set all the required options for GLFW
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_SAMPLES, 16);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
_window = glfwCreateWindow(800, 600, title.c_str(), nullptr, nullptr);
if (!_window) {
std::cout << "Failed to create the GLFW window" << std::endl;
glfwTerminate();
return;
}
glfwMakeContextCurrent(_window);
gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
glfwSwapInterval(1);
_context = std::make_unique<Context>(_window);
glEnable(GL_MULTISAMPLE);
}
Window::~Window() {
destroy();
}
void Window::setTitle(std::string newTitle) {
glfwSetWindowTitle(_window, newTitle.c_str());
}
void Window::destroy() {
if(_destroyed) return;
_destroyed = true;
glfwDestroyWindow(_window);
glfwTerminate();
}
bool Window::isWindowOpened() {
return !glfwWindowShouldClose(_window);
}
void Window::setKeyCallback(GLFWkeyfun func) {
glfwSetKeyCallback(_window, func);
}
void Window::setScrollCallback(GLFWscrollfun func) {
glfwSetScrollCallback(_window, func);
}
void Window::setupFrame() {
int width, height;
glfwGetFramebufferSize(_window, &width, &height);
glViewport(0, 0, width, height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
}
void Window::finalizeFrame() {
glfwSwapBuffers(_window);
glfwPollEvents();
} | 24.08046 | 123 | 0.681623 |
d8bab90ef5648fdbaf3215e78ab86b647e808d74 | 88 | cpp | C++ | src/core/Distributor.cpp | jozhalaj/gateway | 49168dcbcf833da690048880bb33542ffbc90ce3 | [
"BSD-3-Clause"
] | 7 | 2018-06-09T05:55:59.000Z | 2021-01-05T05:19:02.000Z | src/core/Distributor.cpp | jozhalaj/gateway | 49168dcbcf833da690048880bb33542ffbc90ce3 | [
"BSD-3-Clause"
] | 1 | 2019-12-25T10:39:06.000Z | 2020-01-03T08:35:29.000Z | src/core/Distributor.cpp | jozhalaj/gateway | 49168dcbcf833da690048880bb33542ffbc90ce3 | [
"BSD-3-Clause"
] | 11 | 2018-05-10T08:29:05.000Z | 2020-01-22T20:49:32.000Z | #include "core/Distributor.h"
using namespace BeeeOn;
Distributor::~Distributor()
{
}
| 11 | 29 | 0.738636 |
d8befa451c1a63907b4b8ddd0f23ce49f4c051be | 862 | cpp | C++ | atcoder/B - Palindrome-philia/AC.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | atcoder/B - Palindrome-philia/AC.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | atcoder/B - Palindrome-philia/AC.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2019-12-08 18:03:30
* solution_verdict: AC language: C++14 (GCC 5.4.1)
* run_time: 1 ms memory_used: 256 KB
* problem: https://atcoder.jp/contests/abc147/tasks/abc147_b
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
string s;cin>>s;int n=s.size();
int ans=0;
for(int i=0;i<n/2;i++)
if(s[i]!=s[n-1-i])ans++;
cout<<ans<<endl;
return 0;
} | 43.1 | 111 | 0.37123 |
d8bf6f2fc9a378f878a916d6e37e9a41f08a12af | 1,313 | cpp | C++ | libdocscript/src/runtime/procedure/lambda_procedure.cpp | sotvokun/docscript | 0718c8943e895672b9570524cd9eb7ff019d079f | [
"MIT"
] | 1 | 2021-12-11T11:04:21.000Z | 2021-12-11T11:04:21.000Z | libdocscript/src/runtime/procedure/lambda_procedure.cpp | sotvokun/docscript | 0718c8943e895672b9570524cd9eb7ff019d079f | [
"MIT"
] | null | null | null | libdocscript/src/runtime/procedure/lambda_procedure.cpp | sotvokun/docscript | 0718c8943e895672b9570524cd9eb7ff019d079f | [
"MIT"
] | null | null | null | #include "libdocscript/runtime/datatype.h"
#include "libdocscript/runtime/procedure.h"
#include "libdocscript/runtime/value.h"
#include "libdocscript/runtime/environment.h"
#include "libdocscript/interpreter.h"
namespace libdocscript::runtime {
// +--------------------+
// Constructor
// +--------------------+
LambdaProcedure::LambdaProcedure(const parm_list& parameters, func_body body)
: Procedure(Procedure::Lambda), _parameters(parameters), _expression(body)
{}
// +--------------------+
// Public Functions
// +--------------------+
Value LambdaProcedure::invoke(const args_list &args, Environment &env) const
{
if(_parameters.size() != args.size()) {
throw UnexceptNumberOfArgument(_parameters.size(), args.size());
}
Environment subenv = env.derive();
for(decltype(_parameters.size()) i = 0; i != _parameters.size(); ++i) {
subenv.set<Value>(_parameters[i], args[i]);
}
return Interpreter(subenv).eval(_expression);
}
// +--------------------+
// Private Functions
// +--------------------+
DataType *LambdaProcedure::rawptr_clone() const
{
return new LambdaProcedure(*this);
}
// +--------------------+
// Type Conversion
// +--------------------+
LambdaProcedure::operator std::string() const
{
return "#lambda-procedure";
}
} | 25.745098 | 77 | 0.600914 |