hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
00e10b9d5e9b6cd82f2600b57d17dd74f9191e9e | 7,875 | cpp | C++ | 1.BouncingBall/BouncingBall/Game.cpp | Cabrra/Physics-Projects | 8fb3ec73b58ab1a2055e47b780bd298ef2c14bbb | [
"MIT"
] | 1 | 2021-12-10T07:34:04.000Z | 2021-12-10T07:34:04.000Z | 1.BouncingBall/BouncingBall/Game.cpp | Cabrra/Physics-Projects | 8fb3ec73b58ab1a2055e47b780bd298ef2c14bbb | [
"MIT"
] | null | null | null | 1.BouncingBall/BouncingBall/Game.cpp | Cabrra/Physics-Projects | 8fb3ec73b58ab1a2055e47b780bd298ef2c14bbb | [
"MIT"
] | null | null | null |
#include"Game.h"
static cGame* game;
Camera camera;
RigidBody ball;
Ground ground;
cGame::cGame():cGameWindows()
{
}
cGame::~cGame()
{
}
bool SetupMatrices()
{
// setup the projection matrix
D3DXMatrixPerspectiveFovLH(&game->projectionMatrix,D3DX_PI/2.0f ,(float)WIDTH /(float)HEIGHT ,1.0f,1000.0f);
Device->SetTransform(D3DTS_PROJECTION,&game->projectionMatrix);
return true;
}
bool cGame::InitializeGame()
{
const float PI=3.14f;
// Iniatialize lights
InitializeLight();
// Initialize world and view matrices
SetupMatrices();
ground.position=D3DXVECTOR3(0,0,0);
ground.CreatePlane(Device,"desert.bmp");
// load the boal by calling Load() with model filename being "bowlball.x" and theDevice=Device
ball.Load("bowlball.x",Device);
//set the ball mass=10kg
ball.mass = 10;
// set ball radius to 0.7m
ball.radius = 0.7f;
// set the ball position at (1 ,0.7,-1)m
ball.position = Vector3D(1.0f, 0.7f, -1.0f);
// set the ball linear velocity to (0,0,0)m/s;
ball.linearVelocity = Vector3D(0, 0, 0);
// set the ball vector gravity to (0,-9.81,0)m/s2
ball.gravity = Vector3D(0, -9.81, 0);
// set the ball Dynamic Friction Coefficient to 0.3 .
ball.DynamicFrictionCoefficient = 0.3f;
// set the ball Static Friction Coefficient to 0.7
ball.StaticFrictionCoefficient = 0.7f;
// set the ball DragCoefficient to 0.04
ball.dragCoefficient = 0.04f;
// set the ball coefficient of Restitution to 0.80f;
ball.coefficientOfRestitution = 0.8f;
// compute the ball weight
ball.weight = ball.gravity * ball.mass;
// compute the normal force on the ball. remember N + W =0 so ==> N=-W=-mg
ball.normalForce = -ball.weight;
// compute ball area
ball.area = 4 * PI*ball.radius*ball.radius;
// set the air density rho on the ball to 1.
ball.rho = 1;
return true;
}
void cGame::UpdateGame(float dt)
{
static bool forceApplied=false; // to help apply a one time force to the ball.
camera.Update(dt);
Device->SetTransform(D3DTS_VIEW,&camera.GetViewMatrix());
if(!forceApplied)
{
// if force not yet applied to the ball ,apply a force ( 100, 400,0 ) Newton to it.
// this force will be applied once
ball.force = Vector3D(100, 400, 0);
// set forceApplied to true
forceApplied = true;
}
else
{
// if force already applied , decrease its intensity by using a dumping factor=0.99 ( force=0.99*force)
ball.force = 0.99 * ball.force;
// now clamp the force to zero vector if its magnitude reaches 0.1 Newton.
if (ball.force.x < 0.1)
ball.force.x = 0;
if (ball.force.y < 0.1)
ball.force.y = 0;
if (ball.force.z < 0.1)
ball.force.z = 0;
}
COLLISION_STATE check ;
// initialize check to No_COLLISION
check = NO_COLLISION;
// Check for collision between the ball and the ground
check = CheckSpherePlaneCollision(ball, ground);
switch(check)
{
// If no collision ,do the followings
case NO_COLLISION :
// compute total force applied=force + weight + dragforce
ball.totalForces = ball.force+ ball.weight + ball.dragForce;
// compute acceleration using Newton 2nd law .
ball.linearAcceleration = ball.totalForces / ball.mass;
// compute the velocity
ball.linearVelocity = ball.linearVelocity + ball.linearAcceleration * dt;
break;
// If collision
case COLLISION:
// Handle sphere plane collision HandleSpherePlaneCollision(ball,ground)
HandleSpherePlaneCollision(ball, ground);
break;
// if resting contact
case RESTING_CONTACT:
// handle Resting contact by calling HandleRestingContact(ball,ground,dt)
HandleRestingContact(ball, ground, dt);
break;
}
// update the ball by calling Update(dt)
ball.Update(dt);
}
bool RenderFrame()
{
// render the ball
ball.Render(Device);
// render the ground
ground.Render(Device);
return true;
}
bool cGame::RenderGame()
{
bool IsRendered=true;
// Clear the backbuffer to a black color
Device->Clear(0,0,D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(225,225,225) ,1.0f,0);
// Begin the scene
if(SUCCEEDED(Device->BeginScene()))
{
//rendering goes here
RenderFrame();
// End the scene
Device->EndScene();
}
else
{
MessageBox(0," BeginScene()-Failed"," Rendering Error",MB_OK) ;
IsRendered=false;
}
// Present the backbuffer contents to the display
Device->Present(0,0,0,0);
return IsRendered;
}
bool cGame::ShutDownD3D()
{
if(Device!=NULL)
{
Device->Release();
Device=NULL;
}
if(D3D!=NULL)
{
D3D->Release();
D3D=NULL;
}
return true;
}
//end of shutdownD3D()
void cGame::Cleanup()
{
}
bool InitializeLight()
{
D3DLIGHT9 light;
ZeroMemory(&light,sizeof(D3DLIGHT9));
light.Type=D3DLIGHT_DIRECTIONAL;
D3DXVECTOR3 lightDirection;
lightDirection=D3DXVECTOR3(0.0f,-2.0f,1.0f);
D3DXVec3Normalize( (D3DXVECTOR3*)&light.Direction,&lightDirection);
//set the diffuse color
light.Diffuse.r=1.0f;
light.Diffuse.g=1.0f;
light.Diffuse.b=1.0f;
light.Diffuse.a=1.0f;
Device->SetLight(0,&light);
Device->LightEnable(0,true);
Device->SetRenderState(D3DRS_DIFFUSEMATERIALSOURCE,D3DMCS_MATERIAL);
// Turn on D3D lighting.
Device->SetRenderState(D3DRS_LIGHTING,true);
return true;
}
INT WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInst,LPSTR lpCmdLine, int nShowCmd)
{
game=new cGame();
/* Create window */
game->CreateGameWindows(hInstance,"Simulation of a Bouncing ball subject to Frictions and Aerodynamic Drag Force");
/* Setup Direct3D */
game->InitializeD3D();
// initialize game
game->InitializeGame();
/* Enter message loop */
game->Run();
/* Shutdown Direct3D */
game->ShutDownD3D();
delete game ;
return 0;
}
HRESULT cGame::InitializeD3D()
{
HRESULT hr=0; // handle to result
// create the IDirect3D object
if(NULL==(D3D=Direct3DCreate9(D3D_SDK_VERSION)))
{
MessageBox(NULL,"DIRECT3DCREATE9-FAILED","ERROR",0);
return E_FAIL;
}
// check the hardware vertex processing capabillty
D3DCAPS9 caps;
D3DDEVTYPE deviceType=D3DDEVTYPE_HAL;
D3D->GetDeviceCaps(D3DADAPTER_DEFAULT,deviceType,&caps);
int vp=0; //vertexProcessing
if(caps.DevCaps & D3DDEVCAPS_HWTRANSFORMANDLIGHT)
{
vp=D3DCREATE_HARDWARE_VERTEXPROCESSING;
}
else
{
vp=D3DCREATE_SOFTWARE_VERTEXPROCESSING;
}
// create Present Parameter and fill it out.
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp,sizeof(d3dpp));
d3dpp.BackBufferWidth =WIDTH;
d3dpp.BackBufferHeight =HEIGHT;
d3dpp.BackBufferFormat =D3DFMT_A8R8G8B8;
d3dpp.BackBufferCount =1;
d3dpp.AutoDepthStencilFormat =D3DFMT_D16; // or use D3DFMT_D24S8;
d3dpp.EnableAutoDepthStencil =true;
d3dpp.Flags =0;
d3dpp.FullScreen_RefreshRateInHz =D3DPRESENT_RATE_DEFAULT;
d3dpp.hDeviceWindow =hwnd;
d3dpp.MultiSampleQuality =0;
d3dpp.MultiSampleType =D3DMULTISAMPLE_NONE;
d3dpp.PresentationInterval =D3DPRESENT_INTERVAL_IMMEDIATE;
d3dpp.SwapEffect =D3DSWAPEFFECT_DISCARD;
d3dpp.Windowed =true;
// now create the device
hr=D3D->CreateDevice(D3DADAPTER_DEFAULT,deviceType,hwnd,vp,&d3dpp,&Device);
if( FAILED (hr))
{
D3D->Release();
MessageBox(NULL,"CreateDevice()-Failed","ERROR",NULL);
return E_FAIL;
}
if(hr==S_OK)
{
// Turn off culling, so we see the front and back of the
/* object.*/
Device->SetRenderState(D3DRS_CULLMODE,D3DCULL_NONE);
Device->SetRenderState(D3DRS_AMBIENT,0xffffffff);
}
return hr;
}
//////////////////////////////////////////////////end of initializeD3D()////////////////////////////////////////
| 21.935933 | 117 | 0.665778 | Cabrra |
00e210add32f93aa4f531acc8ba57dd3fc189f84 | 3,063 | cpp | C++ | 3rdparty/GPSTk/ext/lib/Vdraw/InterpolatedColorMap.cpp | mfkiwl/ICE | e660d031bb1bcea664db1de4946fd8781be5b627 | [
"MIT"
] | 50 | 2019-10-12T01:22:20.000Z | 2022-02-15T23:28:26.000Z | 3rdparty/GPSTk/ext/lib/Vdraw/InterpolatedColorMap.cpp | wuyou33/Enabling-Robust-State-Estimation-through-Measurement-Error-Covariance-Adaptation | 2f1ff054b7c5059da80bb3b2f80c05861a02cc36 | [
"MIT"
] | null | null | null | 3rdparty/GPSTk/ext/lib/Vdraw/InterpolatedColorMap.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 InterpolatedColorMap.cpp Defines an interpolated color map. Class defintions.
#include "InterpolatedColorMap.hpp"
namespace vdraw
{
InterpolatedColorMap::InterpolatedColorMap(int icols, int irows, const Palette &pp, double base)
{
init(icols,irows);
p = pp;
for(int row=0;row<rows;row++)
for(int col=0;col<cols;col++)
c[row][col] = base;
}
InterpolatedColorMap::InterpolatedColorMap(const InterpolatedColorMap &o)
{
init(o.cols,o.rows);
p = o.p;
for(int row=0;row<rows;row++)
for(int col=0;col<cols;col++)
c[row][col] = o.c[row][col];
}
InterpolatedColorMap& InterpolatedColorMap::operator=(InterpolatedColorMap o)
{
// o is a copy, swap the variables
std::swap(rows,o.rows);
std::swap(cols,o.cols);
std::swap(p,o.p);
std::swap(c,o.c);
// o is destructed with the old data from this
return *this;
}
void InterpolatedColorMap::init(int icols, int irows)
{
if(icols == 0 || irows == 0)
{
cols = rows = 0;
c = 0;
return;
}
cols = icols;
rows = irows;
// Initialize the color array
c = new double*[rows];
for(int row=0;row<rows;row++)
c[row] = new double[cols];
}
void InterpolatedColorMap::reset()
{
if(c)
{
for(int row=0;row<rows;row++)
delete[] c[row];
delete[] c;
}
p = Palette();
cols=rows=0;
c=0;
}
}
| 28.626168 | 98 | 0.587006 | mfkiwl |
00e51de226e6c674e33aca642a7a7012fe56e0c3 | 3,025 | cpp | C++ | tests/StringWriteBatchTest.cpp | LPetrlik/karindb | 8fe2b953c13f1d1aed9bb550799f7cfaf13b50ea | [
"MIT"
] | null | null | null | tests/StringWriteBatchTest.cpp | LPetrlik/karindb | 8fe2b953c13f1d1aed9bb550799f7cfaf13b50ea | [
"MIT"
] | null | null | null | tests/StringWriteBatchTest.cpp | LPetrlik/karindb | 8fe2b953c13f1d1aed9bb550799f7cfaf13b50ea | [
"MIT"
] | null | null | null | /* Copyright (c) 2015 Kerio Technologies s.r.o.
*
* 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 OF THIRD PARTY RIGHTS.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE
* LIABLE FOR ANY CLAIM, OR ANY SPECIAL 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.
*
* Except as contained in this notice, the name of a copyright holder shall not
* be used in advertising or otherwise to promote the sale, use or other
* dealings in this Software without prior written authorization of the
* copyright holder.
*/
#include "stdafx.h"
#include <kerio/hashdb/HashDB.h>
#include <kerio/hashdbHelpers/StringWriteBatch.h>
#include "StringWriteBatchTest.h"
using namespace kerio::hashdb;
void StringWriteBatchTest::testMultipleWrites()
{
const std::string expectedKey1("TTHyRxwZw7nbrTL1g3\005L5rl9mSE24G2FUA0RSPjKrA\1");
const partNum_t expectedPartNum1 = 13;
const std::string expectedValue1("l42OJZmo52O7jkRdaSPwGHledilbvs7Vkfi7nEE/oM0NIrZHBnxgiHWKEw==");
const std::string expectedKey2("ad;skd;d;lqkdlqd;cdl;ckd;lc;l;kd;lcfkd");
const partNum_t expectedPartNum2 = 99;
const std::string expectedValue2("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000");
boost::scoped_ptr<StringWriteBatch> writeBatch(new StringWriteBatch);
TS_ASSERT_EQUALS(0U, writeBatch->approxDataSize());
writeBatch->add(expectedKey1, expectedPartNum1, expectedValue1);
writeBatch->add(expectedKey2, expectedPartNum2, expectedValue2);
TS_ASSERT(writeBatch->approxDataSize() != 0U);
TS_ASSERT_EQUALS(writeBatch->count(), 2U);
TS_ASSERT_EQUALS(writeBatch->keyAt(0).getRef(), expectedKey1);
TS_ASSERT_EQUALS(writeBatch->partNumAt(0), expectedPartNum1);
TS_ASSERT_EQUALS(writeBatch->valueAt(0).getRef(), expectedValue1);
TS_ASSERT_EQUALS(writeBatch->keyAt(1).getRef(), expectedKey2);
TS_ASSERT_EQUALS(writeBatch->partNumAt(1), expectedPartNum2);
TS_ASSERT_EQUALS(writeBatch->valueAt(1).getRef(), expectedValue2);
writeBatch->clear();
TS_ASSERT_EQUALS(writeBatch->count(), 0U);
}
| 45.833333 | 138 | 0.787438 | LPetrlik |
00e55293aab01ecf987b9f298d3d71a5418d7168 | 46,413 | cpp | C++ | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/quicktime/QTLiveUtils.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/quicktime/QTLiveUtils.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/quicktime/QTLiveUtils.cpp | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2007 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <cstdio>
#include <cstdlib>
#include <string>
#include <sstream>
#include "osg/Image"
#include "osg/Notify"
#include "osg/Geode"
#include "osg/GL"
#include "osgDB/FileNameUtils"
#include "osgDB/Registry"
#include "osgDB/FileUtils"
#ifdef __APPLE__
#include <QuickTime/QuickTime.h>
#include <Carbon/Carbon.h>
#define QT_HANDLE_IMAGES_ALSO
#else
#include <QTML.h>
#include <Movies.h>
#include <Quickdraw.h>
#include <QDOffscreen.h>
#include <QuicktimeComponents.h>
#include <FixMath.h>
#include <CGBitmapContext.h>
#include <CGImage.h>
#include <CGColorSpace.h>
#include <ImageCompression.h>
#include <TextUtils.h>
#endif
#include "QTLiveUtils.h"
// Utils
char* pstr_printable(StringPtr src_pstr)
{
char* dst_cstr = new char[256];
p2cstrcpy(dst_cstr, src_pstr);
return dst_cstr;
}
void initialize_quicktime_qtml()
{
osg::notify(osg::NOTICE) << "QT QTML: Starting up... " << std::endl;
OSErr err;
#ifndef __APPLE__
err = InitializeQTML(0);
if (err!=0)
osg::notify(osg::FATAL) << "Error while initializing quicktime QTML: " << err << std::endl;
else
osg::notify(osg::NOTICE) << "QT QTML: initialized successfully" << std::endl;
#endif
}
void terminite_quicktime_qtml()
{
osg::notify(osg::NOTICE) << "QT QTML: Closing down... " << std::endl;
#ifndef __APPLE__
TerminateQTML();
#endif
osg::notify(osg::NOTICE) << "QT QTML: Closed successfully" << std::endl;
}
void enter_quicktime_movies()
{
osg::notify(osg::NOTICE) << "QT Movies: Starting up... " << std::endl;
OSErr err;
err = EnterMovies();
if (err!=0)
osg::notify(osg::FATAL) << "Error while initializing Movies: " << err << std::endl;
else
osg::notify(osg::NOTICE) << "QT Movies: initialized successfully" << std::endl;
}
void leave_quicktime_movies()
{
osg::notify(osg::NOTICE) << "QT Movies: Closing down... " << std::endl;
#ifndef __APPLE__
ExitMovies();
#endif
osg::notify(osg::NOTICE) << "QT Movies: closed successfully" << std::endl;
}
#if TARGET_OS_MAC
void enter_quicktime_movies_mt()
{
osg::notify(osg::NOTICE) << "QT Movies MT: Starting up... " << std::endl;
OSErr err;
err = EnterMoviesOnThread(0);
if (err!=0)
osg::notify(osg::FATAL) << "Error while initializing Movies MT: " << err << std::endl;
else
osg::notify(osg::NOTICE) << "QT Movies MT: initialized successfully" << std::endl;
}
void leave_quicktime_movies_mt()
{
osg::notify(osg::NOTICE) << "QT Movies MT: Closing down... " << std::endl;
#ifndef __APPLE__
ExitMoviesOnThread();
#endif
osg::notify(osg::NOTICE) << "QT Movies MT: closed successfully" << std::endl;
}
#endif
QTScopedQTMLInitialiser::QTScopedQTMLInitialiser()
{
initialize_quicktime_qtml();
}
QTScopedQTMLInitialiser::~QTScopedQTMLInitialiser()
{
terminite_quicktime_qtml();
}
QTScopedMovieInitialiser::QTScopedMovieInitialiser()
{
enter_quicktime_movies();
}
QTScopedMovieInitialiser::~QTScopedMovieInitialiser()
{
leave_quicktime_movies();
}
#if TARGET_OS_MAC
QTScopedMovieInitialiser_MT::QTScopedMovieInitialiser_MT()
{
enter_quicktime_movies_mt();
}
QTScopedMovieInitialiser_MT::~QTScopedMovieInitialiser_MT()
{
leave_quicktime_movies_mt();
}
#endif
// DigitizerInfo input/output Capability checker
bool supports_capability( long input_flags, long option_flags )
{
long result_l = (input_flags & option_flags);
return result_l == option_flags;
}
// Capability
void print_video_component_capability(VideoDigitizerComponent aComponent)
{
// Returns capability and status information about a specified video digitizer component.
VideoDigitizerError vid_err;
DigitizerInfo vid_info;
// Capability flags
osg::notify(osg::NOTICE) << std::endl;
vid_err = VDGetDigitizerInfo(aComponent, &vid_info);
if (vid_err) osg::notify(osg::NOTICE) << "VDGetDigitizerInfo(aComponent, &vid_info) - ERROR" << std::endl;
else
{
osg::notify(osg::NOTICE) << "DigitizerInfo:" << std::endl;
short vdigType = vid_info.vdigType;
if (vdigType == vdTypeBasic) osg::notify(osg::NOTICE) << "Digitizer Type : Basic (no clipping)" << std::endl;
if (vdigType == vdTypeAlpha) osg::notify(osg::NOTICE) << "Digitizer Type : Alpha clipping" << std::endl;
if (vdigType == vdTypeMask) osg::notify(osg::NOTICE) << "Digitizer Type : Mask Plane clipping" << std::endl;
if (vdigType == vdTypeKey) osg::notify(osg::NOTICE) << "Digitizer Type : Key Color(s) clipping" << std::endl;
short vdigSlot = vid_info.slot;
osg::notify(osg::NOTICE) << "Hardwre Slot : " << vdigSlot << std::endl;
osg::notify(osg::NOTICE) << "Input Capability:" << std::endl << std::boolalpha;
long inputCapabilityFlags = vid_info.inputCapabilityFlags;
osg::notify(osg::NOTICE) << " NTSC : " << supports_capability(inputCapabilityFlags, digiInDoesNTSC) << std::endl;
osg::notify(osg::NOTICE) << " PAL : " << supports_capability(inputCapabilityFlags, digiInDoesPAL) << std::endl;
osg::notify(osg::NOTICE) << " Composite : " << supports_capability(inputCapabilityFlags, digiInDoesComposite) << std::endl;
osg::notify(osg::NOTICE) << " Component : " << supports_capability(inputCapabilityFlags, digiInDoesComponent) << std::endl;
osg::notify(osg::NOTICE) << " SVideo : " << supports_capability(inputCapabilityFlags, digiInDoesSVideo) << std::endl;
osg::notify(osg::NOTICE) << "Input Current:" << std::endl;
long inputCurrentFlags = vid_info.inputCurrentFlags;
osg::notify(osg::NOTICE) << " NTSC : " << supports_capability(inputCurrentFlags, digiInDoesNTSC) << std::endl;
osg::notify(osg::NOTICE) << " PAL : " << supports_capability(inputCurrentFlags, digiInDoesPAL) << std::endl;
osg::notify(osg::NOTICE) << " Composite : " << supports_capability(inputCurrentFlags, digiInDoesComposite) << std::endl;
osg::notify(osg::NOTICE) << " Component : " << supports_capability(inputCurrentFlags, digiInDoesComponent) << std::endl;
osg::notify(osg::NOTICE) << " SVideo : " << supports_capability(inputCurrentFlags, digiInDoesSVideo) << std::endl;
// Heights
short minDestHeight = vid_info.minDestHeight;
short minDestWidth = vid_info.minDestWidth;
short maxDestWidth = vid_info.maxDestWidth;
short maxDestHeight = vid_info.maxDestHeight;
osg::notify(osg::NOTICE) << "Min destination width,height : " << minDestWidth << " " << minDestHeight << std::endl;
osg::notify(osg::NOTICE) << "Max destination width,height : " << maxDestWidth << " " << maxDestHeight << std::endl;
// Current Status
long inputFlags, outputFlags;
vid_err = VDGetCurrentFlags(aComponent, &inputFlags, &outputFlags);
osg::notify(osg::NOTICE) << " NTSC : " << supports_capability(inputFlags, digiInDoesNTSC) << std::endl;
osg::notify(osg::NOTICE) << " PAL : " << supports_capability(inputFlags, digiInDoesPAL) << std::endl;
osg::notify(osg::NOTICE) << " Composite : " << supports_capability(inputFlags, digiInDoesComposite) << std::endl;
osg::notify(osg::NOTICE) << " Component : " << supports_capability(inputFlags, digiInDoesComponent) << std::endl;
osg::notify(osg::NOTICE) << " SVideo : " << supports_capability(inputFlags, digiInDoesSVideo) << std::endl;
osg::notify(osg::NOTICE) << " GenLock : " << supports_capability(inputFlags, digiInDoesGenLock) << std::endl;
osg::notify(osg::NOTICE) << " SECAM : " << supports_capability(inputFlags, digiInDoesSECAM) << std::endl;
osg::notify(osg::NOTICE) << " VTR_Broadcast : " << supports_capability(inputFlags, digiInVTR_Broadcast) << std::endl;
osg::notify(osg::NOTICE) << " Color : " << supports_capability(inputFlags, digiInDoesColor) << std::endl;
osg::notify(osg::NOTICE) << " BW : " << supports_capability(inputFlags, digiInDoesBW) << std::endl;
osg::notify(osg::NOTICE) << " *SignalLock* : " << supports_capability(inputFlags, digiInSignalLock) << std::endl;
// Preferrd Width Height
long pref_width, pref_height;
vid_err = VDGetPreferredImageDimensions(aComponent, &pref_width, &pref_height);
if (vid_err) osg::notify(osg::NOTICE) << "VDGetPreferredImageDimensions(aComponent, &pref_width, &pref_height) - ERROR" << std::endl;
else osg::notify(osg::NOTICE) << "Preferrred width,height : " << pref_width << " " << pref_height << std::endl;
// Inputs
short inputs;
vid_err = VDGetNumberOfInputs(aComponent, &inputs);
if (vid_err) osg::notify(osg::NOTICE) << "VDGetNumberOfInputs(aComponent, &inputs) - ERROR" << std::endl;
else osg::notify(osg::NOTICE) << "Number of inputs : " << inputs << std::endl;
for (short i=0; i <= inputs; ++i)
{
Str255 name;
vid_err = VDGetInputName(aComponent,(long)i, name);
if (vid_err) osg::notify(osg::NOTICE) << "VDGetInputName(aComponent,(long)i, name) - ERROR" << std::endl;
else osg::notify(osg::NOTICE) << "Name of input " << i << " : " << pstr_printable(name) << std::endl;
short input_format;
vid_err = VDGetInputFormat(aComponent,(long)i, &input_format);
if (vid_err) osg::notify(osg::NOTICE) << "VDGetInputFormat(aComponent,(long)i, &input_format) - ERROR" << std::endl;
else
{
if (input_format == compositeIn) osg::notify(osg::NOTICE) << "Format of input : compositeIn" << std::endl;
if (input_format == sVideoIn) osg::notify(osg::NOTICE) << "Format of input : sVideoIn" << std::endl;
if (input_format == rgbComponentIn) osg::notify(osg::NOTICE) << "Format of input : rgbComponentIn" << std::endl;
if (input_format == rgbComponentSyncIn) osg::notify(osg::NOTICE) << "Format of input : rgbComponentSyncIn" << std::endl;
if (input_format == yuvComponentIn) osg::notify(osg::NOTICE) << "Format of input : yuvComponentIn" << std::endl;
if (input_format == yuvComponentSyncIn) osg::notify(osg::NOTICE) << "Format of input : yuvComponentSyncIn" << std::endl;
if (input_format == sdiIn) osg::notify(osg::NOTICE) << "Format of input : sdiIn" << std::endl;
}
}
// CURRENT Input
short active_input;
vid_err = VDGetInput(aComponent, &active_input);
if (vid_err) osg::notify(osg::NOTICE) << "VDGetInput(aComponent, &active_input) - ERROR" << std::endl;
else osg::notify(osg::NOTICE) << "Currently active input : " << active_input << std::endl;
}
}
void probe_video_digitizer_components()
{
// Extra scopes for DEBUG and breakpoint/stack checking plus QT init/destroy
{
// Begin QuickTime
QTScopedQTMLInitialiser qt_init;
QTScopedMovieInitialiser qt_movie_init;
// #define videoDigitizerComponentType = 'vdig'
ComponentDescription video_component_description;
video_component_description.componentType = 'vdig'; /* A unique 4-byte code indentifying the command set */
video_component_description.componentSubType = 0; /* Particular flavor of this instance */
video_component_description.componentManufacturer = 0; /* Vendor indentification */
video_component_description.componentFlags = 0; /* 8 each for Component,Type,SubType,Manuf/revision */
video_component_description.componentFlagsMask = 0; /* Mask for specifying which flags to consider in search, zero during registration */
long num_video_components = CountComponents (&video_component_description);
osg::notify(osg::NOTICE) << " available Video DigitizerComponents : " << num_video_components << std::endl;
if (num_video_components)
{
Component aComponent = 0;
do
{
ComponentDescription full_video_component_description = video_component_description;
aComponent = FindNextComponent(aComponent, &full_video_component_description);
if (aComponent)
{
osg::notify(osg::NOTICE) << "Component" << std::endl;
OSErr err;
Handle compName = NewHandle(256);
Handle compInfo = NewHandle(256);
err = GetComponentInfo( aComponent, &full_video_component_description, compName,compInfo,0);
osg::notify(osg::NOTICE) << " Name: " << pstr_printable((StringPtr)*compName) << std::endl;
osg::notify(osg::NOTICE) << " Desc: " << pstr_printable((StringPtr)*compInfo) << std::endl;
//Capabilities
VideoDigitizerComponent component_instance = OpenComponent(aComponent);
print_video_component_capability(component_instance);
CloseComponent(component_instance);
}
}
while (0 != aComponent);
}
// End QuickTime
}
}
static Boolean MyModalFilter(DialogPtr theDialog, const EventRecord *theEvent, short *itemHit, long refCon)
{
return false;
}
OSG_SGDeviceList print_sequence_grabber_device_list(SGDeviceList deviceList)
{
ComponentResult result = noErr;
short count = (*deviceList)->count;
short selectedIndex = (*deviceList)->selectedIndex;
osg::notify(osg::NOTICE) << "DeviceList : " << count << " devices in total" << std::endl;
osg::notify(osg::NOTICE) << "DeviceList : " << selectedIndex << " is current device" << std::endl;
// Create List
OSG_SGDeviceList device_list;
OSG_SGDevicePair device_pair;
for (short i=0; i<count; ++i)
{
// Devices
osg::notify(osg::NOTICE) << std::endl;
SGDeviceName deviceNameRec = (*deviceList)->entry[i];
Str63 deviceNameStr;
memcpy(deviceNameStr, deviceNameRec.name, sizeof(Str63));
osg::notify(osg::NOTICE) << " " << "Device ID : " << i << " : DeviceNameStr : " << pstr_printable(deviceNameStr) << std::endl;
SGDeviceInputList deviceInputList = deviceNameRec.inputs;
if (deviceInputList)
{
// Inputs
short inputCount = (*deviceInputList)->count;
short inputSelectedIndex = (*deviceInputList)->selectedIndex;
osg::notify(osg::NOTICE) << " " << "InputList : " << inputCount << " inputs in total" << std::endl;
osg::notify(osg::NOTICE) << " " << "InputList : " << inputSelectedIndex << " is current input" << std::endl;
for (short inp=0; inp<inputCount; ++inp)
{
SGDeviceInputName inputNameRec = (*deviceInputList)->entry[inp];
Str63 inputNameStr;
memcpy(inputNameStr, inputNameRec.name, sizeof(Str63));
osg::notify(osg::NOTICE) << " " << "InputNameStr : " << inp << " " << pstr_printable(inputNameStr) << std::endl;
// Build up device list
std::ostringstream os;
os << i << ":" << inp << ".live";
device_pair.first = os.str();
device_pair.second = std::string(pstr_printable(deviceNameStr)) + std::string(" ") + std::string(pstr_printable(inputNameStr));
// Append
device_list.push_back(device_pair);
}
}
else
{
osg::notify(osg::NOTICE) << " InputList is empty!" << std::endl;
}
}
return device_list;
}
std::vector<OSG_SGDeviceList> probe_sequence_grabber_components()
{
// Create List
std::vector<OSG_SGDeviceList> devices_list;
OSG_SGDeviceList device_list;
// Extra scopes for DEBUG and breakpoint/stack checking plus QT init/destroy
{
// Begin QuickTime
QTScopedQTMLInitialiser qt_init;
QTScopedMovieInitialiser qt_movie_init;
// #define videoDigitizerComponentType = 'vdig'
ComponentDescription sg_component_description;
sg_component_description.componentType = SeqGrabComponentType; /* A unique 4-byte code indentifying the command set */
sg_component_description.componentSubType = 0L; /* Particular flavor of this instance */
sg_component_description.componentManufacturer = 'appl'; /* Vendor indentification */
sg_component_description.componentFlags = 0L; /* 8 each for Component,Type,SubType,Manuf/revision */
sg_component_description.componentFlagsMask = 0L; /* Mask for specifying which flags to consider in search, zero during registration */
long num_sg_components = CountComponents (&sg_component_description);
osg::notify(osg::NOTICE) << " available SequenceGrabber Components : " << num_sg_components << std::endl;
if (num_sg_components)
{
Component aComponent = 0;
do
{
ComponentDescription full_sg_component_description = sg_component_description;
aComponent = FindNextComponent(aComponent, &full_sg_component_description);
if (aComponent)
{
osg::notify(osg::NOTICE) << "Component" << std::endl;
OSErr err;
Handle compName = NewHandle(256);
Handle compInfo = NewHandle(256);
err = GetComponentInfo( aComponent, &full_sg_component_description, compName,compInfo,0);
osg::notify(osg::NOTICE) << " Name: " << pstr_printable((StringPtr)*compName) << std::endl;
osg::notify(osg::NOTICE) << " Desc: " << pstr_printable((StringPtr)*compInfo) << std::endl;
SeqGrabComponent gSeqGrabber;
SGChannel gVideoChannel;
SGChannel gSoundChannel;
Rect gActiveVideoRect;
gSeqGrabber = OpenComponent (aComponent);
// If we got a sequence grabber, set it up
if (gSeqGrabber != 0L)
{
ComponentResult result = noErr;
// Initialize the sequence grabber
result = SGInitialize (gSeqGrabber);
if (result == noErr)
{
// Check capability and setting of Sequence Grabber
Rect destinationBounds;
OSStatus err;
GDHandle origDevice;
CGrafPtr origPort;
GWorldPtr gw;
PixMapHandle pixmap = NULL;
int* destinationData = new int [1024*1024]; // 1024*1024*4 bytes (32bit RGBA)
destinationBounds.left = 0;
destinationBounds.top = 0;
destinationBounds.right = 2048;
destinationBounds.bottom = 2048;
err = QTNewGWorldFromPtr(&gw, k32ARGBPixelFormat, &destinationBounds,
NULL, NULL, 0, (Ptr)destinationData, 4*1024);
if (err !=0 )
osg::notify(osg::FATAL) << "Could not create gWorld" << std::endl;
else
{
// Create GWorld
GetGWorld (&origPort, &origDevice);
SetGWorld (gw, NULL); // set current graphics port to offscreen
pixmap = GetGWorldPixMap (gw);
if (pixmap)
{
if (!LockPixels (pixmap)) // lock offscreen pixel map
{
osg::notify(osg::FATAL) << "Could not lock PixMap" << std::endl;
}
}
// Set GWorld
result = SGSetGWorld(gSeqGrabber, (CGrafPtr)gw, 0);
// Set GWorld back
// SetGWorld(origPort, origDevice);
if (result != noErr)
{
osg::notify(osg::FATAL) << "Could not set GWorld on SG" << std::endl;
}
else
{
// Get a video channel
result = SGNewChannel (gSeqGrabber, VideoMediaType, &gVideoChannel);
if ((gVideoChannel != nil) && (result == noErr))
{
// Init
// result = SGInitChannel(gVideoChannel, gSeqGrabber);
// if (result != noErr)
// {
// osg::notify(osg::NOTICE) << "SGInitChannel - failed!" << std::endl;
// }
// Usage
result = SGSetChannelUsage (gVideoChannel, seqGrabPreview);
// Panel
// Crashes every time
// result = SGSettingsDialog(gSeqGrabber, gVideoChannel, 0, 0, seqGrabSettingsPreviewOnly, &MyModalFilter, 0);
// Bounds
result = SGGetSrcVideoBounds (gVideoChannel, &gActiveVideoRect);
osg::notify(osg::NOTICE) << "SrcVideoBounds: " << gActiveVideoRect.right << " " << gActiveVideoRect.bottom << std::endl;
Str255 deviceName;
Str255 inputName;
short inputNumber;
result = SGGetChannelDeviceAndInputNames( gVideoChannel, deviceName, inputName, &inputNumber);
if (result != noErr)
{
osg::notify(osg::NOTICE) << "Could not get DeviceAndInput names from Video SG" << std::endl;
}
osg::notify(osg::NOTICE) << "ChannelDeviceAndInputNamesNumber: " << pstr_printable(deviceName) << " : " << pstr_printable(inputName) << " : " << inputNumber << std::endl;
SGDeviceList deviceList;
result = SGGetChannelDeviceList( gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
if (result != noErr)
{
osg::notify(osg::NOTICE) << "Could not get DeviceList from Video SG" << std::endl;
}
else
{
osg::notify(osg::NOTICE) << "DeviceList from Video SG ok" << std::endl;
device_list = print_sequence_grabber_device_list(deviceList);
devices_list.push_back(device_list);
}
}
// Get a sound channel
result = SGNewChannel (gSeqGrabber, SoundMediaType, &gSoundChannel);
if ((gSoundChannel != nil) && (result == noErr))
{
// Usage
result = SGSetChannelUsage (gSoundChannel, seqGrabPreview);
Str255 deviceName;
Str255 inputName;
short inputNumber;
result = SGGetChannelDeviceAndInputNames( gVideoChannel, deviceName, inputName, &inputNumber);
if (result != noErr)
{
osg::notify(osg::NOTICE) << "Could not get DeviceAndInput names from Sound SG" << std::endl;
}
osg::notify(osg::NOTICE) << "ChannelDeviceAndInputNamesNumber: " << pstr_printable(deviceName) << " : " << pstr_printable(inputName) << " : " << inputNumber << std::endl;
SGDeviceList deviceList;
result = SGGetChannelDeviceList( gSoundChannel, sgDeviceListIncludeInputs, &deviceList);
if (result != noErr)
{
osg::notify(osg::NOTICE) << "Could not get DeviceList from Sound SG" << std::endl;
}
else
{
osg::notify(osg::NOTICE) << "DeviceList from Sound SG ok" << std::endl;
device_list = print_sequence_grabber_device_list(deviceList);
devices_list.push_back(device_list);
}
}
}
SetGWorld(origPort, origDevice);
DisposeGWorld(gw);
}
}
}
SGDisposeChannel(gSeqGrabber, gVideoChannel);
CloseComponent(gSeqGrabber);
}
}
while (0 != aComponent);
}
// End QuickTime
}
return devices_list;
}
void get_video_device_bounds_idstr(short deviceID, short deviceInputID, short& out_width, short& out_height, Str63& out_deviceIDStr)
{
// Extra scopes for DEBUG and breakpoint/stack checking plus QT init/destroy
{
// Begin QuickTime
QTScopedQTMLInitialiser qt_init;
QTScopedMovieInitialiser qt_movie_init;
ComponentDescription sg_component_description;
sg_component_description.componentType = SeqGrabComponentType; /* A unique 4-byte code indentifying the command set */
sg_component_description.componentSubType = 0L; /* Particular flavor of this instance */
sg_component_description.componentManufacturer = 0L; /* Vendor indentification */
sg_component_description.componentFlags = 0L; /* 8 each for Component,Type,SubType,Manuf/revision */
sg_component_description.componentFlagsMask = 0L; /* Mask for specifying which flags to consider in search, zero during registration */
long num_sg_components = CountComponents (&sg_component_description);
if (num_sg_components)
{
Component aComponent = 0;
do
{
ComponentDescription full_sg_component_description = sg_component_description;
aComponent = FindNextComponent(aComponent, &full_sg_component_description);
if (aComponent)
{
SeqGrabComponent gSeqGrabber;
SGChannel gVideoChannel;
Rect gActiveVideoRect;
gSeqGrabber = OpenComponent (aComponent);
// If we got a sequence grabber, set it up
if (gSeqGrabber != 0L)
{
ComponentResult result = noErr;
// Initialize the sequence grabber
result = SGInitialize (gSeqGrabber);
if (result == noErr)
{
// Check capability and setting of Sequence Grabber
Rect destinationBounds;
OSStatus err;
GDHandle origDevice;
CGrafPtr origPort;
GWorldPtr gw;
PixMapHandle pixmap = NULL;
int* destinationData = new int [1024*1024]; // 1024*1024*4 bytes (32bit RGBA)
destinationBounds.left = 0;
destinationBounds.top = 0;
destinationBounds.right = 256;
destinationBounds.bottom = 256;
err = QTNewGWorldFromPtr(&gw, k32ARGBPixelFormat, &destinationBounds,
NULL, NULL, 0, (Ptr)destinationData, 4*256);
if (err !=0 )
osg::notify(osg::NOTICE) << "Could not create gWorld" << std::endl;
else
{
// Create GWorld
GetGWorld (&origPort, &origDevice);
SetGWorld (gw, NULL); // set current graphics port to offscreen
pixmap = GetGWorldPixMap (gw);
if (pixmap)
{
if (!LockPixels (pixmap)) // lock offscreen pixel map
osg::notify(osg::FATAL) << "Could not lock PixMap" << std::endl;
}
// Set GWorld
result = SGSetGWorld(gSeqGrabber, (CGrafPtr)gw, 0);
// Set GWorld back
// SetGWorld(origPort, origDevice);
if (result != noErr)
{
osg::notify(osg::FATAL) << "Could not set GWorld on SG" << std::endl;
}
else
{
// Get a video channel
result = SGNewChannel (gSeqGrabber, VideoMediaType, &gVideoChannel);
if ((gVideoChannel != nil) && (result == noErr))
{
result = SGSetChannelUsage (gVideoChannel, seqGrabPreview);
Str255 deviceName;
Str255 inputName;
short inputNumber;
result = SGGetChannelDeviceAndInputNames( gVideoChannel, deviceName, inputName, &inputNumber);
SGDeviceList deviceList;
result = SGGetChannelDeviceList( gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
short count = (*deviceList)->count;
if (deviceID >= count)
osg::notify(osg::FATAL) << "DeviceID : " << deviceID << " too large - we only have " << count << " devices" << std::endl;
SGDeviceName deviceNameRec = (*deviceList)->entry[deviceID];
SGDeviceInputList deviceInputList = deviceNameRec.inputs;
if (deviceInputList == 0)
osg::notify(osg::FATAL) << "DeviceInputList is empty!" << std::endl;
else
{
short inputCount = (*deviceInputList)->count;
if (deviceInputID >= inputCount)
osg::notify(osg::FATAL) << "DeviceInputID : " << deviceInputID << " too large - we only have " << inputCount << " inputs for device" << std::endl;
}
// Ok
Str63 deviceNameStr;
memcpy(deviceNameStr, deviceNameRec.name, sizeof(Str63));
// Set
result = SGSetChannelDevice ( gVideoChannel, deviceNameStr);
result = SGSetChannelDeviceInput( gVideoChannel, deviceInputID);
VideoDigitizerComponent vdig = SGGetVideoDigitizerComponent(gVideoChannel);
VideoDigitizerError vid_err;
vid_err = VDSetInputStandard (vdig, palIn);
result = SGVideoDigitizerChanged( gVideoChannel);
result = SGGetSrcVideoBounds ( gVideoChannel, &gActiveVideoRect);
osg::notify(osg::NOTICE) << "SrcVideoBounds: " << gActiveVideoRect.right << " " << gActiveVideoRect.bottom << std::endl;
// Out
out_width = gActiveVideoRect.right;
out_height = gActiveVideoRect.bottom;
memcpy(out_deviceIDStr, deviceNameRec.name, sizeof(Str63));
}
}
SetGWorld(origPort, origDevice);
DisposeGWorld(gw);
}
}
}
SGDisposeChannel(gSeqGrabber, gVideoChannel);
CloseComponent(gSeqGrabber);
}
}
while (0 != aComponent);
}
// End QuickTime
}
}
void get_sound_device_idstr(short soundDeviceID, short soundDeviceInputID, Str63& out_soundDeviceIDStr)
{
// Extra scopes for DEBUG and breakpoint/stack checking plus QT init/destroy
{
// Begin QuickTime
QTScopedQTMLInitialiser qt_init;
QTScopedMovieInitialiser qt_movie_init;
// #define videoDigitizerComponentType = 'vdig'
ComponentDescription sg_component_description;
sg_component_description.componentType = SeqGrabComponentType; /* A unique 4-byte code indentifying the command set */
sg_component_description.componentSubType = 0L; /* Particular flavor of this instance */
sg_component_description.componentManufacturer = 0L; /* Vendor indentification */
sg_component_description.componentFlags = 0L; /* 8 each for Component,Type,SubType,Manuf/revision */
sg_component_description.componentFlagsMask = 0L; /* Mask for specifying which flags to consider in search, zero during registration */
long num_sg_components = CountComponents (&sg_component_description);
if (num_sg_components)
{
Component aComponent = 0;
do
{
ComponentDescription full_sg_component_description = sg_component_description;
aComponent = FindNextComponent(aComponent, &full_sg_component_description);
if (aComponent)
{
SeqGrabComponent gSeqGrabber;
SGChannel gSoundChannel;
gSeqGrabber = OpenComponent (aComponent);
// If we got a sequence grabber, set it up
if (gSeqGrabber != 0L)
{
ComponentResult result = noErr;
// Initialize the sequence grabber
result = SGInitialize (gSeqGrabber);
if (result == noErr)
{
// Check capability and setting of Sequence Grabber
// Get a sound channel
result = SGNewChannel (gSeqGrabber, SoundMediaType, &gSoundChannel);
if ((gSoundChannel != nil) && (result == noErr))
{
result = SGSetChannelUsage (gSoundChannel, seqGrabPreview);
Str255 deviceName;
Str255 inputName;
short inputNumber;
result = SGGetChannelDeviceAndInputNames( gSoundChannel, deviceName, inputName, &inputNumber);
SGDeviceList deviceList;
result = SGGetChannelDeviceList( gSoundChannel, sgDeviceListIncludeInputs, &deviceList);
short count = (*deviceList)->count;
if (soundDeviceID >= count)
osg::notify(osg::FATAL) << "DeviceID : " << soundDeviceID << " too large - we only have " << count << " devices" << std::endl;
SGDeviceName deviceNameRec = (*deviceList)->entry[soundDeviceID];
SGDeviceInputList deviceInputList = deviceNameRec.inputs;
short inputCount = (*deviceInputList)->count;
if (soundDeviceInputID >= inputCount)
osg::notify(osg::FATAL) << "DeviceInputID : " << soundDeviceInputID << " too large - we only have " << inputCount << " inputs for device" << std::endl;
// Ok
Str63 deviceNameStr;
memcpy(deviceNameStr, deviceNameRec.name, sizeof(Str63));
// Set
result = SGSetChannelDevice ( gSoundChannel, deviceNameStr);
result = SGSetChannelDeviceInput( gSoundChannel, soundDeviceInputID);
// Out
memcpy(out_soundDeviceIDStr, deviceNameRec.name, sizeof(Str63));
SGDisposeChannel(gSeqGrabber, gSoundChannel);
}
}
CloseComponent(gSeqGrabber);
}
}
}
while (0 != aComponent);
}
// End QuickTime
}
}
// Getting Information About Video Digitizer Components
// You can use the VDGetDigitizerInfo function in your application to retrieve
// information about the capabilities of a video digitizer component. You can use
// the VDGetCurrentFlags function to obtain current status information from a video digitizer component.
// Setting Source Characteristics
// You can use the VDGetMaxSrcRect function in your application to get the size and location of the maximum
// source rectangle. Similarly, the VDGetActiveSrcRect function allows you to get this information about
// the active source rectangle, and the VDGetVBlankRect function enables you to obtain information about the vertical blanking rectangle.
// You can use the VDSetDigitizerRect function to set the size and location of the digitizer rectangle.
// The VDGetDigitizerRect function lets you retrieve the size and location of this rectangle.
// Imput Source
// Some of these functions provide information about the available video inputs. Applications can use
// the VDGetNumberOfInputs function to determine the number of video inputs supported by the digitizer component.
// The VDGetInputFormat function allows applications to find out the video format (composite, s-video, or component) employed by a specified input.
// You can use the VDSetInput function in your application to specify the input to be used by the digitizer component.
// The VDGetInput function returns the currently selected input.
// The VDSetInputStandard function allows you to specify the video signaling standard to be used by the video digitizer component.
/*
QTVideoOutputRestoreState
QTVideoOutputSaveState
Selecting an Input Source
VDGetInput
VDGetInputFormat
VDGetNumberOfInputs
VDSetInput
VDSetInputStandard
Setting Source Characteristics
VDGetActiveSrcRect
VDGetDigitizerRect
VDGetMaxSrcRect
VDGetVBlankRect
VDSetDigitizerRect
Setting Video Destinations
VDGetMaxAuxBuffer
VDGetPlayThruDestination
VDPreflightDestination
VDPreflightGlobalRect
VDSetPlayThruDestination
VDSetPlayThruGlobalRect
Video Clipping
VDClearClipRgn
VDGetClipState
VDSetClipRgn
VDSetClipState
*/
/*
QTVideoOutputCopyIndAudioOutputDeviceUID
QTVideoOutputGetIndImageDecompressor
VDGetInputGammaRecord
VDGetInputName
VDGetPreferredImageDimensions
VDIIDCGetCSRData
VDIIDCGetDefaultFeatures
VDIIDCGetFeatures
VDIIDCGetFeaturesForSpecifier
VDIIDCSetCSRData
VDIIDCSetFeatures
VDSetDestinationPort
VDSetInputGammaRecord
VDSetPreferredImageDimensions
VDUseSafeBuffers
*/
//void test ()
//{
//if ((i == count-1) && (inp == inputCount-1))
//{
// osg::notify(osg::NOTICE) << " * TEST SGSetChannelDevice(..) : " << pstr_printable(deviceNameRec.name) << std::endl;
// result = SGSetChannelDevice (gVideoChannel, deviceNameStr);
// if (result == noErr)
// {
// result = SGSetChannelDeviceInput( gVideoChannel, 0 );
// result = SGGetSrcVideoBounds (gVideoChannel, &gActiveVideoRect);
// osg::notify(osg::NOTICE) << "SrcVideoBounds: " << gActiveVideoRect.right << " " << gActiveVideoRect.bottom << std::endl;
// Str255 deviceName2;
// Str255 inputName2;
// short inputNumber2;
// result = SGGetChannelDeviceAndInputNames( gVideoChannel, deviceName2, inputName2, &inputNumber2);
// osg::notify(osg::NOTICE) << "ChannelDeviceAndInputNamesNumber: " << pstr_printable(deviceName2) << " : " << pstr_printable(inputName2) << " : " << inputNumber2 << std::endl;
// result = SGGetChannelDeviceList( gVideoChannel, sgDeviceListIncludeInputs, &deviceList);
// if (result != noErr)
// {
// osg::notify(osg::NOTICE) << "Could not get DeviceList from Video SG" << std::endl;
// }
// else
// {
// osg::notify(osg::NOTICE) << "DeviceList from Video SG ok" << std::endl;
// short count = (*deviceList)->count;
// short selectedIndex = (*deviceList)->selectedIndex;
// osg::notify(osg::NOTICE) << "DeviceList : " << count << " devices in total" << std::endl;
// osg::notify(osg::NOTICE) << "DeviceList : " << selectedIndex << " is current device" << std::endl;
// }
// }
// else
// {
// osg::notify(osg::NOTICE) << "SGSetChannelDevice - failed!" << std::endl;
// }
// osg::notify(osg::NOTICE) << " * TEST SGSetChannelDevice(..) end" << std::endl;
//}
| 54.732311 | 212 | 0.518842 | UM-ARM-Lab |
00e772d902274d5d7c0b4282699996356f36ead0 | 3,563 | cc | C++ | onnxruntime/test/server/unit_tests/server_configuration_test.cc | hqucms/onnxruntime | 6e4e76414639f50836a64546603c8957227857b0 | [
"MIT"
] | 3 | 2019-11-25T10:26:57.000Z | 2021-05-14T08:11:29.000Z | onnxruntime/test/server/unit_tests/server_configuration_test.cc | hqucms/onnxruntime | 6e4e76414639f50836a64546603c8957227857b0 | [
"MIT"
] | 10 | 2019-03-25T21:47:46.000Z | 2019-04-30T02:33:05.000Z | onnxruntime/test/server/unit_tests/server_configuration_test.cc | hqucms/onnxruntime | 6e4e76414639f50836a64546603c8957227857b0 | [
"MIT"
] | 4 | 2021-06-05T19:52:22.000Z | 2021-11-30T13:58:13.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "server/server_configuration.h"
namespace onnxruntime {
namespace server {
namespace test {
TEST(ConfigParsingTests, AllArgs) {
char* test_argv[] = {
const_cast<char*>("/path/to/binary"),
const_cast<char*>("--model_path"), const_cast<char*>("testdata/mul_1.onnx"),
const_cast<char*>("--address"), const_cast<char*>("4.4.4.4"),
const_cast<char*>("--http_port"), const_cast<char*>("80"),
const_cast<char*>("--num_http_threads"), const_cast<char*>("1"),
const_cast<char*>("--log_level"), const_cast<char*>("info")};
onnxruntime::server::ServerConfiguration config{};
Result res = config.ParseInput(11, test_argv);
EXPECT_EQ(res, Result::ContinueSuccess);
EXPECT_EQ(config.model_path, "testdata/mul_1.onnx");
EXPECT_EQ(config.address, "4.4.4.4");
EXPECT_EQ(config.http_port, 80);
EXPECT_EQ(config.num_http_threads, 1);
EXPECT_EQ(config.logging_level, ORT_LOGGING_LEVEL_INFO);
}
TEST(ConfigParsingTests, Defaults) {
char* test_argv[] = {
const_cast<char*>("/path/to/binary"),
const_cast<char*>("--model"), const_cast<char*>("testdata/mul_1.onnx"),
const_cast<char*>("--num_http_threads"), const_cast<char*>("3")};
onnxruntime::server::ServerConfiguration config{};
Result res = config.ParseInput(5, test_argv);
EXPECT_EQ(res, Result::ContinueSuccess);
EXPECT_EQ(config.model_path, "testdata/mul_1.onnx");
EXPECT_EQ(config.address, "0.0.0.0");
EXPECT_EQ(config.http_port, 8001);
EXPECT_EQ(config.num_http_threads, 3);
EXPECT_EQ(config.logging_level, ORT_LOGGING_LEVEL_INFO);
}
TEST(ConfigParsingTests, Help) {
char* test_argv[] = {
const_cast<char*>("/path/to/binary"),
const_cast<char*>("--help")};
onnxruntime::server::ServerConfiguration config{};
auto res = config.ParseInput(2, test_argv);
EXPECT_EQ(res, Result::ExitSuccess);
}
TEST(ConfigParsingTests, NoModelArg) {
char* test_argv[] = {
const_cast<char*>("/path/to/binary"),
const_cast<char*>("--num_http_threads"), const_cast<char*>("3")};
onnxruntime::server::ServerConfiguration config{};
Result res = config.ParseInput(3, test_argv);
EXPECT_EQ(res, Result::ExitFailure);
}
TEST(ConfigParsingTests, ModelNotFound) {
char* test_argv[] = {
const_cast<char*>("/path/to/binary"),
const_cast<char*>("--model_path"), const_cast<char*>("does/not/exist"),
const_cast<char*>("--address"), const_cast<char*>("4.4.4.4"),
const_cast<char*>("--http_port"), const_cast<char*>("80"),
const_cast<char*>("--num_http_threads"), const_cast<char*>("1")};
onnxruntime::server::ServerConfiguration config{};
Result res = config.ParseInput(9, test_argv);
EXPECT_EQ(res, Result::ExitFailure);
}
TEST(ConfigParsingTests, WrongLoggingLevel) {
char* test_argv[] = {
const_cast<char*>("/path/to/binary"),
const_cast<char*>("--log_level"), const_cast<char*>("not a logging level"),
const_cast<char*>("--model_path"), const_cast<char*>("testdata/mul_1.onnx"),
const_cast<char*>("--address"), const_cast<char*>("4.4.4.4"),
const_cast<char*>("--http_port"), const_cast<char*>("80"),
const_cast<char*>("--num_http_threads"), const_cast<char*>("1")};
onnxruntime::server::ServerConfiguration config{};
Result res = config.ParseInput(11, test_argv);
EXPECT_EQ(res, Result::ExitFailure);
}
} // namespace test
} // namespace server
} // namespace onnxruntime | 36.731959 | 82 | 0.685658 | hqucms |
00ecf3f7e33716204ac223630b3469014b19a522 | 2,099 | cpp | C++ | tests/integration/session_api_tests/basic_0_session_api_test.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 61 | 2020-07-06T17:11:46.000Z | 2022-03-12T14:42:51.000Z | tests/integration/session_api_tests/basic_0_session_api_test.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 1 | 2021-02-25T01:30:29.000Z | 2021-11-09T11:13:14.000Z | tests/integration/session_api_tests/basic_0_session_api_test.cpp | gglin001/popart | 3225214343f6d98550b6620e809a3544e8bcbfc6 | [
"MIT"
] | 6 | 2020-07-15T12:33:13.000Z | 2021-11-07T06:55:00.000Z | // Copyright (c) 2019 Graphcore Ltd. All rights reserved.
#define BOOST_TEST_MODULE Basic0SessionApiTest
#include <boost/test/unit_test.hpp>
#include <filereader.hpp>
#include <popart/builder.hpp>
#include <popart/dataflow.hpp>
#include <popart/devicemanager.hpp>
#include <popart/inputshapeinfo.hpp>
#include <popart/ndarraywrapper.hpp>
#include <popart/op/l1.hpp>
#include <popart/session.hpp>
#include <popart/tensorinfo.hpp>
#include <popart/tensornames.hpp>
#include <popart/testdevice.hpp>
#include <algorithm>
#include <map>
#include <random>
#include <tuple>
#include <vector>
bool prePrepCallError(const popart::error &ex) {
std::string what = ex.what();
BOOST_CHECK(what.find("be called before") != std::string::npos);
return true;
}
BOOST_AUTO_TEST_CASE(Basic0SessionApi) {
using namespace popart;
auto opts = SessionOptions();
auto builder = Builder::create();
TensorInfo xInfo{"FLOAT", std::vector<int64_t>{1, 2, 3, 4, 5}};
TensorId xId = builder->addInputTensor(xInfo);
auto aiOnnx = builder->aiOnnxOpset9();
TensorId yId = aiOnnx.relu({xId});
builder->addOutputTensor(xId);
auto proto = builder->getModelProto();
auto art = AnchorReturnType("All");
auto dataFlow = DataFlow(1, {{yId, art}});
auto device = popart::createTestDevice(TEST_TARGET);
auto session = popart::InferenceSession::createFromOnnxModel(
proto,
dataFlow,
device,
popart::InputShapeInfo(),
opts,
popart::Patterns(PatternsLevel::NoPatterns).enableRuntimeAsserts(false));
// create anchor and co.
std::vector<float> rawOutputValues(xInfo.nelms());
popart::NDArrayWrapper<float> outValues(rawOutputValues.data(), xInfo);
std::map<popart::TensorId, popart::IArray &> anchors = {{yId, outValues}};
// create input and co.
std::vector<float> vXData(xInfo.nelms());
popart::NDArrayWrapper<float> xData(vXData.data(), xInfo);
std::map<popart::TensorId, popart::IArray &> inputs = {{xId, xData}};
popart::StepIO stepio(inputs, anchors);
BOOST_CHECK_EXCEPTION(session->run(stepio), popart::error, prePrepCallError);
}
| 30.867647 | 79 | 0.717485 | gglin001 |
00ef54ab3bf93ca4b4d9fa4f5fdb88b1fde45dd3 | 10,119 | cpp | C++ | src/chrono_synchrono/flatbuffer/message/SynTrackedVehicleMessage.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 1 | 2020-01-18T02:39:17.000Z | 2020-01-18T02:39:17.000Z | src/chrono_synchrono/flatbuffer/message/SynTrackedVehicleMessage.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | null | null | null | src/chrono_synchrono/flatbuffer/message/SynTrackedVehicleMessage.cpp | zzhou292/chrono-collision | c2a20e171bb0eb8819636d370887aa32d68547c6 | [
"BSD-3-Clause"
] | 1 | 2019-07-16T00:23:00.000Z | 2019-07-16T00:23:00.000Z | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2020 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Aaron Young
// =============================================================================
//
// Wraps data received from a tracked vehicle flatbuffer state message, into a
// corresponding C++ object.
// See also flatbuffer/fbs/Agent.fbs
//
// =============================================================================
#include "chrono_synchrono/flatbuffer/message/SynTrackedVehicleMessage.h"
namespace chrono {
namespace synchrono {
namespace Agent = SynFlatBuffers::Agent;
namespace TrackedVehicle = SynFlatBuffers::Agent::TrackedVehicle;
/// Constructors
SynTrackedVehicleMessage::SynTrackedVehicleMessage(int rank,
std::string json,
std::shared_ptr<SynTrackedVehicleState> state,
std::shared_ptr<SynTrackedVehicleDescription> description)
: SynAgentMessage(rank, SynMessageType::TRACKED_VEHICLE, json) {
m_state = state ? state : chrono_types::make_shared<SynTrackedVehicleState>();
m_description = m_vehicle_description = description ? description //
: chrono_types::make_shared<SynTrackedVehicleDescription>();
}
SynTrackedVehicleMessage::SynTrackedVehicleMessage(int rank,
std::shared_ptr<SynTrackedVehicleState> state,
std::shared_ptr<SynTrackedVehicleDescription> description)
: SynAgentMessage(rank, SynMessageType::TRACKED_VEHICLE) {
m_state = state;
m_description = m_vehicle_description = description ? description //
: chrono_types::make_shared<SynTrackedVehicleDescription>();
}
void SynTrackedVehicleMessage::StateFromMessage(const SynFlatBuffers::Message* message) {
// System of casts from SynFlatBuffers::Message to SynFlatBuffers::Agent::TrackedVehicle::State
if (message->message_type() != SynFlatBuffers::Type_Agent_State)
return;
auto agent_state = message->message_as_Agent_State();
auto state = agent_state->message_as_TrackedVehicle_State();
SynPose chassis(state->chassis());
std::vector<SynPose> track_shoes;
for (auto track_shoe : (*state->track_shoes()))
track_shoes.emplace_back(track_shoe);
std::vector<SynPose> sprockets;
for (auto sprocket : (*state->sprockets()))
sprockets.emplace_back(sprocket);
std::vector<SynPose> idlers;
for (auto idler : (*state->idlers()))
idlers.emplace_back(idler);
std::vector<SynPose> road_wheels;
for (auto road_wheel : (*state->road_wheels()))
road_wheels.emplace_back(road_wheel);
m_state->SetState(state->time(), chassis, track_shoes, sprockets, idlers, road_wheels);
}
/// Generate FlatBuffers message from this message's state
FlatBufferMessage SynTrackedVehicleMessage::MessageFromState(flatbuffers::FlatBufferBuilder& builder) {
auto chassis = m_state->chassis.ToFlatBuffers(builder);
std::vector<flatbuffers::Offset<SynFlatBuffers::Pose>> track_shoes;
for (auto& track_shoe : m_state->track_shoes)
track_shoes.push_back(track_shoe.ToFlatBuffers(builder));
std::vector<flatbuffers::Offset<SynFlatBuffers::Pose>> sprockets;
for (auto& sprocket : m_state->sprockets)
sprockets.push_back(sprocket.ToFlatBuffers(builder));
std::vector<flatbuffers::Offset<SynFlatBuffers::Pose>> idlers;
for (auto& idler : m_state->idlers)
idlers.push_back(idler.ToFlatBuffers(builder));
std::vector<flatbuffers::Offset<SynFlatBuffers::Pose>> road_wheels;
for (auto& road_wheel : m_state->road_wheels)
road_wheels.push_back(road_wheel.ToFlatBuffers(builder));
auto vehicle_type = Agent::Type_TrackedVehicle_State;
auto vehicle_state = TrackedVehicle::CreateStateDirect(builder, //
m_state->time, //
chassis, //
&track_shoes, //
&sprockets, //
&idlers, //
&road_wheels); //
auto flatbuffer_state = Agent::CreateState(builder, vehicle_type, vehicle_state.Union());
auto flatbuffer_message = SynFlatBuffers::CreateMessage(builder, //
SynFlatBuffers::Type_Agent_State, //
flatbuffer_state.Union(), //
m_rank); //
return flatbuffers::Offset<SynFlatBuffers::Message>(flatbuffer_message);
}
/// Generate description from FlatBuffers message
void SynTrackedVehicleMessage::DescriptionFromMessage(const SynFlatBuffers::Message* message) {
/// Cast from SynFlatBuffers::Message to SynFlatBuffers::Agent::TrackedVehicle::Description
if (message->message_type() != SynFlatBuffers::Type_Agent_Description)
return;
auto description = message->message_as_Agent_Description();
m_rank = message->rank();
if (description->json()->Length())
m_vehicle_description->json = description->json()->str();
else {
auto vehicle_description = description->description_as_TrackedVehicle_Description();
m_vehicle_description->SetVisualizationFiles(vehicle_description->chassis_vis_file()->str(), //
vehicle_description->track_shoe_vis_file()->str(), //
vehicle_description->left_sprocket_vis_file()->str(), //
vehicle_description->right_sprocket_vis_file()->str(), //
vehicle_description->left_idler_vis_file()->str(), //
vehicle_description->right_idler_vis_file()->str(), //
vehicle_description->left_road_wheel_vis_file()->str(), //
vehicle_description->right_road_wheel_vis_file()->str()); //
m_vehicle_description->SetNumAssemblyComponents(vehicle_description->num_track_shoes(), //
vehicle_description->num_sprockets(), //
vehicle_description->num_idlers(), //
vehicle_description->num_road_wheels()); //
}
}
/// Generate FlatBuffers message from this agent's description
FlatBufferMessage SynTrackedVehicleMessage::MessageFromDescription(flatbuffers::FlatBufferBuilder& builder) {
auto flatbuffer_json = builder.CreateString(m_vehicle_description->json);
auto flatbuffer_type = Agent::Type_TrackedVehicle_Description;
flatbuffers::Offset<TrackedVehicle::Description> vehicle_description = 0;
if (m_vehicle_description->json.empty()) {
vehicle_description =
TrackedVehicle::CreateDescriptionDirect(builder,
m_vehicle_description->m_chassis_vis_file.c_str(), //
m_vehicle_description->m_track_shoe_vis_file.c_str(), //
m_vehicle_description->m_left_sprocket_vis_file.c_str(), //
m_vehicle_description->m_right_sprocket_vis_file.c_str(), //
m_vehicle_description->m_left_idler_vis_file.c_str(), //
m_vehicle_description->m_right_idler_vis_file.c_str(), //
m_vehicle_description->m_left_road_wheel_vis_file.c_str(), //
m_vehicle_description->m_right_road_wheel_vis_file.c_str(), //
m_vehicle_description->m_num_track_shoes, //
m_vehicle_description->m_num_sprockets, //
m_vehicle_description->m_num_idlers, //
m_vehicle_description->m_num_road_wheels); //
}
auto flatbuffer_description = Agent::CreateDescription(builder, //
flatbuffer_type, //
vehicle_description.Union(), //
flatbuffer_json); //
return SynFlatBuffers::CreateMessage(builder, //
SynFlatBuffers::Type_Agent_Description, //
flatbuffer_description.Union(), //
m_rank); //
}
} // namespace synchrono
} // namespace chrono
| 55.598901 | 116 | 0.528412 | zzhou292 |
00f5aa571f72775b671c3176cae847391548883d | 3,156 | cpp | C++ | Train/Sheet/Sheet-B/extra/extra 01 - 15/02.[Trees on the level].cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | 1 | 2019-12-19T06:51:20.000Z | 2019-12-19T06:51:20.000Z | Train/Sheet/Sheet-B/extra/extra 01 - 15/02.[Trees on the level].cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | Train/Sheet/Sheet-B/extra/extra 01 - 15/02.[Trees on the level].cpp | mohamedGamalAbuGalala/Practice | 2a5fa3bdaf995d0c304f04231e1a69e6960f72c8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <math.h>
#include <vector>
#include <algorithm>
#include <string.h>
#include <array>
#include <iterator>
#include <set>
#include <cmath>
#include<iomanip> // Stew(10) :: 12 ........ 8 spaces and 2 digits in 10 padding right
#define pb push_back
#define up upper_bound
#define lp lower_bound
#define pr pair<int,int>
#define ll long long int
using namespace std;
vector<pair<int, string>> ar[257];
vector<string> dat;
int mx;
void split(const string &s, const char* delim, vector<string> & v) {
// to avoid modifying original string
// first duplicate the original string and return a char pointer then free the memory
char * dup = strdup(s.c_str());
char * token = strtok(dup, delim);
while (token != NULL) {
v.push_back(string(token));
// the call is treated as a subsequent calls to strtok:
// the function continues from where it left in previous invocation
token = strtok(NULL, delim);
}
free(dup);
}
int calc(string s) {
int res = 0;
for (int i = 0, si = s.size(); i < si; ++i) {
if (s[i] == 'R')
res = (res * 2) + 1;
else
res = (res * 2);
}
return res;
}
bool dubl(string v, int i) {
vector<string>::iterator it = find(dat.begin(), dat.end(), v);
int ind = it - dat.begin();
if (it != dat.end() && ind != i)
return 1;
return 0;
}
bool found_parent(string v) {
vector<string>::iterator it = find(dat.begin(), dat.end(), v);
if (it != dat.end())
return 1;
return 0;
}
bool ok() {
bool ft = 0, pnf = 0;
for (int i = 0, siz = dat.size(); i < siz; ++i) {
string cur = dat[i];
if (dubl(cur, i))
ft = 1;
string p = cur.substr(0, cur.size() - 1);
if (p.size() == 0)
p = "r";
if (cur != "r")
if (!found_parent(p))
pnf = 1;
}
return (!ft && !pnf);
}
bool cmp(pair<int, string> b, pair<int, string> a) {
if (a.first > b.first)
return 1;
return 0;
}
void print() {
if (ok()) {
if (ar[0].size() != 0)
cout << ar[0][0].second;
for (int i = 1; i <= mx; ++i) {
sort(ar[i].begin(), ar[i].end(), cmp);
for (int j = 0, si = ar[i].size(); j < si; ++j)
cout << ' ' << ar[i][j].second;
}
cout << '\n';
} else
cout << "not complete\n";
vector<pair<int, string>> tmp;
memset(ar, 0, sizeof ar);
dat.clear();
mx = 0;
}
int main() {
string inp;
while (cin >> inp) {
if (inp == "()")
print();
vector<string> sp;
split(inp, "(,)", sp);
pair<int, string> tmp;
if (sp.size() == 1) {
dat.pb("r");
tmp.first = 0, tmp.second = sp[0];
ar[0].pb(tmp);
mx = max(0, mx);
} else if (sp.size() == 2) {
dat.pb(sp[1]);
tmp.first = calc(sp[1]), tmp.second = sp[0];
ar[sp[1].size()].pb(tmp);
int length = sp[1].size();
mx = max(length, mx);
}
}
return 0;
}
/* Test-Cases
*
*
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (1,RRR) (4,RR) (20,LR) (19,LRL) (18,LRR) (17,RLL) (16,RLR) (15,RRL) ()
(3,L) (4,R) ()
(11,LL) (7,LLL) (8,R)
(5,) (4,L) (13,RL) (2,LLR) (2,LLR) (1,RRR) (4,RR) (20,LR) (19,LRL) (18,LRR) (17,RLL) (16,RLR) (15,RRL) ()
(3,L) (4,R) (4,) ()
(5,) ()
()
5 4 8 11 20 13 4 7 2 19 18 17 16 15 1
not complete
not complete
4 3 4
5
not complete
*
*/
| 21.04 | 106 | 0.556717 | mohamedGamalAbuGalala |
00f6096a32516c1909fb567de8ca7710814968db | 8,351 | cpp | C++ | src/localization/arena-detection/ImageProcessor.cpp | elikos/elikos_localization | 0eca76e5c836b1b0f407afffe0d1b85605d3cfa1 | [
"MIT"
] | 1 | 2019-02-24T08:29:06.000Z | 2019-02-24T08:29:06.000Z | src/localization/arena-detection/ImageProcessor.cpp | elikos/elikos_localization | 0eca76e5c836b1b0f407afffe0d1b85605d3cfa1 | [
"MIT"
] | null | null | null | src/localization/arena-detection/ImageProcessor.cpp | elikos/elikos_localization | 0eca76e5c836b1b0f407afffe0d1b85605d3cfa1 | [
"MIT"
] | 1 | 2019-02-12T23:06:13.000Z | 2019-02-12T23:06:13.000Z | #include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <Eigen/Geometry>
#include <iostream>
#include <unordered_map>
#include "LineGroup.h"
#include "DBSCAN.h"
#include "ImageProcessor.h"
namespace localization {
using Vector = Eigen::Vector2f;
ImageProcessor::ImageProcessor(const CameraInfo& cameraInfo, const QuadState& state)
: cameraInfo_(cameraInfo), state_(state), preProcessing_(cameraInfo, state), intersectionTransform_(cameraInfo, state)
{
srand(time(NULL));
}
ImageProcessor::~ImageProcessor()
{
}
void ImageProcessor::processImage(cv::Mat& input, cv::Mat& result)
{
cv::Mat preProcessed;
cv::Mat perspectiveTransform;
preProcessing_.preProcessImage(input, preProcessed, perspectiveTransform);
cv::Mat edges;
findEdges(preProcessed, edges);
findLines(edges);
result = cv::Mat(edges.size(), CV_8UC3, cv::Scalar(0, 0, 0));
analyzeLineCluster(result, edges.size(), perspectiveTransform);
/*
cv::Mat debug;
cv::warpPerspective(input, debug, perspectiveTransform, debug.size());
std::vector<cv::Point2f> dst;
std::vector<cv::Point2f> src;
for (int i = 0; i < intersections_.size(); ++i)
{
src.push_back(cv::Point2f(intersections_[i].x(), intersections_[i].y()));
}
if (!dst.empty())
{
cv::perspectiveTransform(src, dst, perspectiveTransform);
std::vector<Eigen::Vector2f> tmp;
for (int i = 0; i < dst.size(); ++i)
{
tmp.push_back(Eigen::Vector2f(dst[i].x, dst[i].y));
}
drawIntersection(tmp, cv::Scalar(150, 150, 0), input);
cv::imshow("debug", input);
cv::waitKey(30);
}
*/
}
void ImageProcessor::findEdges(const cv::Mat& src, cv::Mat& edges)
{
cv::Canny(src, edges, 1, 30, 3);
}
void ImageProcessor::drawLine(cv::Mat& dst, const Line& line, const cv::Scalar& color) const
{
Vector centroid = line.getCentroid();
Vector orientation = line.getOrientation();
cv::Point2f pt1, pt2;
pt1.x = cvRound(centroid.x() + 1000 * (orientation.x()));
pt1.y = cvRound(centroid.y() + 1000 * (orientation.y()));
pt2.x = cvRound(centroid.x() - 1000 * (orientation.x()));
pt2.y = cvRound(centroid.y() - 1000 * (orientation.y()));
cv::line(dst, pt1, pt2, color, 1, CV_AA);
cv::circle(dst, cv::Point2f(centroid.x(), centroid.y()), 5, cv::Scalar(150, 0, 150), -1);
}
void ImageProcessor::findLines(const cv::Mat& edges)
{
std::vector<cv::Vec2f> rawLines;
cv::HoughLines(edges, rawLines, 1, CV_PI / 180, 100, 0, 0 );
buildLineArray(rawLines);
}
void ImageProcessor::analyzeLineCluster(cv::Mat& debug, const cv::Size& size, const cv::Mat& perspectiveTransform)
{
/*
if (lineCluster_.size() == 0)
{
return;
}
*/
for (int i = 0; i < lineCluster_.size(); ++i)
{
drawLine(debug, lineCluster_[i], cv::Scalar(100, 100, 100));
}
lineDetection_.filterLineCluster(lineCluster_);
const std::vector<Line>& filteredLines = lineDetection_.getFilteredLines();
for (int i = 0; i < filteredLines.size(); ++i)
{
drawLine(debug, filteredLines[i], cv::Scalar(150, 0, 150));
}
std::vector<LineGroup> orientationGroup;
groupByOrientation(orientationGroup, lineCluster_);
findLineIntersections(orientationGroup, size);
std::vector<int> clusterMemberships;
tf::Transform origin2camera = state_.getOrigin2Fcu() * state_.getFcu2Camera();
tf::Vector3 camDirection = tf::quatRotate(origin2camera.getRotation(), tf::Vector3(0.0, 0.0, 1.0));
camDirection.normalize();
float S = std::cos(std::atan(std::sqrt(std::pow(camDirection.x(), 2) + std::pow(camDirection.y(), 2)) / camDirection.z()));
int radius = 0.5 * S * cameraInfo_.focalLength / state_.getOrigin2Fcu().getOrigin().z();
DBSCAN::DBSCAN(intersections_, radius, 2, clusterMemberships);
std::vector<Vector> intersections;
parseClusterMemberships(clusterMemberships, intersections);
//drawIntersection(intersections_, cv::Scalar(150, 150, 0), debug);
drawIntersection(intersections, cv::Scalar(0, 0, 150), debug);
intersectionTransform_.transformIntersections(intersections, perspectiveTransform, size);
}
void ImageProcessor::parseClusterMemberships(const std::vector<int>& clusterMemberships, std::vector<Vector>& intersections)
{
if (clusterMemberships.size() != intersections_.size()) return;
std::unordered_map<int, std::pair<Vector, int>> groups;
for (int i = 0; i < clusterMemberships.size(); ++i) {
int groupId = clusterMemberships[i];
std::unordered_map<int, std::pair<Vector, int>>::iterator it = groups.find(groupId);
if (it != groups.end()) {
it->second.first *= it->second.second;
it->second.first += intersections_[i];
it->second.second++;
it->second.first.x() /= it->second.second;
it->second.first.y() /= it->second.second;
} else {
groups.insert({groupId, {intersections_[i], 1}});
}
}
std::unordered_map<int, std::pair<Vector, int>>::iterator it;
for(it = groups.begin(); it != groups.end(); it++) {
intersections.push_back(it->second.first);
}
}
void ImageProcessor::findLineIntersections(const std::vector<LineGroup>& orientationGroups, const cv::Size& size)
{
intersections_.clear();
for (size_t i = 0; i < orientationGroups.size(); ++i) {
const LineGroup& firstGroup = orientationGroups[i];
for (size_t j = (i + 1) % orientationGroups.size(); j < orientationGroups.size() - 1; j++) {
const LineGroup& otherGroup = orientationGroups[j];
findLineIntersections(firstGroup, otherGroup, size);
}
}
}
void ImageProcessor::findLineIntersections(const LineGroup& firstGroup, const LineGroup otherGroup, const cv::Size& size)
{
const std::vector<const Line*> firstLines = firstGroup.getLines();
const std::vector<const Line*> otherLines = otherGroup.getLines();
for (int i = 0; i < firstLines.size(); ++i)
{
const Line* firstLine = firstLines[i];
for (int j = 0; j < otherLines.size(); j++)
{
const Line* otherLine = otherLines[j];
if (std::abs(otherLine->getOrientation().dot(firstLine->getOrientation())) > 0.8)
{
continue;
}
Vector intersection;
if (firstLines[i]->findIntersection(*otherLines[j], intersection)) {
Eigen::AlignedBox<float, 2> box(Vector(0.0, 0.0), Vector(size.width, size.height));
if (box.contains(intersection)) {
intersections_.push_back(intersection);
}
}
}
}
}
void ImageProcessor::drawIntersection(const std::vector<Vector>& intersections, const cv::Scalar& color, cv::Mat& dst)
{
for (int i = 0; i < intersections.size(); ++i) {
cv::circle(dst, cv::Point2f(intersections[i].x(), intersections[i].y()), 5, color, -1);
}
}
void ImageProcessor::groupByOrientation(std::vector<LineGroup>& orientationGroup, const std::vector<Line>& lines)
{
for (size_t i = 0; i < lineCluster_.size(); ++i) {
groupByOrientation(orientationGroup, lineCluster_[i]);
}
}
void ImageProcessor::groupByOrientation(std::vector<LineGroup>& group, Line& line)
{
const double PRECISION_TRESHOLD = 0.9;
double bestPrecision = 0.0;
LineGroup* bestGroup = nullptr;
bool groupFound = false;
for (int i = 0; i < group.size(); i++) {
double precision = std::abs(group[i].getAvgOrientation().dot(line.getOrientation()));
if (precision > PRECISION_TRESHOLD && precision > bestPrecision)
{
bestGroup = &group[i];
bestPrecision = precision;
groupFound = true;
}
}
if(groupFound) {
bestGroup->add(line);
} else {
group.push_back(LineGroup(line));
}
}
void ImageProcessor::buildLineArray(const std::vector<cv::Vec2f>& lineCluster)
{
Eigen::AlignedBox<float, 2> frame(Vector(0.0, 0.0), Vector(640.0, 480.0));
lineCluster_.clear();
for (int i = 0; i < lineCluster.size(); ++i)
{
lineCluster_.push_back(Line(lineCluster[i][0], lineCluster[i][1], frame));
}
}
}
| 33.007905 | 127 | 0.635014 | elikos |
00f7683f5fc55e88997d8a93b199d6512cf3204d | 2,384 | cpp | C++ | src/AppInstallerRepositoryCore/ManifestJSONParser.cpp | ryfu-msft/winget-cli | 9f8ceea4fb8959552075d7c6f8679abc6a310306 | [
"MIT"
] | null | null | null | src/AppInstallerRepositoryCore/ManifestJSONParser.cpp | ryfu-msft/winget-cli | 9f8ceea4fb8959552075d7c6f8679abc6a310306 | [
"MIT"
] | null | null | null | src/AppInstallerRepositoryCore/ManifestJSONParser.cpp | ryfu-msft/winget-cli | 9f8ceea4fb8959552075d7c6f8679abc6a310306 | [
"MIT"
] | 1 | 2022-01-18T19:23:34.000Z | 2022-01-18T19:23:34.000Z | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "Public/winget/ManifestJSONParser.h"
#include "Rest/Schema/1_0/Json/ManifestDeserializer.h"
#include "Rest/Schema/1_1/Json/ManifestDeserializer.h"
namespace AppInstaller::Repository::JSON
{
struct ManifestJSONParser::impl
{
// The deserializer. We only have one lineage (1.0+) right now.
std::unique_ptr<Rest::Schema::V1_0::Json::ManifestDeserializer> m_deserializer;
};
ManifestJSONParser::ManifestJSONParser(const Utility::Version& responseSchemaVersion)
{
const auto& parts = responseSchemaVersion.GetParts();
THROW_HR_IF(E_INVALIDARG, parts.empty());
m_pImpl = std::make_unique<impl>();
if (parts[0].Integer == 1)
{
if (parts.size() == 1 || parts[1].Integer == 0)
{
m_pImpl->m_deserializer = std::make_unique<Rest::Schema::V1_0::Json::ManifestDeserializer>();
}
else
{
m_pImpl->m_deserializer = std::make_unique<Rest::Schema::V1_1::Json::ManifestDeserializer>();
}
}
else
{
THROW_HR(HRESULT_FROM_WIN32(ERROR_UNSUPPORTED_TYPE));
}
}
ManifestJSONParser::ManifestJSONParser(ManifestJSONParser&&) noexcept = default;
ManifestJSONParser& ManifestJSONParser::operator=(ManifestJSONParser&&) noexcept = default;
ManifestJSONParser::~ManifestJSONParser() = default;
std::vector<Manifest::Manifest> ManifestJSONParser::Deserialize(const web::json::value& response) const
{
return m_pImpl->m_deserializer->Deserialize(response);
}
std::vector<Manifest::Manifest> ManifestJSONParser::DeserializeData(const web::json::value& data) const
{
return m_pImpl->m_deserializer->DeserializeData(data);
}
std::vector<Manifest::AppsAndFeaturesEntry> ManifestJSONParser::DeserializeAppsAndFeaturesEntries(const web::json::array& data) const
{
return m_pImpl->m_deserializer->DeserializeAppsAndFeaturesEntries(data);
}
std::optional<Manifest::ManifestLocalization> ManifestJSONParser::DeserializeLocale(const web::json::value& locale) const
{
return m_pImpl->m_deserializer->DeserializeLocale(locale);
}
}
| 36.121212 | 138 | 0.657718 | ryfu-msft |
00f801e99fc8cd3518af0a6e74d0ffdde4534d32 | 6,472 | hpp | C++ | src/hotspot/share/runtime/os_perf.hpp | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:52:15.000Z | 2020-12-26T04:52:15.000Z | src/hotspot/share/runtime/os_perf.hpp | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 1 | 2020-12-26T04:57:19.000Z | 2020-12-26T04:57:19.000Z | src/hotspot/share/runtime/os_perf.hpp | 1690296356/jdk | eaf668d1510c28d51e26c397b582b66ebdf7e263 | [
"Apache-2.0"
] | 1 | 2021-12-06T01:13:18.000Z | 2021-12-06T01:13:18.000Z | /*
* Copyright (c) 2012, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_RUNTIME_OS_PERF_HPP
#define SHARE_RUNTIME_OS_PERF_HPP
#include "memory/allocation.hpp"
#include "utilities/globalDefinitions.hpp"
#include "utilities/macros.hpp"
#define FUNCTIONALITY_NOT_IMPLEMENTED -8
class EnvironmentVariable : public CHeapObj<mtInternal> {
public:
char* _key;
char* _value;
EnvironmentVariable() {
_key = NULL;
_value = NULL;
}
~EnvironmentVariable() {
FREE_C_HEAP_ARRAY(char, _key);
FREE_C_HEAP_ARRAY(char, _value);
}
EnvironmentVariable(char* key, char* value) {
_key = key;
_value = value;
}
};
class CPUInformation : public CHeapObj<mtInternal> {
private:
int _no_of_sockets;
int _no_of_cores;
int _no_of_hw_threads;
const char* _description;
const char* _name;
public:
CPUInformation() {
_no_of_sockets = 0;
_no_of_cores = 0;
_no_of_hw_threads = 0;
_description = NULL;
_name = NULL;
}
int number_of_sockets(void) const {
return _no_of_sockets;
}
void set_number_of_sockets(int no_of_sockets) {
_no_of_sockets = no_of_sockets;
}
int number_of_cores(void) const {
return _no_of_cores;
}
void set_number_of_cores(int no_of_cores) {
_no_of_cores = no_of_cores;
}
int number_of_hardware_threads(void) const {
return _no_of_hw_threads;
}
void set_number_of_hardware_threads(int no_of_hw_threads) {
_no_of_hw_threads = no_of_hw_threads;
}
const char* cpu_name(void) const {
return _name;
}
void set_cpu_name(const char* cpu_name) {
_name = cpu_name;
}
const char* cpu_description(void) const {
return _description;
}
void set_cpu_description(const char* cpu_description) {
_description = cpu_description;
}
};
class SystemProcess : public CHeapObj<mtInternal> {
private:
int _pid;
char* _name;
char* _path;
char* _command_line;
SystemProcess* _next;
public:
SystemProcess() {
_pid = 0;
_name = NULL;
_path = NULL;
_command_line = NULL;
_next = NULL;
}
SystemProcess(int pid, char* name, char* path, char* command_line, SystemProcess* next) {
_pid = pid;
_name = name;
_path = path;
_command_line = command_line;
_next = next;
}
void set_next(SystemProcess* sys_process) {
_next = sys_process;
}
SystemProcess* next(void) const {
return _next;
}
int pid(void) const {
return _pid;
}
void set_pid(int pid) {
_pid = pid;
}
const char* name(void) const {
return _name;
}
void set_name(char* name) {
_name = name;
}
const char* path(void) const {
return _path;
}
void set_path(char* path) {
_path = path;
}
const char* command_line(void) const {
return _command_line;
}
void set_command_line(char* command_line) {
_command_line = command_line;
}
virtual ~SystemProcess(void) {
FREE_C_HEAP_ARRAY(char, _name);
FREE_C_HEAP_ARRAY(char, _path);
FREE_C_HEAP_ARRAY(char, _command_line);
}
};
class NetworkInterface : public ResourceObj {
private:
char* _name;
uint64_t _bytes_in;
uint64_t _bytes_out;
NetworkInterface* _next;
NONCOPYABLE(NetworkInterface);
public:
NetworkInterface(const char* name, uint64_t bytes_in, uint64_t bytes_out, NetworkInterface* next) :
_name(NULL),
_bytes_in(bytes_in),
_bytes_out(bytes_out),
_next(next) {
assert(name != NULL, "invariant");
const size_t length = strlen(name);
assert(allocated_on_res_area(), "invariant");
_name = NEW_RESOURCE_ARRAY(char, length + 1);
strncpy(_name, name, length + 1);
assert(strncmp(_name, name, length) == 0, "invariant");
}
NetworkInterface* next() const {
return _next;
}
const char* get_name() const {
return _name;
}
uint64_t get_bytes_out() const {
return _bytes_out;
}
uint64_t get_bytes_in() const {
return _bytes_in;
}
};
class CPUInformationInterface : public CHeapObj<mtInternal> {
private:
CPUInformation* _cpu_info;
public:
CPUInformationInterface();
bool initialize();
~CPUInformationInterface();
int cpu_information(CPUInformation& cpu_info);
};
class CPUPerformanceInterface : public CHeapObj<mtInternal> {
private:
class CPUPerformance;
CPUPerformance* _impl;
public:
CPUPerformanceInterface();
~CPUPerformanceInterface();
bool initialize();
int cpu_load(int which_logical_cpu, double* const cpu_load) const;
int context_switch_rate(double* const rate) const;
int cpu_load_total_process(double* const cpu_load) const;
int cpu_loads_process(double* const pjvmUserLoad,
double* const pjvmKernelLoad,
double* const psystemTotalLoad) const;
};
class SystemProcessInterface : public CHeapObj<mtInternal> {
private:
class SystemProcesses;
SystemProcesses* _impl;
public:
SystemProcessInterface();
~SystemProcessInterface();
bool initialize();
// information about system processes
int system_processes(SystemProcess** system_procs, int* const no_of_sys_processes) const;
};
class NetworkPerformanceInterface : public CHeapObj<mtInternal> {
private:
class NetworkPerformance;
NetworkPerformance* _impl;
NONCOPYABLE(NetworkPerformanceInterface);
public:
NetworkPerformanceInterface();
bool initialize();
~NetworkPerformanceInterface();
int network_utilization(NetworkInterface** network_interfaces) const;
};
#endif // SHARE_RUNTIME_OS_PERF_HPP
| 23.032028 | 101 | 0.709054 | 1690296356 |
00fc039e11d72fbd50f8d2e9e542853f518a8967 | 1,626 | hh | C++ | src/windows/libraries/ws2_32/types/WSABUF_IMPL.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 23 | 2021-02-17T16:58:52.000Z | 2022-02-12T17:01:06.000Z | src/windows/libraries/ws2_32/types/WSABUF_IMPL.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 1 | 2021-04-01T22:41:32.000Z | 2021-09-24T14:14:17.000Z | src/windows/libraries/ws2_32/types/WSABUF_IMPL.hh | IntroVirt/IntroVirt | 917f735f3430d0855d8b59c814bea7669251901c | [
"Apache-2.0"
] | 4 | 2021-02-17T16:53:18.000Z | 2021-04-13T16:51:10.000Z | /*
* Copyright 2021 Assured Information Security, 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.
*/
#pragma once
#include <introvirt/windows/libraries/ws2_32/types/WSABUF.hh>
namespace introvirt {
namespace windows {
namespace ws2_32 {
namespace structs {
template <typename PtrType>
struct _WSABUF {
uint32_t len;
PtrType buf;
};
} // namespace structs
template <typename PtrType>
class WSABUF_IMPL final : public WSABUF {
public:
uint32_t len() const override { return ptr_->len; }
void len(uint32_t len) override { ptr_->len = len; }
guest_ptr<const uint8_t[]> buf() const override {
return const_cast<WSABUF_IMPL<PtrType>*>(this)->buf();
}
guest_ptr<uint8_t[]> buf() override {
return guest_ptr<uint8_t[]>(ptr_.domain(), ptr_->buf, ptr_.page_directory(), len());
}
void buf(const guest_ptr<uint8_t[]>& buf) override { ptr_->buf = buf.address(); }
WSABUF_IMPL(const guest_ptr<void>& ptr) : ptr_(ptr) {}
private:
guest_ptr<structs::_WSABUF<PtrType>> ptr_;
};
} // namespace ws2_32
} // namespace windows
} // namespace introvirt | 29.035714 | 92 | 0.702337 | IntroVirt |
00ff824cf08ba008e87d810cf3332cefd969862a | 278 | cpp | C++ | CompetitiveProgramming/HackerEarth/BasicsofImplementation/CountDigits.cpp | send2manoo/Data-Structure-C | c9763ec9709421a558a8dee5e3d811dd8e343960 | [
"Apache-2.0"
] | 1 | 2020-01-20T09:15:13.000Z | 2020-01-20T09:15:13.000Z | CompetitiveProgramming/HackerEarth/BasicsofImplementation/CountDigits.cpp | send2manoo/Data-Structure-C | c9763ec9709421a558a8dee5e3d811dd8e343960 | [
"Apache-2.0"
] | null | null | null | CompetitiveProgramming/HackerEarth/BasicsofImplementation/CountDigits.cpp | send2manoo/Data-Structure-C | c9763ec9709421a558a8dee5e3d811dd8e343960 | [
"Apache-2.0"
] | 1 | 2020-10-01T06:33:39.000Z | 2020-10-01T06:33:39.000Z | #include <iostream>
using namespace std;
int main()
{
string S;
int S_length = 0, i=0, zero = 0, one = 0, two = 0, three = 0, four = 0, five = 0, six = 0, seven = 0 , eight = 0, nine = 0;
cin >> S;
S_length = S.length();
for (i = 0; i < S_length; i++)
{
}
return 0;
} | 19.857143 | 124 | 0.543165 | send2manoo |
2e008c9e96dab0976d65ffe9d7c295e03b2431d4 | 8,291 | cpp | C++ | src/slg/materials/metal2.cpp | mbrukman/LuxCore | 49a243f441785c9ba7ec1efcbd82fc0bf2595bfe | [
"Apache-2.0"
] | null | null | null | src/slg/materials/metal2.cpp | mbrukman/LuxCore | 49a243f441785c9ba7ec1efcbd82fc0bf2595bfe | [
"Apache-2.0"
] | null | null | null | src/slg/materials/metal2.cpp | mbrukman/LuxCore | 49a243f441785c9ba7ec1efcbd82fc0bf2595bfe | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
* Copyright 1998-2020 by authors (see AUTHORS.txt) *
* *
* This file is part of LuxCoreRender. *
* *
* 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 "slg/materials/metal2.h"
using namespace std;
using namespace luxrays;
using namespace slg;
//------------------------------------------------------------------------------
// Metal2 material
//
// LuxRender Metal2 material porting.
//------------------------------------------------------------------------------
Metal2Material::Metal2Material(const Texture *frontTransp, const Texture *backTransp,
const Texture *emitted, const Texture *bump,
const Texture *nn, const Texture *kk, const Texture *u, const Texture *v) :
Material(frontTransp, backTransp, emitted, bump),
fresnelTex(NULL), n(nn), k(kk), nu(u), nv(v) {
glossiness = ComputeGlossiness(nu, nv);
}
Metal2Material::Metal2Material(const Texture *frontTransp, const Texture *backTransp,
const Texture *emitted, const Texture *bump,
const FresnelTexture *ft, const Texture *u, const Texture *v) :
Material(frontTransp, backTransp, emitted, bump),
fresnelTex(ft), n(NULL), k(NULL), nu(u), nv(v) {
glossiness = ComputeGlossiness(nu, nv);
}
Spectrum Metal2Material::Albedo(const HitPoint &hitPoint) const {
Spectrum F;
if (fresnelTex)
F = fresnelTex->Evaluate(hitPoint, 1.f);
else {
// For compatibility with the past
const Spectrum etaVal = n->GetSpectrumValue(hitPoint).Clamp(.001f);
const Spectrum kVal = k->GetSpectrumValue(hitPoint).Clamp(.001f);
F = FresnelTexture::GeneralEvaluate(etaVal, kVal, 1.f);
}
F.Clamp(0.f, 1.f);
return F;
}
Spectrum Metal2Material::Evaluate(const HitPoint &hitPoint,
const Vector &localLightDir, const Vector &localEyeDir, BSDFEvent *event,
float *directPdfW, float *reversePdfW) const {
const float u = Clamp(nu->GetFloatValue(hitPoint), 1e-9f, 1.f);
const float v = Clamp(nv->GetFloatValue(hitPoint), 1e-9f, 1.f);
const float u2 = u * u;
const float v2 = v * v;
const float anisotropy = (u2 < v2) ? (1.f - u2 / v2) : u2 > 0.f ? (v2 / u2 - 1.f) : 0.f;
const float roughness = u * v;
const Vector wh(Normalize(localLightDir + localEyeDir));
const float cosWH = Dot(localLightDir, wh);
if (directPdfW)
*directPdfW = SchlickDistribution_Pdf(roughness, wh, anisotropy) / (4.f * cosWH);
if (reversePdfW)
*reversePdfW = SchlickDistribution_Pdf(roughness, wh, anisotropy) / (4.f * cosWH);
Spectrum F;
if (fresnelTex)
F = fresnelTex->Evaluate(hitPoint, cosWH);
else {
// For compatibility with the past
const Spectrum etaVal = n->GetSpectrumValue(hitPoint).Clamp(.001f);
const Spectrum kVal = k->GetSpectrumValue(hitPoint).Clamp(.001f);
F = FresnelTexture::GeneralEvaluate(etaVal, kVal, cosWH);
}
F.Clamp(0.f, 1.f);
const float G = SchlickDistribution_G(roughness, localLightDir, localEyeDir);
*event = GLOSSY | REFLECT;
return (SchlickDistribution_D(roughness, wh, anisotropy) * G / (4.f * fabsf(localEyeDir.z))) * F;
}
Spectrum Metal2Material::Sample(const HitPoint &hitPoint,
const Vector &localFixedDir, Vector *localSampledDir,
const float u0, const float u1, const float passThroughEvent,
float *pdfW, BSDFEvent *event, const BSDFEvent eventHint) const {
if (fabsf(localFixedDir.z) < DEFAULT_COS_EPSILON_STATIC)
return Spectrum();
const float u = Clamp(nu->GetFloatValue(hitPoint), 1e-9f, 1.f);
const float v = Clamp(nv->GetFloatValue(hitPoint), 1e-9f, 1.f);
const float u2 = u * u;
const float v2 = v * v;
const float anisotropy = (u2 < v2) ? (1.f - u2 / v2) : u2 > 0.f ? (v2 / u2 - 1.f) : 0.f;
const float roughness = u * v;
Vector wh;
float d, specPdf;
SchlickDistribution_SampleH(roughness, anisotropy, u0, u1, &wh, &d, &specPdf);
const float cosWH = Dot(localFixedDir, wh);
*localSampledDir = 2.f * cosWH * wh - localFixedDir;
const float coso = fabsf(localFixedDir.z);
const float cosi = fabsf(localSampledDir->z);
if ((cosi < DEFAULT_COS_EPSILON_STATIC) || (localFixedDir.z * localSampledDir->z < 0.f))
return Spectrum();
*pdfW = specPdf / (4.f * fabsf(cosWH));
if (*pdfW <= 0.f)
return Spectrum();
const float G = SchlickDistribution_G(roughness, localFixedDir, *localSampledDir);
Spectrum F;
if (fresnelTex)
F = fresnelTex->Evaluate(hitPoint, cosWH);
else {
// For compatibility with the past
const Spectrum etaVal = n->GetSpectrumValue(hitPoint).Clamp(.001f);
const Spectrum kVal = k->GetSpectrumValue(hitPoint).Clamp(.001f);
F = FresnelTexture::GeneralEvaluate(etaVal, kVal, cosWH);
}
F.Clamp(0.f, 1.f);
float factor = (d / specPdf) * G * fabsf(cosWH);
if (!hitPoint.fromLight)
factor /= coso;
else
factor /= cosi;
*event = GLOSSY | REFLECT;
return factor * F;
}
void Metal2Material::Pdf(const HitPoint &hitPoint,
const Vector &localLightDir, const Vector &localEyeDir,
float *directPdfW, float *reversePdfW) const {
const float u = Clamp(nu->GetFloatValue(hitPoint), 1e-9f, 1.f);
const float v = Clamp(nv->GetFloatValue(hitPoint), 1e-9f, 1.f);
const float u2 = u * u;
const float v2 = v * v;
const float anisotropy = (u2 < v2) ? (1.f - u2 / v2) : u2 > 0.f ? (v2 / u2 - 1.f) : 0.f;
const float roughness = u * v;
const Vector wh(Normalize(localLightDir + localEyeDir));
if (directPdfW)
*directPdfW = SchlickDistribution_Pdf(roughness, wh, anisotropy) / (4.f * AbsDot(localLightDir, wh));
if (reversePdfW)
*reversePdfW = SchlickDistribution_Pdf(roughness, wh, anisotropy) / (4.f * AbsDot(localLightDir, wh));
}
void Metal2Material::AddReferencedTextures(boost::unordered_set<const Texture *> &referencedTexs) const {
Material::AddReferencedTextures(referencedTexs);
if (fresnelTex)
fresnelTex->AddReferencedTextures(referencedTexs);
if (n)
n->AddReferencedTextures(referencedTexs);
if (k)
k->AddReferencedTextures(referencedTexs);
nu->AddReferencedTextures(referencedTexs);
nv->AddReferencedTextures(referencedTexs);
}
void Metal2Material::UpdateTextureReferences(const Texture *oldTex, const Texture *newTex) {
Material::UpdateTextureReferences(oldTex, newTex);
bool updateGlossiness = false;
if (fresnelTex == oldTex)
fresnelTex = (FresnelTexture *)newTex;
if (n == oldTex)
n = newTex;
if (k == oldTex)
k = newTex;
if (nu == oldTex) {
nu = newTex;
updateGlossiness = true;
}
if (nv == oldTex) {
nv = newTex;
updateGlossiness = true;
}
if (updateGlossiness)
glossiness = ComputeGlossiness(nu, nv);
}
Properties Metal2Material::ToProperties(const ImageMapCache &imgMapCache, const bool useRealFileName) const {
Properties props;
const string name = GetName();
props.Set(Property("scene.materials." + name + ".type")("metal2"));
if (fresnelTex)
props.Set(Property("scene.materials." + name + ".fresnel")(fresnelTex->GetSDLValue()));
if (n)
props.Set(Property("scene.materials." + name + ".n")(n->GetSDLValue()));
if (k)
props.Set(Property("scene.materials." + name + ".k")(k->GetSDLValue()));
props.Set(Property("scene.materials." + name + ".uroughness")(nu->GetSDLValue()));
props.Set(Property("scene.materials." + name + ".vroughness")(nv->GetSDLValue()));
props.Set(Material::ToProperties(imgMapCache, useRealFileName));
return props;
}
| 37.013393 | 110 | 0.640936 | mbrukman |
2e0307c3a32675cb8a349d8b80b2eb8dc25f9874 | 4,758 | hpp | C++ | output/include/core/fs/io_device.hpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | 1 | 2019-07-31T06:44:46.000Z | 2019-07-31T06:44:46.000Z | src/pilo/core/fs/io_device.hpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | null | null | null | src/pilo/core/fs/io_device.hpp | picofox/pilo | 59e12c947307d664c4ca9dcc232b481d06be104a | [
"MIT"
] | null | null | null | #pragma once
#include "core/coredefs.hpp"
#define MB_IO_DEV_OPEN_FLAG_APPEND (1<<0)
#define MB_IO_DEV_OPEN_SYNC (1<<1)
#define MB_IO_DEV_OPEN_NO_OS_CACHE (1<<2)
#define MB_IO_DEV_OPEN_REOPEN (1<<3)
#define MB_IO_DEV_INIT_FLAG_AUTO_CREATE (1<<0)
#define MB_IO_DEV_INIT_FLAG_FORCE_DELETE_DIR (1<<1)
#define MB_IO_DEV_INIT_FLAG_FORCE_DELETE_FILE (1<<2)
#define MB_IO_DEV_INIT_FLAG_AUTO_DELETE (1<<3)
#define MB_IO_DEV_INIT_FLAG_AUTO_DELETE_ON_FINALIZE (1<<4)
namespace pilo
{
namespace core
{
namespace fs
{
typedef enum
{
# ifdef WINDOWS
eDAM_CreateAlways = CREATE_ALWAYS,/**< Creates a new file, always. */
eDAM_CreateNew = CREATE_NEW,/**< Creates a new file, only if it does not already exist. */
eDAM_OpenAlways = OPEN_ALWAYS, /**< Opens a file, always.*/
eDAM_OpenExisting = OPEN_EXISTING, /**< Opens a file or device, only if it exists. */
eDAM_TruncateExisting = TRUNCATE_EXISTING, /**< Opens a file and truncates it so that its size is zero bytes, only if it exists.*/
# else
eDAM_CreateAlways = (O_CREAT | O_TRUNC),/**< Creates a new file, always. */
eDAM_CreateNew = (O_EXCL | O_CREAT),/**< Creates a new file, only if it does not already exist. */
eDAM_OpenAlways = O_CREAT, /**< Opens a file, always.*/
eDAM_OpenExisting = 0, /**< Opens a file or device, only if it exists. */
eDAM_TruncateExisting = O_TRUNC, /**< Opens a file and truncates it so that its size is zero bytes, only if it exists.*/
# endif
} DeviceAccessModeEnumeration;
typedef enum
{
# ifdef WINDOWS
eDRWM_None = 0,
eDRWM_Read = GENERIC_READ,
eDRWM_Write = GENERIC_WRITE,
eDRWM_ReadWrite = (GENERIC_READ | GENERIC_WRITE),
# else
eDRWM_None = 0,
eDRWM_Read = O_RDONLY,
eDRWM_Write = O_WRONLY,
eDRWM_ReadWrite = O_RDWR,
# endif
} DeviceRWModeEnumeration;
typedef enum
{
# ifdef WINDOWS
eDSW_Begin = FILE_BEGIN,
eDSW_Current = FILE_CURRENT,
eDSW_END = FILE_CURRENT,
# else
eDSW_Begin = SEEK_SET,
eDSW_Current = SEEK_CUR,
eDSW_END = SEEK_END,
# endif
} DeviceSeekWhenceEnumeration;
class io_device
{
public:
enum EnumIODeviceState
{
eIODS_Uninitialized = 0,
eIODS_Initialized = 1,
eIODS_Opend = 2,
};
io_device()
{
_m_context = nullptr;
_m_state = eIODS_Uninitialized;
_m_init_flags = 0;
_m_access_mode = eDAM_OpenExisting;
_m_rw_mode = eDRWM_None;
_m_open_flag = 0;
}
virtual ~io_device()
{
}
virtual ::pilo::error_number_t initialize(const char* path, ::pilo::u32_t flag, void* context) = 0;
virtual ::pilo::error_number_t finalize() = 0;
virtual ::pilo::error_number_t open(DeviceAccessModeEnumeration dev_acc_mode, DeviceRWModeEnumeration rw_mode, ::pilo::u32_t flag) = 0;
virtual ::pilo::error_number_t close() = 0;
virtual ::pilo::error_number_t read(void* buffer, size_t len, size_t* read_len) = 0;
virtual ::pilo::error_number_t write(const void* buffer, size_t len, size_t* written_len) = 0;
virtual ::pilo::error_number_t flush(::pilo::i32_t mode) = 0;
virtual ::pilo::error_number_t seek(::pilo::i64_t offset, DeviceSeekWhenceEnumeration eWhence, ::pilo::i64_t* r_offset) = 0;
inline void set_context(void* context)
{
_m_context = context;
}
protected:
void* _m_context;
volatile EnumIODeviceState _m_state;
::pilo::u32_t _m_init_flags;
DeviceAccessModeEnumeration _m_access_mode;
DeviceRWModeEnumeration _m_rw_mode;
::pilo::u32_t _m_open_flag;
};
}
}
} | 39.322314 | 151 | 0.519756 | picofox |
2e03f529a57225cb29ee158fc39249c2fea07d33 | 5,585 | cc | C++ | google/cloud/dataproc/cluster_controller_connection.cc | sydney-munro/google-cloud-cpp | 374b52e5cec78962358bdd5913d4118a47af1952 | [
"Apache-2.0"
] | null | null | null | google/cloud/dataproc/cluster_controller_connection.cc | sydney-munro/google-cloud-cpp | 374b52e5cec78962358bdd5913d4118a47af1952 | [
"Apache-2.0"
] | null | null | null | google/cloud/dataproc/cluster_controller_connection.cc | sydney-munro/google-cloud-cpp | 374b52e5cec78962358bdd5913d4118a47af1952 | [
"Apache-2.0"
] | null | null | null | // Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated by the Codegen C++ plugin.
// If you make any local changes, they will be lost.
// source: google/cloud/dataproc/v1/clusters.proto
#include "google/cloud/dataproc/cluster_controller_connection.h"
#include "google/cloud/dataproc/cluster_controller_options.h"
#include "google/cloud/dataproc/internal/cluster_controller_connection_impl.h"
#include "google/cloud/dataproc/internal/cluster_controller_option_defaults.h"
#include "google/cloud/dataproc/internal/cluster_controller_stub_factory.h"
#include "google/cloud/background_threads.h"
#include "google/cloud/common_options.h"
#include "google/cloud/grpc_options.h"
#include "google/cloud/internal/pagination_range.h"
#include <memory>
namespace google {
namespace cloud {
namespace dataproc {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
ClusterControllerConnection::~ClusterControllerConnection() = default;
future<StatusOr<google::cloud::dataproc::v1::Cluster>>
ClusterControllerConnection::CreateCluster(
google::cloud::dataproc::v1::CreateClusterRequest const&) {
return google::cloud::make_ready_future<
StatusOr<google::cloud::dataproc::v1::Cluster>>(
Status(StatusCode::kUnimplemented, "not implemented"));
}
future<StatusOr<google::cloud::dataproc::v1::Cluster>>
ClusterControllerConnection::UpdateCluster(
google::cloud::dataproc::v1::UpdateClusterRequest const&) {
return google::cloud::make_ready_future<
StatusOr<google::cloud::dataproc::v1::Cluster>>(
Status(StatusCode::kUnimplemented, "not implemented"));
}
future<StatusOr<google::cloud::dataproc::v1::Cluster>>
ClusterControllerConnection::StopCluster(
google::cloud::dataproc::v1::StopClusterRequest const&) {
return google::cloud::make_ready_future<
StatusOr<google::cloud::dataproc::v1::Cluster>>(
Status(StatusCode::kUnimplemented, "not implemented"));
}
future<StatusOr<google::cloud::dataproc::v1::Cluster>>
ClusterControllerConnection::StartCluster(
google::cloud::dataproc::v1::StartClusterRequest const&) {
return google::cloud::make_ready_future<
StatusOr<google::cloud::dataproc::v1::Cluster>>(
Status(StatusCode::kUnimplemented, "not implemented"));
}
future<StatusOr<google::cloud::dataproc::v1::ClusterOperationMetadata>>
ClusterControllerConnection::DeleteCluster(
google::cloud::dataproc::v1::DeleteClusterRequest const&) {
return google::cloud::make_ready_future<
StatusOr<google::cloud::dataproc::v1::ClusterOperationMetadata>>(
Status(StatusCode::kUnimplemented, "not implemented"));
}
StatusOr<google::cloud::dataproc::v1::Cluster>
ClusterControllerConnection::GetCluster(
google::cloud::dataproc::v1::GetClusterRequest const&) {
return Status(StatusCode::kUnimplemented, "not implemented");
}
StreamRange<google::cloud::dataproc::v1::Cluster>
ClusterControllerConnection::ListClusters(
google::cloud::dataproc::v1::
ListClustersRequest) { // NOLINT(performance-unnecessary-value-param)
return google::cloud::internal::MakeUnimplementedPaginationRange<
StreamRange<google::cloud::dataproc::v1::Cluster>>();
}
future<StatusOr<google::cloud::dataproc::v1::DiagnoseClusterResults>>
ClusterControllerConnection::DiagnoseCluster(
google::cloud::dataproc::v1::DiagnoseClusterRequest const&) {
return google::cloud::make_ready_future<
StatusOr<google::cloud::dataproc::v1::DiagnoseClusterResults>>(
Status(StatusCode::kUnimplemented, "not implemented"));
}
std::shared_ptr<ClusterControllerConnection> MakeClusterControllerConnection(
Options options) {
internal::CheckExpectedOptions<CommonOptionList, GrpcOptionList,
ClusterControllerPolicyOptionList>(options,
__func__);
options =
dataproc_internal::ClusterControllerDefaultOptions(std::move(options));
auto background = internal::MakeBackgroundThreadsFactory(options)();
auto stub = dataproc_internal::CreateDefaultClusterControllerStub(
background->cq(), options);
return std::make_shared<dataproc_internal::ClusterControllerConnectionImpl>(
std::move(background), std::move(stub), std::move(options));
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace dataproc
} // namespace cloud
} // namespace google
namespace google {
namespace cloud {
namespace dataproc_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
std::shared_ptr<dataproc::ClusterControllerConnection>
MakeClusterControllerConnection(std::shared_ptr<ClusterControllerStub> stub,
Options options) {
options = ClusterControllerDefaultOptions(std::move(options));
auto background = internal::MakeBackgroundThreadsFactory(options)();
return std::make_shared<dataproc_internal::ClusterControllerConnectionImpl>(
std::move(background), std::move(stub), std::move(options));
}
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
} // namespace dataproc_internal
} // namespace cloud
} // namespace google
| 41.066176 | 82 | 0.755058 | sydney-munro |
2e05ffbdcfc0058fbc589b079f97fab11807e86c | 22,737 | hpp | C++ | selene/base/Kernel.hpp | kmhofmann/selene | 11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb | [
"MIT"
] | 284 | 2017-11-20T08:23:54.000Z | 2022-03-30T12:52:00.000Z | selene/base/Kernel.hpp | kmhofmann/selene | 11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb | [
"MIT"
] | 9 | 2018-02-14T08:21:41.000Z | 2021-07-27T19:52:12.000Z | selene/base/Kernel.hpp | kmhofmann/selene | 11718e1a7de6ff6251c46e4ef429a7cfb1bdb9eb | [
"MIT"
] | 17 | 2018-03-10T00:01:36.000Z | 2021-06-29T10:44:27.000Z | // This file is part of the `Selene` library.
// Copyright 2017-2019 Michael Hofmann (https://github.com/kmhofmann).
// Distributed under MIT license. See accompanying LICENSE file in the top-level directory.
#ifndef SELENE_BASE_KERNEL_HPP
#define SELENE_BASE_KERNEL_HPP
/// @file
#include <selene/base/Assert.hpp>
#include <selene/base/Round.hpp>
#include <selene/base/Types.hpp>
#include <selene/base/Utils.hpp>
#include <selene/base/_impl/ExplicitType.hpp>
#include <algorithm>
#include <array>
#include <cstdint>
#include <limits>
#include <vector>
#include <cmath>
namespace sln {
/// \addtogroup group-base
/// @{
using KernelSize = std::ptrdiff_t;
constexpr static auto kernel_size_dynamic = KernelSize{-1};
template <typename ValueType_, KernelSize k_ = kernel_size_dynamic>
class Kernel;
/** \brief 1-dimensional kernel class.
*
* This class represents a 1-dimensional kernel, for use in image convolutions.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The kernel size. If it is set to `kernel_size_dynamic`, the data used to store the kernel elements
* will be allocated dynamically (i.e. using a `std::vector`); otherwise, it will be allocated on the stack
* (i.e. using a `std::array`).
*/
template <typename ValueType_, KernelSize k_>
class Kernel
{
public:
using value_type = ValueType_;
using iterator = typename std::array<ValueType_, k_>::iterator;
using const_iterator = typename std::array<ValueType_, k_>::const_iterator;
constexpr Kernel() = default; ///< Default constructor.
constexpr Kernel(const std::array<ValueType_, k_>& data);
~Kernel() = default; ///< Defaulted destructor.
constexpr Kernel(const Kernel&) = default; ///< Defaulted copy constructor.
constexpr Kernel& operator=(const Kernel&) = default; ///< Defaulted copy assignment operator.
constexpr Kernel(Kernel&&) noexcept = default; ///< Defaulted move constructor.
constexpr Kernel& operator=(Kernel&&) noexcept = default; ///< Defaulted move assignment operator.
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
[[nodiscard]] constexpr std::size_t size() const noexcept;
constexpr value_type operator[](std::size_t idx) const noexcept;
constexpr void normalize(value_type sum) noexcept;
constexpr void normalize() noexcept;
private:
std::array<ValueType_, k_> data_;
static_assert(k_ >= 0, "Kernel size must be non-negative");
static_assert(std::is_trivial_v<ValueType_>, "Value type of kernel is not trivial");
};
/** \brief 1-dimensional kernel class. Partial specialization for k_ == kernel_size_dynamic.
*
* @tparam ValueType_ The value type of the kernel elements.
*/
template <typename ValueType_>
class Kernel<ValueType_, kernel_size_dynamic>
{
public:
using value_type = ValueType_;
using iterator = typename std::vector<ValueType_>::iterator;
using const_iterator = typename std::vector<ValueType_>::const_iterator;
Kernel() = default; ///< Default constructor.
Kernel(std::initializer_list<ValueType_> init);
explicit Kernel(std::vector<value_type>&& vec);
~Kernel() = default; ///< Defaulted destructor.
Kernel(const Kernel&) = default; ///< Defaulted copy constructor.
Kernel& operator=(const Kernel&) = default; ///< Defaulted copy assignment operator.
Kernel(Kernel&&) noexcept = default; ///< Defaulted move constructor.
Kernel& operator=(Kernel&&) noexcept = default; ///< Defaulted move assignment operator.
iterator begin() noexcept;
const_iterator begin() const noexcept;
const_iterator cbegin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
const_iterator cend() const noexcept;
std::size_t size() const noexcept;
value_type operator[](std::size_t idx) const noexcept;
void normalize(value_type sum) noexcept;
void normalize() noexcept;
private:
std::vector<ValueType_> data_;
static_assert(std::is_trivial_v<ValueType_>, "Value type of kernel is not trivial");
};
template <typename ValueType, KernelSize k>
constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel, ValueType sum);
template <typename ValueType, KernelSize k>
constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel);
template <KernelSize kernel_size, typename ValueType = default_float_t>
auto gaussian_kernel(default_float_t sigma, bool renormalize = true);
template <typename ValueType = default_float_t>
auto gaussian_kernel(default_float_t sigma, KernelSize size, bool renormalize = true);
template <typename ValueType = default_float_t>
auto gaussian_kernel(default_float_t sigma, default_float_t range_nr_std_deviations, bool renormalize = true);
template <KernelSize kernel_size, typename ValueType = default_float_t>
constexpr auto uniform_kernel();
template <typename ValueType = default_float_t>
auto uniform_kernel(KernelSize size);
template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType, KernelSize k,
typename = std::enable_if_t<k != kernel_size_dynamic>>
constexpr Kernel<OutValueType, k> integer_kernel(const Kernel<ValueType, k>& kernel);
template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType>
Kernel<OutValueType, kernel_size_dynamic> integer_kernel(const Kernel<ValueType, kernel_size_dynamic>& kernel);
/// @}
// ----------
// Implementation:
/** \brief Constructor from a `std::array`.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @param data The data the kernel should contain.
*/
template <typename ValueType_, KernelSize k_>
constexpr Kernel<ValueType_, k_>::Kernel(const std::array<ValueType_, k_>& data)
: data_(data)
{ }
/** \brief Returns an iterator to the beginning of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return An iterator to the beginning of the kernel data.
*/
template <typename ValueType_, KernelSize k_>
auto Kernel<ValueType_, k_>::begin() noexcept -> iterator
{
return data_.begin();
}
/** \brief Returns a constant iterator to the beginning of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return A constant iterator to the beginning of the kernel data.
*/
template <typename ValueType_, KernelSize k_>
auto Kernel<ValueType_, k_>::begin() const noexcept -> const_iterator
{
return data_.begin();
}
/** \brief Returns a constant iterator to the beginning of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return A constant iterator to the beginning of the kernel data.
*/
template <typename ValueType_, KernelSize k_>
auto Kernel<ValueType_, k_>::cbegin() const noexcept -> const_iterator
{
return data_.cbegin();
}
/** \brief Returns an iterator to the end of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return An iterator to the end of the kernel data.
*/
template <typename ValueType_, KernelSize k_>
auto Kernel<ValueType_, k_>::end() noexcept -> iterator
{
return data_.end();
}
/** \brief Returns a constant iterator to the end of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return A constant iterator to the end of the kernel data.
*/
template <typename ValueType_, KernelSize k_>
auto Kernel<ValueType_, k_>::end() const noexcept -> const_iterator
{
return data_.end();
}
/** \brief Returns a constant iterator to the end of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return A constant iterator to the end of the kernel data.
*/
template <typename ValueType_, KernelSize k_>
auto Kernel<ValueType_, k_>::cend() const noexcept -> const_iterator
{
return data_.cend();
}
/** \brief Returns the size (length) of the kernel.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @return The kernel size.
*/
template <typename ValueType_, KernelSize k_>
constexpr std::size_t Kernel<ValueType_, k_>::size() const noexcept
{
return static_cast<std::size_t>(k_);
}
/** \brief Access the n-th kernel element.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @param idx The index of the element to access.
* @return The n-th kernel element, speficied by `idx`.
*/
template <typename ValueType_, KernelSize k_>
constexpr auto Kernel<ValueType_, k_>::operator[](std::size_t idx) const noexcept -> value_type
{
SELENE_ASSERT(idx < k_);
return data_[idx];
}
/** \brief Normalizes the kernel by dividing each element by the specified sum.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @param sum The value that each element will be divided by.
*/
template <typename ValueType_, KernelSize k_>
constexpr void Kernel<ValueType_, k_>::normalize(value_type sum) noexcept
{
for (std::size_t i = 0; i < data_.size(); ++i)
{
data_[i] /= sum;
}
}
/** \brief Normalizes the kernel such that the sum of (absolute) elements is 1.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
*/
template <typename ValueType_, KernelSize k_>
constexpr void Kernel<ValueType_, k_>::normalize() noexcept
{
auto abs_sum = value_type{0};
for (std::size_t i = 0; i < data_.size(); ++i)
{
abs_sum += (data_[i] >= 0) ? data_[i] : -data_[i];
}
normalize(abs_sum);
}
// -----
/** \brief Constructor from an initializer list.
*
* @tparam ValueType_ The value type of the kernel elements.
* @param init The data the kernel should contain, in form of an initializer list.
*/
template <typename ValueType_>
Kernel<ValueType_, kernel_size_dynamic>::Kernel(std::initializer_list<ValueType_> init)
: data_(init)
{
}
/** \brief Constructor from a `std::vector`.
*
* @tparam ValueType_ The value type of the kernel elements.
* @param vec The data the kernel should contain.
*/
template <typename ValueType_>
Kernel<ValueType_, kernel_size_dynamic>::Kernel(std::vector<value_type>&& vec)
: data_(std::move(vec))
{
}
/** \brief Returns an iterator to the beginning of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return An iterator to the beginning of the kernel data.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::begin() noexcept -> iterator
{
return data_.begin();
}
/** \brief Returns a constant iterator to the beginning of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return A constant iterator to the beginning of the kernel data.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::begin() const noexcept -> const_iterator
{
return data_.begin();
}
/** \brief Returns a constant iterator to the beginning of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return A constant iterator to the beginning of the kernel data.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::cbegin() const noexcept -> const_iterator
{
return data_.cbegin();
}
/** \brief Returns an iterator to the end of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return An iterator to the end of the kernel data.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::end() noexcept -> iterator
{
return data_.end();
}
/** \brief Returns a constant iterator to the end of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return A constant iterator to the end of the kernel data.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::end() const noexcept -> const_iterator
{
return data_.end();
}
/** \brief Returns a constant iterator to the end of the kernel data.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return A constant iterator to the end of the kernel data.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::cend() const noexcept -> const_iterator
{
return data_.cend();
}
/** \brief Returns the size (length) of the kernel.
*
* @tparam ValueType_ The value type of the kernel elements.
* @return The kernel size.
*/
template <typename ValueType_>
std::size_t Kernel<ValueType_, kernel_size_dynamic>::size() const noexcept
{
return data_.size();
}
/** \brief Access the n-th kernel element.
*
* @tparam ValueType_ The value type of the kernel elements.
* @param idx The index of the element to access.
* @return The n-th kernel element, speficied by `idx`.
*/
template <typename ValueType_>
auto Kernel<ValueType_, kernel_size_dynamic>::operator[](std::size_t idx) const noexcept -> value_type
{
SELENE_ASSERT(idx < data_.size());
return data_[idx];
}
/** \brief Normalizes the kernel by dividing each element by the specified sum.
*
* @tparam ValueType_ The value type of the kernel elements.
* @param sum The value that each element will be divided by.
*/
template <typename ValueType_>
void Kernel<ValueType_, kernel_size_dynamic>::normalize(value_type sum) noexcept
{
for (std::size_t i = 0; i < data_.size(); ++i)
{
data_[i] /= sum;
}
}
/** \brief Normalizes the kernel such that the sum of (absolute) elements is 1.
*
* @tparam ValueType_ The value type of the kernel elements.
*/
template <typename ValueType_>
void Kernel<ValueType_, kernel_size_dynamic>::normalize() noexcept
{
auto abs_sum = value_type{0};
for (std::size_t i = 0; i < data_.size(); ++i)
{
abs_sum += std::abs(data_[i]);
}
normalize(abs_sum);
}
// -----
namespace impl {
template <typename ValueType = default_float_t>
inline auto gaussian_pdf(ValueType x, ValueType mu, ValueType sigma)
{
constexpr auto f = ValueType(0.3989422804014326779); // 1.0 / sqrt(2.0 * M_PI)
const auto diff = x - mu;
return (f / sigma) * std::exp(-(diff * diff / (ValueType{2} * sigma * sigma)));
}
template <typename Container>
inline auto fill_with_gaussian_pdf(Container& c, std::ptrdiff_t center_idx, default_float_t sigma)
{
using size_type = std::ptrdiff_t;
using value_type = typename Container::value_type;
auto sum = value_type{0};
for (std::size_t i = 0; i < c.size(); ++i)
{
const auto x = value_type(static_cast<size_type>(i) - center_idx);
const auto g = gaussian_pdf(x, value_type{0}, sigma);
c[i] = g;
sum += g;
}
return sum;
}
} // namespace impl
/** \brief Returns a normalized kernel, where each element of the input kernel has been divided by the specified sum.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @param kernel The input kernel.
* @param sum The value that each element of the input kernel will be divided by.
* @return The normalized kernel.
*/
template <typename ValueType, KernelSize k>
constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel, ValueType sum)
{
auto normalized_kernel = kernel;
normalized_kernel.normalize(sum);
return normalized_kernel;
}
/** \brief Returns a normalized kernel, such that the sum of (absolute) elements is 1.
*
* @tparam ValueType_ The value type of the kernel elements.
* @tparam k_ The number of kernel elements.
* @param kernel The input kernel.
* @return The normalized kernel.
*/
template <typename ValueType, KernelSize k>
constexpr Kernel<ValueType, k> normalize(const Kernel<ValueType, k>& kernel)
{
auto normalized_kernel = kernel;
normalized_kernel.normalize();
return normalized_kernel;
}
/** \brief Returns a kernel discretely sampled from a Gaussian (normal) distribution.
*
* @tparam kernel_size The kernel size.
* @tparam ValueType The value type of the kernel elements.
* @param sigma The standard deviation of the Gaussian distribution.
* @param renormalize If true, the kernel will be normalized after sampling, such the the sum of its elements is 1.
* @return A kernel representing a sampled Gaussian distribution.
*/
template <KernelSize kernel_size, typename ValueType>
inline auto gaussian_kernel(default_float_t sigma, bool renormalize)
{
static_assert(kernel_size % 2 == 1, "Gaussian kernel size must be odd");
constexpr auto center_idx = kernel_size / 2;
static_assert(center_idx == (kernel_size - 1) / 2);
auto arr = std::array<ValueType, kernel_size>();
const auto sum = impl::fill_with_gaussian_pdf(arr, center_idx, sigma);
auto kernel = Kernel<ValueType, kernel_size>(arr);
if (renormalize)
{
kernel.normalize(sum);
}
return kernel;
}
/** \brief Returns a kernel discretely sampled from a Gaussian (normal) distribution.
*
* @tparam ValueType The value type of the kernel elements.
* @param sigma The standard deviation of the Gaussian distribution.
* @param size The kernel size.
* @param renormalize If true, the kernel will be normalized after sampling, such the the sum of its elements is 1.
* @return A kernel representing a sampled Gaussian distribution.
*/
template <typename ValueType>
inline auto gaussian_kernel(default_float_t sigma, KernelSize size, bool renormalize)
{
//SELENE_ASSERT(size % 2 == 1);
const auto full_size = (size % 2 == 0) ? size + 1 : size; // ensure kernel size is odd
const auto center_idx = full_size / 2;
SELENE_ASSERT(center_idx == (full_size - 1) / 2);
auto vec = std::vector<ValueType>(static_cast<std::size_t>(full_size));
const auto sum = impl::fill_with_gaussian_pdf(vec, center_idx, sigma);
auto kernel = Kernel<ValueType, kernel_size_dynamic>(std::move(vec));
if (renormalize)
{
kernel.normalize(sum);
}
return kernel;
}
/** \brief Returns a kernel discretely sampled from a Gaussian (normal) distribution.
*
* Using this overload, the kernel size will be determined by the given range in times of standard deviation.
*
* @tparam ValueType The value type of the kernel elements.
* @param sigma The standard deviation of the Gaussian distribution.
* @param range_nr_std_deviations How many standard deviations should be represented.
* @param renormalize If true, the kernel will be normalized after sampling, such the the sum of its elements is 1.
* @return A kernel representing a sampled Gaussian distribution.
*/
template <typename ValueType>
inline auto gaussian_kernel(default_float_t sigma, default_float_t range_nr_std_deviations, bool renormalize)
{
using size_type = std::ptrdiff_t;
const auto half_size = static_cast<size_type>(std::ceil(sigma * range_nr_std_deviations));
const auto full_size = 2 * std::max(size_type{1}, half_size) + 1;
const auto center_idx = full_size / 2;
SELENE_ASSERT(center_idx == (full_size - 1) / 2);
auto vec = std::vector<ValueType>(static_cast<std::size_t>(full_size));
const auto sum = impl::fill_with_gaussian_pdf(vec, center_idx, sigma);
auto kernel = Kernel<ValueType, kernel_size_dynamic>(std::move(vec));
if (renormalize)
{
kernel.normalize(sum);
}
return kernel;
}
/** \brief Returns a kernel representing a discrete uniform distribution.
*
* @tparam kernel_size The kernel size.
* @tparam ValueType The value type of the kernel elements.
* @return A kernel representing a discrete uniform distribution.
*/
template <KernelSize kernel_size, typename ValueType>
constexpr auto uniform_kernel()
{
static_assert(kernel_size > 0, "Kernel size must be >0.");
constexpr auto value = ValueType(1.0) / ValueType(kernel_size);
constexpr auto arr = sln::make_array_n_equal<ValueType, kernel_size>(value);
return Kernel<ValueType, kernel_size>(arr);
}
/** \brief Returns a kernel representing a discrete uniform distribution.
*
* @tparam ValueType The value type of the kernel elements.
* @param size The kernel size.
* @return A kernel representing a discrete uniform distribution.
*/
template <typename ValueType>
inline auto uniform_kernel(KernelSize size)
{
if (size == 0)
{
return Kernel<ValueType, kernel_size_dynamic>();
}
const auto value = ValueType(1.0) / ValueType(size);
auto vec = std::vector<ValueType>(static_cast<std::size_t>(size), value);
return Kernel<ValueType, kernel_size_dynamic>(std::move(vec));
}
/** \brief Converts a floating point kernel into a kernel containing scaled integral values.
*
* @tparam OutValueType The output element type of the kernel to be returned.
* @tparam scale_factor The multiplication factor for scaling the input kernel elements with.
* @tparam ValueType The value type of the input kernel elements.
* @tparam k The kernel size.
* @param kernel The input floating point kernel.
* @return An integer kernel, scaled by the respective factor
*/
template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType, KernelSize k, typename>
constexpr auto integer_kernel(const Kernel<ValueType, k>& kernel)
-> Kernel<OutValueType, k>
{
static_assert(std::is_integral_v<OutValueType>, "Output type has to be integral");
std::array<OutValueType, k> arr = {{OutValueType{}}};
for (std::size_t i = 0; i < arr.size(); ++i)
{
arr[i] = sln::constexpr_round<OutValueType>(kernel[i] * scale_factor);
}
return Kernel<OutValueType, k>(arr);
}
/** \brief Converts a floating point kernel into a kernel containing scaled integral values.
*
* @tparam OutValueType The output element type of the kernel to be returned.
* @tparam scale_factor The multiplication factor for scaling the input kernel elements with.
* @tparam ValueType The value type of the input kernel elements.
* @param kernel The input floating point kernel.
* @return An integer kernel, scaled by the respective factor
*/
template <typename OutValueType, std::ptrdiff_t scale_factor, typename ValueType>
inline auto integer_kernel(const Kernel<ValueType, kernel_size_dynamic>& kernel)
-> Kernel<OutValueType, kernel_size_dynamic>
{
static_assert(std::is_integral_v<OutValueType>, "Output type has to be integral");
std::vector<OutValueType> vec(kernel.size());
for (std::size_t i = 0; i < vec.size(); ++i)
{
vec[i] = sln::round<OutValueType>(kernel[i] * scale_factor);
}
return Kernel<OutValueType, kernel_size_dynamic>(std::move(vec));
}
} // namespace sln
#endif // SELENE_BASE_KERNEL_HPP
| 33.584934 | 118 | 0.734881 | kmhofmann |
2e073496ac144b8a6bfddb35875375faa5b602d8 | 701 | hpp | C++ | include/srpc/net/client/Client.hpp | ISSuh/SimpleRPC | 429f14d26a783ff092f326a49576d945f82ad610 | [
"MIT"
] | null | null | null | include/srpc/net/client/Client.hpp | ISSuh/SimpleRPC | 429f14d26a783ff092f326a49576d945f82ad610 | [
"MIT"
] | null | null | null | include/srpc/net/client/Client.hpp | ISSuh/SimpleRPC | 429f14d26a783ff092f326a49576d945f82ad610 | [
"MIT"
] | null | null | null | /**
*
* Copyright: Copyright (c) 2020, ISSuh
*
*/
#ifndef SRPC_NET_CLIENT_CLIENT_HPP_
#define SRPC_NET_CLIENT_CLIENT_HPP_
#include <string>
namespace srpc {
class Client {
public:
Client() = default;
virtual ~Client() = default;
virtual void connect(const std::string& host, const std::string& port) = 0;
virtual void close() = 0;
virtual void request(const std::string& serviceName,
const std::string& rpcName,
const std::string& params) = 0;
virtual void onConnect() = 0;
virtual void onRead(std::string serializedMessage) = 0;
virtual void onWrite() = 0;
};
} // namespace srpc
#endif // SRPC_NET_CLIENT_CLIENT_HPP_
| 20.617647 | 77 | 0.650499 | ISSuh |
2e0b091088cf71f68a084d4552744de6ae5d4717 | 1,017 | cpp | C++ | Projects/RealityEngine/source/Core/Tools/Logger.cpp | Volta948/RealityEngine | 1a9e4b7db00617176d06004af934d6602dd5920a | [
"BSD-3-Clause"
] | null | null | null | Projects/RealityEngine/source/Core/Tools/Logger.cpp | Volta948/RealityEngine | 1a9e4b7db00617176d06004af934d6602dd5920a | [
"BSD-3-Clause"
] | null | null | null | Projects/RealityEngine/source/Core/Tools/Logger.cpp | Volta948/RealityEngine | 1a9e4b7db00617176d06004af934d6602dd5920a | [
"BSD-3-Clause"
] | 1 | 2021-11-05T02:55:27.000Z | 2021-11-05T02:55:27.000Z | // Copyright Reality Engine. All Rights Reserved.
#include "Core/Tools/Logger.h"
#include <cstdarg>
#include <fstream>
Reality::Logger::Logger() :
m_File{ std::make_unique<std::ofstream>(L"Logs/Logs.txt", std::ios::out | std::ios::trunc) }
{}
Reality::Logger::~Logger() = default;
void Reality::Logger::Log(const char*, int line, const char* func, LogVerbosity, unsigned severity,
const char* message, ...)
{
if (severity < Severity) {
return;
}
std::lock_guard guard{ m_Lock };
static constexpr auto s_BufferSize{ 512ull };
char buffer[s_BufferSize];
const auto charSize{ std::snprintf(buffer, s_BufferSize, "Function %s line %d at %s.\n", func, line, __TIME__) };
m_File->write(buffer, charSize);
std::va_list args{};
va_start(args, message);
const auto messageSize{ std::vsnprintf(buffer, s_BufferSize, message, args) };
va_end(args);
m_File->write(buffer, messageSize);
if (Callback) {
Callback(buffer);
}
else {
std::puts(buffer);
}
} | 24.214286 | 115 | 0.6647 | Volta948 |
2e0d0122bacb5ad04230aba27e3e9ecbf382b718 | 502 | cpp | C++ | libs/renderer/src/renderer/plugin/collection.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/renderer/src/renderer/plugin/collection.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/renderer/src/renderer/plugin/collection.cpp | 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)
#include <sge/plugin/impl/instantiate_collection.hpp>
#include <sge/renderer/core.hpp>
#include <sge/renderer/plugin/collection.hpp>
#include <sge/renderer/plugin/iterator.hpp>
#include <sge/renderer/plugin/traits.hpp>
SGE_PLUGIN_IMPL_INSTANTIATE_COLLECTION(sge::renderer::core);
| 38.615385 | 61 | 0.750996 | cpreh |
2e0ee15dff2c766adf01350b6a9fdd5048e8f91d | 1,066 | cpp | C++ | source/physics/private/internal/simulation/frameparts/framebody.cpp | fpuma/Physics2dModule | c329e45d05c77b81a45e0d509fe8deb1d327c686 | [
"MIT"
] | null | null | null | source/physics/private/internal/simulation/frameparts/framebody.cpp | fpuma/Physics2dModule | c329e45d05c77b81a45e0d509fe8deb1d327c686 | [
"MIT"
] | null | null | null | source/physics/private/internal/simulation/frameparts/framebody.cpp | fpuma/Physics2dModule | c329e45d05c77b81a45e0d509fe8deb1d327c686 | [
"MIT"
] | null | null | null | #include <precompiledphysics.h>
#include "framebody.h"
#include <utils/geometry/shapes/shape.h>
#include <box2d/b2_body.h>
#include <box2d/b2_fixture.h>
namespace puma::physics
{
FrameBody::FrameBody( FramePartID _id )
: m_framePart( _id )
{
}
/*Vec2 Body::getOffset() const
{
return m_offset;
}*/
float FrameBody::getFriction() const
{
return m_framePart.getFriction();
}
void FrameBody::setFriction( float _friction )
{
m_framePart.setFriction( _friction );
}
float FrameBody::getDensity() const
{
return m_framePart.getDensity();
}
void FrameBody::setDensity( float _density )
{
m_framePart.setDensity( _density );
}
float FrameBody::getRestitution() const
{
return m_framePart.getRestitution();
}
void FrameBody::setRestitution( float _restitution )
{
m_framePart.setRestitution( _restitution );
}
bool FrameBody::isValid() const
{
return m_framePart.isValid();
}
} | 19.035714 | 56 | 0.621013 | fpuma |
2e10119220e1abe4a2a5173f0b0de2a11a453ae8 | 1,010 | cpp | C++ | ComputerScienceSubj.cpp | tsvetan-gabrovski/SUSI-Project | c4d6544b5463a35b2bdcb876578324d47a10b315 | [
"MIT"
] | null | null | null | ComputerScienceSubj.cpp | tsvetan-gabrovski/SUSI-Project | c4d6544b5463a35b2bdcb876578324d47a10b315 | [
"MIT"
] | null | null | null | ComputerScienceSubj.cpp | tsvetan-gabrovski/SUSI-Project | c4d6544b5463a35b2bdcb876578324d47a10b315 | [
"MIT"
] | null | null | null | #include "ComputerScienceSubj.h"
ComputerScienceSubj::ComputerScienceSubj()
{
this->setName("ComputerScience.txt");
}
void ComputerScienceSubj::createFIle()
{
std::ofstream out(this->getNameSubject());
out << "Course1\n" << "Algebra,Discret Structures,Differential and Integral calculus1,Introduction to programming," <<
"Geometry,Differential and Integral calculus 2,Object-oriented programming,Languages and computability,\n";
out << "Course2\n" << "Computer English,Computer architectures,Data structures,Fundamentals of computer graphics,Functional programming," <<
"Algebra2,Design and analysis of alhorithms,Computer networks,Operatins research,Operating systems,\n";
out << "Course3\n" << "Logical programming,Network programming,System programming,Numerical analysis," <<
"Database,Probability and statistics,Parallel processing systems,Software technologies,\n";
out << "Course4\n" << "Web Technologies,Artificial intelligence,Software architectures";
out.close();
} | 50.5 | 142 | 0.769307 | tsvetan-gabrovski |
2e13a83ec6b42d1a520912be1e57cd820af9f82e | 148 | hpp | C++ | src/Notifications.hpp | makuto/japanese-for-me | a32944bc6e709c572a93b94d205bd14bd75dbff4 | [
"MIT"
] | null | null | null | src/Notifications.hpp | makuto/japanese-for-me | a32944bc6e709c572a93b94d205bd14bd75dbff4 | [
"MIT"
] | null | null | null | src/Notifications.hpp | makuto/japanese-for-me | a32944bc6e709c572a93b94d205bd14bd75dbff4 | [
"MIT"
] | null | null | null | #pragma once
class NotificationsHandler
{
public:
NotificationsHandler();
~NotificationsHandler();
void sendNotification(const char* text);
};
| 13.454545 | 41 | 0.77027 | makuto |
2e13b5ce7c226d18f818236da5cc2b9fa37542d5 | 1,955 | cpp | C++ | Medusa/MedusaCore/Core/Pattern/Predicate/PredicateConfig.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2019-04-22T09:09:50.000Z | 2019-04-22T09:09:50.000Z | Medusa/MedusaCore/Core/Pattern/Predicate/PredicateConfig.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | null | null | null | Medusa/MedusaCore/Core/Pattern/Predicate/PredicateConfig.cpp | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2021-06-30T14:08:03.000Z | 2021-06-30T14:08:03.000Z | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#include "MedusaCorePreCompiled.h"
#include "PredicateConfig.h"
#include "Core/Pattern/Predicate/PredicateFactory.h"
#include "Core/Pattern/Predicate/IPredicate.h"
#include "Core/Log/Log.h"
MEDUSA_BEGIN;
bool PredicateConfig::LoadFromData(StringRef path, const MemoryByteData& data, uint format /*= 0*/)
{
Unload();
RETURN_FALSE_IF(data.IsNull());
pugi::xml_document doc;
pugi::xml_parse_result result = doc.load_buffer(data.Data(), data.Size());
if (!result)
{
Log::AssertFailedFormat("Cannot parse xml:{} because {}", path.c_str(), result.description());
return false;
}
FOR_EACH_COLLECTION_STL(i, doc.first_child().children())
{
pugi::xml_node child = *i;
StringRef typeName = child.name();
uint id = child.attribute("Id").as_uint(0);
StringRef parameter = child.attribute("Parameter").value();
#ifdef MEDUSA_SAFE_CHECK
if (ContainsId(id))
{
Log::AssertFailedFormat("Duplicate id:{} in {}", id, typeName.c_str());
}
#endif
IPredicate* predicate = PredicateFactory::Instance().SmartCreate(typeName);
predicate->SetId(id);
predicate->SetParamter(parameter);
predicate->Initialize();
Add(id, predicate);
LoadPredicate(child, predicate);
}
return true;
}
void PredicateConfig::LoadPredicate(pugi::xml_node node, IPredicate* parent)
{
FOR_EACH_COLLECTION_STL(i, node.children())
{
pugi::xml_node child = *i;
StringRef typeName = child.name();
StringRef paramter = child.attribute("Paramter").value();
IPredicate* predicate = PredicateFactory::Instance().SmartCreate(typeName);
predicate->SetParamter(paramter);
predicate->Initialize();
LoadPredicate(child, predicate);
parent->Add(predicate);
}
}
void PredicateConfig::Unload()
{
Clear();
}
MEDUSA_END; | 26.418919 | 100 | 0.697187 | JamesLinus |
2e1485ad2f45fde33689f4fb8ab88f2ad53fa067 | 774 | cpp | C++ | src/Game.cpp | Hello56721/wars | d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026 | [
"MIT"
] | 1 | 2021-09-29T14:33:37.000Z | 2021-09-29T14:33:37.000Z | src/Game.cpp | Hello56721/wars | d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026 | [
"MIT"
] | null | null | null | src/Game.cpp | Hello56721/wars | d8fb1b88fbb8e863e95d17a2ff96cd5dc197f026 | [
"MIT"
] | null | null | null | #include <pch.hpp>
#include <Game.hpp>
#include <scenes/TestScene.hpp>
using wars::Game;
using wars::scenes::TestScene;
Game::Game(): m_input(m_window)
{
std::cout << "[INFO]: Using OpenGL " << glGetString(GL_VERSION) << "\n";
int maximumTextureSize = 0;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maximumTextureSize);
std::cout << "[INFO]: Maximum Texture size is " << maximumTextureSize << "\n";
Scene::setActiveScene<TestScene>();
}
void Game::mainLoop()
{
// Show the window only when the main loop has began.
m_window.show();
while (m_window.isOpen())
{
Scene::updateActiveScene();
Scene::renderActiveScene();
m_window.update();
}
}
Game::~Game()
{
Scene::removeActiveScene();
} | 18.428571 | 82 | 0.621447 | Hello56721 |
2e178db7e33c163e0cccdfc46c70386814872ce8 | 3,842 | hpp | C++ | boost/xml/dom/node.hpp | stefanseefeld/boost.xml | f68b661566b1e8a487295f63c846bd8012c1eb94 | [
"BSL-1.0"
] | 1 | 2018-03-22T14:23:28.000Z | 2018-03-22T14:23:28.000Z | boost/xml/dom/node.hpp | stefanseefeld/boost.xml | f68b661566b1e8a487295f63c846bd8012c1eb94 | [
"BSL-1.0"
] | null | null | null | boost/xml/dom/node.hpp | stefanseefeld/boost.xml | f68b661566b1e8a487295f63c846bd8012c1eb94 | [
"BSL-1.0"
] | null | null | null | #ifndef boost_xml_dom_node_hpp_
#define boost_xml_dom_node_hpp_
#include <boost/xml/dom/nodefwd.hpp>
#include <boost/xml/dom/iterator.hpp>
#include <stdexcept>
namespace boost
{
namespace xml
{
namespace dom
{
enum node_type
{
INTERNAL = 0,
ELEMENT,
ATTRIBUTE,
TEXT,
CDATA,
PI,
COMMENT,
};
template <typename N>
class node_ptr
{
public:
node_ptr() : impl_(0) {}
node_ptr(N const &n) : impl_(n) {}
//. downcasting copy-constructor (e.g. element_ptr -> node_ptr)
template <typename N2>
node_ptr(node_ptr<N2> n) : impl_(*n.get()) {}
N &operator*() { return this->impl_;}
N *operator->() { return &this->impl_;}
N *get() { return &this->impl_;}
operator bool() const { return this->impl_.impl();}
private:
N impl_;
};
template <typename T, typename N>
inline T cast(node_ptr<N> n);
template <typename S>
class node : public detail::wrapper<xmlNode*>
{
template <typename N> friend class iterator;
friend class node_ptr<node<S> >;
friend class node_ptr<node<S> const>;
friend class element<S>;
friend class xpath<S>;
friend node_ptr<node<S> > detail::ptr_factory<node<S> >(xmlNode *);
friend node_ptr<node<S> const> detail::ptr_factory<node<S> const>(xmlNode *);
template <typename T, typename N> friend T cast(node_ptr<N>);
public:
bool operator== (node<S> const &n) { return impl() == impl(n);}
node_type type() const { return types[this->impl()->type];}
//. Return the node's name.
S name() const { return converter<S>::out(this->impl()->name);}
//. Return the node's path within its document.
S path() const;
//. Return the node's active base (See XBase).
S base() const;
//. Return the node's active language.
S lang() const;
//. Return the parent node, if any.
node_ptr<element<S> const> parent() const
{ return detail::ptr_factory<element<S> >(this->impl()->parent);}
node_ptr<element<S> > parent()
{ return detail::ptr_factory<element<S> >(this->impl()->parent);}
protected:
node(xmlNode *n) : detail::wrapper<xmlNode*>(n) {}
node(node<S> const &n) : detail::wrapper<xmlNode*>(n) {}
node<S> &operator=(node<S> const &n)
{
detail::wrapper<xmlNode*>::operator=(n);
return *this;
}
private:
static node_type const types[22];
static char const *names[7];
};
template <typename S>
inline S node<S>::path() const
{
xmlChar *path = xmlGetNodePath(this->impl());
S retn = converter<S>::out(path);
xmlFree(path);
return retn;
}
template <typename S>
inline S node<S>::base() const
{
xmlChar *path = xmlNodeGetBase(0, this->impl());
S retn = converter<S>::out(path);
xmlFree(path);
return retn;
}
template <typename S>
inline S node<S>::lang() const
{
xmlChar *path = xmlNodeGetLang(this->impl());
S retn = converter<S>::out(path);
xmlFree(path);
return retn;
}
template <typename S>
node_type const node<S>::types[22] =
{
INTERNAL,
ELEMENT, //XML_ELEMENT_NODE
ATTRIBUTE, //XML_ATTRIBUTE_NODE
TEXT, //XML_TEXT_NODE
CDATA, //XML_CDATA_SECTION_NODE
INTERNAL, //XML_ENTITY_REF_NODE
INTERNAL, //XML_ENTITY_NODE
PI, //XML_PI_NODE
COMMENT, //XML_COMMENT_NODE
INTERNAL, //XML_DOCUMENT_NODE
INTERNAL, //XML_DOCUMENT_TYPE_NODE
INTERNAL, //XML_DOCUMENT_FRAG_NODE
INTERNAL, //XML_NOTATION_NODE
INTERNAL, //XML_HTML_DOCUMENT_NODE
INTERNAL, //XML_DTD_NODE
INTERNAL, //XML_ELEMENT_DECL
INTERNAL, //XML_ATTRIBUTE_DECL
INTERNAL, //XML_ENTITY_DECL
INTERNAL, //XML_NAMESPACE_DECL
INTERNAL, //XML_XINCLUDE_START
INTERNAL, //XML_XINCLUDE_END
INTERNAL, //XML_DOCB_DOCUMENT_NODE
};
template <typename S>
char const *node<S>::names[7] =
{
"internal node",
"element",
"attribute",
"text node",
"cdata block",
"processing instruction",
"comment"
};
} // namespace boost::xml::dom
} // namespace boost::xml
} // namespace boost
#endif
| 23.716049 | 79 | 0.675169 | stefanseefeld |
2e1b6b4a494dffcd58c5feac28e4afb5e1d26dbc | 14,091 | hpp | C++ | include/gbBase/Allocator/AllocationStrategyRing.hpp | ComicSansMS/GhulbusBase | 9d07e0ab6e80c93121d261605d0f3c859af149da | [
"MIT"
] | 22 | 2016-02-01T03:52:29.000Z | 2020-12-11T18:43:42.000Z | include/gbBase/Allocator/AllocationStrategyRing.hpp | ComicSansMS/GhulbusBase | 9d07e0ab6e80c93121d261605d0f3c859af149da | [
"MIT"
] | null | null | null | include/gbBase/Allocator/AllocationStrategyRing.hpp | ComicSansMS/GhulbusBase | 9d07e0ab6e80c93121d261605d0f3c859af149da | [
"MIT"
] | 7 | 2017-02-13T15:25:58.000Z | 2019-05-10T19:54:31.000Z | #ifndef GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_ALLOCATOR_ALLOCATION_STRATEGY_RING_HPP
#define GHULBUS_LIBRARY_INCLUDE_GUARD_BASE_ALLOCATOR_ALLOCATION_STRATEGY_RING_HPP
/** @file
*
* @brief Ring allocation strategy.
* @author Andreas Weis (der_ghulbus@ghulbus-inc.de)
*/
#include <gbBase/config.hpp>
#include <gbBase/Allocator/DebugPolicy.hpp>
#include <gbBase/Allocator/StorageView.hpp>
#include <gbBase/Assert.hpp>
#include <cstddef>
#include <cstring>
#include <limits>
#include <memory>
#include <new>
namespace GHULBUS_BASE_NAMESPACE
{
namespace Allocator
{
namespace AllocationStrategy
{
/** The ring allocation strategy.
* A ring is an extension of the Stack allocation strategy, that uses a doubly-linked list of Headers, instead of
* the singly-linked list used by Stack. This allows memory to be reclaimed from both ends of the list, not just
* the top, enabling both LIFO and FIFO style allocations, as well as mixes of the two.
* Reclaiming memory from the beginning will leave a gap of free memory at the start of the storage buffer.
* In order to make use of that memory, the ring will attempt to *wrap-around* when it runs out of memory
* towards the end of the storage buffer. The wrap-around is imperfect in that a contiguous block cannot be wrapped,
* thus the end of the storage buffer acts as a natural fragmentation point in the conceptually circular memory space.
*
* The following picture shows the internal state after 4 allocations p1 through p4. This state is very similar
* to that of a Stack allocator, except that all Headers also maintain pointers to the next element.
* - Each allocated block is preceded by a Header and optionally by a padding region
* to satisfy alignment requirements.
* - Padding is performed such that each pN meets the requested alignment requirement *and*
* the preceding header meets the natural alignment requirement for Header.
* - Each header contains a pointer to the start of the previous header, the start of the next header,
* and a flag indicating whether the corresponding block was deallocated.
* - m_topHeader points to the top-most header that has not been deallocated.
* - m_bottomHeader points to the bottom-most header that has not been deallocated.
* - The start of the free memory is pointed to by m_freeMemoryOffset.
* - Memory can be reclaimed from both sides by moving the m_bottomHeader pointer to the right, or the
* m_topHeader pointer to the left.
* - Note that since headers do not track the size of their blocks, deallocation can only move
* the free memory offset back to the start of the header of the deallocated block, leaving the
* padding bytes in the unavailable memory region. If the next allocation now has a weaker alignment
* requirement, those bytes will be effectively lost. It would be possible to use a few additional
* bits in the header to store the alignment of the block, but this was not deemed worth the
* resulting runtime overhead. The lost bytes will get reclaimed when the previous block is freed.
* Padding bytes before the very first block will never be reclaimed. This only applies to deallocation
* from the top. Deallocation from the bottom always forwards the m_bottomHeader pointer to the
* next header, effectively reclaiming the padding area preceding that header.
*
* <pre>
* +----------------------<<-next_header-<<-------------------------------------+
* | +--<<-prev_header-<<--+ |
* +--<<-prev_header-<<-------|----+ +----|--<<-prev_header-<<------ +|
* | +-->>-next_header->>+ | +-next_h->+ | +->>-next_header->>-+ ||
* v | v | | v | | v ||
* +--------+-------+---------+--------+-------+--------+-------+---------+--------+-------+-------------+
* | Header | Block | Padding | Header | Block | Header | Block | Padding | Header | Block | Free Memory |
* +--------+-------+---------+--------+-------+--------+-------+---------+--------+-------+-------------+
* ^ ^ ^ ^ ^ ^ ^
* | p1 p2 p3 | p4 |
* m_storage.ptr m_bottomHeader m_topHeader m_freeMemoryOffset
*
* </pre>
*
* The following picture illustrates the internal state of a wrapped-around ring. An allocation p5 is located
* near the end of the ring, but all allocations preceding it have already been freed. The new allocation
* p6 is too big to fit in the remaining free memory area to the right of p5, so the ring wraps around,
* placing p6 at the beginning of the storage instead.
* - Once a ring has been wrapped around, the free memory at the end of the buffer becomes unavailable,
* until all of the bottom allocations preceding it have been freed.
* - In the wrapped-around case, m_freeMemoryOffset cannot grow bigger than m_bottomHeader.
*
* <pre>
* +--------------->>--prev_header-->>---------------------+
* +----|-------------------------<<--next_header--<<-----------|-----+
* +--<<|prev_header-<<--+ | |
* | |+-next_h->-+ | | |
* v || v | v |
* +--------+-------+--------+-------+--------------------------+--------+----------+--------------------+
* | Header | Block | Header | Block | Free Memory | Header | Block | Free Memory (unav.)|
* +--------+-------+--------+-------+--------------------------+--------+----------+--------------------+
* ^ ^ ^ ^ ^ ^ ^
* | p6 | p7 | | p5
* m_storage.ptr m_topHeader m_freeMemoryOffset m_bottomHeader
*
* </pre>
*
* Upon deallocation:
* - The header for the corresponding allocation is marked as free.
* - The m_topHeader will be moved to the left along the list of previous headers until
* it no longer points to a header that is marked free.
* - The m_bottomHeader will be moved to the right along the list of next headers until
* it no longer points to a header that is marked free.
* - The m_freeMemoryOffset will point to the beginning of the last free header encountered
* from the top, or to the beginning of the storage if no more headers remain.
*
* @tparam Debug_T One of the DebugPolicy policies.
*/
template<typename Debug_T = Allocator::DebugPolicy::AllocateDeallocateCounter>
class Ring : private Debug_T {
public:
/** Header used for internal bookkeeping of allocations.
* Each block of memory returned by allocate() is preceded by a header.
*/
class Header {
private:
/** Packed data field.
* The header needs to store the following information:
* - pointer to the next Header
* - pointer to the previous Header
* - flag indicating whether the block was freed
* The flag is packed into the least significant bit of the previous pointer,
* as that one is always 0 due to Header's own alignment requirements.
*/
std::uintptr_t m_data[2];
public:
explicit Header(Header* previous_header)
{
static_assert(sizeof(Header*) == sizeof(std::uintptr_t));
static_assert(alignof(Header) >= 2);
m_data[0] = 0;
std::memcpy(&m_data[1], &previous_header, sizeof(Header*));
}
void setNextHeader(Header* header)
{
GHULBUS_PRECONDITION_DBG(header && !m_data[0]);
std::memcpy(&m_data, &header, sizeof(Header*));
}
void clearPreviousHeader()
{
GHULBUS_PRECONDITION_DBG((m_data[1] & ~(std::uintptr_t(0x01) )) != 0);
std::uintptr_t const tmp = (m_data[1] & 0x01);
std::memcpy(&m_data[1], &tmp, sizeof(Header*));
}
void clearNextHeader()
{
GHULBUS_PRECONDITION_DBG(m_data[0] != 0);
m_data[0] = 0;
}
Header* nextHeader() const
{
Header* ret;
std::memcpy(&ret, &m_data, sizeof(Header*));
return ret;
}
Header* previousHeader() const
{
std::uintptr_t const tmp = m_data[1] & ~(std::uintptr_t(0x01));
Header* ret;
std::memcpy(&ret, &tmp, sizeof(Header*));
return ret;
}
void markFree()
{
m_data[1] |= 0x01;
}
bool wasFreed() const
{
return ((m_data[1] & 0x01) != 0);
}
};
private:
StorageView m_storage;
Header* m_topHeader; ///< Header of the top-most (most-recent) allocation.
Header* m_bottomHeader; ///< Header of the bottom-most (oldest) allocation.
std::size_t m_freeMemoryOffset; ///< Offset to the start of the free memory region in bytes
public:
/** @tparam Storage_T A Storage type that can be used as an argument to makeStorageView().
*/
template<typename Storage_T>
explicit Ring(Storage_T& storage) noexcept
:m_storage(makeStorageView(storage)), m_topHeader(nullptr), m_bottomHeader(nullptr), m_freeMemoryOffset(0)
{}
std::byte* allocate(std::size_t n, std::size_t alignment)
{
auto const getFreeMemoryContiguous = [this](std::size_t offs) -> std::size_t {
std::byte* offs_ptr = (m_storage.ptr + offs);
std::byte* bottom_ptr = reinterpret_cast<std::byte*>(m_bottomHeader);
if(bottom_ptr < offs_ptr) {
// linear case: free space from offset to end of storage
return m_storage.size - offs;
} else {
// wrap-around case: free space from offset to bottom header
return bottom_ptr - offs_ptr;
}
};
// we have to leave room for the header before the pointer that we return
std::size_t free_space = getFreeMemoryContiguous(m_freeMemoryOffset);
bool const out_of_memory = (free_space < sizeof(Header));
free_space -= (out_of_memory) ? 0 : sizeof(Header);
void* ptr = reinterpret_cast<void*>(m_storage.ptr + getFreeMemoryOffset() + sizeof(Header));
// the alignment has to be at least alignof(Header) to guarantee that the header is
// stored at its natural alignment.
// As usual, this assumes that all alignments are powers of two.
if(out_of_memory || (!std::align(std::max(alignment, alignof(Header)), n, ptr, free_space))) {
// we are out of memory, so try wrap around the ring
if(isWrappedAround() || ((free_space = getFreeMemoryContiguous(0)) < sizeof(Header))) {
// already wrapped, or not enough space for header even after wrapping
throw std::bad_alloc();
}
free_space -= sizeof(Header);
ptr = reinterpret_cast<void*>(m_storage.ptr + sizeof(Header));
if(!std::align(std::max(alignment, alignof(Header)), n, ptr, free_space)) {
// not enough free space in the beginning either
throw std::bad_alloc();
}
}
std::byte* ret = reinterpret_cast<std::byte*>(ptr);
// setup a header in the memory region immediately preceding ret
Header* new_header = new (ret - sizeof(Header)) Header(m_topHeader);
if(m_topHeader == nullptr) {
m_bottomHeader = new_header;
} else {
m_topHeader->setNextHeader(new_header);
}
m_topHeader = new_header;
GHULBUS_ASSERT_DBG(m_bottomHeader);
m_freeMemoryOffset = (ret - m_storage.ptr) + n;
this->onAllocate(n, alignment, ret);
return ret;
}
void deallocate(std::byte* p, std::size_t n)
{
this->onDeallocate(p, n);
// mark the deallocated block as freed in the header
Header* header_start = reinterpret_cast<Header*>(p - sizeof(Header));
header_start->markFree();
// advance the top header to the left until it no longer points to a freed header
while(m_topHeader && (m_topHeader->wasFreed())) {
header_start = m_topHeader;
m_topHeader = header_start->previousHeader();
if(m_topHeader) {
m_topHeader->clearNextHeader();
m_freeMemoryOffset = (reinterpret_cast<std::byte*>(header_start) - m_storage.ptr);
} else {
GHULBUS_ASSERT_DBG(m_bottomHeader == header_start);
m_bottomHeader = nullptr;
m_freeMemoryOffset = 0;
}
header_start->~Header();
}
// advance the bottom header to the right until it no longer points to a freed header
while(m_bottomHeader && (m_bottomHeader->wasFreed())) {
header_start = m_bottomHeader;
m_bottomHeader = header_start->nextHeader();
if(m_bottomHeader) { m_bottomHeader->clearPreviousHeader(); }
header_start->~Header();
}
}
/** Returns the offset in bytes from the start of the storage to the start of the free memory region.
*/
std::size_t getFreeMemoryOffset() const noexcept
{
return m_freeMemoryOffset;
}
/** Indicated whether the allocator is currently in the wrapped-around state.
* A ring is wrapped if new allocations are taken from the beginning of the storage,
* while there are still active allocations at the end of the storage.
*/
bool isWrappedAround() const
{
// we are wrapped iff the current offset is left of the bottom header
return (m_storage.ptr + getFreeMemoryOffset()) <= reinterpret_cast<std::byte*>(m_bottomHeader);
}
};
}
}
}
#endif
| 47.285235 | 118 | 0.59137 | ComicSansMS |
2e1c6bd9ceb3e4b41686c7cca9d6089458bf7366 | 1,596 | cc | C++ | lib/xz-coder.cc | tkubotake/nwc-toolkit | 0f15669cf70b767724a11cb73f8e634765fee365 | [
"BSD-3-Clause"
] | 6 | 2017-04-06T01:49:36.000Z | 2021-03-14T15:01:59.000Z | lib/xz-coder.cc | tkubotake/nwc-toolkit | 0f15669cf70b767724a11cb73f8e634765fee365 | [
"BSD-3-Clause"
] | null | null | null | lib/xz-coder.cc | tkubotake/nwc-toolkit | 0f15669cf70b767724a11cb73f8e634765fee365 | [
"BSD-3-Clause"
] | 1 | 2021-12-24T22:23:29.000Z | 2021-12-24T22:23:29.000Z | // Copyright 2010 Susumu Yata <syata@acm.org>
#include <nwc-toolkit/xz-coder.h>
namespace nwc_toolkit {
bool XzCoder::OpenEncoder(int preset) {
if (is_open()) {
return false;
}
int xz_preset = preset;
switch (preset) {
case DEFAULT_PRESET: {
xz_preset = 6;
break;
}
case BEST_SPEED_PRESET: {
xz_preset = 0;
break;
}
case BEST_COMPRESSION_PRESET: {
xz_preset = 9 | LZMA_PRESET_EXTREME;
break;
}
default: {
xz_preset = preset & ~EXTREME_PRESET_FLAG;
if ((xz_preset < 0) || (xz_preset > 9)) {
return false;
} else if ((preset & EXTREME_PRESET_FLAG) == EXTREME_PRESET_FLAG) {
xz_preset |= LZMA_PRESET_EXTREME;
}
}
}
::lzma_ret ret = ::lzma_easy_encoder(&stream_, xz_preset, LZMA_CHECK_CRC64);
if (ret != LZMA_OK) {
return false;
}
mode_ = ENCODER_MODE;
return true;
}
bool XzCoder::OpenDecoder() {
if (is_open()) {
return false;
}
::lzma_ret ret = ::lzma_stream_decoder(&stream_, 128 << 20, 0);
if (ret != LZMA_OK) {
return false;
}
mode_ = DECODER_MODE;
return true;
}
bool XzCoder::Close() {
if (!is_open()) {
return false;
}
::lzma_end(&stream_);
InitStream();
mode_ = NO_MODE;
is_end_ = false;
return true;
}
bool XzCoder::Code(::lzma_action action) {
if (!is_open() || is_end()) {
return false;
}
::lzma_ret ret = ::lzma_code(&stream_, action);
if (ret == LZMA_STREAM_END) {
is_end_ = true;
return true;
}
return (ret == LZMA_OK) || (ret == LZMA_BUF_ERROR);
}
} // namespace nwc_toolkit
| 20.461538 | 78 | 0.60589 | tkubotake |
2e1fbed4203bb08d6c4fc90530683bd6e89f6993 | 6,016 | hpp | C++ | src/libgit2xx/git2xx/Git.hpp | DrFrankenstein/goot | 2ea08283bd2fb52360ecd6a36d210fcc19332334 | [
"MIT"
] | null | null | null | src/libgit2xx/git2xx/Git.hpp | DrFrankenstein/goot | 2ea08283bd2fb52360ecd6a36d210fcc19332334 | [
"MIT"
] | null | null | null | src/libgit2xx/git2xx/Git.hpp | DrFrankenstein/goot | 2ea08283bd2fb52360ecd6a36d210fcc19332334 | [
"MIT"
] | null | null | null | #pragma once
#include "Buffer.hpp"
#include "Error.hpp"
#include "Repository.hpp"
#include "StrArray.hpp"
#include <cstddef>
#include <git2/config.h>
#include <git2/global.h>
#include <git2/repository.h>
#include <git2/sys/alloc.h>
#include <git2/types.h>
#include <string>
#include <utility>
#ifdef _MSC_VER
# include <BaseTsd.h>
using ssize_t = SSIZE_T;
#endif
namespace Git
{
/**
* A RAII wrapper around libgit2's init and shutdown functions, and a central
* entry point to the library.
*/
class Git
{
public:
Git() { git_libgit2_init(); }
~Git() { git_libgit2_shutdown(); }
// we _could_ allow copying since libgit2 uses refcounting, but it might
// also lead to too many unnecessary calls to init and shutdown if best
// practices aren't followed.
Git(const Git& other) = delete;
auto operator=(const Git& other) -> Git& = delete;
// no moving: there's no such thing as a null instance of this class, so
// destroying the donor instance will still cause a call to shutdown.
Git(Git&& other) = delete;
auto operator=(Git&& other) -> Git& = delete;
auto features() { return git_libgit2_features(); }
auto maxWindowSize() { return getOpt<std::size_t>(GIT_OPT_GET_MWINDOW_SIZE); }
auto setMaxWindowSize(std::size_t size) { setOpt(GIT_OPT_SET_MWINDOW_SIZE, size); }
auto maxWindowMappedLimit() { return getOpt<std::size_t>(GIT_OPT_GET_MWINDOW_MAPPED_LIMIT); }
auto setMaxWindowMappedLimit(std::size_t size) { setOpt(GIT_OPT_SET_MWINDOW_MAPPED_LIMIT, size); }
auto maxWindowFileLimit() { return getOpt<std::size_t>(GIT_OPT_GET_MWINDOW_FILE_LIMIT); }
auto setMaxWindowFileLimit(std::size_t size) { setOpt(GIT_OPT_SET_MWINDOW_FILE_LIMIT, size); }
auto searchPath(git_config_level_t level) { return getOpt(GIT_OPT_GET_SEARCH_PATH, level); }
auto setSearchPath(git_config_level_t level, const std::string& path) { setOpt(GIT_OPT_SET_SEARCH_PATH, level, path.c_str()); }
auto setCacheObjectLimit(git_object_t type, std::size_t size) { setOpt(GIT_OPT_SET_CACHE_OBJECT_LIMIT, type, size); }
auto setCacheMaxSize(ssize_t max_storage_bytes) { setOpt(GIT_OPT_SET_CACHE_MAX_SIZE, max_storage_bytes); }
auto enableCaching(bool enable) { setOpt(GIT_OPT_ENABLE_CACHING, static_cast<int>(enable)); }
auto cachedMemory()
{
ssize_t current, allowed;
git_libgit2_opts(GIT_OPT_GET_CACHED_MEMORY, ¤t, &allowed);
return std::tuple { current, allowed };
}
auto templatePath() { return getOpt(GIT_OPT_GET_TEMPLATE_PATH); }
auto setTemplatePath(const std::string& path) { setOpt(GIT_OPT_SET_TEMPLATE_PATH, path.c_str()); }
auto setSslCertFile(const std::string& file) { setOpt(GIT_OPT_SET_SSL_CERT_LOCATIONS, file.c_str(), nullptr); }
auto setSslCertPath(const std::string& path) { setOpt(GIT_OPT_SET_SSL_CERT_LOCATIONS, nullptr, path.c_str()); }
auto setSslCiphers(const std::string& ciphers) { setOpt(GIT_OPT_SET_SSL_CIPHERS, ciphers.c_str()); }
auto userAgent() { return getOpt(GIT_OPT_GET_USER_AGENT); }
auto setUserAgent(const std::string& user_agent) { setOpt(GIT_OPT_SET_USER_AGENT, user_agent.c_str()); }
auto windowsShareMode() { return getOpt<unsigned long>(GIT_OPT_GET_WINDOWS_SHAREMODE); }
auto setWindowsShareMode(unsigned long value) { setOpt(GIT_OPT_SET_WINDOWS_SHAREMODE, value); }
auto enableStrictObjectCreation(bool enable) { setOpt(GIT_OPT_ENABLE_STRICT_OBJECT_CREATION, static_cast<int>(enable)); }
auto enableStrictSymbolicRefCreation(bool enable) { setOpt(GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION, static_cast<int>(enable)); }
auto enableStrictHashVerification(bool enable) { setOpt(GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION, static_cast<int>(enable)); }
auto enableOffsetDelta(bool enable) { setOpt(GIT_OPT_ENABLE_OFS_DELTA, static_cast<int>(enable)); }
auto enableFsyncGitdir(bool enable) { setOpt(GIT_OPT_ENABLE_FSYNC_GITDIR, static_cast<int>(enable)); }
auto setAllocator(git_allocator* allocator) { setOpt(GIT_OPT_SET_ALLOCATOR, allocator); }
auto enableUnsavedIndexSafety(bool enable) { setOpt(GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY, static_cast<int>(enable)); }
auto packMaxObjects() { return getOpt<std::size_t>(GIT_OPT_GET_PACK_MAX_OBJECTS); }
auto setPackMaxObjects(std::size_t objects) { setOpt(GIT_OPT_SET_PACK_MAX_OBJECTS, objects); }
auto disablePackKeepFileChecks(bool disable) { setOpt(GIT_OPT_DISABLE_PACK_KEEP_FILE_CHECKS, static_cast<int>(disable)); }
auto enableHttpExpectContinue(bool enable) { setOpt(GIT_OPT_ENABLE_HTTP_EXPECT_CONTINUE, static_cast<int>(enable)); }
auto setOdbPackedPriority(int priority) { setOpt(GIT_OPT_SET_ODB_PACKED_PRIORITY, priority); }
auto setOdbLoosePriority(int priority) { setOpt(GIT_OPT_SET_ODB_LOOSE_PRIORITY, priority); }
auto extensions() { return getOptStrs(GIT_OPT_GET_EXTENSIONS); }
auto setExtensions(std::span<const char*> extensions) { setOpt(GIT_OPT_SET_EXTENSIONS, extensions.data(), extensions.size()); }
auto openRepository(
const std::string& path,
git_repository_open_flag_t flags = GIT_REPOSITORY_OPEN_NO_SEARCH,
const std::string& ceiling_dirs = {})
{
Repository repo;
const auto status = git_repository_open_ext(
&repo,
path.c_str(),
flags,
ceiling_dirs.empty() ? nullptr : ceiling_dirs.c_str());
ensureOk(status);
return repo;
}
private:
template<class Out, class... Args>
auto getOpt(git_libgit2_opt_t opt, Args... args)
{
Out retval;
const auto status = git_libgit2_opts(opt, args..., &retval);
ensureOk(status);
return retval;
}
template<class... Args>
auto getOpt(git_libgit2_opt_t opt, Args... args)
{
Buffer buf;
const auto status = git_libgit2_opts(opt, args..., &buf);
ensureOk(status);
return buf;
}
template<class... Args>
auto getOptStrs(git_libgit2_opt_t opt, Args... args)
{
StrArray array;
const auto status = git_libgit2_opts(opt, args..., &array);
ensureOk(status);
return array;
}
template<class... Args>
auto setOpt(git_libgit2_opt_t opt, Args... args)
{
const auto status = git_libgit2_opts(opt, args...);
ensureOk(status);
}
};
}
| 36.907975 | 133 | 0.759641 | DrFrankenstein |
2e205baea6d122bbb0340dba71649a40cba55445 | 1,556 | cpp | C++ | src/SignalSlotFactory.cpp | Joeasaurus/spina | 00a331aec57c3d18adc9eed02d992b44c659ea10 | [
"MIT"
] | null | null | null | src/SignalSlotFactory.cpp | Joeasaurus/spina | 00a331aec57c3d18adc9eed02d992b44c659ea10 | [
"MIT"
] | null | null | null | src/SignalSlotFactory.cpp | Joeasaurus/spina | 00a331aec57c3d18adc9eed02d992b44c659ea10 | [
"MIT"
] | 1 | 2021-12-26T17:12:08.000Z | 2021-12-26T17:12:08.000Z | #include "SignalSlotFactory.hpp"
namespace spina {
// Create
typename SignalSlotFactory::signal_ptr SignalSlotFactory::createSignal(const std::string& name) {
signals[name] = std::shared_ptr<signal_t>(new signal_t);
return signals[name];
};
void SignalSlotFactory::createSlot(const std::string& name, const SignalSlotFactory::slot_t subscriber) {
slots.insert({ name, subscriber });
};
// Connect
typename SignalSlotFactory::conn_t SignalSlotFactory::connect(const std::string& name, const SignalSlotFactory::slot_t &subscriber, const int& index) {
auto sig = assert_signal_exists(name);
return sig->second->connect(index, subscriber);
};
typename SignalSlotFactory::conn_t SignalSlotFactory::connect(const std::string& signal_name, const std::string& slot_name, const int& index) {
auto sl = assert_slot_exists(slot_name);
return connect(signal_name, sl->second, index);
};
// Asserts
typename SignalSlotFactory::signal_map::iterator SignalSlotFactory::assert_signal_exists(const std::string& name) {
auto sig = signals.find(name);
if (sig == signals.end())
throw 50;
return sig;
};
typename SignalSlotFactory::slot_map::iterator SignalSlotFactory::assert_slot_exists(const std::string& name) {
auto sig = slots.find(name);
if (sig == slots.end())
throw 50;
return sig;
};
// Raise
void SignalSlotFactory::raise(const std::string& signal_name, const std::string& data) {
auto sig = assert_signal_exists(signal_name);
auto p = sig->second.get();
(*p)(data);
};
}
| 29.358491 | 151 | 0.720437 | Joeasaurus |
2e20d4f01525e78ddaa507048601ed6a56e9a05b | 996 | cpp | C++ | tests/Day21.cpp | willkill07/AdventOfCode2021 | 06e62cd8a8c7f1e99374075b7302f6dcfb770bb0 | [
"Apache-2.0"
] | 12 | 2021-12-02T01:44:53.000Z | 2022-02-02T17:22:23.000Z | tests/Day21.cpp | willkill07/AdventOfCode2021 | 06e62cd8a8c7f1e99374075b7302f6dcfb770bb0 | [
"Apache-2.0"
] | null | null | null | tests/Day21.cpp | willkill07/AdventOfCode2021 | 06e62cd8a8c7f1e99374075b7302f6dcfb770bb0 | [
"Apache-2.0"
] | 1 | 2021-12-03T04:25:32.000Z | 2021-12-03T04:25:32.000Z | #include <catch2/catch_all.hpp>
#include "AdventTest.hpp"
#include "AdventDay.hpp"
#include "Day21.hpp"
using namespace day21;
namespace {
char const* input = R"MULTILINE(Player 1 starting position: 4
Player 2 starting position: 8)MULTILINE";
auto const expected_part1 = 739785u;
auto const expected_part2 = 444356092776315lu;
using Day = AdventDay<id, parsed, result1, result2>;
}
SCENARIO("2021.day.21","[2021][21]") {
GIVEN("Sample input") {
tmp_file sample{id};
sample.append(input);
auto parsed = Day::parse(sample.name());
WHEN("Running Part 1") {
auto actual = Day::solve<false>(parsed);
THEN("We get the correct answer") {
REQUIRE(actual == expected_part1);
}
}
AND_WHEN("Running Part 2") {
auto actual = Day::solve<true>(parsed);
THEN("We get the correct answer") {
REQUIRE(actual == expected_part2);
}
}
}
}
| 23.714286 | 61 | 0.596386 | willkill07 |
2e223b660845b5275acf039b08fd8bfa13cb2ef8 | 1,164 | cpp | C++ | discrete-maths/matroids/a_schedule.cpp | nothingelsematters/university | 5561969b1b11678228aaf7e6660e8b1a93d10294 | [
"WTFPL"
] | 1 | 2018-06-03T17:48:50.000Z | 2018-06-03T17:48:50.000Z | discrete-maths/matroids/a_schedule.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | null | null | null | discrete-maths/matroids/a_schedule.cpp | nothingelsematters/University | b1e188cb59e5a436731b92c914494626a99e1ae0 | [
"WTFPL"
] | 14 | 2019-04-07T21:27:09.000Z | 2021-12-05T13:37:25.000Z | #include <fstream>
#include <iostream>
#include <algorithm>
#include <vector>
#include <set>
int main() {
std::ifstream fin("schedule.in");
size_t quantity;
fin >> quantity;
std::vector<std::pair<long long, long long>> task;
for (size_t i = 0; i < quantity; ++i) {
long long a, b;
fin >> a >> b;
task.emplace_back(a, b);
}
fin.close();
std::sort(task.begin(), task.end());
long long penalty = 0;
long long time = 0;
std::multiset<long long> punish;
for (long long i = 0; i < quantity; ++i) {
// std::cout << last << ' ' << task[i].first << '\n';
if (time >= task[i].first) {
if (!punish.empty() && *(punish.begin()) < task[i].second) {
penalty += *(punish.begin());
punish.erase(punish.begin());
punish.insert(task[i].second);
} else {
penalty += task[i].second;
}
} else {
// std::cout << task[i].first << ' ';
punish.insert(task[i].second);
++time;
}
}
std::ofstream fout("schedule.out");
fout << penalty;
}
| 27.714286 | 72 | 0.485395 | nothingelsematters |
2e24f22ba791b2431b901fb6a773c4b54a471a06 | 524 | hpp | C++ | src/core/Texture.hpp | Xnork/Project-Engine-SDL2 | c49b2c1d83373f027624b3e5ff2f52633100db73 | [
"MIT"
] | null | null | null | src/core/Texture.hpp | Xnork/Project-Engine-SDL2 | c49b2c1d83373f027624b3e5ff2f52633100db73 | [
"MIT"
] | null | null | null | src/core/Texture.hpp | Xnork/Project-Engine-SDL2 | c49b2c1d83373f027624b3e5ff2f52633100db73 | [
"MIT"
] | null | null | null | #ifndef TEXTURE_H
#define TEXTURE_H
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <iostream>
#include <cstring>
#include "math/Vector2.hpp"
using namespace std;
class Texture
{
public:
Texture();
explicit Texture(const string, SDL_Renderer*);
virtual SDL_Texture *getTextureSDL() noexcept;
const Vector2i getTextureSize() const;
virtual void loadFromFile(const string, SDL_Renderer*);
virtual ~Texture();
private:
SDL_Texture *texture;
Vector2i texture_size;
};
#endif | 18.068966 | 59 | 0.719466 | Xnork |
2e26951b789d18a2b4ca0ddb3fca67cce92bff4e | 2,501 | cpp | C++ | Veri/VeriSiniflari/tekmarketbilgileri.cpp | mtc61/techmarket | 64533703db4256686abe428c007fd4a784ad2b5b | [
"Apache-2.0"
] | null | null | null | Veri/VeriSiniflari/tekmarketbilgileri.cpp | mtc61/techmarket | 64533703db4256686abe428c007fd4a784ad2b5b | [
"Apache-2.0"
] | null | null | null | Veri/VeriSiniflari/tekmarketbilgileri.cpp | mtc61/techmarket | 64533703db4256686abe428c007fd4a784ad2b5b | [
"Apache-2.0"
] | null | null | null | #include "tekmarketbilgileri.h"
TEKMarketBilgileri::TEKMarketBilgileri(QObject *parent) : QObject(parent)
{
}
IdTuru TEKMarketBilgileri::getId() const
{
return TeknoMarketId;
}
void TEKMarketBilgileri::setId(const IdTuru &value)
{
if(value == TeknoMarketId)
return;
TeknoMarketId = value;
emit IdDegisti(TeknoMarketId);
}
Metin TEKMarketBilgileri::getTeknoMarketAdi() const
{
return TeknoMarketAdi;
}
void TEKMarketBilgileri::setTeknoMarketAdi(const Metin &value)
{
if(value == TeknoMarketAdi)
return;
TeknoMarketAdi = value;
emit TeknoMarketAdiDegisti(TeknoMarketAdi);
}
Metin TEKMarketBilgileri::getTeknoMarketAdresi() const
{
return TeknoMarketAdresi;
}
void TEKMarketBilgileri::setTeknoMarketAdresi(const Metin &value)
{
if(value == TeknoMarketAdresi)
return;
TeknoMarketAdresi = value;
emit TeknoMarketAdresiDegisti(TeknoMarketAdresi);
}
Metin TEKMarketBilgileri::getTeknoMarketYetkilisi() const
{
return TeknoMarketYetkilisi;
}
void TEKMarketBilgileri::setTeknoMarketYetkilisi(const Metin &value)
{
if(value == TeknoMarketYetkilisi)
return;
TeknoMarketYetkilisi = value;
emit TeknoMarketYetkilisiDegisti(TeknoMarketYetkilisi);
}
Tamsayi TEKMarketBilgileri::getTeknoMarketTelefonu() const
{
return TeknoMarketTelefonu;
}
void TEKMarketBilgileri::setTeknoMarketTelefonu(const Tamsayi &value)
{
if(value == TeknoMarketTelefonu)
return;
TeknoMarketTelefonu = value;
emit TeknoMarketTelefonuDegisti(TeknoMarketTelefonu);
}
QDataStream &operator<<(QDataStream &stream , TEKMarketBilgileriptr &veri){
stream << veri->getId() << veri->getTeknoMarketAdi() << veri->getTeknoMarketAdresi() << veri->getTeknoMarketYetkilisi()
<< veri->getTeknoMarketTelefonu() ;
return stream;
}
QDataStream &operator>>(QDataStream &stream, TEKMarketBilgileriptr &veri){
IdTuru TeknoMarketId;
Metin TeknoMarketAdi,TeknoMarketAdresi,TeknoMarketYetkilisi;
Tamsayi TeknoMarketTelefonu;
stream >> TeknoMarketId >> TeknoMarketAdi >> TeknoMarketAdresi >> TeknoMarketYetkilisi >> TeknoMarketTelefonu ;
veri= std :: make_shared<TEKMarketBilgileri>();
veri ->setId(TeknoMarketId);
veri ->setTeknoMarketAdi(TeknoMarketAdi);
veri ->setTeknoMarketAdresi(TeknoMarketAdresi);
veri ->setTeknoMarketYetkilisi(TeknoMarketYetkilisi);
veri ->setTeknoMarketTelefonu(TeknoMarketTelefonu);
return stream;
}
| 24.281553 | 123 | 0.738505 | mtc61 |
2e2b00d5922cb0446fdad5d830fa7ec024757705 | 656 | cpp | C++ | codeforces/misc/143a.cpp | saranshbht/codes-and-more-codes | 0bd2e46ca613b3b81e1196d393902e86a43aa353 | [
"MIT"
] | null | null | null | codeforces/misc/143a.cpp | saranshbht/codes-and-more-codes | 0bd2e46ca613b3b81e1196d393902e86a43aa353 | [
"MIT"
] | null | null | null | codeforces/misc/143a.cpp | saranshbht/codes-and-more-codes | 0bd2e46ca613b3b81e1196d393902e86a43aa353 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ll long long
int main() {
int r1, r2, c1, c2, d1, d2, a, b, c, d;
cin >> r1 >> r2 >> c1 >> c2 >> d1 >> d2;
int i;
for (i = 1; i <= 9; i++) {
a = i;
b = r1 - a;
c = c1 - a;
d = c2 - b;
if ((a != b) && (a != c) && (a != d) && (b != c) && (b != d) && (c != d) && (a + b == r1) && (c + d == r2) && (a + d == d1) && (b + c == d2) && (a + c == c1) && (b + d == c2) && (a >= 1 && a <= 9) && (b >= 1 && b <= 9) && (c >= 1 && c <= 9) && (d >= 1 && d <= 9)) {
break;
}
}
if (i != 10) {
cout << a << " " << b << "\n" << c << " " << d;
} else {
cout << "-1";
}
cout << endl;
return 0;
} | 27.333333 | 267 | 0.324695 | saranshbht |
2e2c43a247a6e7ad72376193ecffea9d265b1364 | 533 | hpp | C++ | obelus/client/interfaces/i_app_system.hpp | monthyx1337/obelus-hack | 8e83eb89ef56788c1b9c5af66b815824d17f309d | [
"MIT"
] | 36 | 2021-07-08T01:30:44.000Z | 2022-03-25T13:16:59.000Z | obelus/client/interfaces/i_app_system.hpp | monthyx1337/obelus-hack | 8e83eb89ef56788c1b9c5af66b815824d17f309d | [
"MIT"
] | 2 | 2021-09-11T05:11:55.000Z | 2022-01-28T07:49:39.000Z | obelus/client/interfaces/i_app_system.hpp | monthyx1337/obelus-hack | 8e83eb89ef56788c1b9c5af66b815824d17f309d | [
"MIT"
] | 14 | 2021-07-08T00:11:12.000Z | 2022-03-20T11:10:17.000Z | #pragma once
class i_app_system;
typedef void* (*create_interface_fn)(const char* name, int* return_code);
class i_app_system {
public:
virtual bool connect(create_interface_fn factory) = 0;
virtual void disconnect() = 0;
virtual void* query_interface(const char* interface_name) = 0;
virtual int init() = 0;
virtual void shutdown() = 0;
virtual const void* get_client() = 0;
virtual int get_tier() = 0;
virtual void reconnect(create_interface_fn factory, const char* interface_name) = 0;
virtual void unknown() = 0;
};
| 28.052632 | 85 | 0.739212 | monthyx1337 |
2e2e86521956cfb6614f65e650f24e7ec1f7c8d2 | 529 | cpp | C++ | src/trial/services/add_two_ints_client.cpp | miroslavradojevic/agv_motion | 54a030dac4fad679b27ca53071f57b88edc28697 | [
"FSFAP"
] | null | null | null | src/trial/services/add_two_ints_client.cpp | miroslavradojevic/agv_motion | 54a030dac4fad679b27ca53071f57b88edc28697 | [
"FSFAP"
] | null | null | null | src/trial/services/add_two_ints_client.cpp | miroslavradojevic/agv_motion | 54a030dac4fad679b27ca53071f57b88edc28697 | [
"FSFAP"
] | null | null | null | #include <ros/ros.h>
#include <rospy_tutorials/AddTwoInts.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "add_two_ints_client");
ros::NodeHandle nh;
ros::ServiceClient client = nh.serviceClient<rospy_tutorials::AddTwoInts>("/add_two_ints");
rospy_tutorials::AddTwoInts srv;
srv.request.a = 12;
srv.request.b = 5;
if (client.call(srv))
{
// process data
ROS_INFO("Sum is %d", (int)srv.response.sum);
}
else
{
ROS_WARN("Service call failed");
}
} | 25.190476 | 95 | 0.625709 | miroslavradojevic |
2e369229575dc0c6112c4f39ef12c5ffaa7d205d | 1,899 | cpp | C++ | training/Codeforces/685A.cpp | voleking/ICPC | fc2cf408fa2607ad29b01eb00a1a212e6d0860a5 | [
"MIT"
] | 68 | 2017-10-08T04:44:23.000Z | 2019-08-06T20:15:02.000Z | training/Codeforces/685A.cpp | voleking/ICPC | fc2cf408fa2607ad29b01eb00a1a212e6d0860a5 | [
"MIT"
] | null | null | null | training/Codeforces/685A.cpp | voleking/ICPC | fc2cf408fa2607ad29b01eb00a1a212e6d0860a5 | [
"MIT"
] | 18 | 2017-05-31T02:52:23.000Z | 2019-07-05T09:18:34.000Z | #include <bits/stdc++.h>
#define IOS std::ios::sync_with_stdio(false);std::cin.tie(nullptr);
using namespace std;
typedef long l;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned long ul;
typedef long double ld;
typedef pair<int, int > Pii;
const double pi = acos(-1.0);
const int INF = INT_MAX;
const int MAX_N = 50005;
template <typename T>
inline T sqr(T a) { return a * a;};
vector<int> v, v1, v2;
int n, m, flag[10], ans = 0, test[10];
vector<int> trans(int n) {
vector<int> res;
if (!n) res.push_back(0);
while (n) {
res.push_back(n % 7);
n /= 7;
}
return res;
}
void dfs(int k) {
if (k == v.size()) {
for (int i = v1.size() - 1; i >= 0; --i)
if (test[i] > v1[i])
return;
else if (test[i] < v1[i]) break;
for (int i = v.size() - 1; i >= v1.size(); --i)
if (test[i] > v2[i - v1.size()])
return;
else if (test[i] < v2[i - v1.size()]) break;
// for (int i = 0; i < v.size(); ++i)
// cout << test[i];
// cout << endl;
++ans;
}
else
for (int i = 0; i < 7; ++i)
if (!flag[i]) {
flag[i] = true;
test[k] = i;
dfs(k + 1);
flag[i] = false;
}
}
int main(int argc, char const *argv[])
{
cin >> n >> m;
--n;--m;
v1 = trans(n), v2 = trans(m);
if (v1.size() + v2.size() > 7) {
cout << 0 << endl;
}
else {
fill(flag, flag + 10, false);
for (int i = 0; i < v1.size(); ++i)
v.push_back(v1[i]);
for (int i = 0; i < v2.size(); ++i)
v.push_back(v2[i]);
// for (int i = 0; i < v.size(); ++i)
// cout << v[i];
// cout << endl << endl;
dfs(0);
cout << ans << endl;
}
return 0;
} | 24.346154 | 67 | 0.441811 | voleking |
aa31c875a706c5943757ad2fcc8eca2e72b9d66d | 1,952 | hpp | C++ | gmsl_camera/src/DataPath.hpp | vehicularkech/gmsl-camera-ros-driver | 1dfadb91c4b5829ca562e362911f1b3dcb7ab083 | [
"MIT"
] | 2 | 2018-04-20T02:26:18.000Z | 2018-10-11T03:20:36.000Z | gmsl_camera/src/DataPath.hpp | vehicularkech/gmsl-camera-ros-driver | 1dfadb91c4b5829ca562e362911f1b3dcb7ab083 | [
"MIT"
] | 1 | 2018-07-12T08:19:31.000Z | 2018-07-12T08:19:31.000Z | gmsl_camera/src/DataPath.hpp | vehicularkech/gmsl-camera-ros-driver | 1dfadb91c4b5829ca562e362911f1b3dcb7ab083 | [
"MIT"
] | 1 | 2019-01-24T03:02:45.000Z | 2019-01-24T03:02:45.000Z | // This code contains NVIDIA Confidential Information and is disclosed
// under the Mutual Non-Disclosure Agreement.
//
// Notice
// ALL NVIDIA DESIGN SPECIFICATIONS AND CODE ("MATERIALS") ARE PROVIDED "AS IS" NVIDIA MAKES
// NO REPRESENTATIONS, WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ANY IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
//
// NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. No third party distribution is allowed unless
// expressly authorized by NVIDIA. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2015-2016 NVIDIA Corporation. All rights reserved.
//
// NVIDIA Corporation and its licensors retain all intellectual property and proprietary
// rights in and to this software and related documentation and any modifications thereto.
// Any use, reproduction, disclosure or distribution of this software and related
// documentation without an express license agreement from NVIDIA Corporation is
// strictly prohibited.
//
/////////////////////////////////////////////////////////////////////////////////////////
#ifndef SAMPLES_COMMON_DATAPATH_HPP__
#define SAMPLES_COMMON_DATAPATH_HPP__
#include <string>
class DataPath
{
public:
// Base path for all data
static std::string get()
{
return "../data";
}
};
#endif // SAMPLES_COMMON_DATAPATH_HPP__
| 42.434783 | 94 | 0.745389 | vehicularkech |
aa334f86237f31707fde90f5165981665b96d318 | 3,259 | cpp | C++ | Grammars/Lab02/Lab02/main.cpp | IceNerd/hogwarts | df1f3e1a94688fd728f6b54653a36a47671293da | [
"Unlicense"
] | null | null | null | Grammars/Lab02/Lab02/main.cpp | IceNerd/hogwarts | df1f3e1a94688fd728f6b54653a36a47671293da | [
"Unlicense"
] | null | null | null | Grammars/Lab02/Lab02/main.cpp | IceNerd/hogwarts | df1f3e1a94688fd728f6b54653a36a47671293da | [
"Unlicense"
] | null | null | null | #include <conio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
#include <vector>
#include "STable.h"
std::string CreateStringFromFile( const std::string& );
std::vector<std::string> Tokenize( const std::string&, const std::string& = " " );
void Analyze( std::vector<std::string>& );
int main()
{
std::vector<std::string> vctTokens;
std::string strAnalyze( CreateStringFromFile( "tester.txt" ) );
vctTokens = Tokenize( strAnalyze, ":'\"<>+%&=.-*/~(){}[];, " );
Analyze( vctTokens );
_getch();
}
std::string CreateStringFromFile( const std::string& strFile )
{
std::ifstream inFile( strFile.c_str() );
char strLine;
std::string strReturn;
if( inFile.is_open() )
{
while( !inFile.eof() )
{
inFile.get( strLine );
//ignore tabs and linebreaks
if( (strLine != '\n') && (strLine != '\t') && (!inFile.eof()) )
{
strReturn += strLine;
}
}
}
inFile.close();
return strReturn;
}
std::vector<std::string> Tokenize( const std::string& strTok, const std::string& strDelim )
{
std::vector<std::string> vctReturn;
std::string::size_type lastPos = strTok.find_first_not_of( strDelim, 0 );
std::string::size_type Pos = strTok.find_first_of( strDelim, lastPos );
vctReturn.clear();
while( strTok[lastPos + 1] )
{
if( lastPos == 0 )
{
vctReturn.push_back( strTok.substr( lastPos, Pos - lastPos ) );
}
else
{
if( strTok.substr( lastPos, 1 ) != " " )
{
vctReturn.push_back( strTok.substr( lastPos, 1 ) );
}
if( Pos - lastPos != 1 )
{
vctReturn.push_back( strTok.substr( lastPos + 1, (Pos - lastPos) - 1 ) );
}
}
lastPos = strTok.find_first_of( strDelim, Pos );
Pos = strTok.find_first_of( strDelim, lastPos + 1 );
}
vctReturn.push_back( strTok.substr( lastPos, 1 ) );
return vctReturn;
}
void Analyze( std::vector<std::string>& vctTokens )
{
if( !vctTokens.empty() )
{
STable SymbolTable( "clegal.txt" );
char chBuffer[100];
//--- propogate our Keywords( 1 )
std::ifstream inKeyFile( "keywords.txt" );
if( inKeyFile.is_open() )
{
while( !inKeyFile.eof() )
{
inKeyFile.getline( chBuffer, 100 );
SymbolTable.Add( chBuffer, 1 );
}
}
inKeyFile.close();
//---
//--- propogate our Operators( 2 )
std::ifstream inOpFile( "operators.txt" );
if( inOpFile.is_open() )
{
while( !inOpFile.eof() )
{
inOpFile.getline( chBuffer, 100 );
SymbolTable.Add( chBuffer, 2 );
}
}
inOpFile.close();
//---
//--- propogate our Symbols( 3 )
std::ifstream inSymFile( "symbols.txt" );
if( inSymFile.is_open() )
{
while( !inSymFile.eof() )
{
inSymFile.getline( chBuffer, 100 );
SymbolTable.Add( chBuffer, 3 );
}
}
inSymFile.close();
//---
for( std::vector<std::string>::iterator iter_i = vctTokens.begin(); iter_i != vctTokens.end(); ++iter_i )
{
std::cout.width(13);
switch( SymbolTable.Find( (*iter_i) ) )
{
case 0:
std::cout<<"IDENTIFIER: ";
break;
case 1:
std::cout<<"KEYWORD: ";
break;
case 2:
std::cout<<"OPERATOR: ";
break;
case 3:
std::cout<<"SYMBOL: ";
break;
default:
std::cout<<"UNKNOWN: ";
break;
}
std::cout<<(*iter_i)<<"\n";
}
}
} | 20.496855 | 107 | 0.597423 | IceNerd |
aa382ae061a2609f8c4eb5e7b32e7a96f8354d7f | 10,374 | cpp | C++ | src/main.cpp | d99kris/nchat | 2c51cf2ff7ab7b655067ba290071d9b005544e68 | [
"MIT"
] | 82 | 2019-02-19T15:00:19.000Z | 2022-03-24T20:22:43.000Z | src/main.cpp | d99kris/nchat | 2c51cf2ff7ab7b655067ba290071d9b005544e68 | [
"MIT"
] | 47 | 2019-03-07T13:07:36.000Z | 2022-03-27T14:32:09.000Z | src/main.cpp | d99kris/nchat | 2c51cf2ff7ab7b655067ba290071d9b005544e68 | [
"MIT"
] | 12 | 2019-03-06T18:58:41.000Z | 2022-03-26T17:41:31.000Z | // main.cpp
//
// Copyright (c) 2019-2021 Kristofer Berggren
// All rights reserved.
//
// nchat is distributed under the MIT license, see LICENSE for details.
#include <iostream>
#include <map>
#include <regex>
#include <set>
#include <string>
#include <path.hpp>
#include "appconfig.h"
#include "apputil.h"
#include "fileutil.h"
#include "log.h"
#include "messagecache.h"
#include "profiles.h"
#include "scopeddirlock.h"
#include "tgchat.h"
#include "ui.h"
#include "uiconfig.h"
#ifdef HAS_DUMMY
#include "duchat.h"
#endif
#ifdef HAS_WHATSAPP
#include "wachat.h"
#endif
static bool SetupProfile();
static void ShowHelp();
static void ShowVersion();
static std::vector<std::shared_ptr<Protocol>> GetProtocols()
{
std::vector<std::shared_ptr<Protocol>> protocols =
{
#ifdef HAS_DUMMY
std::make_shared<DuChat>(),
#endif
std::make_shared<TgChat>(),
#ifdef HAS_WHATSAPP
std::make_shared<WaChat>(),
#endif
};
return protocols;
}
int main(int argc, char* argv[])
{
// Defaults
umask(S_IRWXG | S_IRWXO);
FileUtil::SetApplicationDir(std::string(getenv("HOME")) + std::string("/.nchat"));
Log::SetVerboseLevel(Log::INFO_LEVEL);
// Argument handling
std::string exportDir;
bool isSetup = false;
std::vector<std::string> args(argv + 1, argv + argc);
for (auto it = args.begin(); it != args.end(); ++it)
{
if (((*it == "-d") || (*it == "--configdir")) && (std::distance(it + 1, args.end()) > 0))
{
++it;
FileUtil::SetApplicationDir(*it);
}
else if ((*it == "-e") || (*it == "--verbose"))
{
Log::SetVerboseLevel(Log::DEBUG_LEVEL);
}
else if ((*it == "-ee") || (*it == "--extra-verbose"))
{
Log::SetVerboseLevel(Log::TRACE_LEVEL);
}
else if ((*it == "-h") || (*it == "--help"))
{
ShowHelp();
return 0;
}
else if (*it == "-m")
{
AppUtil::SetDeveloperMode(true);
}
else if ((*it == "-s") || (*it == "--setup"))
{
isSetup = true;
}
else if ((*it == "-v") || (*it == "--version"))
{
ShowVersion();
return 0;
}
else if (((*it == "-x") || (*it == "--export")) && (std::distance(it + 1, args.end()) > 0))
{
++it;
exportDir = *it;
}
else
{
ShowHelp();
return 1;
}
}
bool isDirInited = false;
static const int dirVersion = 1;
if (!apathy::Path(FileUtil::GetApplicationDir()).exists())
{
FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion);
isDirInited = true;
}
ScopedDirLock dirLock(FileUtil::GetApplicationDir());
if (!dirLock.IsLocked())
{
std::cerr <<
"error: unable to acquire lock for " << FileUtil::GetApplicationDir() << "\n" <<
" only one nchat session per account/confdir is supported.\n";
return 1;
}
if (!isDirInited)
{
int storedVersion = FileUtil::GetDirVersion(FileUtil::GetApplicationDir());
if (storedVersion != dirVersion)
{
if (isSetup)
{
FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion);
}
else
{
std::cout << "Config dir " << FileUtil::GetApplicationDir() << " is incompatible with this version of nchat\n";
if ((storedVersion == -1) && FileUtil::Exists(FileUtil::GetApplicationDir() + "/tdlib"))
{
std::cout << "Attempt to migrate config dir to new version (y/n)? ";
std::string migrateYesNo;
std::getline(std::cin, migrateYesNo);
if (migrateYesNo != "y")
{
std::cout << "Migration cancelled, exiting.\n";
return 1;
}
std::cout << "Enter phone number (optional, ex. +6511111111): ";
std::string phoneNumber = "";
std::getline(std::cin, phoneNumber);
std::string profileName = "Telegram_" + phoneNumber;
std::string tmpDir = "/tmp/" + profileName;
FileUtil::RmDir(tmpDir);
FileUtil::MkDir(tmpDir);
FileUtil::Move(FileUtil::GetApplicationDir() + "/tdlib", tmpDir + "/tdlib");
FileUtil::Move(FileUtil::GetApplicationDir() + "/telegram.conf", tmpDir + "/telegram.conf");
FileUtil::InitDirVersion(FileUtil::GetApplicationDir(), dirVersion);
Profiles::Init();
FileUtil::Move(tmpDir, FileUtil::GetApplicationDir() + "/profiles/" + profileName);
}
else
{
std::cerr << "error: invalid config dir content, exiting.\n";
return 1;
}
}
}
}
// Init profiles dir
Profiles::Init();
// Init logging
const std::string& logPath = FileUtil::GetApplicationDir() + std::string("/log.txt");
Log::SetPath(logPath);
std::string appNameVersion = AppUtil::GetAppNameVersion();
LOG_INFO("starting %s", appNameVersion.c_str());
// Run setup if required
if (isSetup)
{
bool rv = SetupProfile();
return rv ? 0 : 1;
}
// Init app config
AppConfig::Init();
// Init ui
std::shared_ptr<Ui> ui = std::make_shared<Ui>();
// Init message cache
const bool cacheEnabled = AppConfig::GetBool("cache_enabled");
std::function<void(std::shared_ptr<ServiceMessage>)> messageHandler =
std::bind(&Ui::MessageHandler, std::ref(*ui), std::placeholders::_1);
MessageCache::Init(cacheEnabled, messageHandler);
// Load profile(s)
std::string profilesDir = FileUtil::GetApplicationDir() + "/profiles";
const std::vector<apathy::Path>& profilePaths = apathy::Path::listdir(profilesDir);
for (auto& profilePath : profilePaths)
{
std::stringstream ss(profilePath.filename());
std::string protocolName;
if (!std::getline(ss, protocolName, '_'))
{
LOG_WARNING("invalid profile name, skipping.");
continue;
}
std::vector<std::shared_ptr<Protocol>> allProtocols = GetProtocols();
for (auto& protocol : allProtocols)
{
if (protocol->GetProfileId() == protocolName)
{
protocol->LoadProfile(profilesDir, profilePath.filename());
ui->AddProtocol(protocol);
MessageCache::AddProfile(profilePath.filename());
}
}
#ifndef HAS_MULTIPROTOCOL
if (!ui->GetProtocols().empty())
{
break;
}
#endif
}
// Protocol config params
std::string isAttachmentPrefetchAll =
(UiConfig::GetNum("attachment_prefetch") == AttachmentPrefetchAll) ? "1" : "0";
// Start protocol(s) and ui
std::unordered_map<std::string, std::shared_ptr<Protocol>>& protocols = ui->GetProtocols();
bool hasProtocols = !protocols.empty();
if (hasProtocols && exportDir.empty())
{
// Login
for (auto& protocol : protocols)
{
protocol.second->SetMessageHandler(messageHandler);
protocol.second->SetProperty(PropertyAttachmentPrefetchAll, isAttachmentPrefetchAll);
protocol.second->Login();
}
// Ui main loop
ui->Run();
// Logout
for (auto& protocol : protocols)
{
protocol.second->Logout();
protocol.second->CloseProfile();
}
}
// Cleanup ui
ui.reset();
// Perform export if requested
if (!exportDir.empty())
{
MessageCache::Export(exportDir);
}
// Cleanup
MessageCache::Cleanup();
AppConfig::Cleanup();
Profiles::Cleanup();
// Exit code
int rv = 0;
if (!hasProtocols)
{
std::cout << "no profiles setup, exiting.\n";
rv = 1;
}
return rv;
}
bool SetupProfile()
{
std::vector<std::shared_ptr<Protocol>> p_Protocols = GetProtocols();
std::cout << "Protocols:" << std::endl;
size_t idx = 0;
for (auto it = p_Protocols.begin(); it != p_Protocols.end(); ++it, ++idx)
{
std::cout << idx << ". " << (*it)->GetProfileId() << std::endl;
}
std::cout << idx << ". Exit setup" << std::endl;
size_t selectidx = idx;
std::cout << "Select protocol (" << selectidx << "): ";
std::string line;
std::getline(std::cin, line);
if (!line.empty())
{
selectidx = stoi(line);
}
if (selectidx >= p_Protocols.size())
{
std::cout << "Setup aborted, exiting." << std::endl;
return false;
}
std::string profileId;
std::string profilesDir = FileUtil::GetApplicationDir() + std::string("/profiles");
#ifndef HAS_MULTIPROTOCOL
FileUtil::RmDir(profilesDir);
FileUtil::MkDir(profilesDir);
Profiles::Init();
#endif
bool rv = p_Protocols.at(selectidx)->SetupProfile(profilesDir, profileId);
if (rv)
{
std::cout << "Succesfully set up profile " << profileId << "\n";
}
else
{
std::cout << "Setup failed\n";
}
return rv;
}
void ShowHelp()
{
std::cout <<
"nchat is a minimalistic terminal-based chat client with support for\n"
"telegram.\n"
"\n"
"Usage: nchat [OPTION]\n"
"\n"
"Command-line Options:\n"
" -d, --confdir <DIR> use a different directory than ~/.nchat\n"
" -e, --verbose enable verbose logging\n"
" -ee, --extra-verbose enable extra verbose logging\n"
" -h, --help display this help and exit\n"
" -s, --setup set up chat protocol account\n"
" -v, --version output version information and exit\n"
" -x, --export <DIR> export message cache to specified dir\n"
"\n"
"Interactive Commands:\n"
" PageDn history next page\n"
" PageUp history previous page\n"
" Tab next chat\n"
" Sh-Tab previous chat\n"
" Ctrl-e insert emoji\n"
" Ctrl-g toggle show help bar\n"
" Ctrl-l toggle show contact list\n"
" Ctrl-p toggle show top bar\n"
" Ctrl-q quit\n"
" Ctrl-s search contacts\n"
" Ctrl-t send file\n"
" Ctrl-u jump to unread chat\n"
" Ctrl-x send message\n"
" Ctrl-y toggle show emojis\n"
" KeyUp select message\n"
"\n"
"Interactive Commands for Selected Message:\n"
" Ctrl-d delete selected message\n"
" Ctrl-r download attached file\n"
" Ctrl-v open/view attached file\n"
" Ctrl-x reply to selected message\n"
"\n"
"Report bugs at https://github.com/d99kris/nchat\n"
"\n";
}
void ShowVersion()
{
std::cout <<
"nchat v" << AppUtil::GetAppVersion() << "\n"
"\n"
"Copyright (c) 2019-2021 Kristofer Berggren\n"
"\n"
"nchat is distributed under the MIT license.\n"
"\n"
"Written by Kristofer Berggren.\n";
}
| 26.329949 | 119 | 0.591768 | d99kris |
aa3cf804ebd650fa05fdf9ce18400749aad0059f | 298 | cpp | C++ | src/Request/BalanceCheck.cpp | ZavierJin/AccountManager | b09235e71fa43a2c6ece1d6739ef44885d28af34 | [
"Apache-2.0"
] | null | null | null | src/Request/BalanceCheck.cpp | ZavierJin/AccountManager | b09235e71fa43a2c6ece1d6739ef44885d28af34 | [
"Apache-2.0"
] | null | null | null | src/Request/BalanceCheck.cpp | ZavierJin/AccountManager | b09235e71fa43a2c6ece1d6739ef44885d28af34 | [
"Apache-2.0"
] | null | null | null | // BalanceCheck.cpp
// Brief introduction: the implementation of BalanceCheck's method
// Create by Zhang Zhecheng 2020/5/18
#include "Request.h"
namespace request
{
BalanceCheck::BalanceCheck(const string &username)
: UserRequest(username, Kind::BalanceCheck){}
} // namespace request
| 29.8 | 66 | 0.748322 | ZavierJin |
aa3d370266bba86ba940dbe0f1f26b7b6dd23bfb | 14,765 | cpp | C++ | sumo-wrapper/code/par-sumo-wrapper.cpp | esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation | cfe6e3e8f333f906430d668f4f2b475dfdd71d9e | [
"MIT"
] | null | null | null | sumo-wrapper/code/par-sumo-wrapper.cpp | esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation | cfe6e3e8f333f906430d668f4f2b475dfdd71d9e | [
"MIT"
] | null | null | null | sumo-wrapper/code/par-sumo-wrapper.cpp | esegredo/Optimisation-Real-world-Traffic-Light-Cycle-Programs-Evolutionary-Computation | cfe6e3e8f333f906430d668f4f2b475dfdd71d9e | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <map>
#include <chrono>
#include <sys/wait.h>
#include "cInstance.hpp"
#include "simpleXMLParser.hpp"
using namespace std;
typedef struct
{
double GvR; // Original Green vs Red
double nGvR; // Normalized GvR
double duration; // Total duration
unsigned numVeh; // Vehicles arriving
unsigned remVeh; // Vehicles not arriving
double stops; // Number of stops (waiting counts and not planned stops)
double waitingTime; // Total time that vehicles have been waiting (at a speed lower than 0.1 m/s)
double fitness; // Fitness
// New stats
double meanTravelTime; // Mean Travel Time
double meanWaitingTime; // Mean Waiting Time
long double CO2; // CO2
long double CO; // CO
long double HC; // HC
long double NOx; // NOx
long double PMx; // PMx
long double fuel; // fuel
long double noise; // noise
} tStatistics;
// Auxiliar functions
// Convert a number to string
// string to_string(unsigned long v);
// Build XML additional file with new tlLogic tags from TL configuration
void buildXMLfile(const cInstance &c, const vector<unsigned> &tl_times, unsigned long long t, string dir);
// Deletes the created files
void deleteFiles(const cInstance &c, unsigned long long t, string dir);
// Read TL configuration (generated by the algorithm)
void readTLtime(string tl_filename, vector<unsigned> &tl);
// Build command for executing SUMO
string buildCommand(const cInstance &c, unsigned long long t, string dir, unsigned int numRep, vector<int> seeds);
// Write the result file
void writeResults(const tStatistics &s, string filename, unsigned int numRep);
// Executes a command with a pipe
string execCommandPipe(string command);
// Calculating statistics
// Calculate GvR value
void calculateGvR(const cInstance &c, const vector<unsigned> & tl_times, tStatistics &s);
// Analyze trip info obtaining how many vehicle arriving, number of stops, total duration, ...
void analyzeTripInfo(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep);
// Analyze Summary File
void analyzeSummary(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep);
// Calculate Fitness
double calculateFitness(const tStatistics &s, unsigned simTime);
// Analyze emission file
void analyzeEmissions(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep);
int main(int argc, char **argv)
{
//time_t current_time = time(0), t2, t3, t4;
auto start = chrono::high_resolution_clock::now();
auto current_time = chrono::duration_cast<chrono::nanoseconds>(start.time_since_epoch()).count();
if(argc != 7)
{
cout << "Usage: " << argv[0] << " <instance_file> <dir> <traffic light configuration> <result files> <delete generated files> <number of repetitions>" << endl;
exit(-1);
}
cInstance instance;
instance.read(argv[1]);
vector<unsigned> tl_times;
readTLtime(argv[3], tl_times);
srand(time(NULL));
vector<int> seeds;
for (int i = 0; i < atoi(argv[6]); i++) {
seeds.push_back(rand());
}
buildXMLfile(instance, tl_times, current_time, argv[2]);
// The parallelisation should start herein
#pragma omp parallel for
for (int i = 0; i < atoi(argv[6]); i++) {
string cmd = buildCommand(instance, current_time, argv[2], i, seeds);
cout << "Executing sumo ..." << endl;
auto t2 = chrono::high_resolution_clock::now();
execCommandPipe(cmd);
auto t3 = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - t2).count();
cout << "SUMO time: " << t3 << endl;
cout << "Obtaining statistics ..." << endl;
// Obtaining statistics
tStatistics s;
calculateGvR(instance, tl_times, s);
analyzeTripInfo(instance, current_time, s, argv[2], i);
analyzeSummary(instance, current_time, s, argv[2], i);
//analyzeEmissions(*instance, current_time, s, i);
// Calculates fitness based on the statistics
s.fitness = calculateFitness(s, instance.getSimulationTime());
writeResults(s, argv[4], i);
}
auto t4 = chrono::duration_cast<chrono::milliseconds>(chrono::high_resolution_clock::now() - start).count();
cout << "Total time: " << t4 << endl;
cout << endl;
if (stoi(argv[5]) == 1)
deleteFiles(instance, current_time, argv[2]);
return 0;
}
// Convert a number to string
/*string to_string(unsigned long v)
{
stringstream ss;
ss << v;
return ss.str();
}*/
void buildXMLfile(const cInstance &c, const vector<unsigned> &tl_times, unsigned long long t, string dir)
{
// string xmlfile = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + ".add.xml";
string xmlfile = c.getPath() + dir + "/" + c.getName() + ".add.xml";
ofstream fout_xml(xmlfile.c_str());
unsigned nTL = c.getNumberOfTLlogics();
vector<string> phases;
unsigned nPhases;
unsigned tl_times_counter = 0;
fout_xml << "<additional>" << endl;
for (int i=0;i<nTL;i++)
{
//fout_xml << "\t<tlLogic id=\"" << c.getTLID(i) << "\" type=\"static\" programID=\"1\" offset=\"0\">" << endl;
fout_xml << "\t<tlLogic id=\"" << c.getTLID(i) << "\" type=\"static\" programID=\"1\" offset=\"" << tl_times[tl_times_counter] << "\">" << endl;
tl_times_counter++;
phases = c.getPhases(i);
nPhases = phases.size();
for (int j=0;j<nPhases;j++)
{
fout_xml << "\t\t<phase duration=\"" << tl_times[tl_times_counter] << "\" state=\"" << phases[j] << "\"/>" << endl;
tl_times_counter++;
}
fout_xml << "\t</tlLogic>" << endl;
}
fout_xml << "</additional>" << endl;
fout_xml.close();
}
void deleteFiles(const cInstance &c, unsigned long long t, string dir) {
// string baseName = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName();
string baseName = c.getPath() + dir + "/" + c.getName();
string cmd = "rm " + baseName + ".add.xml";
execCommandPipe(cmd);
cmd = "rm " + baseName + "-*-summary.xml";
execCommandPipe(cmd);
cmd = "rm " + baseName + "-*-tripinfo.xml";
execCommandPipe(cmd);
cmd = "rm " + baseName + "-*-vehicles.xml";
execCommandPipe(cmd);
}
void readTLtime(string tl_filename, vector<unsigned> &tl)
{
ifstream fin_tl(tl_filename.c_str());
unsigned t;
fin_tl >> t;
while(!fin_tl.eof())
{
tl.push_back(t);
fin_tl >> t;
}
fin_tl.close();
}
string buildCommand(const cInstance &c, unsigned long long t, string dir, unsigned int numRep, vector<int> seeds)
{
//string cmd = "sumo ";
string cmd = "sumo -W ";
string name1 = c.getPath() + c.getName(); // Required instace files
//string name2 = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName(); // generated files by this application
string name2 = c.getPath() + dir + "/" + c.getName(); // generated files by this application
// Input files:
cmd += "-n " + name1 + ".net.xml "; // Network file
cmd += "-r " + name1 + ".rou.xml "; // Routes file
cmd += "-a " + name2 + ".add.xml "; // TL file
// Output files:
//cmd += "--save-configuration " + name2 + ".cfg "; // Save configuration <= With this option configuration file is generated but no SUMO execution is performed
//cmd += "--emission-output " + name1 + "-emissions.xml "; // Emissions result
cmd += "--summary-output " + name2 + "-" + to_string(numRep) + "-summary.xml "; // Summary result
cmd += "--vehroute-output " + name2 + "-" + to_string(numRep) + "-vehicles.xml "; // Vehicle routes result
cmd += "--tripinfo-output " + name2 + "-" + to_string(numRep) + "-tripinfo.xml "; // tripinfo result
// Options:
cmd += "-b 0 "; // Begin time
cmd += "-e " + to_string(c.getSimulationTime()) + " "; // End time
cmd += "-s 0 "; // route steps (with value 0, the whole routes file is loaded)
cmd += "--time-to-teleport -1 "; // Disable teleporting
cmd += "--no-step-log "; // Disable console output
//cmd += "--device.hbefa.probability 1.0 "; // Tripinfo file will include emissions stats
cmd += "--device.emissions.probability 1.0 ";
//cmd += "--seed " + to_string(t); // random seed
//cmd += "--seed 23432 ";
//cmd += "--random true ";
//cmd += "--thread-rngs 8 ";
cmd += "--seed " + to_string(seeds[numRep]) + " ";
// THIS IS NEW!!!! No validation
cmd += "--xml-validation never";
return cmd;
}
// GvR (Green vs Red)
// Requires tl configuration (no sumo simulation required)
// GvR = \sum_{i=0}^{totalPhases}{GvR_phase(i)}
// GvR_phase(i) = duration(i) * (number_of_greens(i) / number_of_reds(i))
// Larger values are better
// Disadvantages: - No normalized - yellow/red phases are not counted
// Alternatives:
// Normaziled GvR: nGvR
// nGVR = 1/number_of_TL * \sum_{i = 0}^{number_of_TL}{ (\sum_{j=0}^{phases_TL(i)}{GvR_phase(j)})/ (\sum_{j=0}^{phases_TL(i)}{duration(j)}) }
// Larger values are better
// Advantages: - Normalized (0/1) - All phases are taken into account
void calculateGvR(const cInstance &c, const vector<unsigned> & tl_times, tStatistics &s)
{
unsigned nTL = c.getNumberOfTLlogics(); // Number of TL logics
unsigned nPhases; // Number of phases of a TL
unsigned nt; // Number of tl in a TL logic
// auxiliar variables
vector<string> phases;
unsigned tl_times_counter = 0;
double gvr, dur, red, green;
s.GvR = s.nGvR = 0;
for (int i=0;i<nTL;i++)
{
phases = c.getPhases(i);
nPhases = phases.size();
tl_times_counter++;
gvr = 0;
dur = 0;
for (int j=0;j<nPhases;j++)
{
red = green = 0;
nt = phases[j].size();
for(int k = 0; k < nt; k++)
{
if(phases[j][k] == 'r') red++;
else if(toupper(phases[j][k]) == 'G') green++;
}
if(red == 0) red++;
gvr += (green/red)*tl_times[tl_times_counter];
dur += tl_times[tl_times_counter];
tl_times_counter++;
}
s.GvR += gvr;
s.nGvR += (gvr/dur);
}
s.nGvR /= nTL;
}
void analyzeTripInfo(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep)
{
// string filename = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + "-tripinfo.xml";
string filename = c.getPath() + dir + "/" + c.getName() + "-" + to_string(numRep) + "-tripinfo.xml";
string line;
ifstream fin(filename.c_str());
map<string, string> m;
int position;
s.numVeh = 0;
s.duration = 0;
s.stops = 0;
s.waitingTime = 0;
s.CO2 = 0;
s.CO = 0;
s.HC = 0;
s.NOx = 0;
s.PMx = 0;
s.fuel = 0;
s.noise = 0;
getline(fin, line);
while(!fin.eof())
{
if(isSubString(line,"id=",position))
{
// get map
getPairMap(line, m);
s.numVeh++;
s.duration += atof(m["duration"].c_str());
// It is the number of times vehicles have been waiting (at a speed lower than 0.1 m/s)
// It does not include the number of planned stops
s.stops += atof(m["waitingCount"].c_str());
// It is the times a vehicle has been waiting (at a speed lower than 0.1 m/s)
// It does not include the planned stops time
s.waitingTime += atof(m["waitingTime"].c_str());
}
else if(isSubString(line,"CO_abs=",position))
{
getPairMap(line, m);
s.CO2 += atof(m["CO2_abs"].c_str());
s.CO += atof(m["CO_abs"].c_str());
s.HC += atof(m["HC_abs"].c_str());
s.NOx += atof(m["NOx_abs"].c_str());
s.PMx += atof(m["PMx_abs"].c_str());
s.fuel += atof(m["fuel_abs"].c_str());
//s.noise += atof(m["noise"].c_str());
}
getline(fin, line);
}
s.remVeh = c.getNumberOfVehicles() - s.numVeh;
fin.close();
}
void analyzeSummary(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep)
{
// string filename = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + "-summary.xml";
string filename = c.getPath() + dir + "/" + c.getName() + "-" + to_string(numRep) + "-summary.xml";
string line,last_line;
ifstream fin(filename.c_str());
map<string, string> m;
int position;
getline(fin, line);
while(!fin.eof())
{
if(isSubString(line,"time=",position))
{
last_line = line;
}
getline(fin, line);
}
// get map
getPairMap(last_line, m);
s.meanTravelTime = atof(m["meanTravelTime"].c_str());
s.meanWaitingTime = atof(m["meanWaitingTime"].c_str());
fin.close();
}
double calculateFitness(const tStatistics &s, unsigned simTime)
{
return (s.duration + (s.remVeh * simTime) + s.waitingTime) / (s.numVeh * s.numVeh + s.GvR);
}
void analyzeEmissions(const cInstance &c, unsigned long long t, tStatistics &s, string dir, unsigned int numRep)
{
// string filename = c.getPath() + dir + "/" + to_string(t) + "-" + c.getName() + "-emissions.xml";
string filename = c.getPath() + dir + "/" + c.getName() + "-" + to_string(numRep) + "-emissions.xml";
string line;
ifstream fin(filename.c_str());
map<string, string> m;
int position;
s.CO2 = 0;
s.CO = 0;
s.HC = 0;
s.NOx = 0;
s.PMx = 0;
s.fuel = 0;
s.noise = 0;
getline(fin, line);
while(!fin.eof())
{
if(isSubString(line,"id=",position))
{
// get map
getPairMap(line, m);
s.CO2 += atof(m["CO2"].c_str());
s.CO += atof(m["CO"].c_str());
s.HC += atof(m["HC"].c_str());
s.NOx += atof(m["NOx"].c_str());
s.PMx += atof(m["PMx"].c_str());
s.fuel += atof(m["fuel"].c_str());
s.noise += atof(m["noise"].c_str());
}
getline(fin, line);
}
fin.close();
}
void writeResults(const tStatistics &s, string filename, unsigned int numRep)
{
filename += "." + to_string(numRep);
ofstream fout(filename.c_str());
fout << s.GvR << " // Original Green vs Red" << endl;
fout << s.nGvR << " // Normalized GvR" << endl;
fout << s.duration << " // Total duration" << endl;
fout << s.numVeh << " // Vehicles arriving" << endl;
fout << s.remVeh << " // Vehicles not arriving" << endl;
fout << s.stops << " // Number of stops (waiting counts)" << endl;
fout << s.waitingTime << " // Total waiting time (at a speed lower than 0.1 m/s)" << endl;
fout << s.fitness << " // Fitness" << endl;
fout << s.meanTravelTime << " // Mean Travel Time" << endl;
fout << s.meanWaitingTime << " // Mean Waiting Time" << endl;
fout << s.CO2 << " // CO2 " << endl;
fout << s.CO << " // CO" << endl;
fout << s.HC << " // HC" << endl;
fout << s.NOx << " // NOx" << endl;
fout << s.PMx << " // PMx" << endl;
fout << s.fuel << " // fuel" << endl;
fout << s.noise << " // noise" << endl;
fout.close();
}
string execCommandPipe(string command) {
const int MAX_BUFFER_SIZE = 128;
FILE* pipe = popen(command.c_str(), "r");
// Waits until the execution ends
if (wait(NULL) == -1){
//cerr << "Error waiting for simulator results" << endl;
return "Error waiting for simulator results";
}
char buffer[MAX_BUFFER_SIZE];
string result = "";
while (!feof(pipe)) {
if (fgets(buffer, MAX_BUFFER_SIZE, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
| 30.256148 | 162 | 0.634338 | esegredo |
aa420e5a2d10e61e1f527d8a68b3453adc373880 | 5,787 | cpp | C++ | src/string.cpp | surreal-Ceres/image32 | 0aabb8aa2f8e45dafea6249a9873080b048183b1 | [
"MIT"
] | 2 | 2020-12-23T16:42:52.000Z | 2021-04-13T20:41:09.000Z | src/string.cpp | surreal-Ceres/image32 | 0aabb8aa2f8e45dafea6249a9873080b048183b1 | [
"MIT"
] | null | null | null | src/string.cpp | surreal-Ceres/image32 | 0aabb8aa2f8e45dafea6249a9873080b048183b1 | [
"MIT"
] | null | null | null | #include "string.h"
#include <iterator>
#include <cstdarg>
#include <vector>
std::string string_to_lower(const std::string& str)
{
std::string result(str);
for(auto it = result.begin(); it != result.end(); it++)
*it = std::tolower(*it);
return result;
}
std::string format_to_string(const char* format, ...)
{
va_list args;
va_start(args, format);
std::size_t required_size = vsnprintf(nullptr, 0, format, args);
std::vector<char> buf(++required_size);
vsnprintf(&buf[0], buf.size(), format, args);
va_end(args);
return std::string(&buf[0]);
}
static size_t insert_utf8_char(std::string* result, wchar_t wchr)
{
int size, bits, b, i;
if (wchr < 128) {
if (result)
result->push_back(wchr);
return 1;
}
bits = 7;
while (wchr >= (1<<bits))
bits++;
size = 2;
b = 11;
while (b < bits) {
size++;
b += 5;
}
if (result) {
b -= (7-size);
int firstbyte = wchr>>b;
for (i=0; i<size; i++)
firstbyte |= (0x80>>i);
result->push_back(firstbyte);
for (i=1; i<size; i++) {
b -= 6;
result->push_back(0x80 | ((wchr>>b)&0x3F));
}
}
return size;
}
std::string to_utf8(const wchar_t* wsrc, const int n)
{
size_t required_size = 0;
const wchar_t* p = wsrc;
for(int i = 0; i < n; i++, ++p)
required_size += insert_utf8_char(nullptr, *p);
if(!required_size)
return std::string();
std::string result;
result.reserve(++required_size);
for(int i = 0; i < n; i++, ++wsrc)
insert_utf8_char(&result, *wsrc);
return result;
}
template<typename BaseIterator>
class utf8_iterator_t : public std::iterator<std::forward_iterator_tag,
std::string::value_type,
std::string::difference_type,
typename BaseIterator::pointer,
typename BaseIterator::reference>
{
public:
typedef typename BaseIterator::pointer pointer;
utf8_iterator_t() {}
explicit utf8_iterator_t(const BaseIterator& it) : m_internal(it) {}
utf8_iterator_t& operator++() {
int c = *m_internal;
++m_internal;
if (c & 0x80) {
int n = 1;
while (c & (0x80>>n))
n++;
c &= (1<<(8-n))-1;
while (--n > 0) {
int t = *m_internal;
++m_internal;
if ((!(t & 0x80)) || (t & 0x40)) {
--m_internal;
return *this;
}
c = (c<<6) | (t & 0x3F);
}
}
return *this;
}
utf8_iterator_t& operator+=(int sum) {
while(sum--)
operator++();
return *this;
}
utf8_iterator_t operator+(int i) {
utf8_iterator_t it(*this);
it += i;
return it;
}
const int operator*() const {
BaseIterator it = m_internal;
int c = *it;
++it;
if (c & 0x80) {
int n = 1;
while (c & (0x80>>n))
n++;
c &= (1<<(8-n))-1;
while (--n > 0) {
int t = *it;
++it;
if ((!(t & 0x80)) || (t & 0x40))
return '^';
c = (c<<6) | (t & 0x3F);
}
}
return c;
}
bool operator==(const utf8_iterator_t& it) const {
return m_internal == it.m_internal;
}
bool operator!=(const utf8_iterator_t& it) const {
return m_internal != it.m_internal;
}
pointer operator->() {
return m_internal.operator->();
}
std::string::difference_type operator-(const utf8_iterator_t& it) const {
return m_internal - it.m_internal;
}
private:
BaseIterator m_internal;
};
class utf8_iterator : public utf8_iterator_t<std::string::iterator> {
public:
utf8_iterator() { }
utf8_iterator(const utf8_iterator_t<std::string::iterator>& it)
: utf8_iterator_t<std::string::iterator>(it) {
}
explicit utf8_iterator(const std::string::iterator& it)
: utf8_iterator_t<std::string::iterator>(it) {
}
};
class utf8_const_iterator : public utf8_iterator_t<std::string::const_iterator> {
public:
utf8_const_iterator() { }
utf8_const_iterator(const utf8_iterator_t<std::string::const_iterator>& it)
: utf8_iterator_t<std::string::const_iterator>(it) {
}
explicit utf8_const_iterator(const std::string::const_iterator& it)
: utf8_iterator_t<std::string::const_iterator>(it) {
}
};
class utf8 {
public:
utf8(std::string& s) : m_begin(utf8_iterator(s.begin())),
m_end(utf8_iterator(s.end())) {
}
const utf8_iterator& begin() const { return m_begin; }
const utf8_iterator& end() const { return m_end; }
private:
utf8_iterator m_begin;
utf8_iterator m_end;
};
class utf8_const {
public:
utf8_const(const std::string& s) : m_begin(utf8_const_iterator(s.begin())),
m_end(utf8_const_iterator(s.end())) {
}
const utf8_const_iterator& begin() const { return m_begin; }
const utf8_const_iterator& end() const { return m_end; }
private:
utf8_const_iterator m_begin;
utf8_const_iterator m_end;
};
int utf8_length(const std::string& str)
{
utf8_const_iterator it(str.begin());
utf8_const_iterator end(str.end());
int size = 0;
while(it != end)
++it, ++size;
return size;
}
std::wstring from_utf8(const std::string& str)
{
int required_size = utf8_length(str);
std::vector<wchar_t> buf(++required_size);
std::vector<wchar_t>::iterator buf_it = buf.begin();
utf8_const_iterator it(str.begin());
utf8_const_iterator end(str.end());
while (it != end) {
*buf_it = *it;
++buf_it;
++it;
}
return std::wstring(&buf[0]);
} | 22.257692 | 81 | 0.563332 | surreal-Ceres |
aa4e4438391c48eb8eb8351320b2ba86b86e9bc4 | 9,263 | cpp | C++ | qt/imageDisplay/RasterResource.cpp | e-foto/e-foto | cf143a1076c03c7bdf5a2f41efad2c98e9272722 | [
"FTL"
] | 3 | 2021-06-28T21:07:58.000Z | 2021-07-02T11:21:49.000Z | qt/imageDisplay/RasterResource.cpp | e-foto/e-foto | cf143a1076c03c7bdf5a2f41efad2c98e9272722 | [
"FTL"
] | null | null | null | qt/imageDisplay/RasterResource.cpp | e-foto/e-foto | cf143a1076c03c7bdf5a2f41efad2c98e9272722 | [
"FTL"
] | null | null | null | #include "RasterResource.h"
#include <QMessageBox>
RasterResource::RasterResource(QString filepath, bool withSmoothIn, bool withSmoothOut)
{
// Abrir a imagem e testar se é válida
QImage* srcImage = new QImage();
_isValid = srcImage->load(filepath);
_levels = 0;
_useSmoothIn = withSmoothIn;
_useSmoothOut = withSmoothOut;
if (!_isValid || srcImage->width() == 0 || srcImage->height() == 0)
{
if (filepath != "")
emitLoadError();
return;
}
// Calcular o numero de niveis da piramide
_imageDim = srcImage->size();
_levels = log(_imageDim.width() < _imageDim.height() ? _imageDim.width() : _imageDim.height() ) / log(2) -4;
// Alocando espaço para a piramide
_pyramid = (QImage**) calloc(_levels, sizeof(QImage*));
// Atribui a imagem original ao primeiro nível
_pyramid[0] = new QImage(srcImage->convertToFormat(QImage::Format_ARGB32));
delete(srcImage);
if (_pyramid[0]->width() == 0 || _pyramid[0]->height() == 0)
{
_isValid = false;
delete(_pyramid[0]);
free(_pyramid);
emitLoadError();
return;
}
// Construindo imagens
for(int l = 1; l < _levels; l++)
{
// Cada imagem do novo nível é igual ao nível anterior reduzida pela metade
int w = _pyramid[l-1]->width()/2;
int h = _pyramid[l-1]->height()/2;
_pyramid[l] = new QImage(_pyramid[l-1]->scaled(w,h,Qt::KeepAspectRatioByExpanding, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation));
if (_pyramid[l]->width() == 0 || _pyramid[l]->height() == 0)
{
_isValid = false;
for (int k = l; l >= 0; l--)
delete(_pyramid[k]);
free(_pyramid);
emitLoadError();
return;
}
}
}
RasterResource::~RasterResource()
{
if (!_isValid)
return;
for(int l = 0; l < _levels; l++)
delete(_pyramid[l]);
free(_pyramid);
}
void RasterResource::emitLoadError()
{
QMessageBox* msgBox = new QMessageBox();
msgBox->setText("Error: The image loading process.");
msgBox->exec();
}
void RasterResource::useSmoothIn(bool useSmooth)
{
_useSmoothIn = useSmooth;
}
void RasterResource::transformImage(double H[9])
{
if (_isValid)
{
QImage newImage(*_pyramid[0]);
QTransform h(H[0],H[3],H[6],H[1],H[4],H[7],H[2],H[5],H[8]);
//qDebug("\n%f %f %f\n%f %f %f\n%f %f %f",H[0],H[3],H[6],H[1],H[4],H[7],H[2],H[5],H[8]);
load(newImage.transformed(h));
}
}
bool RasterResource::load(QImage image)
{
// Impede carga de imagem nula
if (image.isNull())
{
emitLoadError();
return false;
}
// Remove imagem pré-existente
if (_isValid)
{
for(int l = 0; l < _levels; l++)
delete(_pyramid[l]);
free(_pyramid);
}
_isValid = true;
// Calcular o numero de niveis da piramide
_imageDim = image.size();
_levels = log(_imageDim.width() < _imageDim.height() ? _imageDim.width() : _imageDim.height() ) / log(2) -4;
if (_levels < 0) _levels = 0;
// Alocando espaço para a piramide
_pyramid = (QImage**) calloc(_levels, sizeof(QImage*));
// Atribui a imagem original ao primeiro nível
_pyramid[0] = new QImage(image.convertToFormat(QImage::Format_ARGB32));
if (_pyramid[0]->width() == 0 || _pyramid[0]->height() == 0)
{
_isValid = false;
delete(_pyramid[0]);
free(_pyramid);
emitLoadError();
return false;
}
// Construindo imagens
for(int l = 1; l < _levels; l++)
{
// Cada imagem do novo nível é igual ao nível anterior reduzida pela metade
int w = _pyramid[l-1]->width()/2;
int h = _pyramid[l-1]->height()/2;
_pyramid[l] = new QImage(_pyramid[l-1]->scaled(w,h,Qt::IgnoreAspectRatio, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation));
if (_pyramid[l]->width() == 0 || _pyramid[l]->height() == 0)
{
_isValid = false;
for (int k = l; l >= 0; l--)
delete(_pyramid[k]);
free(_pyramid);
emitLoadError();
return false;
}
}
return _isValid;
}
bool RasterResource::load(QString filepath)
{
// Abrir a imagem e testar se é válida
QImage image;
if (image.load(filepath))
{
for(int l = 0; l < _levels; l++)
delete(_pyramid[l]);
free(_pyramid);
_isValid = true;
}
else
{
return false;
}
// Calcular o numero de niveis da piramide
_imageDim = image.size();
_levels = log(_imageDim.width() < _imageDim.height() ? _imageDim.width() : _imageDim.height() ) / log(2) -4;
if (_levels < 0) _levels = 0;
// Alocando espaço para a piramide
_pyramid = (QImage**) calloc(_levels, sizeof(QImage*));
// Atribui a imagem original ao primeiro nível
_pyramid[0] = new QImage(image.convertToFormat(QImage::Format_ARGB32));
if (_pyramid[0]->width() == 0 || _pyramid[0]->height() == 0)
{
_isValid = false;
delete(_pyramid[0]);
free(_pyramid);
emitLoadError();
return false;
}
// Construindo imagens
for(int l = 1; l < _levels; l++)
{
// Cada imagem do novo nível é igual ao nível anterior reduzida pela metade
int w = _pyramid[l-1]->width()/2;
int h = _pyramid[l-1]->height()/2;
_pyramid[l] = new QImage(_pyramid[l-1]->scaled(w,h,Qt::IgnoreAspectRatio, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation));
if (_pyramid[l]->width() == 0 || _pyramid[l]->height() == 0)
{
_isValid = false;
for (int k = l; l >= 0; l--)
delete(_pyramid[k]);
free(_pyramid);
emitLoadError();
return false;
}
}
return _isValid;
}
bool RasterResource::save(QString filepath, QString format)
{
if (_pyramid && _pyramid[0]->save(filepath,format.toLocal8Bit().constData()))
return true;
return false;
}
bool RasterResource::isValid()
{
return _isValid;
}
int RasterResource::width()
{
return _imageDim.width();
}
int RasterResource::height()
{
return _imageDim.height();
}
QSize RasterResource::size()
{
return _imageDim;
}
int RasterResource::levels()
{
return _levels;
}
QPointF RasterResource::center()
{
return QPointF(width()/2.0,height()/2.0);
}
QImage RasterResource::getImageCut(QSize targetSize, QRectF imageCut)
{
// Este método poderia possuir a assinatura getImageCut(QSize targetSize, QPointF viewPoint, double scale)
// Contudo devido a possível incompatibilidade com o TeCanvas ele ficou da forma atual
QImage result;
if (_isValid)
{
// Inicialização de variáveis para o recorte na imagem do topo da pilha
QRect rectToCut = imageCut.toRect();
QImage* img = _pyramid[0];
int l = 0;
// Na prática, qualquer corte deveria possuir a mesma escala em width e height
// mas isso não ocorre para o recorte de Overview. Por isso recuperamos a escala assim:
double wscale = targetSize.width() / imageCut.width();
double hscale = targetSize.height() / imageCut.height();
double scale = (wscale > hscale) ? wscale : hscale;
// Seleciona a imagem correta a recortar, faz o recorte e ajustes para perfeito encaixe do centro do recorte na imagem com a imagem resultante
if (scale > 1.0)
{
// Este caso precisa ser tratado com atenção.
// Precisamos manter o aspécto da imagem, o zoom correto e o ponto central do recorte corretamente alinhado
// Primeiro evitamos problemas com o espaço recortado aumentando ligeiramente a área de recorte
//comentar depois
rectToCut.setLeft(rectToCut.left()-1);
rectToCut.setTop(rectToCut.top()-1);
rectToCut.setWidth(rectToCut.width()+2);
rectToCut.setHeight(rectToCut.height()+2);
// Criamos um newTargetSize para a nova escala com o aspécto do primeiro recorte
QSize newTargetSize = rectToCut.size() * scale;
// Um recorte final vai garantir a posição corretamente alinhada e o targetSize pedido
QRect finalCut(((imageCut.topLeft() - QPointF(rectToCut.topLeft())) * scale).toPoint(), targetSize);
result = img->copy(rectToCut).scaled(newTargetSize,Qt::KeepAspectRatioByExpanding, _useSmoothIn ? Qt::SmoothTransformation : Qt::FastTransformation).copy(finalCut);
}
else if (scale > 0.5)
{
// Corta e reduz a imagem a partir do primeiro nível da pirâmide. Este é o caso mais simples
result = img->copy(rectToCut).scaled(targetSize,Qt::KeepAspectRatioByExpanding, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation);
}
else
{
// Procura o nível correto da pirâmide que será utilizado e o novo imageCut
while (scale <= 0.5 && l<_levels-1)
{
scale *= 2;
l++;
QPointF center(QPointF(imageCut.center().x()/2.0,imageCut.center().y()/2.0));
imageCut.setSize(imageCut.size()/2.0);
imageCut.moveCenter(center);
}
// Troca a imagem pela imagem do nível correto, seleciona o novo corte e recorta.
img = _pyramid[l];
rectToCut = imageCut.toRect();
result = img->copy(rectToCut).scaled(targetSize,Qt::KeepAspectRatioByExpanding, _useSmoothOut ? Qt::SmoothTransformation : Qt::FastTransformation);
}
}
//Nem toda tela tem 96 dpi, refazer depois
result.setDotsPerMeterX(3780);
result.setDotsPerMeterY(3780);
return result;
}
QColor RasterResource::getColor(QPoint at)
{
if (_isValid && at.x() >= 0 && at.y() >= 0 && at.x() < width() -1 && at.y() < height() - 1)
return QColor(_pyramid[0]->pixel(at));
else
return QColor();
}
unsigned int RasterResource::getGrayColor(QPointF at, bool linear)
{
unsigned int result = 0;
if (_isValid && at.x() >= 0 && at.y() >= 0 && at.x() < width() -1 && at.y() < height() - 1)
{
if (linear)
{
// adicionar a parte linear aqui depois.
}
else result = qGray(_pyramid[0]->pixel((int)floor(at.x()),(int)floor(at.y())));
}
return result;
}
| 27.900602 | 167 | 0.675159 | e-foto |
aa52f3f111e963b54ded8bd3b1c171624d6797d5 | 5,388 | hpp | C++ | headers/server_enum.hpp | DynasticSponge/Frederick2 | 410ad4a3ca43547d645248e13d27497e6c5b5f26 | [
"MIT"
] | null | null | null | headers/server_enum.hpp | DynasticSponge/Frederick2 | 410ad4a3ca43547d645248e13d27497e6c5b5f26 | [
"MIT"
] | null | null | null | headers/server_enum.hpp | DynasticSponge/Frederick2 | 410ad4a3ca43547d645248e13d27497e6c5b5f26 | [
"MIT"
] | null | null | null | //
// server_enum.hpp
// ~~~~~~~~~~~~~~~
//
// Author: Joseph Adomatis
// Copyright (c) 2020 Joseph R Adomatis (joseph dot adomatis at gmail dot com)
//
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef SERVER_ENUM_HPP
#define SERVER_ENUM_HPP
#include "frederick2_namespace.hpp"
enum class frederick2::httpEnums::httpMethod
{
ENUMERROR,
CONNECT,
DELETE,
GET,
HEAD,
OPTIONS,
PATCH,
POST,
PUT,
TRACE
};
enum class frederick2::httpEnums::httpProtocol
{
ENUMERROR,
HTTP
};
enum class frederick2::httpEnums::httpStatus
{
ENUMERROR = -1,
///////////////////////////////////////////////////////////////////////////////
// INFORMATIONAL_RESPONSE
///////////////////////////////////////////////////////////////////////////////
CONTINUE = 100,
SWITCHING_PROTOCOLS = 101,
PROCESSING = 102,
EARLY_HINTS = 103,
///////////////////////////////////////////////////////////////////////////////
// SUCCESS
///////////////////////////////////////////////////////////////////////////////
OK = 200,
CREATED = 201,
ACCEPTED = 202,
NON_AUTHORITATIVE_INFORMATION = 203,
NO_CONTENT = 204,
RESET_CONTENT = 205,
PARTIAL_CONTENT = 206,
MULTI_STATUS = 207,
ALREADY_REPORTED = 208,
IM_USED = 226,
///////////////////////////////////////////////////////////////////////////////
// REDIRECTION
///////////////////////////////////////////////////////////////////////////////
MULTIPLE_CHOICES = 300,
MOVED_PERMANENTLY = 301,
FOUND = 302,
SEE_OTHER = 303,
NOT_MODIFIED = 304,
USE_PROXY = 305,
SWITCH_PROXY = 306,
TEMPORARY_REDIRECT = 307,
PERMANENT_REDIRECT = 308,
///////////////////////////////////////////////////////////////////////////////
// CLIENT ERRORS
///////////////////////////////////////////////////////////////////////////////
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
METHOD_NOT_ALLOWED = 405,
NOT_ACCEPTABLE = 406,
PROXY_AUTHENTICATION_REQUIRED = 407,
REQUEST_TIMEOUT = 408,
CONFLICT = 409,
GONE = 410,
LENGTH_REQUIRED = 411,
PRECONDITION_FAILED = 412,
PAYLOAD_TOO_LARGE = 413,
URI_TOO_LONG = 414,
UNSUPPORTED_MEDIA_TYPE = 415,
RANGE_NOT_SATISFIABLE = 416,
EXPECTATION_FAILED = 417,
IM_A_TEAPOT = 418,
MISDIRECTED_REQUEST = 421,
UNPROCESSABLE_ENTITY = 422,
LOCKED = 423,
FAILED_DEPENDENCY = 424,
TOO_EARLY = 425,
UPGRADE_REQUIRED = 426,
PRECONDITION_REQUIRED = 428,
TOO_MANY_REQUESTS = 429,
REQUEST_HEADER_FIELDS_TOO_LARGE = 431,
UNAVAILABLE_FOR_LEGAL_REASONS = 451,
///////////////////////////////////////////////////////////////////////////////
// SERVER ERRORS
///////////////////////////////////////////////////////////////////////////////
INTERNAL_SERVER_ERROR = 500,
NOT_IMPLEMENTED = 501,
BAD_GATEWAY = 502,
SERVICE_UNAVAILABLE = 503,
GATEWAY_TIMEOUT = 504,
HTTP_VERSION_NOT_SUPPORTED = 505,
VARIANT_ALSO_NEGOTIATES = 506,
INSUFFICIENT_STORAGE = 507,
LOOP_DETECTED = 508,
NOT_EXTENDED = 510,
NETWORK_AUTHENTICATION_REQUIRED = 511
};
enum class frederick2::httpEnums::resourceType
{
ENUMERROR,
DYNAMIC,
FILESYSTEM,
STATIC
};
enum class frederick2::httpEnums::uriHostType
{
ENUMERROR,
IPV4_ADDRESS,
IPV6_ADDRESS,
REGISTERED_NAME
};
enum class frederick2::httpEnums::uriScheme
{
ENUMERROR,
http,
https
};
class frederick2::httpEnums::converter
{
public:
converter();
static std::string method2str(frederick2::httpEnums::httpMethod);
static std::string protocol2str(frederick2::httpEnums::httpProtocol);
static std::string status2str(frederick2::httpEnums::httpStatus);
static frederick2::httpEnums::httpMethod str2method(const std::string&);
static frederick2::httpEnums::httpProtocol str2protocol(const std::string&);
static frederick2::httpEnums::uriScheme str2scheme(const std::string&);
~converter();
protected:
private:
///////////////////////////////////////////////////////////////////////////////
// Private Functions
///////////////////////////////////////////////////////////////////////////////
static void initValidMethods();
static void initValidProtocols();
static void initValidSchemes();
static void initValidMethodStrings();
static void initValidProtocolStrings();
static void initValidStatusStrings();
///////////////////////////////////////////////////////////////////////////////
// Private Properties
///////////////////////////////////////////////////////////////////////////////
static inline bool isInitVM = false;
static inline bool isInitVP = false;
static inline bool isInitVS = false;
static inline bool isInitVMS = false;
static inline bool isInitVPS = false;
static inline bool isInitVSS = false;
static inline strMAPmethod validMethods;
static inline strMAPprotocol validProtocols;
static inline strMAPscheme validSchemes;
static inline methodMAPstr validMethodStrings;
static inline protocolMAPstr validProtocolStrings;
static inline statusMAPstr validStatusStrings;
};
#endif | 30.100559 | 119 | 0.522086 | DynasticSponge |
aa570e94789ea2eb8d8da55e79805a91cf5f1b09 | 20,497 | cpp | C++ | Assets/FrameCapturer-master/Plugin/fccore/Foundation/PixelFormat.cpp | Okashiou/VJx | 491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0 | [
"MIT"
] | null | null | null | Assets/FrameCapturer-master/Plugin/fccore/Foundation/PixelFormat.cpp | Okashiou/VJx | 491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0 | [
"MIT"
] | null | null | null | Assets/FrameCapturer-master/Plugin/fccore/Foundation/PixelFormat.cpp | Okashiou/VJx | 491cc37e3d6eddd78e4c99d5f211c5e2b2d498f0 | [
"MIT"
] | null | null | null | #include "pch.h"
#include "fcInternal.h"
#include "Buffer.h"
#include "PixelFormat.h"
#define fcEnableISPCKernel
int fcGetPixelSize(fcPixelFormat format)
{
switch (format)
{
case fcPixelFormat_RGBAu8: return 4;
case fcPixelFormat_RGBu8: return 3;
case fcPixelFormat_RGu8: return 2;
case fcPixelFormat_Ru8: return 1;
case fcPixelFormat_RGBAf16:
case fcPixelFormat_RGBAi16: return 8;
case fcPixelFormat_RGBf16:
case fcPixelFormat_RGBi16: return 6;
case fcPixelFormat_RGf16:
case fcPixelFormat_RGi16: return 4;
case fcPixelFormat_Rf16:
case fcPixelFormat_Ri16: return 2;
case fcPixelFormat_RGBAf32:
case fcPixelFormat_RGBAi32: return 16;
case fcPixelFormat_RGBf32:
case fcPixelFormat_RGBi32: return 12;
case fcPixelFormat_RGf32:
case fcPixelFormat_RGi32: return 8;
case fcPixelFormat_Rf32:
case fcPixelFormat_Ri32: return 4;
}
return 0;
}
void fcImageFlipY(void *image_, int width, int height, fcPixelFormat fmt)
{
size_t pitch = width * fcGetPixelSize(fmt);
Buffer buf_((size_t)pitch);
char *image = (char*)image_;
char *buf = &buf_[0];
for (int y = 0; y < height / 2; ++y) {
int iy = height - y - 1;
memcpy(buf, image + (pitch*y), pitch);
memcpy(image + (pitch*y), image + (pitch*iy), pitch);
memcpy(image + (pitch*iy), buf, pitch);
}
}
#ifdef fcEnableISPCKernel
#include "ConvertKernel.h"
void fcScaleArray(uint8_t *data, size_t size, float scale) { ispc::ScaleU8(data, (uint32_t)size, scale); }
void fcScaleArray(uint16_t *data, size_t size, float scale) { ispc::ScaleI16(data, (uint32_t)size, scale); }
void fcScaleArray(int32_t *data, size_t size, float scale) { ispc::ScaleI32(data, (uint32_t)size, scale); }
void fcScaleArray(half *data, size_t size, float scale) { ispc::ScaleF16((int16_t*)data, (uint32_t)size, scale); }
void fcScaleArray(float *data, size_t size, float scale) { ispc::ScaleF32(data, (uint32_t)size, scale); }
const void* fcConvertPixelFormat_ISPC(void *dst, fcPixelFormat dstfmt, const void *src, fcPixelFormat srcfmt, size_t size_)
{
uint32_t size = (uint32_t)size_;
switch (srcfmt) {
case fcPixelFormat_RGBAu8:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: return src;
case fcPixelFormat_RGBu8: ispc::RGBAu8ToRGBu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGBAu8ToRGu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGBAu8ToRu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGBAu8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGBAu8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGBAu8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGBAu8ToRf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGBAu8ToRGBAf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGBAu8ToRGBf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGBAu8ToRGf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGBAu8ToRf32((float*)dst, (uint8_t*)src, size); break;
}
break;
case fcPixelFormat_RGBu8:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGBu8ToRGBAu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBu8: return src;
case fcPixelFormat_RGu8: ispc::RGBu8ToRGu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGBu8ToRu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGBu8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGBu8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGBu8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGBu8ToRf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGBu8ToRGBAf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGBu8ToRGBf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGBu8ToRGf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGBu8ToRf32((float*)dst, (uint8_t*)src, size); break;
}
break;
case fcPixelFormat_RGu8:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGu8ToRGBAu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGu8ToRGBu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGu8: return src;
case fcPixelFormat_Ru8: ispc::RGu8ToRu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGu8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGu8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGu8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGu8ToRf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGu8ToRGBAf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGu8ToRGBf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGu8ToRGf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGu8ToRf32((float*)dst, (uint8_t*)src, size); break;
}
break;
case fcPixelFormat_Ru8:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::Ru8ToRGBAu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBu8: ispc::Ru8ToRGBu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGu8: ispc::Ru8ToRGu8((uint8_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Ru8: return src;
case fcPixelFormat_RGBAf16: ispc::Ru8ToRGBAf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf16: ispc::Ru8ToRGBf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf16: ispc::Ru8ToRGf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf16: ispc::Ru8ToRf16((int16_t*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::Ru8ToRGBAf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::Ru8ToRGBf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::Ru8ToRGf32((float*)dst, (uint8_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::Ru8ToRf32((float*)dst, (uint8_t*)src, size); break;
}
break;
case fcPixelFormat_RGBAf16:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGBAf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGBAf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGBAf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGBAf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::RGBAf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBi16: ispc::RGBAf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGi16: ispc::RGBAf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ri16: ispc::RGBAf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf16: return src;
case fcPixelFormat_RGBf16: ispc::RGBAf16ToRGBf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGBAf16ToRGf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGBAf16ToRf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGBAf16ToRGBAf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGBAf16ToRGBf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGBAf16ToRGf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGBAf16ToRf32((float*)dst, (int16_t*)src, size); break;
}
break;
case fcPixelFormat_RGBf16:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGBf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGBf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGBf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGBf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::RGBf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBi16: ispc::RGBf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGi16: ispc::RGBf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ri16: ispc::RGBf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGBf16ToRGBAf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf16: return src;
case fcPixelFormat_RGf16: ispc::RGBf16ToRGf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGBf16ToRf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGBf16ToRGBAf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGBf16ToRGBf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGBf16ToRGf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGBf16ToRf32((float*)dst, (int16_t*)src, size); break;
}
break;
case fcPixelFormat_RGf16:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::RGf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBi16: ispc::RGf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGi16: ispc::RGf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ri16: ispc::RGf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGf16ToRGBAf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGf16ToRGBf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf16: return src;
case fcPixelFormat_Rf16: ispc::RGf16ToRf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGf16ToRGBAf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGf16ToRGBf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGf16ToRGf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGf16ToRf32((float*)dst, (int16_t*)src, size); break;
}
break;
case fcPixelFormat_Rf16:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::Rf16ToRGBAu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBu8: ispc::Rf16ToRGBu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGu8: ispc::Rf16ToRGu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ru8: ispc::Rf16ToRu8((uint8_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::Rf16ToRGBAi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBi16: ispc::Rf16ToRGBi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGi16: ispc::Rf16ToRGi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Ri16: ispc::Rf16ToRi16((uint16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::Rf16ToRGBAf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf16: ispc::Rf16ToRGBf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf16: ispc::Rf16ToRGf16((int16_t*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf16: return src;
case fcPixelFormat_RGBAf32: ispc::Rf16ToRGBAf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGBf32: ispc::Rf16ToRGBf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_RGf32: ispc::Rf16ToRGf32((float*)dst, (int16_t*)src, size); break;
case fcPixelFormat_Rf32: ispc::Rf16ToRf32((float*)dst, (int16_t*)src, size); break;
}
break;
case fcPixelFormat_RGBAf32:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGBAf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGBAf32ToRGBu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGBAf32ToRGu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGBAf32ToRu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::RGBAf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBi16: ispc::RGBAf32ToRGBi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGi16: ispc::RGBAf32ToRGi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ri16: ispc::RGBAf32ToRi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGBAf32ToRGBAf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGBAf32ToRGBf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGBAf32ToRGf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGBAf32ToRf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf32: return src;
case fcPixelFormat_RGBf32: ispc::RGBAf32ToRGBf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_RGf32: ispc::RGBAf32ToRGf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGBAf32ToRf32((float*)dst, (float*)src, size); break;
}
break;
case fcPixelFormat_RGBf32:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGBf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGBf32ToRGBu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGBf32ToRGu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGBf32ToRu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::RGBf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBi16: ispc::RGBf32ToRGBi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGi16: ispc::RGBf32ToRGi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ri16: ispc::RGBf32ToRi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGBf32ToRGBAf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGBf32ToRGBf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGBf32ToRGf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGBf32ToRf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGBf32ToRGBAf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf32: return src;
case fcPixelFormat_RGf32: ispc::RGBf32ToRGf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_Rf32: ispc::RGBf32ToRf32((float*)dst, (float*)src, size); break;
}
break;
case fcPixelFormat_RGf32:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::RGf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBu8: ispc::RGf32ToRGBu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGu8: ispc::RGf32ToRGu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ru8: ispc::RGf32ToRu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::RGf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBi16: ispc::RGf32ToRGBi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGi16: ispc::RGf32ToRGi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ri16: ispc::RGf32ToRi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::RGf32ToRGBAf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf16: ispc::RGf32ToRGBf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGf16: ispc::RGf32ToRGf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Rf16: ispc::RGf32ToRf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::RGf32ToRGBAf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf32: ispc::RGf32ToRGBf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_RGf32: return src;
case fcPixelFormat_Rf32: ispc::RGf32ToRf32((float*)dst, (float*)src, size); break;
}
break;
case fcPixelFormat_Rf32:
switch (dstfmt) {
case fcPixelFormat_RGBAu8: ispc::Rf32ToRGBAu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBu8: ispc::Rf32ToRGBu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGu8: ispc::Rf32ToRGu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ru8: ispc::Rf32ToRu8((uint8_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAi16: ispc::Rf32ToRGBAi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBi16: ispc::Rf32ToRGBi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGi16: ispc::Rf32ToRGi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Ri16: ispc::Rf32ToRi16((uint16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf16: ispc::Rf32ToRGBAf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf16: ispc::Rf32ToRGBf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGf16: ispc::Rf32ToRGf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_Rf16: ispc::Rf32ToRf16((int16_t*)dst, (float*)src, size); break;
case fcPixelFormat_RGBAf32: ispc::Rf32ToRGBAf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_RGBf32: ispc::Rf32ToRGBf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_RGf32: ispc::Rf32ToRGf32((float*)dst, (float*)src, size); break;
case fcPixelFormat_Rf32: return src;
}
break;
}
return dst;
}
fcAPI const void* fcConvertPixelFormat(void *dst, fcPixelFormat dstfmt, const void *src, fcPixelFormat srcfmt, size_t size)
{
return fcConvertPixelFormat_ISPC(dst, dstfmt, src, srcfmt, size);
}
void fcF32ToU8Samples(uint8_t *dst, const float *src, size_t size)
{
ispc::F32ToU8Samples(dst, src, (uint32_t)size);
}
void fcF32ToI16Samples(int16_t *dst, const float *src, size_t size)
{
ispc::F32ToI16Samples(dst, src, (uint32_t)size);
}
void fcF32ToI24Samples(uint8_t *dst, const float *src, size_t size)
{
ispc::F32ToI24Samples(dst, src, (uint32_t)size);
}
void fcF32ToI32Samples(int32_t *dst, const float *src, size_t size)
{
ispc::F32ToI32Samples(dst, src, (uint32_t)size);
}
void fcF32ToI32ScaleSamples(int32_t *dst, const float *src, size_t size, float scale)
{
ispc::F32ToI32ScaleSamples(dst, src, (uint32_t)size, scale);
}
#endif // fcEnableISPCKernel
| 62.874233 | 123 | 0.690784 | Okashiou |
aa5b53057aedea3d92c9887b302923faca18e753 | 25,676 | cpp | C++ | Editor/src/gdeditor.cpp | guilmont/GDManager | dedb0b6c5e1c55886def5360837cbce2485c0d78 | [
"Apache-2.0"
] | null | null | null | Editor/src/gdeditor.cpp | guilmont/GDManager | dedb0b6c5e1c55886def5360837cbce2485c0d78 | [
"Apache-2.0"
] | null | null | null | Editor/src/gdeditor.cpp | guilmont/GDManager | dedb0b6c5e1c55886def5360837cbce2485c0d78 | [
"Apache-2.0"
] | null | null | null | #include "gdeditor.h"
static std::string type2Label(GDM::Type type)
{
switch (type)
{
case GDM::Type::GROUP:
return "GROUP";
case GDM::Type::INT32:
return "INT32";
case GDM::Type::INT64:
return "INT64";
case GDM::Type::UINT8:
return "UINT8";
case GDM::Type::UINT16:
return "UINT16";
case GDM::Type::UINT32:
return "UINT32";
case GDM::Type::UINT64:
return "UINT64";
case GDM::Type::FLOAT:
return "FLOAT";
case GDM::Type::DOUBLE:
return "DOUBLE";
default:
GRender::pout("Type unkown");
assert(false);
return "";
}
}
static GDM::Type label2Type(const std::string &label)
{
if (label.compare("GROUP") == 0)
return GDM::Type::GROUP;
else if (label.compare("INT32") == 0)
return GDM::Type::INT32;
else if (label.compare("INT64") == 0)
return GDM::Type::INT64;
else if (label.compare("UINT8") == 0)
return GDM::Type::UINT8;
else if (label.compare("UINT16") == 0)
return GDM::Type::UINT16;
else if (label.compare("UINT32") == 0)
return GDM::Type::UINT32;
else if (label.compare("UINT64") == 0)
return GDM::Type::UINT64;
else if (label.compare("FLOAT") == 0)
return GDM::Type::FLOAT;
else if (label.compare("DOUBLE") == 0)
return GDM::Type::DOUBLE;
else
{
GRender::pout("Type unkown");
assert(false);
return GDM::Type::NONE;
}
}
static bool SliderU64(const char* label, uint64_t* val, uint64_t low, uint64_t high)
{
return ImGui::SliderScalar(label, ImGuiDataType_U64, val, &low, &high);
}
template <typename TP>
static void rewrite(const char *buf, uint64_t pos, uint8_t *ptr)
{
TP val = static_cast<TP>(std::stod(buf));
uint8_t *vv = reinterpret_cast<uint8_t *>(&val);
std::copy(vv, vv + sizeof(TP), ptr + pos * sizeof(TP));
}
template <typename TP>
static void lineFunction(GDM::Data* data, int selected, uint64_t id)
{
GDM::Shape sp = data->getShape();
const TP* ptr = data->getArray<TP>();
uint64_t N = selected == 0 ? sp.width : sp.height;
std::vector<TP> vecX(N), vecY(N);
for (uint64_t k = 0; k < N; k++)
{
vecX[k] = TP(k);
vecY[k] = selected == 0 ? ptr[id * sp.width + k] : ptr[k * sp.width + id];
}
ImPlot::PlotLine("function",vecX.data(), vecY.data(), int(N));
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
GDEditor::GDEditor(void)
{
fs::current_path(INSTALL_PATH);
GRender::pout("Welcome to my GDEditor!!");
initialize("GDEditor", 1200, 800, "assets/GDEditor/layout.ini");
}
GDEditor::~GDEditor(void) {}
void GDEditor::onUserUpdate(float deltaTime)
{
if (close_file.size() > 0)
{
vFile.erase(close_file);
close_file = "";
if (vFile.size() > 0)
currentFile = &(vFile.begin()->second);
else
currentFile = nullptr;
currentObj = nullptr;
addObj.view = false;
addObj.group = nullptr;
}
bool
ctrl = (keyboard[GKey::LEFT_CONTROL] == GEvent::PRESS) || (keyboard[GKey::RIGHT_CONTROL] == GEvent::PRESS),
shift = (keyboard[GKey::LEFT_SHIFT] == GEvent::PRESS) || (keyboard[GKey::RIGHT_SHIFT] == GEvent::PRESS),
I = keyboard['I'] == GEvent::PRESS,
P = keyboard['P'] == GEvent::PRESS,
N = keyboard['N'] == GEvent::PRESS,
O = keyboard['O'] == GEvent::PRESS,
S = keyboard['S'] == GEvent::PRESS;
if ((ctrl & shift) & I)
view_imguidemo = true;
if ((ctrl & shift) & P)
view_implotdemo = true;
if (ctrl & N)
dialog.createDialog(GDialog::SAVE, "New file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); });
if (ctrl & O)
dialog.createDialog(GDialog::OPEN, "Open file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); });
}
void GDEditor::ImGuiLayer(void)
{
if (view_imguidemo)
ImGui::ShowDemoWindow(&view_imguidemo);
if (view_implotdemo)
ImPlot::ShowDemoWindow(&view_implotdemo);
if (plotPointer)
(this->*plotWindow)();
if (addObj.view)
addObject(addObj.group);
if (currentFile)
{
treeViewWindow();
detailWindow();
}
}
void GDEditor::ImGuiMenuLayer(void)
{
if (ImGui::BeginMenu("File"))
{
if (ImGui::MenuItem("New file...", "Ctrl+N"))
dialog.createDialog(GDialog::SAVE, "New file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); });
if (ImGui::MenuItem("Open...", "Ctrl+O"))
dialog.createDialog(GDialog::OPEN, "Open file...", {"gdm", "gd"}, this, [](const fs::path &path, void *ptr) -> void { reinterpret_cast<GDEditor *>(ptr)->openFile(path); });
if (ImGui::MenuItem("Save"))
saveFile();
if (ImGui::MenuItem("Exit"))
closeApp();
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Tools"))
{
if (ImGui::MenuItem("Show mailbox"))
mailbox.setActive();
if (ImGui::MenuItem("Release memory"))
for (auto &[name, arq] : vFile)
releaseMemory(&arq);
ImGui::EndMenu();
} // file-menu
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
void GDEditor::recursiveTreeLoop(GDM::Group *group, ImGuiTreeNodeFlags nodeFlags)
{
std::string remove = "";
for (auto &[label, obj] : group->children())
{
ImGui::PushID(label.c_str());
if (obj->getType() == GDM::Type::GROUP)
{
ImGui::SetNextTreeNodeOpen(false, ImGuiCond_Once); // it will run the first time
bool openTree = ImGui::TreeNodeEx(label.c_str(), nodeFlags);
float fSize = ImGui::GetWindowContentRegionWidth() - 8.5f * ImGui::GetFontSize();
ImGui::SameLine(fSize);
if (ImGui::Button("Details", {3.5f * ImGui::GetFontSize(), 0}))
currentObj = obj;
ImGui::SameLine();
if (ImGui::Button("+", {2.0f * ImGui::GetFontSize(), 0}))
{
addObj.view = true;
addObj.group = reinterpret_cast<GDM::Group *>(obj);
}
ImGui::SameLine();
if (ImGui::Button("-", {2.0f * ImGui::GetFontSize(), 0}))
remove = label;
if (openTree)
{
recursiveTreeLoop(reinterpret_cast<GDM::Group *>(obj), nodeFlags);
ImGui::TreePop();
}
}
else
{
bool selected = false;
if (ImGui::Selectable(label.c_str(), &selected))
currentObj = obj;
}
ImGui::PopID();
} // loop-children
// Removing group if necessary
if (remove.size() > 0)
group->remove(remove);
}
void GDEditor::treeViewWindow(void)
{
const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos;
ImGui::SetNextWindowPos({workpos.x + 20, workpos.y + 40}, ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize({400, 700}, ImGuiCond_FirstUseEver);
ImGui::Begin("Tree view");
if (ImGui::BeginTabBar("MyTabBar"))
{
for (auto &[label, arq] : vFile)
{
const std::string &name = label.filename().string();
if (ImGui::BeginTabItem(name.c_str()))
{
currentFile = &arq;
ImGui::EndTabItem();
}
}
ImGui::EndTabBar();
}
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_None;
nodeFlags |= ImGuiTreeNodeFlags_DefaultOpen;
nodeFlags |= ImGuiTreeNodeFlags_Framed;
nodeFlags |= ImGuiTreeNodeFlags_FramePadding;
nodeFlags |= ImGuiTreeNodeFlags_SpanAvailWidth;
nodeFlags |= ImGuiTreeNodeFlags_AllowItemOverlap;
ImGui::PushID(currentFile->getLabel().c_str());
std::string name = currentFile->getFilePath().filename().string();
bool openTree = ImGui::TreeNodeEx(name.c_str(), nodeFlags);
float fSize = ImGui::GetWindowContentRegionWidth() - 10.0f * ImGui::GetFontSize();
ImGui::SameLine(fSize);
if (ImGui::Button("+", {2.0f * ImGui::GetFontSize(), 0}))
{
addObj.view = true;
addObj.group = currentFile;
}
ImGui::SameLine();
if (ImGui::Button("Details", {3.5f * ImGui::GetFontSize(), 0}))
currentObj = currentFile;
ImGui::SameLine();
if (ImGui::Button("Close", { 3.5f * ImGui::GetFontSize(), 0 }))
{
plotPointer = nullptr;
plotWindow = nullptr;
close_file = currentFile->getFilePath().string();
mailbox.createInfo("Closing file " + close_file);
}
if (openTree)
{
recursiveTreeLoop(reinterpret_cast<GDM::Group *>(currentFile), nodeFlags);
ImGui::TreePop();
}
ImGui::PopID();
ImGui::End();
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
void GDEditor::detailWindow(void)
{
const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos;
ImGui::SetNextWindowPos({workpos.x + 450, workpos.y + 40}, ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize({700, 700}, ImGuiCond_FirstUseEver);
ImGui::Begin("Details");
if (currentObj == nullptr)
{
ImGui::Text("No object selected");
ImGui::End();
return;
}
auto text = [&](const std::string &title, const std::string &txt) -> void
{
fonts.text(title.c_str(), "bold");
ImGui::SameLine();
ImGui::Text(txt.c_str());
};
fonts.text("Label:", "bold");
ImGui::SameLine();
static char locLabel[GDM::MAX_LABEL_SIZE] = {0x00};
sprintf(locLabel, "%s", currentObj->getLabel().c_str());
if (ImGui::InputText("##label", locLabel, GDM::MAX_LABEL_SIZE, ImGuiInputTextFlags_EnterReturnsTrue))
currentObj->rename(locLabel);
if (currentObj->parent)
{
std::string par = "";
GDM::Object *obj = currentObj;
while (obj->parent)
{
obj = obj->parent;
par = "/" + obj->getLabel() + par;
}
text("Path:", par.c_str());
}
text("Type:", type2Label(currentObj->getType()).c_str());
if (currentObj->getType() == GDM::Type::GROUP)
text("Number of children:", std::to_string(reinterpret_cast<GDM::Group *>(currentObj)->getNumChildren()));
else
{
GDM::Data *dt = reinterpret_cast<GDM::Data *>(currentObj);
GDM::Shape shape = dt->getShape();
text("Shape:", "{ " + std::to_string(shape.height) + ", " + std::to_string(shape.width) + " }");
}
ImGui::Spacing();
if (ImGui::Button("Delete"))
{
GDM::Group *ptr = currentObj->parent;
ptr->remove(currentObj->getLabel());
currentObj = ptr;
ImGui::End();
return;
}
ImGui::Spacing();
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
ImGui::Spacing();
//////////////////////////////////////////////////////////
// All types have descriptions
GDM::Description &description = currentObj->descriptions();
fonts.text("Description:", "bold");
ImGui::SameLine();
if (ImGui::Button("Add"))
{
description["---"] = "---";
}
if (description.size() > 0)
{
// Creatign table to display description
ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX | ImGuiTableFlags_Borders;
if (ImGui::BeginTable("descriptionTable", 3, flags, {0, std::min<float>(256, 1.5f * (description.size() + 1) * ImGui::GetFontSize())}))
{
// Header
ImGui::TableSetupColumn("Label");
ImGui::TableSetupColumn("Description");
ImGui::TableHeadersRow();
// Main body
std::string remove = "", add = "";
for (auto &[label, desc] : description)
{
ImGui::TableNextRow();
ImGui::PushID(label.c_str());
ImGui::TableSetColumnIndex(0);
static char loc1[GDM::MAX_LABEL_SIZE];
sprintf(loc1, "%s", label.c_str());
ImGui::SetNextItemWidth(10.0f * ImGui::GetFontSize());
if (ImGui::InputText("##label", loc1, GDM::MAX_LABEL_SIZE, ImGuiInputTextFlags_EnterReturnsTrue))
{
add = std::string(loc1);
remove = label;
}
ImGui::TableSetColumnIndex(1);
static char loc2[512] = {0x00};
sprintf(loc2, "%s", desc.c_str());
ImGui::SetNextItemWidth(ImGui::GetWindowWidth() - 18.0f * ImGui::GetFontSize());
if (ImGui::InputText("##desc", loc2, 512, ImGuiInputTextFlags_EnterReturnsTrue))
description[label] = std::string(loc2);
ImGui::TableSetColumnIndex(2);
if (ImGui::Button("Remove"))
remove = label;
ImGui::PopID();
}
// Removing description if necessary
if (add.size() > 0)
description[add] = description[remove];
if (remove.size() > 0)
description.erase(remove);
ImGui::EndTable();
}
}
if (currentObj->getType() == GDM::Type::GROUP)
{
ImGui::End();
return;
}
//////////////////////////////////////////////////////////
// We have a data type, so we should display its values if demanded
ImGui::Spacing();
ImGui::Spacing();
ImGui::Separator();
ImGui::Spacing();
ImGui::Spacing();
GDM::Data *dt = reinterpret_cast<GDM::Data *>(currentObj);
fonts.text("Value:", "bold");
if (dt->getSizeBytes() > sizeof(uint64_t))
{
ImGui::SameLine();
if (ImGui::Button(dt->isLoaded() ? "Hide" : "View"))
{
if (dt->isLoaded())
dt->release();
else
dt->load(); // this will load data
}
}
if (dt->isLoaded())
{
if (dt->getSizeBytes() > sizeof(uint64_t))
{
ImGui::SameLine();
if (ImGui::Button("Heatmap"))
{
plotPointer = dt;
plotWindow = &GDEditor::plotHeatmap;
}
ImGui::SameLine();
if (ImGui::Button("Line plot"))
{
plotPointer = dt;
plotWindow = &GDEditor::plotLines;
}
}
}
else
{
ImGui::End();
return;
}
GDM::Shape shape = dt->getShape();
GDM::Type type = dt->getType();
uint8_t *ptr = dt->getRawBuffer(); // This is the raw buffer pointer
uint64_t maxRows = std::min<uint64_t>(32, shape.height);
uint64_t maxCols = std::min<uint64_t>(32, shape.width);
static uint64_t rowZero = 0, rowTop = maxRows;
static uint64_t colZero = 0, colTop = maxCols;
if (maxRows < shape.height)
{
int64_t val = static_cast<int64_t>(rowZero);
SliderU64("Rows", &rowZero, 0, shape.height - 32);
rowZero = std::min(rowZero, shape.height);
rowTop = std::min(rowZero + 32, shape.height);
}
else
{
rowZero = 0;
rowTop = maxRows;
}
if (maxCols < shape.width)
{
SliderU64("Cols", &colZero, 0, shape.width - 32);
colZero = std::min(colZero, shape.width);
colTop = std::min(colZero + 32, shape.width);
}
else
{
colZero = 0;
colTop = maxCols;
}
ImGuiTableFlags flags = ImGuiTableFlags_RowBg | ImGuiTableFlags_ScrollY | ImGuiTableFlags_ScrollX | ImGuiTableFlags_Borders | ImGuiTableFlags_NoHostExtendX | ImGuiTableFlags_NoHostExtendY;
if (ImGui::BeginTable("dataTable", int(maxCols + 1), flags))
{
ImGui::TableNextRow();
for (uint64_t column = 1; column <= maxCols; column++)
{
ImGui::TableSetColumnIndex(int(column));
fonts.text(std::to_string(colZero + column - 1).c_str(), "bold");
}
// Main body
for (uint64_t row = rowZero; row < rowTop; row++)
{
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
fonts.text(std::to_string(row).c_str(), "bold");
for (uint64_t column = colZero; column < colTop; column++)
{
uint64_t ct = row * shape.width + column;
ImGui::TableSetColumnIndex(int(column + 1 - colZero));
char buf[64] = {0x00};
switch (type)
{
case GDM::Type::INT32:
sprintf(buf, "%d", reinterpret_cast<int32_t *>(ptr)[ct]);
break;
case GDM::Type::INT64:
sprintf(buf, "%jd", reinterpret_cast<int64_t *>(ptr)[ct]);
break;
case GDM::Type::UINT8:
sprintf(buf, "%u", reinterpret_cast<uint8_t *>(ptr)[ct]);
break;
case GDM::Type::UINT16:
sprintf(buf, "%u", reinterpret_cast<uint16_t *>(ptr)[ct]);
break;
case GDM::Type::UINT32:
sprintf(buf, "%u", reinterpret_cast<uint32_t *>(ptr)[ct]);
break;
case GDM::Type::UINT64:
sprintf(buf, "%ju", reinterpret_cast<uint64_t *>(ptr)[ct]);
break;
case GDM::Type::FLOAT:
sprintf(buf, "%.6f", reinterpret_cast<float *>(ptr)[ct]);
break;
case GDM::Type::DOUBLE:
sprintf(buf, "%.6lf", reinterpret_cast<double *>(ptr)[ct]);
break;
}
ImGui::PushID(std::to_string(row * shape.width + column).c_str());
ImGui::SetNextItemWidth(5.0f * ImGui::GetFontSize());
if (ImGui::InputText("##decimal", buf, 64, ImGuiInputTextFlags_CharsDecimal | ImGuiInputTextFlags_EnterReturnsTrue))
{
switch (type)
{
case GDM::Type::INT32:
rewrite<int32_t>(buf, ct, ptr);
break;
case GDM::Type::INT64:
rewrite<int64_t>(buf, ct, ptr);
break;
case GDM::Type::UINT8:
rewrite<uint8_t>(buf, ct, ptr);
break;
case GDM::Type::UINT16:
rewrite<uint16_t>(buf, ct, ptr);
break;
case GDM::Type::UINT32:
rewrite<uint32_t>(buf, ct, ptr);
break;
case GDM::Type::UINT64:
rewrite<uint64_t>(buf, ct, ptr);
break;
case GDM::Type::FLOAT:
rewrite<float>(buf, ct, ptr);
break;
case GDM::Type::DOUBLE:
rewrite<double>(buf, ct, ptr);
break;
}
}
ImGui::PopID();
// Seeking next element in array
ct++;
}
}
ImGui::EndTable();
}
ImGui::End();
}
void GDEditor::plotHeatmap(void)
{
const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos;
ImGui::SetNextWindowPos({ workpos.x + 40, workpos.y + 40}, ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize({ 700, 700 }, ImGuiCond_FirstUseEver);
bool is_open = true; // So we can close this window from this function
ImGui::Begin("Plots", &is_open);
static float scale_min = 0;
static float scale_max = 1.0f;
static ImPlotColormap map = ImPlotColormap_Viridis;
if (ImPlot::ColormapButton(ImPlot::GetColormapName(map), ImVec2(225, 0), map)) {
map = (map + 1) % ImPlot::GetColormapCount();
ImPlot::BustColorCache("##Heatmap1");
}
ImGui::SameLine();
ImGui::LabelText("##Colormap Index", "%s", "Change Colormap");
ImGui::SetNextItemWidth(225);
ImGui::DragFloatRange2("Min / Max", &scale_min, &scale_max, 0.01f, -20, 20);
GDM::Shape sp = plotPointer->getShape();
const uint8_t* ptr = plotPointer->getRawBuffer();
float ratio = float(sp.height) / float(sp.width);
float width = 0.8f * ImGui::GetContentRegionAvailWidth(),
height = width * ratio;
ImPlot::PushColormap(map);
if (ImPlot::BeginPlot("##Heatmap1", NULL, NULL, {width, height }, ImPlotFlags_NoLegend))
{
int
width = static_cast<int>(sp.width),
height = static_cast<int>(sp.height);
switch (plotPointer->getType())
{
case GDM::Type::INT32:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImS32*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::INT64:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImS64*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::UINT8:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU8*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::UINT16:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU16*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::UINT32:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU32*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::UINT64:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const ImU64*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::FLOAT:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const float*>(ptr), height, width, scale_min, scale_max, NULL);
break;
case GDM::Type::DOUBLE:
ImPlot::PlotHeatmap("heat", reinterpret_cast<const double*>(ptr), height, width, scale_min, scale_max, NULL);
break;
default:
throw "Type not recognized!!";
break;
}
ImPlot::EndPlot();
}
ImGui::SameLine();
ImPlot::ColormapScale("##HeatScale", scale_min, scale_max, { 0.15f * width, height });
ImGui::End();
if (!is_open)
plotPointer = nullptr;
}
void GDEditor::plotLines(void)
{
const ImVec2 workpos = ImGui::GetMainViewport()->WorkPos;
ImGui::SetNextWindowPos({ workpos.x + 40, workpos.y + 40 }, ImGuiCond_FirstUseEver);
ImGui::SetNextWindowSize({ 700, 700 }, ImGuiCond_FirstUseEver);
GDM::Shape sp = plotPointer->getShape();
bool is_open = true; // So we can close this window from this function
ImGui::Begin("Plots", &is_open);
static int selected = 0;
ImGui::RadioButton("Rows", &selected, 0); ImGui::SameLine();
ImGui::RadioButton("Columns", &selected, 1);
static int id = 0;
ImGui::DragInt("ID", &id, 1.0f, 0, selected == 0 ? int(sp.height)-1 : int(sp.width)-1);
const char* labx = "Index";
char laby[64] = { 0 };
sprintf(laby, "%s %d", (selected == 0 ? "Row" : "Column"), id);
float
width = 0.95f * ImGui::GetContentRegionAvailWidth(),
height = 0.7f * width;
if (ImPlot::BeginPlot(plotPointer->getLabel().c_str(), labx, laby, { width, height }, ImPlotFlags_NoLegend)) {
ImPlot::SetNextMarkerStyle(ImPlotMarker_Circle);
switch (plotPointer->getType())
{
case GDM::Type::INT32:
lineFunction<ImS32>(plotPointer, selected, id);
break;
case GDM::Type::INT64:
lineFunction<ImS64>(plotPointer, selected, id);
break;
case GDM::Type::UINT8:
lineFunction<ImU8>(plotPointer, selected, id);
break;
case GDM::Type::UINT16:
lineFunction<ImU16>(plotPointer, selected, id);
break;
case GDM::Type::UINT32:
lineFunction<ImU32>(plotPointer, selected, id);
break;
case GDM::Type::UINT64:
lineFunction<ImU64>(plotPointer, selected, id);
break;
case GDM::Type::FLOAT:
lineFunction<float>(plotPointer, selected, id);
break;
case GDM::Type::DOUBLE:
lineFunction<double>(plotPointer, selected, id);
break;
default:
throw "Type not recognized!!";
break;
}
ImPlot::EndPlot();
}
ImGui::PopID();
ImGui::End();
if (!is_open)
plotPointer = nullptr;
}
void GDEditor::addObject(GDM::Group *group)
{
ImGui::Begin("Add object", &addObj.view);
fonts.text("Label:", "bold");
ImGui::SameLine();
bool check = false;
static char buf[GDM::MAX_LABEL_SIZE] = {0x00};
if (ImGui::InputText("##addLabel", buf, GDM::MAX_LABEL_SIZE, ImGuiInputTextFlags_EnterReturnsTrue))
check = true;
const char *items[] = {"GROUP", "INT32", "INT64", "UINT8", "UINT16", "UINT32", "UINT64", "FLOAT", "DOUBLE"};
static int item_current_idx = 0; // Here we store our selection data as an index.
const char *combo_label = items[item_current_idx]; // Label to preview before opening the combo (technically it could be anything)
fonts.text("Type:", "bold");
ImGui::SameLine();
if (ImGui::BeginCombo("##type", combo_label))
{
for (int n = 0; n < IM_ARRAYSIZE(items); n++)
{
const bool is_selected = (item_current_idx == n);
if (ImGui::Selectable(items[n], is_selected))
item_current_idx = n;
// Set the initial focus when opening the combo (scrolling + keyboard navigation focus)
if (is_selected)
ImGui::SetItemDefaultFocus();
}
ImGui::EndCombo();
}
GDM::Type type = label2Type(items[item_current_idx]);
static int32_t dim[2] = {1, 1};
if (type != GDM::Type::GROUP)
{
// Determinining
fonts.text("Shape:", "bold");
ImGui::SameLine();
ImGui::DragInt2("##shape", dim, 0.1f, 1);
}
if (ImGui::Button("Add") || check)
{
if (type == GDM::Type::GROUP)
addObj.group->addGroup(buf); // TODO: Check if label already exists
else
{
GDM::Shape shape = {static_cast<uint32_t>(dim[0]), static_cast<uint32_t>(dim[1])};
switch (type)
{
case GDM::Type::INT32:
addObj.group->add<int32_t>(buf, nullptr, shape);
break;
case GDM::Type::INT64:
addObj.group->add<int64_t>(buf, nullptr, shape);
break;
case GDM::Type::UINT8:
addObj.group->add<uint8_t>(buf, nullptr, shape);
break;
case GDM::Type::UINT16:
addObj.group->add<uint16_t>(buf, nullptr, shape);
break;
case GDM::Type::UINT32:
addObj.group->add<uint32_t>(buf, nullptr, shape);
break;
case GDM::Type::UINT64:
addObj.group->add<uint64_t>(buf, nullptr, shape);
break;
case GDM::Type::FLOAT:
addObj.group->add<float>(buf, nullptr, shape);
break;
case GDM::Type::DOUBLE:
addObj.group->add<double>(buf, nullptr, shape);
break;
}
}
addObj.view = false;
}
ImGui::SameLine();
if (ImGui::Button("Cancel"))
addObj.view = false;
ImGui::End();
}
void GDEditor::releaseMemory(GDM::Group* group)
{
for (auto& [label, obj] : group->children())
{
if (obj->getType() == GDM::Type::GROUP)
{
releaseMemory(reinterpret_cast<GDM::Group*>(obj));
}
else
{
GDM::Data* ptr = reinterpret_cast<GDM::Data*>(obj);
if (ptr->isLoaded())
ptr->release();
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
void GDEditor::openFile(const fs::path &inPath)
{
if (vFile.find(inPath) != vFile.end())
mailbox.createWarn("File already openned!!");
else
{
mailbox.createInfo("Openning file: " + inPath.string());
vFile.emplace(inPath, inPath);
currentFile = &vFile[inPath];
}
}
void GDEditor::saveFile(void)
{
if (currentFile)
{
mailbox.createInfo("Saving file to " + currentFile->getFilePath().string());
currentFile->save();
}
}
| 26.226762 | 190 | 0.601418 | guilmont |
aa5cb80d29873cd202b9e6d1c585e14ab78e793f | 2,666 | cpp | C++ | tests/lsscript_sequencing.cpp | hamsham/LightScript | 22af688178067ebdb6f053e3916307ed799b3fb9 | [
"BSD-3-Clause"
] | 1 | 2015-11-07T03:59:57.000Z | 2015-11-07T03:59:57.000Z | tests/lsscript_sequencing.cpp | hamsham/LightScript | 22af688178067ebdb6f053e3916307ed799b3fb9 | [
"BSD-3-Clause"
] | null | null | null | tests/lsscript_sequencing.cpp | hamsham/LightScript | 22af688178067ebdb6f053e3916307ed799b3fb9 | [
"BSD-3-Clause"
] | 1 | 2015-10-16T06:07:54.000Z | 2015-10-16T06:07:54.000Z | /*
* File: sequence_test.cpp
* Author: hammy
*
* Created on Feb 26, 2015, 12:38:57 AM
*/
#include <cassert>
#include <iostream>
#include "lightsky/script/Script.h"
template <class data_t> using lsPointer = ls::script::Pointer_t<data_t>;
using lsVariable = ls::script::Variable;
using ls::script::create_variable;
using ls::script::destroy_variable;
using lsFunctor = ls::script::Functor;
using ls::script::create_functor;
using ls::script::destroy_functor;
using ls::script::ScriptRunner;
int main()
{
lsPointer<lsFunctor> testFunc1 = create_functor(ScriptHash_AddInts);
lsPointer<lsFunctor> testFunc2 = create_functor(ScriptHash_SubInts);
lsPointer<lsFunctor> testFunc3 = create_functor(ScriptHash_MulInts);
lsPointer<lsFunctor> testFunc4 = create_functor(ScriptHash_DivInts);
lsPointer<lsVariable> testVar1 = create_variable(ScriptHash_int);
lsPointer<lsVariable> testVar2 = create_variable(ScriptHash_int);
lsPointer<lsVariable> testVar3 = create_variable(ScriptHash_int);
lsPointer<lsVariable> testVar5 = create_variable(ScriptHash_string);
if (!testVar5)
{
std::cout << "Unable to create a string variable." << std::endl;
}
LS_SCRIPT_VAR_DATA(testVar1, int) = 1;
LS_SCRIPT_VAR_DATA(testVar2, int) = 2;
LS_SCRIPT_VAR_DATA(testVar3, int) = 0; // dummy value
testFunc1->arg(0, testVar1.get()); // param 1 = 1
testFunc1->arg(1, testVar2.get()); // param 2 = 2
testFunc1->arg(2, testVar3.get()); // return value should equal 1+2=3
testFunc1->next_func_ptr(testFunc2.get());
testFunc2->arg(0, testVar1.get());
testFunc2->arg(1, testVar2.get());
testFunc2->arg(2, testVar2.get()); // should equal 1-2=-3
testFunc2->next_func_ptr(testFunc3.get());
testFunc3->arg(0, testVar1.get());
testFunc3->arg(1, testVar2.get());
testFunc3->arg(2, testVar2.get()); // should equal 1*2=2
testFunc3->next_func_ptr(testFunc4.get());
testFunc4->arg(0, testVar1.get());
testFunc4->arg(1, testVar2.get());
testFunc4->arg(2, testVar2.get()); // should equal 1/2=1 (int division)
testFunc4->next_func_ptr(nullptr);
ScriptRunner runner {};
runner.run(testFunc1.get());
assert(LS_SCRIPT_VAR_DATA(testVar3, int) == 1 / 2);
std::cout << "Successfully ran the script tests." << std::endl;
std::cout << "The final variable values are:" << std::endl;
std::cout << "\tVariable 1: " << LS_SCRIPT_VAR_DATA(testVar1, int) << std::endl;
std::cout << "\tVariable 2: " << LS_SCRIPT_VAR_DATA(testVar2, int) << std::endl;
std::cout << "\tVariable 3: " << LS_SCRIPT_VAR_DATA(testVar3, int) << std::endl;
return 0;
}
| 33.325 | 84 | 0.684546 | hamsham |
aa5d110c209eafb80b53e1df4929bed17b2a523b | 114 | hpp | C++ | test/old_tests/Composable/precomp.hpp | sylveon/cppwinrt | 4d5c5ae3de386ce1f18c3410a27b9ceb40aa524d | [
"MIT"
] | 859 | 2016-10-13T00:11:52.000Z | 2019-05-06T15:45:46.000Z | test/old_tests/Composable/precomp.hpp | shinsetsu/cppwinrt | ae0378373d2318d91448b8697a91d5b65a1fb2e5 | [
"MIT"
] | 655 | 2019-10-08T12:15:16.000Z | 2022-03-31T18:26:40.000Z | test/old_tests/Composable/precomp.hpp | shinsetsu/cppwinrt | ae0378373d2318d91448b8697a91d5b65a1fb2e5 | [
"MIT"
] | 137 | 2016-10-13T04:19:59.000Z | 2018-11-09T05:08:03.000Z | #pragma once
#pragma warning(disable:4100)
#include "winrt/Windows.Foundation.h"
#include "winrt/Composable.h"
| 16.285714 | 37 | 0.763158 | sylveon |
aa5f519a08763d889fcdd4f1d6cf16cee2c97647 | 888 | cpp | C++ | src/core/RenderBuffer.cpp | Ubpa/UGL | 4db5b8a090ffa1018e52e77209b8723289798531 | [
"MIT"
] | null | null | null | src/core/RenderBuffer.cpp | Ubpa/UGL | 4db5b8a090ffa1018e52e77209b8723289798531 | [
"MIT"
] | null | null | null | src/core/RenderBuffer.cpp | Ubpa/UGL | 4db5b8a090ffa1018e52e77209b8723289798531 | [
"MIT"
] | null | null | null | #include <UGL/RenderBuffer.h>
#include <UGL/Texture2D.h>
using namespace Ubpa;
using namespace Ubpa::gl;
using namespace std;
RenderBuffer::RenderBuffer() {
gl::GenRenderbuffers(1, id.init_ptr());
}
RenderBuffer::~RenderBuffer() {
Clear();
}
RenderBuffer::RenderBuffer(RenderBuffer&& fb) noexcept
: Obj{ move(fb.id) } {}
RenderBuffer& RenderBuffer::operator=(RenderBuffer&& fb) noexcept {
Clear();
id = move(fb.id);
return *this;
}
void RenderBuffer::Clear() {
if (IsValid()) {
gl::DeleteRenderbuffers(1, id.del_ptr());
id.Clear();
}
}
void RenderBuffer::Bind() const {
gl::BindRenderbuffer(id);
}
void RenderBuffer::BindReset() {
gl::BindRenderbuffer(static_cast<GLuint>(0));
}
void RenderBuffer::SetStorage(FramebufferInternalFormat internalformat, size_t width, size_t height) {
Bind();
gl::RenderbufferStorage(internalformat, width, height);
BindReset();
}
| 19.304348 | 102 | 0.717342 | Ubpa |
aa5f82437444424d60c4241dcd3ef5e04ff08539 | 9,565 | cc | C++ | passes/opt/muxpack.cc | jfng/yosys | 2116c585810cddb73777b46ea9aad0d6d511d82b | [
"ISC"
] | 33 | 2018-10-09T16:17:53.000Z | 2022-01-18T11:32:31.000Z | passes/opt/muxpack.cc | jfng/yosys | 2116c585810cddb73777b46ea9aad0d6d511d82b | [
"ISC"
] | 55 | 2018-11-19T21:59:12.000Z | 2021-12-17T11:02:51.000Z | passes/opt/muxpack.cc | jfng/yosys | 2116c585810cddb73777b46ea9aad0d6d511d82b | [
"ISC"
] | 10 | 2019-03-15T17:28:55.000Z | 2021-08-02T16:41:10.000Z | /*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <clifford@clifford.at>
* 2019 Eddie Hung <eddie@fpgeh.com>
*
* 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 "kernel/yosys.h"
#include "kernel/sigtools.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct ExclusiveDatabase
{
Module *module;
const SigMap &sigmap;
dict<SigBit, std::pair<SigSpec,std::vector<Const>>> sig_cmp_prev;
ExclusiveDatabase(Module *module, const SigMap &sigmap) : module(module), sigmap(sigmap)
{
SigSpec const_sig, nonconst_sig;
SigBit y_port;
pool<Cell*> reduce_or;
for (auto cell : module->cells()) {
if (cell->type == ID($eq)) {
nonconst_sig = sigmap(cell->getPort(ID::A));
const_sig = sigmap(cell->getPort(ID::B));
if (!const_sig.is_fully_const()) {
if (!nonconst_sig.is_fully_const())
continue;
std::swap(nonconst_sig, const_sig);
}
y_port = sigmap(cell->getPort(ID::Y));
}
else if (cell->type == ID($logic_not)) {
nonconst_sig = sigmap(cell->getPort(ID::A));
const_sig = Const(State::S0, GetSize(nonconst_sig));
y_port = sigmap(cell->getPort(ID::Y));
}
else if (cell->type == ID($reduce_or)) {
reduce_or.insert(cell);
continue;
}
else continue;
log_assert(!nonconst_sig.empty());
log_assert(!const_sig.empty());
sig_cmp_prev[y_port] = std::make_pair(nonconst_sig,std::vector<Const>{const_sig.as_const()});
}
for (auto cell : reduce_or) {
nonconst_sig = SigSpec();
std::vector<Const> values;
SigSpec a_port = sigmap(cell->getPort(ID::A));
for (auto bit : a_port) {
auto it = sig_cmp_prev.find(bit);
if (it == sig_cmp_prev.end()) {
nonconst_sig = SigSpec();
break;
}
if (nonconst_sig.empty())
nonconst_sig = it->second.first;
else if (nonconst_sig != it->second.first) {
nonconst_sig = SigSpec();
break;
}
for (auto value : it->second.second)
values.push_back(value);
}
if (nonconst_sig.empty())
continue;
y_port = sigmap(cell->getPort(ID::Y));
sig_cmp_prev[y_port] = std::make_pair(nonconst_sig,std::move(values));
}
}
bool query(const SigSpec &sig) const
{
SigSpec nonconst_sig;
pool<Const> const_values;
for (auto bit : sig.bits()) {
auto it = sig_cmp_prev.find(bit);
if (it == sig_cmp_prev.end())
return false;
if (nonconst_sig.empty())
nonconst_sig = it->second.first;
else if (nonconst_sig != it->second.first)
return false;
for (auto value : it->second.second)
if (!const_values.insert(value).second)
return false;
}
return true;
}
};
struct MuxpackWorker
{
Module *module;
SigMap sigmap;
int mux_count, pmux_count;
pool<Cell*> remove_cells;
dict<SigSpec, Cell*> sig_chain_next;
dict<SigSpec, Cell*> sig_chain_prev;
pool<SigBit> sigbit_with_non_chain_users;
pool<Cell*> chain_start_cells;
pool<Cell*> candidate_cells;
ExclusiveDatabase excl_db;
void make_sig_chain_next_prev()
{
for (auto wire : module->wires())
{
if (wire->port_output || wire->get_bool_attribute(ID::keep)) {
for (auto bit : sigmap(wire))
sigbit_with_non_chain_users.insert(bit);
}
}
for (auto cell : module->cells())
{
if (cell->type.in(ID($mux), ID($pmux)) && !cell->get_bool_attribute(ID::keep))
{
SigSpec a_sig = sigmap(cell->getPort(ID::A));
SigSpec b_sig;
if (cell->type == ID($mux))
b_sig = sigmap(cell->getPort(ID::B));
SigSpec y_sig = sigmap(cell->getPort(ID::Y));
if (sig_chain_next.count(a_sig))
for (auto a_bit : a_sig.bits())
sigbit_with_non_chain_users.insert(a_bit);
else {
sig_chain_next[a_sig] = cell;
candidate_cells.insert(cell);
}
if (!b_sig.empty()) {
if (sig_chain_next.count(b_sig))
for (auto b_bit : b_sig.bits())
sigbit_with_non_chain_users.insert(b_bit);
else {
sig_chain_next[b_sig] = cell;
candidate_cells.insert(cell);
}
}
sig_chain_prev[y_sig] = cell;
continue;
}
for (auto conn : cell->connections())
if (cell->input(conn.first))
for (auto bit : sigmap(conn.second))
sigbit_with_non_chain_users.insert(bit);
}
}
void find_chain_start_cells()
{
for (auto cell : candidate_cells)
{
log_debug("Considering %s (%s)\n", log_id(cell), log_id(cell->type));
SigSpec a_sig = sigmap(cell->getPort(ID::A));
if (cell->type == ID($mux)) {
SigSpec b_sig = sigmap(cell->getPort(ID::B));
if (sig_chain_prev.count(a_sig) + sig_chain_prev.count(b_sig) != 1)
goto start_cell;
if (!sig_chain_prev.count(a_sig))
a_sig = b_sig;
}
else if (cell->type == ID($pmux)) {
if (!sig_chain_prev.count(a_sig))
goto start_cell;
}
else log_abort();
for (auto bit : a_sig.bits())
if (sigbit_with_non_chain_users.count(bit))
goto start_cell;
{
Cell *prev_cell = sig_chain_prev.at(a_sig);
log_assert(prev_cell);
SigSpec s_sig = sigmap(cell->getPort(ID::S));
s_sig.append(sigmap(prev_cell->getPort(ID::S)));
if (!excl_db.query(s_sig))
goto start_cell;
}
continue;
start_cell:
chain_start_cells.insert(cell);
}
}
vector<Cell*> create_chain(Cell *start_cell)
{
vector<Cell*> chain;
Cell *c = start_cell;
while (c != nullptr)
{
chain.push_back(c);
SigSpec y_sig = sigmap(c->getPort(ID::Y));
if (sig_chain_next.count(y_sig) == 0)
break;
c = sig_chain_next.at(y_sig);
if (chain_start_cells.count(c) != 0)
break;
}
return chain;
}
void process_chain(vector<Cell*> &chain)
{
if (GetSize(chain) < 2)
return;
int cursor = 0;
while (cursor < GetSize(chain))
{
int cases = GetSize(chain) - cursor;
Cell *first_cell = chain[cursor];
dict<int, SigBit> taps_dict;
if (cases < 2) {
cursor++;
continue;
}
Cell *last_cell = chain[cursor+cases-1];
log("Converting %s.%s ... %s.%s to a pmux with %d cases.\n",
log_id(module), log_id(first_cell), log_id(module), log_id(last_cell), cases);
mux_count += cases;
pmux_count += 1;
first_cell->type = ID($pmux);
SigSpec b_sig = first_cell->getPort(ID::B);
SigSpec s_sig = first_cell->getPort(ID::S);
for (int i = 1; i < cases; i++) {
Cell* prev_cell = chain[cursor+i-1];
Cell* cursor_cell = chain[cursor+i];
if (sigmap(prev_cell->getPort(ID::Y)) == sigmap(cursor_cell->getPort(ID::A))) {
b_sig.append(cursor_cell->getPort(ID::B));
s_sig.append(cursor_cell->getPort(ID::S));
}
else {
log_assert(cursor_cell->type == ID($mux));
b_sig.append(cursor_cell->getPort(ID::A));
s_sig.append(module->LogicNot(NEW_ID, cursor_cell->getPort(ID::S)));
}
remove_cells.insert(cursor_cell);
}
first_cell->setPort(ID::B, b_sig);
first_cell->setPort(ID::S, s_sig);
first_cell->setParam(ID::S_WIDTH, GetSize(s_sig));
first_cell->setPort(ID::Y, last_cell->getPort(ID::Y));
cursor += cases;
}
}
void cleanup()
{
for (auto cell : remove_cells)
module->remove(cell);
remove_cells.clear();
sig_chain_next.clear();
sig_chain_prev.clear();
chain_start_cells.clear();
candidate_cells.clear();
}
MuxpackWorker(Module *module) :
module(module), sigmap(module), mux_count(0), pmux_count(0), excl_db(module, sigmap)
{
make_sig_chain_next_prev();
find_chain_start_cells();
for (auto c : chain_start_cells) {
vector<Cell*> chain = create_chain(c);
process_chain(chain);
}
cleanup();
}
};
struct MuxpackPass : public Pass {
MuxpackPass() : Pass("muxpack", "$mux/$pmux cascades to $pmux") { }
void help() override
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" muxpack [selection]\n");
log("\n");
log("This pass converts cascaded chains of $pmux cells (e.g. those create from case\n");
log("constructs) and $mux cells (e.g. those created by if-else constructs) into\n");
log("$pmux cells.\n");
log("\n");
log("This optimisation is conservative --- it will only pack $mux or $pmux cells\n");
log("whose select lines are driven by '$eq' cells with other such cells if it can be\n");
log("certain that their select inputs are mutually exclusive.\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) override
{
log_header(design, "Executing MUXPACK pass ($mux cell cascades to $pmux).\n");
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
break;
}
extra_args(args, argidx, design);
int mux_count = 0;
int pmux_count = 0;
for (auto module : design->selected_modules()) {
MuxpackWorker worker(module);
mux_count += worker.mux_count;
pmux_count += worker.pmux_count;
}
log("Converted %d (p)mux cells into %d pmux cells.\n", mux_count, pmux_count);
}
} MuxpackPass;
PRIVATE_NAMESPACE_END
| 25.921409 | 96 | 0.648824 | jfng |
aa6384a49df1d137e7cfc1c1b7f7957242c33d9a | 935 | cpp | C++ | test/utilities/template.bitset/bitset.members/any.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 1,244 | 2015-01-02T21:08:56.000Z | 2022-03-22T21:34:16.000Z | test/utilities/template.bitset/bitset.members/any.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 125 | 2015-01-22T01:08:00.000Z | 2020-05-25T08:28:17.000Z | test/utilities/template.bitset/bitset.members/any.pass.cpp | caiohamamura/libcxx | 27c836ff3a9c505deb9fd1616012924de8ff9279 | [
"MIT"
] | 124 | 2015-01-12T15:06:17.000Z | 2022-03-26T07:48:53.000Z | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test bool any() const;
#include <bitset>
#include <cassert>
template <std::size_t N>
void test_any()
{
std::bitset<N> v;
v.reset();
assert(v.any() == false);
v.set();
assert(v.any() == (N != 0));
if (N > 1)
{
v[N/2] = false;
assert(v.any() == true);
v.reset();
v[N/2] = true;
assert(v.any() == true);
}
}
int main()
{
test_any<0>();
test_any<1>();
test_any<31>();
test_any<32>();
test_any<33>();
test_any<63>();
test_any<64>();
test_any<65>();
test_any<1000>();
}
| 20.777778 | 80 | 0.427807 | caiohamamura |
aa65398a61e1b17699300f3639089ecf03236630 | 779 | cpp | C++ | src/debug_gui/types/camera3d.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/debug_gui/types/camera3d.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/debug_gui/types/camera3d.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | #include "../../camera3d.hpp"
#include "../entry_field.hpp"
namespace rev {
const char* Camera3D::getDebugName() const noexcept {
return "Camera3D";
}
bool Camera3D::property(const bool edit) {
auto f = debug::EntryField("Camera3D", edit);
ImGui::Columns(1);
if(f.entry("pose", _rflag.ref<Pose>()))
refPose();
ImGui::Columns(2);
if(f.entry("Fov", _rflag.ref<Fov>()))
refFov();
if(f.entry("Aspect", _rflag.ref<Aspect>()))
refAspect();
if(f.entry("NearZ", _rflag.ref<NearZ>()))
refNearZ();
if(f.entry("FarZ", _rflag.ref<FarZ>()))
refFarZ();
f.show("Accum", uint64_t(getAccum()));
auto& rot = getPose().getRotation();
f.show("Right", rot.getRight());
f.show("Up", rot.getUp());
f.show("Dir", rot.getDir());
return f.modified();
}
}
| 25.966667 | 54 | 0.620026 | degarashi |
aa668b5cb37ed7dd43b860069a05572ef7871a8c | 1,026 | cpp | C++ | src/materials/PortalScatterer_t.cpp | guillaumetousignant/another_path_tracer | 2738b32f91443ce15d1e7ab8ab77903bdfca695b | [
"MIT"
] | 1 | 2019-08-08T12:19:45.000Z | 2019-08-08T12:19:45.000Z | src/materials/PortalScatterer_t.cpp | guillaumetousignant/another_path_tracer | 2738b32f91443ce15d1e7ab8ab77903bdfca695b | [
"MIT"
] | 38 | 2019-07-11T16:18:00.000Z | 2021-09-16T14:54:36.000Z | src/materials/PortalScatterer_t.cpp | guillaumetousignant/another_path_tracer | 2738b32f91443ce15d1e7ab8ab77903bdfca695b | [
"MIT"
] | null | null | null | #include "materials/PortalScatterer_t.h"
#include "entities/TransformMatrix_t.h"
#include "entities/RandomGenerator_t.h"
APTracer::Materials::PortalScatterer_t::PortalScatterer_t(APTracer::Entities::TransformMatrix_t* transformation, std::list<APTracer::Entities::Medium_t*> medium_list, double scattering_distance, double ind, unsigned int priority)
: Medium_t(ind, priority), transformation_(transformation), medium_list_(std::move(medium_list)), scattering_coefficient_(1/scattering_distance), unif_(0.0, 1.0) {}
auto APTracer::Materials::PortalScatterer_t::scatter(APTracer::Entities::Ray_t &ray) -> bool {
const double distance = -std::log(unif_(APTracer::Entities::rng()))/scattering_coefficient_;
if (distance >= ray.dist_) {
return false;
}
ray.dist_ = distance;
ray.origin_ = transformation_->multVec(ray.origin_ + ray.direction_ * ray.dist_);
ray.direction_ = transformation_->multDir(ray.direction_);
ray.medium_list_ = medium_list_;
return true;
} | 51.3 | 230 | 0.741715 | guillaumetousignant |
aa6bc184df9da1b35fe983d11f2779acaa978ee4 | 1,154 | cpp | C++ | WA/UVa-10410.cpp | chenhw26/OnlineJudgeByChw | 112560816a34062ddaf502d81f25dbb9a2ccd7d5 | [
"MIT"
] | null | null | null | WA/UVa-10410.cpp | chenhw26/OnlineJudgeByChw | 112560816a34062ddaf502d81f25dbb9a2ccd7d5 | [
"MIT"
] | null | null | null | WA/UVa-10410.cpp | chenhw26/OnlineJudgeByChw | 112560816a34062ddaf502d81f25dbb9a2ccd7d5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <set>
using namespace std;
int find(int a, int n, int *arr, int begin = 1){
for(int i = begin; i <= n; ++i)
if(arr[i] == a) return i;
return 0;
}
int main(){
int n;
while(cin >> n){
int bfs[n + 5] = {0}, dfs[n + 5] = {0};
set<int> ans[n + 5];
bool findAns[n + 5] = {0};
for (int i = 1; i <= n; ++i) cin >> bfs[i];
for (int i = 1; i <= n; ++i) cin >> dfs[i];
for (int i = 1; i <= n; ++i){
int indexInDFS = find(bfs[i], n, dfs);
int firstSon = dfs[indexInDFS + 1];
int firstSonIndexInBFS = find(firstSon, n, bfs, i + 1);
if(firstSonIndexInBFS){
int subling = bfs[i + 1];
int sublingSon = dfs[find(subling, n, dfs) + 1];
int sublingSonIndexInBFS = find(sublingSon, n, bfs, i + 2);
int endIndex = sublingSonIndexInBFS && !findAns[sublingSon]? sublingSonIndexInBFS: n + 1;
for (int j = firstSonIndexInBFS; j < endIndex; ++j){
if(!findAns[bfs[j]]){
ans[bfs[i]].insert(bfs[j]);
findAns[bfs[j]] = true;
}
}
}
}
for (int i = 1; i <= n; ++i){
cout << i << ':';
for (auto son: ans[i])
cout << ' ' << son;
cout << endl;
}
}
return 0;
} | 26.227273 | 93 | 0.533795 | chenhw26 |
aa6ccc40393607ba110b06791af3732e152a2448 | 15,500 | inl | C++ | c++/Palm/PalmField.inl | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | c++/Palm/PalmField.inl | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | c++/Palm/PalmField.inl | aamshukov/miscellaneous | 6fc0d2cb98daff70d14f87b2dfc4e58e61d2df60 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////
//......................................................................................
// This is a part of AI Library [Arthur's Interfaces Library]. .
// 1998-2001 Arthur Amshukov .
//......................................................................................
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND .
// DO NOT REMOVE MY NAME AND THIS NOTICE FROM THE SOURCE .
//......................................................................................
////////////////////////////////////////////////////////////////////////////////////////
#ifndef __PALM_FIELD_INL__
#define __PALM_FIELD_INL__
#ifdef __PALM_OS__
#pragma once
__BEGIN_NAMESPACE__
////////////////////////////////////////////////////////////////////////////////////////
// class PalmField
// ----- ---------
__INLINE__ PalmField::operator FieldType* ()
{
return static_cast<FieldType*>(Control);
}
__INLINE__ PalmField::operator const FieldType* () const
{
return const_cast<const FieldType*>(Control);
}
__INLINE__ char* PalmField::GetTextPtr()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetTextPtr(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetTextPtr(const char* _text)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_text != null, Error::eInvalidArg, PalmField::XPalmField);
::FldSetTextPtr(static_cast<FieldType*>(Control), const_cast<char*>(_text));
}
__INLINE__ void PalmField::SetText(MemHandle _handle, uint16 _offset, uint16 _size)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_handle != 0, Error::eInvalidArg, PalmField::XPalmField);
::FldSetText(static_cast<FieldType*>(Control), _handle, _offset, _size);
}
__INLINE__ MemHandle PalmField::GetTextHandle()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetTextHandle(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetTextHandle(MemHandle _handle)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_handle != 0, Error::eInvalidArg, PalmField::XPalmField);
::FldSetTextHandle(static_cast<FieldType*>(Control), _handle);
}
__INLINE__ uint16 PalmField::GetTextLength()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetTextLength(static_cast<FieldType*>(Control));
}
__INLINE__ uint16 PalmField::GetTextHeight()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetTextHeight(static_cast<FieldType*>(Control));
}
__INLINE__ uint16 PalmField::CalcFieldHeight(const char* _chars, uint16 _width)
{
palmxassert(_chars != null, Error::eInvalidArg, PalmField::XPalmField);
return ::FldCalcFieldHeight(_chars, _width);
}
__INLINE__ uint16 PalmField::GetMaxChars()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetMaxChars(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetMaxChars(uint16 _max_chars)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetMaxChars(static_cast<FieldType*>(Control), _max_chars);
}
__INLINE__ void PalmField::RecalculateField(bool _redraw)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldRecalculateField(static_cast<FieldType*>(Control), _redraw);
}
__INLINE__ void PalmField::CompactText()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldCompactText(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::FreeMemory()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldFreeMemory(static_cast<FieldType*>(Control));
}
__INLINE__ uint16 PalmField::GetTextAllocatedSize()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetTextAllocatedSize(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetTextAllocatedSize(uint16 _size)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_size > 0, Error::eInvalidArg, PalmField::XPalmField);
::FldSetTextAllocatedSize(static_cast<FieldType*>(Control), _size);
}
__INLINE__ void PalmField::GetAttributes(FieldAttrType& _attr)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldGetAttributes(static_cast<FieldType*>(Control), &_attr);
}
__INLINE__ void PalmField::SetAttributes(const FieldAttrType& _attr)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetAttributes(static_cast<FieldType*>(Control), &_attr);
}
__INLINE__ bool PalmField::Insert(const char* _text, uint16 _len)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_text != null && _len > 0, Error::eInvalidArg, PalmField::XPalmField);
return ::FldInsert(static_cast<FieldType*>(Control), _text, _len);
}
__INLINE__ void PalmField::Delete(uint16 _start, uint16 _end)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_start <= _end, Error::eInvalidArg, PalmField::XPalmField);
::FldDelete(static_cast<FieldType*>(Control), _start, _end);
}
__INLINE__ void PalmField::Copy()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldCopy(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::Cut()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldCut(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::Paste()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldPaste(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::Undo()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldUndo(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::DrawField()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldDrawField(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::EraseField()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldEraseField(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::GetBounds(Rect& _r)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldGetBounds(static_cast<FieldType*>(Control), &_r);
}
__INLINE__ void PalmField::SetBounds(const Rect& _r)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetBounds(static_cast<FieldType*>(Control), &_r);
}
__INLINE__ FontID PalmField::GetFont()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetFont(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetFont(FontID _id)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetFont(static_cast<FieldType*>(Control), _id);
}
__INLINE__ void PalmField::SetUsable(bool _usable)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetUsable(static_cast<FieldType*>(Control), _usable);
}
__INLINE__ bool PalmField::MakeFullyVisible()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldMakeFullyVisible(static_cast<FieldType*>(Control));
}
__INLINE__ uint16 PalmField::GetNumberOfBlankLines()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetNumberOfBlankLines(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::GrabFocus()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldGrabFocus(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::ReleaseFocus()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldReleaseFocus(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::GetSelection(uint16& _start, uint16& _end)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldGetSelection(static_cast<FieldType*>(Control), &_start, &_end);
}
__INLINE__ void PalmField::SetSelection(uint16 _start, uint16 _end)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
palmxassert(_start <= _end, Error::eInvalidArg, PalmField::XPalmField);
::FldSetSelection(static_cast<FieldType*>(Control), _start, _end);
}
__INLINE__ uint16 PalmField::GetInsPtPosition()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetInsPtPosition(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetInsPtPosition(uint16 _pos)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetInsPtPosition(static_cast<FieldType*>(Control), _pos);
}
__INLINE__ void PalmField::SetInsertionPoint(uint16 _pos)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetInsertionPoint(static_cast<FieldType*>(Control), _pos);
}
__INLINE__ bool PalmField::IsScrollable(WinDirectionType _dir)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldScrollable(static_cast<FieldType*>(Control), _dir);
}
__INLINE__ void PalmField::ScrollField(uint16 _count, WinDirectionType _dir)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldScrollField(static_cast<FieldType*>(Control), _count, _dir);
}
__INLINE__ uint16 PalmField::GetScrollPosition()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetScrollPosition(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetScrollPosition(uint16 _pos)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetScrollPosition(static_cast<FieldType*>(Control), _pos);
}
__INLINE__ void PalmField::GetScrollValues(uint16& _scroll_pos, uint16& _text_height, uint16& _field_height)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldGetScrollValues(static_cast<FieldType*>(Control), &_scroll_pos, &_text_height, &_field_height);
}
__INLINE__ uint16 PalmField::GetVisibleLines()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldGetVisibleLines(static_cast<FieldType*>(Control));
}
__INLINE__ uint16 PalmField::WordWrap(const char* _text, int16 _len)
{
palmxassert(_text != null, Error::eInvalidArg, PalmField::XPalmField);
return ::FldWordWrap(_text, _len);
}
__INLINE__ bool PalmField::Dirty()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldDirty(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SetDirty(bool _dirty)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetDirty(static_cast<FieldType*>(Control), _dirty);
}
__INLINE__ void PalmField::SendChangeNotification()
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSendChangeNotification(static_cast<FieldType*>(Control));
}
__INLINE__ void PalmField::SendHeightChangeNotification(uint16 _pos, int16 _num_lines)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSendHeightChangeNotification(static_cast<FieldType*>(Control), _pos, _num_lines);
}
__INLINE__ bool PalmField::HandleEvent(EventType& _event)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldHandleEvent(static_cast<FieldType*>(Control), &_event);
}
#if (__PALM_OS__ >= 0x0400)
__INLINE__ void PalmField::SetMaxVisibleLines(uint8 _max_lines)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
::FldSetMaxVisibleLines(static_cast<FieldType*>(Control), _max_lines);
}
#endif
__INLINE__ FieldType* PalmField::Clone(uint16 _id,
Coord _x, Coord _y, Coord _w, Coord _h,
FontID _font_id, uint32 _max_chars, bool _editable,
bool _underlined, bool _single_line, bool _dynamic,
JustificationType _justification, bool _autoshift,
bool _has_scrollbars, bool _numeric)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldNewField(&Control, _id, _x, _y, _w, _h, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric);
}
__INLINE__ FieldType* PalmField::Clone(uint16 _id,
const Point& _pt, const Size& _sz,
FontID _font_id, uint32 _max_chars, bool _editable,
bool _underlined, bool _single_line, bool _dynamic,
JustificationType _justification, bool _autoshift,
bool _has_scrollbars, bool _numeric)
{
palmxassert(Control != null, Error::eUninitialized, PalmField::XPalmField);
return ::FldNewField(&Control, _id, _pt.x, _pt.y, _sz.cx, _sz.cy, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric);
}
__INLINE__ FieldType* PalmField::Clone(void** _form, uint16 _id,
Coord _x, Coord _y, Coord _w, Coord _h,
FontID _font_id, uint32 _max_chars, bool _editable,
bool _underlined, bool _single_line, bool _dynamic,
JustificationType _justification, bool _autoshift,
bool _has_scrollbars, bool _numeric)
{
palmxassert(_form != null, Error::eInvalidArg, PalmField::XPalmField);
return ::FldNewField(_form, _id, _x, _y, _w, _h, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric);
}
__INLINE__ FieldType* PalmField::Clone(void** _form, uint16 _id,
const Point& _pt, const Size& _sz,
FontID _font_id, uint32 _max_chars, bool _editable,
bool _underlined, bool _single_line, bool _dynamic,
JustificationType _justification, bool _autoshift,
bool _has_scrollbars, bool _numeric)
{
palmxassert(_form != null, Error::eInvalidArg, PalmField::XPalmField);
return ::FldNewField(_form, _id, _pt.x, _pt.y, _sz.cx, _sz.cy, _font_id, _max_chars, _editable, _underlined, _single_line, _dynamic, _justification, _autoshift, _has_scrollbars, _numeric);
}
////////////////////////////////////////////////////////////////////////////////////////
__END_NAMESPACE__
#endif // __PALM_OS__
#endif // __PALM_FIELD_INL__
| 38.75 | 195 | 0.684839 | aamshukov |
aa70d7599f31fced9d60ef5bb7c1d4e64bed6af5 | 274 | hh | C++ | extern/clean-core/src/clean-core/stringhash.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/clean-core/src/clean-core/stringhash.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | extern/clean-core/src/clean-core/stringhash.hh | rovedit/Fort-Candle | 445fb94852df56c279c71b95c820500e7fb33cf7 | [
"MIT"
] | null | null | null | #pragma once
#include <clean-core/hash_combine.hh>
namespace cc
{
constexpr hash_t stringhash(char const* s)
{
if (!s)
return 0;
hash_t h = hash_combine();
while (*s)
{
h = hash_combine(h, hash_t(*s));
s++;
}
return h;
}
}
| 13.047619 | 42 | 0.547445 | rovedit |
aa714391fa9f24c129d6b44298d1991dc4ad96eb | 2,466 | cpp | C++ | hphp/runtime/debugger/cmd/cmd_quit.cpp | abhishekgahlot/hiphop-php | 5b367ac44a7a9a6e4c777ae0786d1c872d3ae0a9 | [
"PHP-3.01",
"Zend-2.0"
] | 1 | 2015-11-05T19:26:02.000Z | 2015-11-05T19:26:02.000Z | hphp/runtime/debugger/cmd/cmd_quit.cpp | abhishekgahlot/hiphop-php | 5b367ac44a7a9a6e4c777ae0786d1c872d3ae0a9 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | hphp/runtime/debugger/cmd/cmd_quit.cpp | abhishekgahlot/hiphop-php | 5b367ac44a7a9a6e4c777ae0786d1c872d3ae0a9 | [
"PHP-3.01",
"Zend-2.0"
] | null | null | null | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "hphp/runtime/debugger/cmd/cmd_quit.h"
namespace HPHP { namespace Eval {
///////////////////////////////////////////////////////////////////////////////
TRACE_SET_MOD(debugger);
// The text to display when the debugger client processes "help quit".
void CmdQuit::help(DebuggerClient &client) {
TRACE(2, "CmdQuit::help\n");
client.helpTitle("Quit Command");
client.helpCmds(
"[q]uit", "quits this program",
nullptr
);
client.helpBody(
"After you type this command, you will not see me anymore."
);
}
// Carries out the Quit command by informing the server the client
// is going away and then getting the client to quit.
void CmdQuit::onClientImpl(DebuggerClient &client) {
TRACE(2, "CmdQuit::onClientImpl\n");
if (DebuggerCommand::displayedHelp(client)) return;
if (client.argCount() == 0) {
client.xend<CmdQuit>(this); // Wait for server ack before closing pipe.
client.quit();
} else {
help(client);
}
}
// Sends an acknowledgment back to the client so that
// it can go ahead and terminate. It it were to do so
// before the server has received the command, the pipe
// will be closed and the proxy will carry on as if there
// were a communication failure, which is not as clean
// explicitly quitting.
bool CmdQuit::onServer(DebuggerProxy &proxy) {
TRACE(2, "CmdQuit::onServer\n");
return proxy.sendToClient(this);
}
///////////////////////////////////////////////////////////////////////////////
}}
| 38.53125 | 79 | 0.528792 | abhishekgahlot |
aa729a6109d216204055f776fa7ca358c67e985b | 53,767 | cpp | C++ | join/sax/tests/packreader_test.cpp | mrabine/join | 63c6193f2cc229328c36748d7f9ef8aca915bec3 | [
"MIT"
] | 1 | 2021-09-14T13:53:07.000Z | 2021-09-14T13:53:07.000Z | join/sax/tests/packreader_test.cpp | joinframework/join | 63c6193f2cc229328c36748d7f9ef8aca915bec3 | [
"MIT"
] | 15 | 2021-08-09T23:55:02.000Z | 2021-11-22T11:05:41.000Z | join/sax/tests/packreader_test.cpp | mrabine/join | 63c6193f2cc229328c36748d7f9ef8aca915bec3 | [
"MIT"
] | null | null | null | /**
* MIT License
*
* Copyright (c) 2021 Mathieu Rabine
*
* 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.
*/
// libjoin.
#include <join/pack.hpp>
// libraries.
#include <gtest/gtest.h>
// C++.
#include <sstream>
// C.
#include <cmath>
using join::Array;
using join::Member;
using join::Object;
using join::Value;
using join::SaxErrc;
using join::PackReader;
/**
* @brief Test deserialize method.
*/
TEST (PackReader, deserialize)
{
std::stringstream stream;
Value value;
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x00'}));
std::string str ({'\xdd', '\x00', '\x00', '\x00', '\x00'});
char data[] = {'\xdd', '\x00', '\x00', '\x00', '\x00', '\x00'};
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_TRUE (value.empty ());
ASSERT_EQ (value.deserialize <PackReader> (str), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_TRUE (value.empty ());
ASSERT_EQ (value.deserialize <PackReader> (data, sizeof (data) - 1), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_TRUE (value.empty ());
ASSERT_EQ (value.deserialize <PackReader> (&data[0], &data[sizeof (data) - 1]), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_TRUE (value.empty ());
ASSERT_EQ (value.deserialize <PackReader> (&data[0], &data[sizeof (data)]), -1);
ASSERT_EQ (join::lastError, SaxErrc::ExtraData);
}
/**
* @brief Test MessagePack parsing pass.
*/
TEST (PackReader, pass)
{
std::stringstream stream;
Value value;
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_TRUE (value.empty ());
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xce', '\x49', '\x96', '\x02', '\xd2'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isInt ());
ASSERT_EQ (value[0], 1234567890);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xc0', '\xc3', '\x4a', '\x45', '\x87', '\xe7', '\xc0', '\x6e'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
ASSERT_DOUBLE_EQ (value[0].getDouble (), -9876.543210);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3d', '\x41', '\x5f', '\xff', '\xe5', '\x3a', '\x68', '\x5d'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
ASSERT_DOUBLE_EQ (value[0].getDouble (), 0.123456789e-12);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x47', '\x03', '\x05', '\x82', '\xff', '\xd7', '\x14', '\x75'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
ASSERT_DOUBLE_EQ (value[0].getDouble (), 1.234567890E+34);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xc3'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isBool ());
ASSERT_EQ (value[0], true);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xc2'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isBool ());
ASSERT_EQ (value[0], false);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xc0'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isNull ());
ASSERT_EQ (value[0], nullptr);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x0b', '\xcb', '\x3f', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x40', '\x58', '\xa6', '\x66', '\x66',
'\x66', '\x66', '\x66', '\xcb', '\x40', '\x58', '\xdc', '\x28', '\xf5', '\xc2', '\x8f', '\x5c', '\xcd', '\x04', '\x2a', '\xcb', '\x40', '\x24', '\x00', '\x00',
'\x00', '\x00', '\x00', '\x00', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x3f', '\xb9', '\x99', '\x99', '\x99', '\x99',
'\x99', '\x9a', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xcb', '\x40', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00',
'\xcb', '\x40', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\xa7', '\x72', '\x6f', '\x73', '\x65', '\x62', '\x75', '\x64'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_EQ (value.size (), 11);
ASSERT_TRUE (value[0].isDouble ());
ASSERT_DOUBLE_EQ (value[0].getDouble (), 0.5);
ASSERT_TRUE (value[1].isDouble ());
ASSERT_DOUBLE_EQ (value[1].getDouble (), 98.6);
ASSERT_TRUE (value[2].isDouble ());
ASSERT_DOUBLE_EQ (value[2].getDouble (), 99.44);
ASSERT_TRUE (value[3].isInt ());
ASSERT_EQ (value[3].getInt (), 1066);
ASSERT_TRUE (value[4].isDouble ());
ASSERT_DOUBLE_EQ (value[4].getDouble (), 1e1);
ASSERT_TRUE (value[5].isDouble ());
ASSERT_DOUBLE_EQ (value[5].getDouble (), 0.1e1);
ASSERT_TRUE (value[6].isDouble ());
ASSERT_DOUBLE_EQ (value[6].getDouble (), 1e-1);
ASSERT_TRUE (value[7].isDouble ());
ASSERT_DOUBLE_EQ (value[7].getDouble (), 1e00);
ASSERT_TRUE (value[8].isDouble ());
ASSERT_DOUBLE_EQ (value[8].getDouble (), 2e+00);
ASSERT_TRUE (value[9].isDouble ());
ASSERT_DOUBLE_EQ (value[9].getDouble (), 2e-00);
ASSERT_TRUE (value[10].isString ());
ASSERT_EQ (value[10], "rosebud");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xac', '\x4e', '\x6f', '\x74', '\x20',
'\x74', '\x6f', '\x6f', '\x20', '\x64', '\x65', '\x65', '\x70'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_TRUE (value.empty ());
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa7', '\x69', '\x6e', '\x74', '\x65', '\x67', '\x65', '\x72', '\xce', '\x49', '\x96', '\x02', '\xd2'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["integer"].isInt ());
ASSERT_EQ (value["integer"], 1234567890);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x72', '\x65', '\x61', '\x6c', '\xcb', '\xc0', '\xc3', '\x4a', '\x45', '\x87', '\xe7', '\xc0', '\x6e'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["real"].isDouble ());
ASSERT_DOUBLE_EQ (value["real"].getDouble (), -9876.543210);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa1', '\x65', '\xcb', '\x3d', '\x41', '\x5f', '\xff', '\xe5', '\x3a', '\x68', '\x5d'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["e"].isDouble ());
ASSERT_DOUBLE_EQ (value["e"].getDouble (), 0.123456789e-12);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa1', '\x45', '\xcb', '\x47', '\x03', '\x05', '\x82', '\xff', '\xd7', '\x14', '\x75'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["E"].isDouble ());
ASSERT_DOUBLE_EQ (value["E"].getDouble (), 1.234567890E+34);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa0', '\xcb', '\x4f', '\xc9', '\xee', '\x09', '\x3a', '\x64', '\xb8', '\x54'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[""].isDouble ());
ASSERT_DOUBLE_EQ (value[""].getDouble (), 23456789012E66);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x7a', '\x65', '\x72', '\x6f', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["zero"].isInt ());
ASSERT_EQ (value["zero"], 0);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa3', '\x6f', '\x6e', '\x65', '\x01'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["one"].isInt ());
ASSERT_EQ (value["one"], 1);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x73', '\x70', '\x61', '\x63', '\x65', '\xa1', '\x20'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["space"].isString ());
ASSERT_EQ (value["space"], " ");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x71', '\x75', '\x6f', '\x74', '\x65', '\xa1', '\x22'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["quote"].isString ());
ASSERT_EQ (value["quote"], "\"");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa9', '\x62', '\x61', '\x63', '\x6b', '\x73', '\x6c', '\x61', '\x73', '\x68', '\xa1', '\x5c'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["backslash"].isString ());
ASSERT_EQ (value["backslash"], "\\");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa8', '\x63', '\x6f', '\x6e', '\x74', '\x72', '\x6f', '\x6c', '\x73', '\xa5', '\x08', '\x0c', '\x0a', '\x0d', '\x09'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["controls"].isString ());
ASSERT_EQ (value["controls"], "\b\f\n\r\t");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x73', '\x6c', '\x61', '\x73', '\x68', '\xa6', '\x2f', '\x20', '\x26', '\x20', '\x5c', '\x2f'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["slash"].isString ());
ASSERT_EQ (value["slash"], "/ & \\/");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x61', '\x6c', '\x70', '\x68', '\x61', '\xb9', '\x61', '\x62', '\x63', '\x64', '\x65', '\x66', '\x67', '\x68',
'\x69', '\x6a', '\x6b', '\x6c', '\x6d', '\x6e', '\x6f', '\x70', '\x71', '\x72', '\x73', '\x74', '\x75', '\x76', '\x77', '\x79', '\x7a'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["alpha"].isString ());
ASSERT_EQ (value["alpha"], "abcdefghijklmnopqrstuvwyz");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x41', '\x4c', '\x50', '\x48', '\x41', '\xb9', '\x41', '\x42', '\x43', '\x44', '\x45', '\x46', '\x47', '\x48',
'\x49', '\x4a', '\x4b', '\x4c', '\x4d', '\x4e', '\x4f', '\x50', '\x51', '\x52', '\x53', '\x54', '\x55', '\x56', '\x57', '\x59', '\x5a'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["ALPHA"].isString ());
ASSERT_EQ (value["ALPHA"], "ABCDEFGHIJKLMNOPQRSTUVWYZ");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x64', '\x69', '\x67', '\x69', '\x74', '\xaa', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37',
'\x38', '\x39'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["digit"].isString ());
ASSERT_EQ (value["digit"], "0123456789");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xaa', '\x30', '\x31', '\x32', '\x33', '\x34', '\x35', '\x36', '\x37', '\x38', '\x39', '\xa5', '\x64', '\x69', '\x67',
'\x69', '\x74'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["0123456789"].isString ());
ASSERT_EQ (value["0123456789"], "digit");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa7', '\x73', '\x70', '\x65', '\x63', '\x69', '\x61', '\x6c', '\xbf', '\x60', '\x31', '\x7e', '\x21', '\x40', '\x23',
'\x24', '\x25', '\x5e', '\x26', '\x2a', '\x28', '\x29', '\x5f', '\x2b', '\x2d', '\x3d', '\x7b', '\x27', '\x3a', '\x5b', '\x2c', '\x5d', '\x7d', '\x7c', '\x3b',
'\x2e', '\x3c', '\x2f', '\x3e', '\x3f'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["special"].isString ());
ASSERT_EQ (value["special"], "`1~!@#$%^&*()_+-={':[,]}|;.</>?");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa3', '\x68', '\x65', '\x78', '\xb1', '\xc4', '\xa3', '\xe4', '\x95', '\xa7', '\xe8', '\xa6', '\xab', '\xec', '\xb7',
'\xaf', '\xea', '\xaf', '\x8d', '\xee', '\xbd', '\x8a'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["hex"].isString ());
ASSERT_EQ (value["hex"].getString (), std::string ({'\xC4', '\xA3', '\xE4', '\x95', '\xA7', '\xE8', '\xA6', '\xAB', '\xEC', '\xB7', '\xAF', '\xEA', '\xAF', '\x8D', '\xEE', '\xBD', '\x8A'}));
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x74', '\x72', '\x75', '\x65', '\xc3'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["true"].isBool ());
ASSERT_EQ (value["true"], true);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x66', '\x61', '\x6c', '\x73', '\x65', '\xc2'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["false"].isBool ());
ASSERT_EQ (value["false"], false);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa4', '\x6e', '\x75', '\x6c', '\x6c', '\xc0'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["null"].isNull ());
ASSERT_EQ (value["null"], nullptr);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x61', '\x72', '\x72', '\x61', '\x79', '\xdd', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["array"].isArray ());
ASSERT_TRUE (value["array"].empty ());
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa6', '\x6f', '\x62', '\x6a', '\x65', '\x63', '\x74', '\xdf', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["object"].isObject ());
ASSERT_TRUE (value["object"].empty ());
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa7', '\x61', '\x64', '\x64', '\x72', '\x65', '\x73', '\x73', '\xb3', '\x35', '\x30', '\x20', '\x53', '\x74', '\x2e',
'\x20', '\x4a', '\x61', '\x6d', '\x65', '\x73', '\x20', '\x53', '\x74', '\x72', '\x65', '\x65', '\x74'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["address"].isString ());
ASSERT_EQ (value["address"], "50 St. James Street");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa3', '\x75', '\x72', '\x6c', '\xbe', '\x68', '\x74', '\x74', '\x70', '\x73', '\x3a', '\x2f', '\x2f', '\x77', '\x77',
'\x77', '\x2e', '\x6a', '\x6f', '\x69', '\x6e', '\x66', '\x72', '\x61', '\x6d', '\x65', '\x77', '\x6f', '\x72', '\x6b', '\x2e', '\x6e', '\x65', '\x74', '\x2f'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["url"].isString ());
ASSERT_EQ (value["url"], "https://www.joinframework.net/");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x02', '\xa7', '\x63', '\x6f', '\x6d', '\x6d', '\x65', '\x6e', '\x74', '\xad', '\x2f', '\x2f', '\x20', '\x2f', '\x2a', '\x20',
'\x3c', '\x21', '\x2d', '\x2d', '\x20', '\x2d', '\x2d', '\xab', '\x23', '\x20', '\x2d', '\x2d', '\x20', '\x2d', '\x2d', '\x3e', '\x20', '\x2a', '\x2f', '\xa1',
'\x20'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["comment"].isString ());
ASSERT_EQ (value["comment"], "// /* <!-- --");
ASSERT_TRUE (value["# -- --> */"].isString ());
ASSERT_EQ (value["# -- --> */"], " ");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x02', '\xad', '\x20', '\x73', '\x20', '\x70', '\x20', '\x61', '\x20', '\x63', '\x20', '\x65', '\x20', '\x64', '\x20', '\xdd',
'\x00', '\x00', '\x00', '\x07', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\xa7', '\x63', '\x6f', '\x6d', '\x70', '\x61', '\x63', '\x74', '\xdd',
'\x00', '\x00', '\x00', '\x07', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[" s p a c e d "].isArray ());
ASSERT_EQ (value[" s p a c e d "][0], 1);
ASSERT_EQ (value[" s p a c e d "][1], 2);
ASSERT_EQ (value[" s p a c e d "][2], 3);
ASSERT_EQ (value[" s p a c e d "][3], 4);
ASSERT_EQ (value[" s p a c e d "][4], 5);
ASSERT_EQ (value[" s p a c e d "][5], 6);
ASSERT_EQ (value[" s p a c e d "][6], 7);
ASSERT_TRUE (value["compact"].isArray ());
ASSERT_EQ (value["compact"][0], 1);
ASSERT_EQ (value["compact"][1], 2);
ASSERT_EQ (value["compact"][2], 3);
ASSERT_EQ (value["compact"][3], 4);
ASSERT_EQ (value["compact"][4], 5);
ASSERT_EQ (value["compact"][5], 6);
ASSERT_EQ (value["compact"][6], 7);
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xb4', '\x6f', '\x62', '\x6a', '\x65', '\x63', '\x74', '\x20', '\x77', '\x69', '\x74', '\x68', '\x20', '\x31', '\x20',
'\x6d', '\x65', '\x6d', '\x62', '\x65', '\x72', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xb4', '\x61', '\x72', '\x72', '\x61', '\x79', '\x20', '\x77', '\x69',
'\x74', '\x68', '\x20', '\x31', '\x20', '\x65', '\x6c', '\x65', '\x6d', '\x65', '\x6e', '\x74'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["object with 1 member"].isArray ());
ASSERT_EQ (value["object with 1 member"][0], "array with 1 element");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xa6', '\x71', '\x75', '\x6f', '\x74', '\x65', '\x73', '\xbb', '\x26', '\x23', '\x33', '\x34', '\x3b', '\x20', '\x22',
'\x20', '\x25', '\x32', '\x32', '\x20', '\x30', '\x78', '\x32', '\x32', '\x20', '\x30', '\x33', '\x34', '\x20', '\x26', '\x23', '\x78', '\x32', '\x32', '\x3b'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["quotes"].isString ());
ASSERT_EQ (value["quotes"], "" \" %22 0x22 034 "");
stream.clear ();
stream.str (std::string ({'\xdf', '\x00', '\x00', '\x00', '\x01', '\xd9', '\x25', '\x22', '\x08', '\x0c', '\x0a', '\x0d', '\x09', '\x60', '\x31', '\x7e', '\x21', '\x40', '\x23', '\x24',
'\x25', '\x5e', '\x26', '\x2a', '\x28', '\x29', '\x5f', '\x2b', '\x2d', '\x3d', '\x5b', '\x5d', '\x7b', '\x7d', '\x7c', '\x3b', '\x3a', '\x27', '\x2c', '\x2e',
'\x2f', '\x3c', '\x3e', '\x3f', '\xb7', '\x41', '\x20', '\x6b', '\x65', '\x79', '\x20', '\x63', '\x61', '\x6e', '\x20', '\x62', '\x65', '\x20', '\x61', '\x6e',
'\x79', '\x20', '\x73', '\x74', '\x72', '\x69', '\x6e', '\x67'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isObject ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value["\"\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"].isString ());
ASSERT_EQ (value["\"\b\f\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?"], "A key can be any string");
}
/**
* @brief Test MessagePack parsing fail.
*/
TEST (PackReader, fail)
{
std::stringstream stream;
Value value;
stream.clear ();
stream.str (std::string ({'\xd9', '\x32', '\x70', '\x61', '\x79', '\x6c', '\x6f', '\x61', '\x64', '\x20', '\x73', '\x68', '\x6f', '\x75', '\x6c', '\x64', '\x20', '\x62', '\x65', '\x20',
'\x61', '\x6e', '\x20', '\x6f', '\x62', '\x6a', '\x65', '\x63', '\x74', '\x20', '\x6f', '\x72', '\x20', '\x61', '\x72', '\x72', '\x61', '\x79', '\x2c', '\x20',
'\x6e', '\x6f', '\x74', '\x20', '\x61', '\x20', '\x73', '\x74', '\x72', '\x69', '\x6e', '\x67'}));
ASSERT_NE (value.deserialize <PackReader> (stream), 0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01', '\xdd', '\x00', '\x00', '\x00', '\x01',
'\xa8', '\x54', '\x6f', '\x6f', '\x20', '\x64', '\x65', '\x65', '\x70'}));
ASSERT_NE (value.deserialize <PackReader> (stream), 0);
}
/**
* @brief Test MessagePack parse double.
*/
TEST (PackReader, dbl)
{
std::stringstream stream;
Value value;
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 0.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x80', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -0.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xbf', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -1.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf8', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.5);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xbf', '\xf8', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -1.5);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x40', '\x09', '\x21', '\xff', '\x2e', '\x48', '\xe8', '\xa7'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 3.1416);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x42', '\x02', '\xa0', '\x5f', '\x20', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1E10);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3d', '\xdb', '\x7C', '\xdf', '\xd9', '\xd7', '\xbd', '\xbb'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1E-10);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xc2', '\x02', '\xa0', '\x5f', '\x20', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -1E10);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xbd', '\xdb', '\x7c', '\xdf', '\xd9', '\xd7', '\xbd', '\xbb'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -1E-10);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x42', '\x06', '\xfc', '\x2b', '\xa8', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.234E+10);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3d', '\xe0', '\xf5', '\xc0', '\x63', '\x56', '\x43', '\xa8'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.234E-10);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x7f', '\xef', '\xff', '\xfc', '\x57', '\xca', '\x82', '\xae'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.79769e+308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x0f', '\xff', '\xfe', '\x2e', '\x81', '\x59', '\xd0'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 2.22507e-308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\xff', '\xef', '\xff', '\xfc', '\x57', '\xca', '\x82', '\xae'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -1.79769e+308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x80', '\x0f', '\xff', '\xfe', '\x2e', '\x81', '\x59', '\xd0'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -2.22507e-308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x80', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x01'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), -4.9406564584124654e-324);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x0f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 2.2250738585072009e-308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 2.2250738585072014e-308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x7f', '\xef', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.7976931348623157e+308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 0.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xef', '\x93', '\xe0', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 0.9868011474609375);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x47', '\x6d', '\x9c', '\x75', '\xd3', '\xac', '\x07', '\x2b'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 123e34);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x44', '\x03', '\xe9', '\x61', '\xfa', '\x3b', '\xa6', '\xa0'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 45913141877270640000.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x0f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 2.2250738585072011e-308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 0.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 0.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x7f', '\xef', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.7976931348623157e+308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 2.2250738585072014e-308);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xef', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 0.99999999999999989);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x3f', '\xf0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x01'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 1.00000000000000022);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x6f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 72057594037927928.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 72057594037927936.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 72057594037927936.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x6f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 72057594037927928.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 72057594037927936.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xdf', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 9223372036854774784.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 9223372036854775808.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 9223372036854775808.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xdf', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 9223372036854774784.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x43', '\xe0', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 9223372036854775808.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x46', '\x5f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 10141204801825834086073718800384.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x46', '\x60', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 10141204801825835211973625643008.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x49', '\x6f', '\xff', '\xff', '\xff', '\xff', '\xff', '\xff'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 5708990770823838890407843763683279797179383808.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x49', '\x70', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 5708990770823839524233143877797980545530986496.0);
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xcb', '\x00', '\x10', '\x00', '\x00', '\x00', '\x00', '\x00', '\x00'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isDouble ());
EXPECT_EQ (value[0].getDouble (), 2.2250738585072014e-308);
}
/**
* @brief Test JSON parse string.
*/
TEST (PackReader, str)
{
std::stringstream stream;
Value value;
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa0'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa5', '\x48', '\x65', '\x6c', '\x6c', '\x6f'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "Hello");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xab', '\x48', '\x65', '\x6c', '\x6c', '\x6f', '\x0a', '\x57', '\x6f', '\x72', '\x6c', '\x64'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "Hello\nWorld");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xab', '\x48', '\x65', '\x6c', '\x6c', '\x6f', '\x00', '\x57', '\x6f', '\x72', '\x6c', '\x64'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "Hello\0World");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa8', '\x22', '\x5c', '\x2f', '\x08', '\x0c', '\x0a', '\x0d', '\x09'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "\"\\/\b\f\n\r\t");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa1', '\x24'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "\x24");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa2', '\xc2', '\xa2'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "\xC2\xA2");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa3', '\xe2', '\x82', '\xac'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "\xE2\x82\xAC");
stream.clear ();
stream.str (std::string ({'\xdd', '\x00', '\x00', '\x00', '\x01', '\xa4', '\xf0', '\x9d', '\x84', '\x9e'}));
ASSERT_EQ (value.deserialize <PackReader> (stream), 0) << join::lastError.message ();
ASSERT_TRUE (value.isArray ());
ASSERT_FALSE (value.empty ());
ASSERT_TRUE (value[0].isString ());
EXPECT_STREQ (value[0].getString ().c_str (), "\xF0\x9D\x84\x9E");
}
/**
* @brief main function.
*/
int main (int argc, char **argv)
{
testing::InitGoogleTest (&argc, argv);
return RUN_ALL_TESTS ();
}
| 53.659681 | 194 | 0.541168 | mrabine |
aa734a91a83581f5a4606e9bda196fedb55a0dd4 | 509 | cpp | C++ | src/luogu/T101689/24647440_ua_5_632ms_128000k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/luogu/T101689/24647440_ua_5_632ms_128000k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | src/luogu/T101689/24647440_ua_5_632ms_128000k_noO2.cpp | lnkkerst/oj-codes | d778489182d644370b2a690aa92c3df6542cc306 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int a[50001];
short b[10001][10001];
int n, m;
int main() {
scanf("%d%d", &n, &m);
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
for(int j = i; j <= n; j++)
++b[j][a[i]];
}
while(m--) {
int l, r, l1, r1;
scanf("%d%d%d%d", &l, &r, &l1, &r1);
int ans = 0;
for(int i = l; i <= r; ++i)
ans += b[r][a[i]] - b[l - 1][a[i]];
printf("%d\n", ans);
}
return 0;
} | 20.36 | 47 | 0.375246 | lnkkerst |
aa7a2cdd5a856906d26cfc612bb67177e936e88b | 378 | cpp | C++ | src/Functions/left.cpp | chalice19/ClickHouse | 2f38e7bc5c2113935ab86260439bb543a1737291 | [
"Apache-2.0"
] | 8,629 | 2016-06-14T21:03:01.000Z | 2019-09-23T07:46:38.000Z | src/Functions/left.cpp | chalice19/ClickHouse | 2f38e7bc5c2113935ab86260439bb543a1737291 | [
"Apache-2.0"
] | 4,335 | 2016-06-15T12:58:31.000Z | 2019-09-23T11:18:43.000Z | src/Functions/left.cpp | chalice19/ClickHouse | 2f38e7bc5c2113935ab86260439bb543a1737291 | [
"Apache-2.0"
] | 1,700 | 2016-06-15T09:25:11.000Z | 2019-09-23T11:16:38.000Z | #include <Functions/FunctionFactory.h>
#include <Functions/LeftRight.h>
namespace DB
{
void registerFunctionLeft(FunctionFactory & factory)
{
factory.registerFunction<FunctionLeftRight<false, SubstringDirection::Left>>(FunctionFactory::CaseInsensitive);
factory.registerFunction<FunctionLeftRight<true, SubstringDirection::Left>>(FunctionFactory::CaseSensitive);
}
}
| 27 | 115 | 0.809524 | chalice19 |
aa7c59166aa6c18afa7647f939283201e04d1acc | 1,155 | hpp | C++ | test/core/fakes/util_fake_string.hpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 731 | 2020-05-07T06:22:59.000Z | 2022-03-31T16:36:03.000Z | test/core/fakes/util_fake_string.hpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 67 | 2020-07-20T19:46:42.000Z | 2022-03-31T15:34:47.000Z | test/core/fakes/util_fake_string.hpp | pit-ray/win-vind | 7386f6f7528d015ce7f1a5ae230d6e63f9492df9 | [
"MIT"
] | 15 | 2021-01-29T04:49:11.000Z | 2022-03-04T22:16:31.000Z | #ifndef _UTIL_FAKE_STRING_HPP
#define _UTIL_FAKE_STRING_HPP
#include "util/string.hpp"
#include <cstring>
#include <cwchar>
#include <string>
namespace vind {
namespace util {
//
// The output string of std::wstring is the fake converted string.
// It is the same bytes as before-string.
//
std::wstring s_to_ws(const std::string& str) {
std::wstring fakestr ;
fakestr.resize(str.size()) ;
std::memcpy(fakestr.data(), str.data(), sizeof(char) * str.size()) ;
return fakestr ;
}
std::string ws_to_s(const std::wstring& wstr) {
std::string out ;
out.resize(wstr.length()) ;
return out ;
}
}
}
// stub function
namespace
{
std::string from_fake_wstr(const std::wstring& str) {
std::string truestr{} ;
auto expected_true_str_length = sizeof(wchar_t) * str.capacity() ;
truestr.resize(expected_true_str_length) ;
std::memcpy(truestr.data(), str.data(), expected_true_str_length) ;
return truestr ;
}
}
#endif
| 26.860465 | 81 | 0.571429 | pit-ray |
aa7f133395e07b517688e9d433f61de49ad78047 | 9,479 | cpp | C++ | src/postprocess/buildex/utility/src/fileparser.cpp | Baltoli/He-2 | c3b20da61d8e0d4878e530fe26affa2ec4a4e717 | [
"MIT"
] | null | null | null | src/postprocess/buildex/utility/src/fileparser.cpp | Baltoli/He-2 | c3b20da61d8e0d4878e530fe26affa2ec4a4e717 | [
"MIT"
] | null | null | null | src/postprocess/buildex/utility/src/fileparser.cpp | Baltoli/He-2 | c3b20da61d8e0d4878e530fe26affa2ec4a4e717 | [
"MIT"
] | null | null | null | // file parser and other file operations are grouped in this file
#include <utility/defines.h>
#include <utility/fileparser.h>
#include <analysis/staticinfo.h>
#include <common/common_defines.h>
#include <common/utilities.h>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
void go_forward_line(std::ifstream& file);
bool go_backward_line(std::ifstream& file);
void go_to_line(uint32_t line_no, std::ifstream& file);
uint32_t go_to_line_dest(std::ifstream& file, uint64_t dest, uint32_t stride);
uint32_t fill_operand(
operand_t* operand, vector<string>& tokens, uint32_t start,
uint32_t version)
{
uint32_t i = start;
operand->type = atoi(tokens[i++].c_str());
operand->width = atoi(tokens[i++].c_str());
if (operand->type == IMM_FLOAT_TYPE) {
operand->float_value = atof(tokens[i++].c_str());
} else {
#ifndef __GNUG__
// operand->value = stoull(tokens[i++].c_str());
operand->value = stoll(tokens[i++]);
#else
operand->value = strtoull(tokens[i++].c_str(), NULL, 10);
#endif
}
if (version == VER_WITH_ADDR_OPND) {
if (operand->type == MEM_STACK_TYPE || operand->type == MEM_HEAP_TYPE) {
/* we need to collect the addr operands */
operand->addr = new operand_t[4];
for (int j = 0; j < 4; j++) {
operand->addr[j].type = atoi(tokens[i++].c_str());
operand->addr[j].width = atoi(tokens[i++].c_str());
#ifndef __GNUG__
operand->addr[j].value = stoull(tokens[i++].c_str());
#else
operand->addr[j].value = strtoull(tokens[i++].c_str(), NULL, 10);
#endif
}
} else {
operand->addr = NULL;
}
} else if (version == VER_NO_ADDR_OPND) {
operand->addr = NULL;
}
return i;
}
/* main file parsing functions */
cinstr_t* get_next_from_ascii_file(ifstream& file, uint32_t version)
{
cinstr_t* instr;
char string_ins[MAX_STRING_LENGTH];
// we need to parse the file here - forward parsing and backward traversal
file.getline(string_ins, MAX_STRING_LENGTH);
string string_cpp(string_ins);
#ifdef DEBUG
#if DEBUG_LEVEL >= 5
cout << string_cpp << endl;
#endif
#endif
instr = NULL;
if (string_cpp.size() > 0) {
instr = new cinstr_t;
vector<string> tokens;
tokens = split(string_cpp, ',');
// now parse the string - this is specific to the string being outputted
instr->opcode = atoi(tokens[0].c_str());
// get the number of destinations
instr->num_dsts = atoi(tokens[1].c_str());
int index = 2;
for (int i = 0; i < instr->num_dsts; i++) {
index = fill_operand(&instr->dsts[i], tokens, index, version);
}
// get the number of sources
instr->num_srcs = atoi(tokens[index++].c_str());
for (int i = 0; i < instr->num_srcs; i++) {
index = fill_operand(&instr->srcs[i], tokens, index, version);
}
instr->eflags = (uint32_t)stoull(tokens[index++].c_str());
instr->pc = atoi(tokens[index++].c_str());
}
#ifdef DEBUG
#if DEBUG_LEVEL >= 5
if (instr != NULL)
print_cinstr(instr);
#endif
#endif
return instr;
}
cinstr_t* get_next_from_bin_file(ifstream& file) { return NULL; }
/* parsing the disasm file */
pair<string, string>
parse_line_disasm(string line, uint32_t* module, uint32_t* app_pc)
{
int i = 0;
string value = "";
while (line[i] != ',') {
value += line[i];
i++;
}
*module = atoi(value.c_str());
i++;
value = "";
while (line[i] != '_') {
value += line[i];
i++;
}
*app_pc = atoi(value.c_str());
i++;
value = "";
while (line[i] != '_') {
value += line[i];
i++;
}
string disasm_string = value;
value = "";
i++;
for (; i < line.size(); i++) {
value += line[i];
}
string module_name = value;
return make_pair(disasm_string, module_name);
}
bool compare_static_info(Static_Info* first, Static_Info* second)
{
if (first->module_no == second->module_no) {
return first->pc < second->pc;
} else {
return first->module_no < second->module_no;
}
}
Static_Info*
parse_debug_disasm(vector<Static_Info*>& static_info, ifstream& file)
{
DEBUG_PRINT(("getting disassembly trace\n"), 2);
while (!file.eof()) {
char string_ins[MAX_STRING_LENGTH];
// we need to parse the file here - forward parsing and backward traversal
file.getline(string_ins, MAX_STRING_LENGTH);
string string_cpp(string_ins);
if (string_cpp.size() > 0) {
uint32_t module_no;
uint32_t app_pc;
pair<string, string> ret
= parse_line_disasm(string_cpp, &module_no, &app_pc);
string disasm_string = ret.first;
string module_name = ret.second;
Static_Info* disasm;
bool found = false;
for (int i = 0; i < static_info.size(); i++) {
if (static_info[i]->module_no == module_no
&& static_info[i]->pc == app_pc) {
disasm = static_info[i];
found = true;
break;
}
}
if (!found) {
disasm = new Static_Info;
disasm->module_no = module_no;
disasm->pc = app_pc;
disasm->disassembly = disasm_string;
disasm->module_name = module_name;
static_info.push_back(disasm);
}
}
}
Static_Info* first = static_info[0];
sort(static_info.begin(), static_info.end(), compare_static_info);
return first;
}
/* advanced instruction oriented file parsing functions */
vector<cinstr_t*> get_all_instructions(ifstream& file, uint32_t version)
{
vector<cinstr_t*> instrs;
while (!file.eof()) {
cinstr_t* instr = get_next_from_ascii_file(file, version);
if (instr != NULL) {
instrs.push_back(instr);
}
}
return instrs;
}
vec_cinstr walk_file_and_get_instructions(
ifstream& file, vector<Static_Info*>& static_info, uint32_t version)
{
cinstr_t* instr;
Static_Info* info;
vec_cinstr instrs;
uint32_t count = 0;
DEBUG_PRINT(("getting dynamic instruction trace from file\n"), 2);
while (!file.eof()) {
instr = get_next_from_ascii_file(file, version);
count++;
if (instr != NULL) {
info = get_static_info(static_info, instr->pc);
if (info == NULL) {
DEBUG_PRINT(
("WARNING: static disassembly not found %d, %d\n", instr->pc,
count),
2);
Static_Info* stat = new Static_Info;
stat->pc = instr->pc;
stat->disassembly = "unknown";
stat->module_no = 65535;
stat->module_name = "unknown";
static_info.push_back(stat);
info = stat;
}
// ASSERT_MSG((info != NULL), ("ERROR: static disassembly not found %d,
// %d\n",instr->pc, count));
instrs.push_back(make_pair(instr, info));
}
}
sort(static_info.begin(), static_info.end(), compare_static_info);
return instrs;
}
void reverse_file(ofstream& out, ifstream& in)
{
char value[MAX_STRING_LENGTH];
in.seekg(-1, ios::end);
in.clear();
bool check = true;
while (check) {
go_backward_line(in);
in.getline(value, MAX_STRING_LENGTH);
out << value << endl;
// cout << value << endl;
check = go_backward_line(in);
}
}
/* generic helper functions for file parsing */
void go_to_line(uint line_no, ifstream& file)
{
file.seekg(file.beg);
uint current_line = 0;
char dummystr[MAX_STRING_LENGTH];
while (current_line < line_no - 1) {
file.getline(dummystr, MAX_STRING_LENGTH);
current_line++;
}
}
void go_forward_line(ifstream& file)
{
char array[MAX_STRING_LENGTH];
file.getline(array, MAX_STRING_LENGTH);
}
bool go_backward_line(ifstream& file)
{
int value = '\0';
unsigned int pos;
file.seekg(-1, ios::cur);
pos = file.tellg();
while ((value != '\n') && (pos != 0)) {
file.seekg(-1, ios::cur);
value = file.peek();
pos = file.tellg();
}
pos = file.tellg();
if (pos == 0) {
return false;
}
file.seekg(1, ios::cur);
return true;
}
uint32_t go_to_line_dest(
ifstream& file, uint64_t dest, uint32_t stride, uint32_t version)
{
/* assume that the file is at the beginning*/
uint32_t lineno = 0;
cinstr_t* instr;
while (!file.eof()) {
instr = get_next_from_ascii_file(file, version);
lineno++;
if (instr != NULL) {
for (int i = 0; i < instr->num_dsts; i++) {
if ((instr->dsts[i].value == dest)
&& (instr->dsts[i].width == stride)) {
DEBUG_PRINT(("found - pc %d\n", instr->pc), 4);
return lineno;
}
}
}
delete instr;
}
return 0;
}
/* debug routines */
void walk_instructions(ifstream& file, uint32_t version)
{
cinstr_t* instr;
rinstr_t* rinstr;
int no_rinstrs;
while (!file.eof()) {
instr = get_next_from_ascii_file(file, version);
if (instr != NULL) {
rinstr = cinstr_to_rinstrs(instr, no_rinstrs, "", 0);
delete[] rinstr;
}
delete instr;
}
}
void print_disasm(vector<Static_Info*>& static_info)
{
for (int i = 0; i < static_info.size(); i++) {
// LOG(log_file,static_info[i]->module_no << "," << static_info[i]->pc <<
// "," << static_info[i]->disassembly << endl)
LOG(log_file, static_info[i]->disassembly << endl);
}
}
string get_disasm_string(vector<Static_Info*>& static_info, uint32_t app_pc)
{
for (int i = 0; i < static_info.size(); i++) {
if (static_info[i]->pc == app_pc) {
return static_info[i]->disassembly;
}
}
return "";
}
| 22.462085 | 78 | 0.622323 | Baltoli |
aa838803d3c90f97d190a710bf84c303df627919 | 4,477 | hpp | C++ | frontend/services/lua_service_wrapper/Lua_Service_Wrapper.hpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | 49 | 2017-08-23T13:24:24.000Z | 2022-03-16T09:10:58.000Z | frontend/services/lua_service_wrapper/Lua_Service_Wrapper.hpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | 200 | 2018-07-20T15:18:26.000Z | 2022-03-31T11:01:44.000Z | frontend/services/lua_service_wrapper/Lua_Service_Wrapper.hpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | 31 | 2017-07-31T16:19:29.000Z | 2022-02-14T23:41:03.000Z | /*
* Lua_Service_Wrapper.hpp
*
* Copyright (C) 2020 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#pragma once
#include "AbstractFrontendService.hpp"
#include "ScriptPaths.h"
#include "mmcore/LuaAPI.h"
#include "LuaCallbacksCollection.h"
namespace megamol {
namespace frontend {
// the Lua Service Wrapper wraps the LuaAPI for use as a frontend service
// the main problem this wrapper addresses is the requirement that Lua scripts
// want to issue a "render frame" (mmFlush, mmRenderNextFrame) command that needs to be executed as a callback in the Lua context,
// the flush has to advance the rendering for one frame, which is the job of the main loop
// but since Lua is itself part of the main loop there arises the problem of Lua recursively calling itself
//
// thus the LuaAPI has two conflicting goals:
// 1) we want it to be a frontend service like all other services
// 2) it (sometimes) needs to take control of the megamol main loop and issue a series of frame flushes from inside a
// Lua callback, without recursively calling itself
//
// this wrapper solves this issue by recognizing when it is executed from inside a Lua callback
// if executed from the normal main loop, the wrapper executes lua
// if executed from inside the lua frame flush callback, it does not call the wrapped LuaAPI object, thus eliminating
// risk of recursive Lua calls
//
// also, the wrapper manages communication with the lua remote console by
// receiving lua requests and executing them via the wrapped LuaAPI object
// the multithreaded ZMQ networking logic is implemented in LuaHostService.h in the core
class Lua_Service_Wrapper final : public AbstractFrontendService {
public:
struct Config {
std::string host_address;
megamol::core::LuaAPI* lua_api_ptr =
nullptr; // lua api object that will be used/called by the service wrapper only one level deep
bool retry_socket_port = false;
bool show_version_notification = true;
};
// sometimes somebody wants to know the name of the service
std::string serviceName() const override {
return "Lua_Service_Wrapper";
}
// constructor should not take arguments, actual object initialization deferred until init()
Lua_Service_Wrapper();
~Lua_Service_Wrapper();
// your service will be constructed and destructed, but not copy-constructed or move-constructed
// so no need to worry about copy or move constructors.
// init service with input config data, e.g. init GLFW with OpenGL and open window with certain decorations/hints
// if init() fails return false (this will terminate program execution), on success return true
bool init(const Config& config);
bool init(void* configPtr) override;
void close() override;
std::vector<FrontendResource>& getProvidedResources() override;
const std::vector<std::string> getRequestedResourceNames() const override;
void setRequestedResources(std::vector<FrontendResource> resources) override;
void updateProvidedResources() override;
void digestChangedRequestedResources() override;
void resetProvidedResources() override;
void preGraphRender() override;
void postGraphRender() override;
// int setPriority(const int p) // priority initially 0
// int getPriority() const;
// bool shouldShutdown() const; // shutdown initially false
// void setShutdown(const bool s = true);
private:
Config m_config;
int m_service_recursion_depth = 0;
// auto-deleted opaque ZMQ networking object from LuaHostService.h
std::unique_ptr<void, std::function<void(void*)>> m_network_host_pimpl;
std::vector<FrontendResource> m_providedResourceReferences;
std::vector<std::string> m_requestedResourcesNames;
std::vector<FrontendResource> m_requestedResourceReferences;
std::list<megamol::frontend_resources::LuaCallbacksCollection> m_callbacks;
megamol::frontend_resources::ScriptPaths m_scriptpath_resource;
std::function<std::tuple<bool, std::string>(std::string const&)> m_executeLuaScript_resource;
std::function<void(std::string const&)> m_setScriptPath_resource;
std::function<void(megamol::frontend_resources::LuaCallbacksCollection const&)> m_registerLuaCallbacks_resource;
void fill_frontend_resources_callbacks(void* callbacks_collection_ptr);
void fill_graph_manipulation_callbacks(void* callbacks_collection_ptr);
};
} // namespace frontend
} // namespace megamol
| 41.841121 | 130 | 0.755193 | xge |
aa88b67294f221a8b29910587df848b66fafbbe6 | 936 | hpp | C++ | LinearAlgebra/operation/equal/equal.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | LinearAlgebra/operation/equal/equal.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | LinearAlgebra/operation/equal/equal.hpp | suiyili/Algorithms | d6ddc8262c5d681ecc78938b6140510793a29d91 | [
"MIT"
] | null | null | null | #pragma once
#include "equal.h"
#include "operation/utility.hpp"
#include <type_traits>
#include <cmath>
namespace algebra::arithmetic {
template <typename T>
inline bool are_equal(const algebra_vector<T> &left, const algebra_vector<T> &right) {
ensure_match(left, right);
if constexpr (std::is_floating_point_v<T>)
return std::abs((left - right).min()) < epsilon<T>;
else
return (left == right).min();
}
template <typename T>
inline bool operator==(const matrix<T> &left, const matrix<T> &right) {
ensure_match(left, right);
for (size_t i = 0U; i < left.columns(); ++i) {
for (size_t j = 0U; j < left.rows(); ++j) {
pixel id{i, j};
if constexpr (std::is_integral_v<T>) {
if (left[id] != right[id]) return false;
} else {
if (epsilon<T> <= std::abs(left[id] - right[id])) return false;
}
}
}
return true;
}
} // namespace algebra::arithmetic | 26 | 86 | 0.617521 | suiyili |
aa895fed680a6d5af9e6b8fd0ebc1a0f60d95832 | 1,192 | cpp | C++ | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab7(Array Based Queue)/quetype(2).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab7(Array Based Queue)/quetype(2).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | CSE 225L Data Structures and Algorithms/Resources/Codes Previous/Spring-2019-CSE225 1/Lab7(Array Based Queue)/quetype(2).cpp | diptu/Teaching | 20655bb2c688ae29566b0a914df4a3e5936a2f61 | [
"MIT"
] | null | null | null | #include"quetype.h"
#include <iostream>
using namespace std;
template<class ItemType>
QueType<ItemType>::QueType(int max)
{
maxQue=max+1;
front=maxQue-1;
rear=maxQue-1;
items=new ItemType[maxQue];
}
template<class ItemType>
QueType<ItemType>::QueType()
{
maxQue=501;
front=maxQue-1;
rear=maxQue-1;
items=new ItemType[maxQue];
}
template<class ItemType>
QueType<ItemType>::~QueType()
{
delete [] items;
}
template<class ItemType>
void QueType<ItemType>::MakeEmpty()
{
front=maxQue-1;
rear=maxQue-1;
}
template<class ItemType>
bool QueType<ItemType>::IsEmpty()
{
return (front==rear);
}
template<class ItemType>
bool QueType<ItemType>::IsFull()
{
return (((rear+1)%maxQue==front));
}
template<class ItemType>
void QueType<ItemType>::Enqueue(ItemType newItem)
{
try
{
if(IsFull())
throw FullQueue();
rear=(rear+1)%maxQue;
items[rear]=newItem;
}
catch(FullQueue f)
{
cout<<"Queue Overflow"<<endl;
}
}
template<class ItemType>
void QueType<ItemType>::Dequeue(ItemType& item)
{
if(IsEmpty())
throw EmptyQueue();
front=(front+1)%maxQue;
item=items[front];
}
| 16.328767 | 49 | 0.647651 | diptu |
aa8a6dd9e66a1cc30715a03dc91c0460308b3560 | 14,899 | hpp | C++ | src/Core/CommandBuffer.hpp | Shmaug/Stratum | 036eccb824867b019c6ed3c589cfb171e9350c0c | [
"MIT"
] | 4 | 2019-12-13T19:29:39.000Z | 2022-02-15T05:51:47.000Z | src/Core/CommandBuffer.hpp | Shmaug/Stratum | 036eccb824867b019c6ed3c589cfb171e9350c0c | [
"MIT"
] | 2 | 2020-04-08T19:59:31.000Z | 2021-06-14T04:29:42.000Z | src/Core/CommandBuffer.hpp | Shmaug/Stratum | 036eccb824867b019c6ed3c589cfb171e9350c0c | [
"MIT"
] | 4 | 2020-03-03T01:29:10.000Z | 2022-02-15T05:51:52.000Z | #pragma once
#include "Fence.hpp"
#include "Framebuffer.hpp"
#include "Pipeline.hpp"
#include <Common/Profiler.hpp>
namespace stm {
class CommandBuffer : public DeviceResource {
public:
// assumes a CommandPool has been created for this_thread in queueFamily
STRATUM_API CommandBuffer(Device& device, const string& name, Device::QueueFamily* queueFamily, vk::CommandBufferLevel level = vk::CommandBufferLevel::ePrimary);
STRATUM_API ~CommandBuffer();
inline vk::CommandBuffer& operator*() { return mCommandBuffer; }
inline vk::CommandBuffer* operator->() { return &mCommandBuffer; }
inline const vk::CommandBuffer& operator*() const { return mCommandBuffer; }
inline const vk::CommandBuffer* operator->() const { return &mCommandBuffer; }
inline Fence& completion_fence() const { return *mCompletionFence; }
inline Device::QueueFamily* queue_family() const { return mQueueFamily; }
inline const shared_ptr<Framebuffer>& bound_framebuffer() const { return mBoundFramebuffer; }
inline uint32_t subpass_index() const { return mSubpassIndex; }
inline const shared_ptr<Pipeline>& bound_pipeline() const { return mBoundPipeline; }
inline const shared_ptr<DescriptorSet>& bound_descriptor_set(uint32_t index) const { return mBoundDescriptorSets[index]; }
// Label a region for a tool such as RenderDoc
STRATUM_API void begin_label(const string& label, const Array4f& color = { 1,1,1,0 });
STRATUM_API void end_label();
STRATUM_API void reset(const string& name = "Command Buffer");
inline bool clear_if_done() {
if (mState == CommandBufferState::eInFlight)
if (mCompletionFence->status() == vk::Result::eSuccess) {
mState = CommandBufferState::eDone;
clear();
return true;
}
return mState == CommandBufferState::eDone;
}
// Add a resource to the device's resource pool after this commandbuffer finishes executing
template<derived_from<DeviceResource> T>
inline T& hold_resource(const shared_ptr<T>& r) {
r->mTracking.emplace(this);
return *static_cast<T*>(mHeldResources.emplace( static_pointer_cast<DeviceResource>(r) ).first->get());
}
template<typename T>
inline const Buffer::View<T>& hold_resource(const Buffer::View<T>& v) {
hold_resource(v.buffer());
return v;
}
inline const Buffer::TexelView& hold_resource(const Buffer::TexelView& v) {
hold_resource(v.buffer());
return v;
}
inline const Buffer::StrideView& hold_resource(const Buffer::StrideView& v) {
hold_resource(v.buffer());
return v;
}
inline const Image::View& hold_resource(const Image::View& v) {
hold_resource(v.image());
return v;
}
inline void barrier(const vk::ArrayProxy<const vk::MemoryBarrier>& b, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage) {
mCommandBuffer.pipelineBarrier(srcStage, dstStage, {}, b, {}, {});
}
inline void barrier(const vk::ArrayProxy<const vk::BufferMemoryBarrier>& b, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage) {
mCommandBuffer.pipelineBarrier(srcStage, dstStage, {}, {}, b, {});
}
inline void barrier(const vk::ArrayProxy<const vk::ImageMemoryBarrier>& b, vk::PipelineStageFlags srcStage, vk::PipelineStageFlags dstStage) {
mCommandBuffer.pipelineBarrier(srcStage, dstStage, {}, {}, {}, b);
}
template<typename T = byte>
inline void barrier(const Buffer::View<T>& buffer, vk::PipelineStageFlags srcStage, vk::AccessFlags srcAccessMask, vk::PipelineStageFlags dstStage, vk::AccessFlags dstAccessMask) {
barrier(vk::BufferMemoryBarrier(srcAccessMask, dstAccessMask, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED, **buffer.buffer(), buffer.offset(), buffer.size_bytes()), srcStage, dstStage);
}
template<typename T = byte, typename S = T>
inline const Buffer::View<S>& copy_buffer(const Buffer::View<T>& src, const Buffer::View<S>& dst) {
if (src.size_bytes() > dst.size_bytes()) throw invalid_argument("src size must be less than or equal to dst size");
mCommandBuffer.copyBuffer(*hold_resource(src.buffer()), *hold_resource(dst.buffer()), { vk::BufferCopy(src.offset(), dst.offset(), src.size_bytes()) });
return dst;
}
template<typename T = byte>
inline Buffer::View<T> copy_buffer(const Buffer::View<T>& src, vk::BufferUsageFlagBits bufferUsage, VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY) {
shared_ptr<Buffer> dst = make_shared<Buffer>(mDevice, src.buffer()->name(), src.size_bytes(), bufferUsage|vk::BufferUsageFlagBits::eTransferDst, memoryUsage);
mCommandBuffer.copyBuffer(*hold_resource(src.buffer()), *hold_resource(dst), { vk::BufferCopy(src.offset(), 0, src.size_bytes()) });
return Buffer::View<T>(dst);
}
template<typename T = byte>
inline Buffer::View<T> copy_buffer(const buffer_vector<T>& src, vk::BufferUsageFlagBits bufferUsage, VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY) {
shared_ptr<Buffer> dst = make_shared<Buffer>(mDevice, src.buffer()->name(), src.size_bytes(), bufferUsage|vk::BufferUsageFlagBits::eTransferDst, memoryUsage);
mCommandBuffer.copyBuffer(*hold_resource(src.buffer()), *hold_resource(dst), { vk::BufferCopy(0, 0, src.size_bytes()) });
return Buffer::View<T>(dst);
}
inline const Image::View& clear_color_image(const Image::View& img, const vk::ClearColorValue& clear) {
img.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal);
mCommandBuffer.clearColorImage(*hold_resource(img.image()), vk::ImageLayout::eTransferDstOptimal, clear, img.subresource_range());
return img;
}
inline const Image::View& clear_color_image(const Image::View& img, const vk::ClearDepthStencilValue& clear) {
img.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal);
mCommandBuffer.clearDepthStencilImage(*hold_resource(img.image()), vk::ImageLayout::eTransferDstOptimal, clear, img.subresource_range());
return img;
}
inline const Image::View& blit_image(const Image::View& src, const Image::View& dst, vk::Filter filter = vk::Filter::eLinear) {
src.transition_barrier(*this, vk::ImageLayout::eTransferSrcOptimal);
dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal);
vector<vk::ImageBlit> blits(src.subresource_range().levelCount);
for (uint32_t i = 0; i < blits.size(); i++) {
array<vk::Offset3D,2> srcOffset;
srcOffset[1].x = src.extent().width;
srcOffset[1].y = src.extent().height;
srcOffset[1].z = src.extent().depth;
array<vk::Offset3D,2> dstOffset;
dstOffset[1].x = dst.extent().width;
dstOffset[1].y = dst.extent().height;
dstOffset[1].z = dst.extent().depth;
blits[i] = vk::ImageBlit(src.subresource(i), srcOffset, src.subresource(i), dstOffset);
}
mCommandBuffer.blitImage(*hold_resource(src.image()), vk::ImageLayout::eTransferSrcOptimal, *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, blits, filter);
return dst;
}
inline const Image::View& copy_image(const Image::View& src, const Image::View& dst) {
src.transition_barrier(*this, vk::ImageLayout::eTransferSrcOptimal);
dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal);
vector<vk::ImageCopy> copies(src.subresource_range().levelCount);
for (uint32_t i = 0; i < copies.size(); i++)
copies[i] = vk::ImageCopy(src.subresource(i), vk::Offset3D{}, src.subresource(i), vk::Offset3D{}, src.extent());
mCommandBuffer.copyImage(*hold_resource(src.image()), vk::ImageLayout::eTransferSrcOptimal, *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, copies);
return dst;
}
inline const Image::View& resolve_image(const Image::View& src, const Image::View& dst) {
src.transition_barrier(*this, vk::ImageLayout::eTransferSrcOptimal);
dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal);
vector<vk::ImageResolve> resolves(src.subresource_range().levelCount);
for (uint32_t i = 0; i < resolves.size(); i++)
resolves[i] = vk::ImageResolve(src.subresource(i), vk::Offset3D{}, src.subresource(i), vk::Offset3D{}, src.extent());
mCommandBuffer.resolveImage(*hold_resource(src.image()), vk::ImageLayout::eTransferSrcOptimal, *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, resolves);
return dst;
}
template<typename T = byte>
inline const Image::View& copy_buffer_to_image(const Buffer::View<T>& src, const Image::View& dst) {
vector<vk::BufferImageCopy> copies(dst.subresource_range().levelCount);
for (uint32_t i = 0; i < dst.subresource_range().levelCount; i++)
copies[i] = vk::BufferImageCopy(src.offset(), 0, 0, dst.subresource(i), {}, dst.extent());
dst.transition_barrier(*this, vk::ImageLayout::eTransferDstOptimal);
mCommandBuffer.copyBufferToImage(*hold_resource(src.buffer()), *hold_resource(dst.image()), vk::ImageLayout::eTransferDstOptimal, copies);
return dst;
}
inline void dispatch(const vk::Extent2D& dim) { mCommandBuffer.dispatch(dim.width, dim.height, 1); }
inline void dispatch(const vk::Extent3D& dim) { mCommandBuffer.dispatch(dim.width, dim.height, dim.depth); }
inline void dispatch(uint32_t x, uint32_t y=1, uint32_t z=1) { mCommandBuffer.dispatch(x, y, z); }
// dispatch on ceil(size / workgroupSize)
inline void dispatch_over(const vk::Extent2D& dim) {
auto cp = dynamic_pointer_cast<ComputePipeline>(mBoundPipeline);
mCommandBuffer.dispatch(
(dim.width + cp->workgroup_size()[0] - 1) / cp->workgroup_size()[0],
(dim.height + cp->workgroup_size()[1] - 1) / cp->workgroup_size()[1],
1);
}
inline void dispatch_over(const vk::Extent3D& dim) {
auto cp = dynamic_pointer_cast<ComputePipeline>(mBoundPipeline);
mCommandBuffer.dispatch(
(dim.width + cp->workgroup_size()[0] - 1) / cp->workgroup_size()[0],
(dim.height + cp->workgroup_size()[1] - 1) / cp->workgroup_size()[1],
(dim.depth + cp->workgroup_size()[2] - 1) / cp->workgroup_size()[2]);
}
inline void dispatch_over(uint32_t x, uint32_t y = 1, uint32_t z = 1) { return dispatch_over(vk::Extent3D(x,y,z)); }
STRATUM_API void begin_render_pass(const shared_ptr<RenderPass>& renderPass, const shared_ptr<Framebuffer>& framebuffer, const vk::Rect2D& renderArea, const vk::ArrayProxyNoTemporaries<const vk::ClearValue>& clearValues, vk::SubpassContents contents = vk::SubpassContents::eInline);
STRATUM_API void next_subpass(vk::SubpassContents contents = vk::SubpassContents::eInline);
STRATUM_API void end_render_pass();
inline bool bind_pipeline(const shared_ptr<Pipeline>& pipeline) {
if (mBoundPipeline == pipeline) return false;
mCommandBuffer.bindPipeline(pipeline->bind_point(), **pipeline);
mBoundPipeline = pipeline;
hold_resource(pipeline);
return true;
}
template<typename T>
inline void push_constant(const string& name, const T& value) {
auto it = mBoundPipeline->push_constants().find(name);
if (it == mBoundPipeline->push_constants().end()) throw invalid_argument("push constant not found");
const auto& range = it->second;
if constexpr (ranges::contiguous_range<T>) {
if (range.size != ranges::size(value)*sizeof(ranges::range_value_t<T>)) throw invalid_argument("argument size must match push constant size (" + to_string(range.size) +")");
mCommandBuffer.pushConstants(mBoundPipeline->layout(), range.stageFlags, range.offset, range.size, ranges::data(value));
} else {
if (range.size != sizeof(T)) throw invalid_argument("argument size must match push constant size (" + to_string(range.size) +")");
mCommandBuffer.pushConstants(mBoundPipeline->layout(), range.stageFlags, range.offset, sizeof(T), &value);
}
}
STRATUM_API void bind_descriptor_set(uint32_t index, const shared_ptr<DescriptorSet>& descriptorSet, const vk::ArrayProxy<const uint32_t>& dynamicOffsets);
inline void bind_descriptor_set(uint32_t index, const shared_ptr<DescriptorSet>& descriptorSet) {
if (index < mBoundDescriptorSets.size() && mBoundDescriptorSets[index] == descriptorSet) return;
bind_descriptor_set(index, descriptorSet, {});
}
template<typename T=byte>
inline void bind_vertex_buffer(uint32_t index, const Buffer::View<T>& view) {
auto& b = mBoundVertexBuffers[index];
if (b != view) {
b = view;
mCommandBuffer.bindVertexBuffers(index, **view.buffer(), view.offset());
hold_resource(view);
}
}
template<ranges::input_range R>
inline void bind_vertex_buffers(uint32_t index, const R& views) {
vector<vk::Buffer> bufs(views.size());
vector<vk::DeviceSize> offsets(views.size());
bool needBind = false;
uint32_t i = 0;
for (const auto& v : views) {
bufs[i] = **v.buffer();
offsets[i] = v.offset();
if (mBoundVertexBuffers[index + i] != v) {
needBind = true;
mBoundVertexBuffers[index + i] = v;
hold_resource(v);
}
i++;
}
if (needBind) mCommandBuffer.bindVertexBuffers(index, bufs, offsets);
}
inline void bind_index_buffer(const Buffer::StrideView& view) {
if (mBoundIndexBuffer != view) {
mBoundIndexBuffer = view;
vk::IndexType type;
if (view.stride() == sizeof(uint32_t)) type = vk::IndexTypeValue<uint32_t>::value;
else if (view.stride() == sizeof(uint16_t)) type = vk::IndexTypeValue<uint16_t>::value;
else if (view.stride() == sizeof(uint8_t)) type = vk::IndexTypeValue<uint8_t>::value;
else throw invalid_argument("invalid stride for index buffer");
mCommandBuffer.bindIndexBuffer(**view.buffer(), view.offset(), type);
hold_resource(view);
}
}
inline Buffer::View<byte> current_vertex_buffer(uint32_t index) {
auto it = mBoundVertexBuffers.find(index);
if (it == mBoundVertexBuffers.end()) return {};
else return it->second;
}
inline const Buffer::StrideView& current_index_buffer() { return mBoundIndexBuffer; }
size_t mPrimitiveCount;
private:
friend class Device;
enum class CommandBufferState { eRecording, eInFlight, eDone };
STRATUM_API void clear();
vk::CommandBuffer mCommandBuffer;
Device::QueueFamily* mQueueFamily;
vk::CommandPool mCommandPool;
CommandBufferState mState;
unique_ptr<Fence> mCompletionFence;
unordered_set<shared_ptr<DeviceResource>> mHeldResources;
// Currently bound objects
shared_ptr<Framebuffer> mBoundFramebuffer;
uint32_t mSubpassIndex = 0;
shared_ptr<Pipeline> mBoundPipeline = nullptr;
unordered_map<uint32_t, Buffer::View<byte>> mBoundVertexBuffers;
Buffer::StrideView mBoundIndexBuffer;
vector<shared_ptr<DescriptorSet>> mBoundDescriptorSets;
};
inline bool DeviceResource::in_use() {
while (!mTracking.empty()) {
if (!(*mTracking.begin())->clear_if_done())
return true;
}
return !mTracking.empty();
}
class ProfilerRegion {
private:
CommandBuffer* mCommandBuffer;
public:
inline ProfilerRegion(const string& label) : ProfilerRegion(label, nullptr) {}
inline ProfilerRegion(const string& label, CommandBuffer& cmd) : ProfilerRegion(label, &cmd) {}
inline ProfilerRegion(const string& label, CommandBuffer* cmd) : mCommandBuffer(cmd) {
Profiler::begin_sample(label);
if (mCommandBuffer) mCommandBuffer->begin_label(label);
}
inline ~ProfilerRegion() {
if (mCommandBuffer) mCommandBuffer->end_label();
Profiler::end_sample();
}
};
} | 47.906752 | 283 | 0.739177 | Shmaug |
aa8a722a066aa06e84a349f81f0ccfc22909efa5 | 451 | hpp | C++ | code/geodb/utility/as_const.hpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/geodb/utility/as_const.hpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | code/geodb/utility/as_const.hpp | mbeckem/msc | 93e71ba163a7ffef4eec3e83934fa793f3f50ff6 | [
"MIT"
] | null | null | null | #ifndef GEODB_UTILITY_AS_CONST_HPP
#define GEODB_UTILITY_AS_CONST_HPP
#include "geodb/common.hpp"
#include "geodb/type_traits.hpp"
/// \file
/// Const casting utilities.
namespace geodb {
template<typename T>
const T* as_const(const T* ptr) {
return ptr;
}
template<typename T, disable_if_t<std::is_pointer<T>::value>* = nullptr>
const T& as_const(const T& ref) {
return ref;
}
} // namespace geodb
#endif // GEODB_UTILITY_AS_CONST_HPP
| 18.04 | 72 | 0.733925 | mbeckem |
aa8af9ea3459db52b692e8c8a1708ae27e1f1964 | 346 | cpp | C++ | docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_12.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_12.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/atl-mfc-shared/reference/codesnippet/CPP/cfile-class_12.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | //example for CFile::Remove
TCHAR* pFileName = _T("Remove_File.dat");
try
{
CFile::Remove(pFileName);
}
catch (CFileException* pEx)
{
TRACE(_T("File %20s cannot be removed\n"), pFileName);
pEx->Delete();
} | 31.454545 | 69 | 0.416185 | bobbrow |
aa8c47b70bc69e0039c64ad542d5321b16783173 | 7,906 | cpp | C++ | ChaosEngine/MaterialImporter.cpp | adrianam4/Chaos-Engine | 2bc5693c0c25118ec58331c4311eac68c94d4d19 | [
"MIT"
] | null | null | null | ChaosEngine/MaterialImporter.cpp | adrianam4/Chaos-Engine | 2bc5693c0c25118ec58331c4311eac68c94d4d19 | [
"MIT"
] | null | null | null | ChaosEngine/MaterialImporter.cpp | adrianam4/Chaos-Engine | 2bc5693c0c25118ec58331c4311eac68c94d4d19 | [
"MIT"
] | null | null | null | #include "Application.h"
#include "MaterialImporter.h"
#include "ResourceMaterial.h"
#include "DevIL/include/il.h"
#include "DevIL/include/ilu.h"
#include "DevIL/include/ilut.h"
#include <string>
MaterialImporter::MaterialImporter()
{
}
MaterialImporter::~MaterialImporter()
{
}
void MaterialImporter::SaveMaterial(std::string sourcePath, std::string compression)
{
ILuint size;
ILubyte* data;
ILint compressionMethod = IL_DXT5;
if (compression == "IL_DXT_NO_COMP")
compressionMethod = IL_DXT_NO_COMP;
if (compression == "IL_DXT1")
compressionMethod = IL_DXT1;
if (compression == "IL_DXT2")
compressionMethod = IL_DXT2;
if (compression == "IL_DXT3")
compressionMethod = IL_DXT3;
if (compression == "IL_DXT4")
compressionMethod = IL_DXT4;
if (compression == "IL_DXT5")
compressionMethod = IL_DXT5;
ilSetInteger(IL_DXTC_FORMAT, compressionMethod);
size = ilSaveL(IL_DDS, nullptr, 0);
std::string auxPath = std::string(sourcePath);
unsigned auxCreateLast = auxPath.find_last_of(".");
std::string auxCreatePath = auxPath.substr(auxCreateLast, auxPath.length() - auxCreateLast);
if (auxCreatePath != ".dds")
{
unsigned start = auxPath.find_last_of("\\");
if (start > 10000)
start = auxPath.find_last_of("/");
auxPath = "Library/Textures/" + auxPath.substr(start + 1, auxPath.length() - start - 4) + "dds";
if (size > 0)
{
data = new ILubyte[size];
if (ilSaveL(IL_DDS, data, size) > 0)
App->fileSystem->Save(auxPath.c_str(), data, size);
delete[] data;
}
}
ddsPath = auxPath;
}
std::vector<int> MaterialImporter::ImportMaterial(std::string sourcePath, bool isDropped, ResourceMatertial* resource)
{
std::vector<int> toReturn;
ILboolean success;
glGenTextures(1, &textId);
glBindTexture(GL_TEXTURE_2D, textId);
toReturn.push_back(textId);
ilGenImages(1, &imageId);
ilBindImage(imageId);
success = ilLoadImage(sourcePath.c_str());
if (resource != nullptr)
{
SaveMaterial(sourcePath.c_str(), resource->metaData.compression);
if (resource->metaData.mipMap)
iluBuildMipmaps();
if (resource->metaData.alienifying)
iluAlienify();
if (resource->metaData.avgBlurring)
iluBlurAvg(resource->metaData.amountAvBlur);
if (resource->metaData.gausianBlurring)
iluBlurGaussian(resource->metaData.amountGausianBlur);
if (resource->metaData.contrast)
iluContrast(resource->metaData.amountContrast);
if (resource->metaData.equalization)
iluEqualize();
if (resource->metaData.gammaCorrection)
iluGammaCorrect(resource->metaData.amountGammaCorrection);
if (resource->metaData.negativity)
iluNegative();
if (resource->metaData.noise)
iluNoisify(resource->metaData.amountNoise);
if (resource->metaData.pixelization)
iluPixelize(resource->metaData.amountPixelation);
if (resource->metaData.sharpering)
iluSharpen(resource->metaData.sharpenFactor, resource->metaData.sharpenIters);
}
else SaveMaterial(sourcePath.c_str(), "IL_DXT5");
w = ilGetInteger(IL_IMAGE_WIDTH);
h = ilGetInteger(IL_IMAGE_HEIGHT);
toReturn.push_back(w);
toReturn.push_back(h);
if (success)
{
success = ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
if (!success)
{
std::cout << "Could not convert image :: " << sourcePath << std::endl;
ilDeleteImages(1, &imageId);
}
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
data = ilGetData();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glBindTexture(GL_TEXTURE_2D, 0);
unsigned start = sourcePath.find_last_of(".");
if (sourcePath.substr(start,sourcePath.length()-start) != ".dds")
{
glDeleteTextures(1, &textId);
}
ilDeleteImages(1, &imageId);
int toFound;
int a;
if (!isDropped)
{
for (a = 0; a < App->renderer3D->models.size(); a++)
{
if (App->editor->objectSelected->id == App->renderer3D->models[a].id)
{
for (int b = 0; b < App->renderer3D->models[a].meshes.size(); b++)
{
glDeleteTextures(1, &App->renderer3D->models[a].meshes[b].textureId);
ilDeleteImages(1, &imageId);
App->renderer3D->models[a].meshes[b].textureId = textId;
}
break;
}
}
}
if (isDropped)
{
toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::CUBE);
if (toFound != -1)
{
for (a = 0; a < App->scene->gameObjects.size() - 1; a++)
{
if (App->editor->objectSelected->id == App->editor->cubes[a]->id)
{
break;
}
}
glDeleteTextures(1, &App->editor->cubes[a]->aTextureId);
ilDeleteImages(1, &App->editor->cubes[a]->imageID);
App->editor->cubes[a]->aTextureId = textId;
}
else {
toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::CYLINDER);
if (toFound != -1)
{
for (a = 0; a < App->scene->gameObjects.size() - 1; a++)
{
if (App->editor->objectSelected->id == App->editor->cylinders[a]->id)
{
break;
}
}
glDeleteTextures(1, &App->editor->cylinders[a]->aTextureId);
ilDeleteImages(1, &App->editor->cylinders[a]->imageID);
App->editor->cylinders[a]->aTextureId = textId;
}
else {
toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::PYRAMID);
if (toFound != -1)
{
for (a = 0; a < App->scene->gameObjects.size() - 1; a++)
{
if (App->editor->objectSelected->id == App->editor->pyramids[a]->id)
{
break;
}
}
glDeleteTextures(1, &App->editor->pyramids[a]->aTextureId);
ilDeleteImages(1, &App->editor->pyramids[a]->imageID);
App->editor->pyramids[a]->aTextureId = textId;
}
else
{
toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::SPHERE);
if (toFound != -1)
{
for (a = 0; a < App->scene->gameObjects.size() - 1; a++)
{
if (App->editor->objectSelected->id == App->editor->spheres[a]->id)
{
break;
}
}
glDeleteTextures(1, &App->editor->spheres[a]->aTextureId);
ilDeleteImages(1, &App->editor->spheres[a]->imageID);
App->editor->spheres[a]->aTextureId = textId;
}
else {
toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::MESH);
if (toFound != -1)
{
for (a = 0; a < App->scene->gameObjects.size() - 1; a++)
{
if (App->editor->objectSelected->id == App->renderer3D->models[a].id)
{
break;
}
}
for (int b = 0; b < App->renderer3D->models[a].meshes.size(); b++)
{
glDeleteTextures(1, &App->renderer3D->models[a].meshes[b].textureId);
ilDeleteImages(1, &imageId);
App->renderer3D->models[a].meshes[b].textureId = textId;
}
}
else
{
toFound = App->editor->objectSelected->SearchComponent(App->editor->objectSelected, ComponentType::PLANE);
if (toFound != -1)
{
for (a = 0; a < App->scene->gameObjects.size() - 1; a++)
{
if (App->editor->objectSelected->id == App->editor->planes[a]->id)
{
break;
}
}
glDeleteTextures(1, &App->editor->planes[a]->aTextureId);
ilDeleteImages(1, &App->editor->planes[a]->imageID);
App->editor->planes[a]->aTextureId = textId;
}
}
}
}
}
}
}
return toReturn;
}
std::vector<int> MaterialImporter::LoadMaterial(std::string sourcePath, bool isDropped)
{
ImportMaterial(sourcePath, isDropped, nullptr);
std::vector<int> aux = ImportMaterial(ddsPath, isDropped, nullptr);
return aux;
}
std::vector<int> MaterialImporter::GetMaterialData()
{
return std::vector<int>();
}
| 28.644928 | 118 | 0.656969 | adrianam4 |
aa8e09d4c4a77647fbda85f91f892ba622a2bc4e | 681 | cpp | C++ | final/pointers/wk3-functions.cpp | coderica/effective_cpp | 456d30cf42c6c71dc7187d88e362651dd79ac3fe | [
"MIT"
] | null | null | null | final/pointers/wk3-functions.cpp | coderica/effective_cpp | 456d30cf42c6c71dc7187d88e362651dd79ac3fe | [
"MIT"
] | null | null | null | final/pointers/wk3-functions.cpp | coderica/effective_cpp | 456d30cf42c6c71dc7187d88e362651dd79ac3fe | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
#include "wk3-user.h"
#include "wk3-utilities.h"
void displayUser(const user &user1)
{
cout << "Name: " << user1.name << endl;
cout << "Gender: " << (user1.gender == male ? "male" : "female") << endl;
cout << "Age: " << user1.age << endl;
if (user1.hasfriends)
cout << "Friends: " << user1.friends[0] << " " << user1.friends[1] << endl;
cout << endl;
}
void updateUserName(user &user1, string name)
{
user1.name = name;
}
void addUserFriends(user & user1, string friend1, string friend2)
{
user1.friends[0] = friend1;
user1.friends[1] = friend2;
user1.hasfriends = true;
}
| 21.28125 | 78 | 0.610866 | coderica |
aa97e99fbd607505aaaa60f8e4c1c431c48c9f3f | 2,202 | cc | C++ | sysrap/tests/map_void_int.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 11 | 2020-07-05T02:39:32.000Z | 2022-03-20T18:52:44.000Z | sysrap/tests/map_void_int.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | null | null | null | sysrap/tests/map_void_int.cc | hanswenzel/opticks | b75b5929b6cf36a5eedeffb3031af2920f75f9f0 | [
"Apache-2.0"
] | 4 | 2020-09-03T20:36:32.000Z | 2022-01-19T07:42:21.000Z | // name=map_void_int ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name
#include <cassert>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <cstring>
/**
This tests a void* index cache for use with Geant4 objects that lack an index
**/
struct Surf
{
const char* name ;
int index ;
Surf(const char* name_, int index_) : name(strdup(name_)), index(index_) {}
};
struct Turf
{
const char* name ;
int index ;
Turf(const char* name_, int index_) : name(strdup(name_)), index(index_) {}
};
inline std::ostream& operator<<(std::ostream& os, const Surf& s){ os << "Surf " << s.index << " " << s.name ; return os; }
inline std::ostream& operator<<(std::ostream& os, const Turf& s){ os << "Turf " << s.index << " " << s.name ; return os; }
struct Cache
{
typedef std::unordered_map<const void*, int> MVI ;
MVI cache ;
void add(const void* obj, int index);
int find(const void* obj) ;
};
void Cache::add(const void* obj, int index)
{
cache[obj] = index ;
}
int Cache::find(const void* obj)
{
MVI::const_iterator e = cache.end();
MVI::const_iterator i = cache.find( obj );
return i == e ? -1 : i->second ;
}
int main(int argc, char** argv)
{
Surf* r = new Surf("red", 100);
Surf* g = new Surf("green", 200);
Surf* b = new Surf("blue", 300);
Turf* c = new Turf("cyan", 1000);
Turf* m = new Turf("magenta", 2000);
Turf* y = new Turf("yellow", 3000);
Turf* k = new Turf("black", 4000);
std::vector<const void*> oo = {r,g,b,c,m,y,k} ;
// hmm after mixing up the types need to have external info on which is which
for(unsigned i=0 ; i < 3 ; i++) std::cout << *(Surf*)oo[i] << std::endl ;
for(unsigned i=3 ; i < oo.size() ; i++) std::cout << *(Turf*)oo[i] << std::endl ;
Cache cache ;
for(unsigned i=0 ; i < oo.size() ; i++)
{
const void* o = oo[i] ;
cache.add(o, i);
int idx = cache.find(o);
assert( idx == int(i) );
}
const void* anon = (const void*)m ;
int idx_m = cache.find(anon) ;
assert( idx_m == 4 );
return 0 ;
}
| 24.197802 | 125 | 0.554042 | hanswenzel |
aa98c29cd43c309ccd3c1c7b4a157ff72cc7bb41 | 1,869 | cc | C++ | src/ui/a11y/testing/fake_a11y_manager.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | 5 | 2022-01-10T20:22:17.000Z | 2022-01-21T20:14:17.000Z | src/ui/a11y/testing/fake_a11y_manager.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | src/ui/a11y/testing/fake_a11y_manager.cc | fabio-d/fuchsia-stardock | e57f5d1cf015fe2294fc2a5aea704842294318d2 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2022 The Fuchsia 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 "src/ui/a11y/testing/fake_a11y_manager.h"
namespace a11y_testing {
FakeSemanticTree::FakeSemanticTree(
fuchsia::accessibility::semantics::SemanticListenerPtr semantic_listener)
: semantic_listener_(std::move(semantic_listener)), semantic_tree_binding_(this) {}
void FakeSemanticTree::CommitUpdates(CommitUpdatesCallback callback) { callback(); }
void FakeSemanticTree::Bind(
fidl::InterfaceRequest<fuchsia::accessibility::semantics::SemanticTree> semantic_tree_request) {
semantic_tree_binding_.Bind(std::move(semantic_tree_request));
}
void FakeSemanticTree::UpdateSemanticNodes(
std::vector<fuchsia::accessibility::semantics::Node> nodes) {}
void FakeSemanticTree::DeleteSemanticNodes(std::vector<uint32_t> node_ids) {}
void FakeSemanticTree::SetSemanticsEnabled(bool enabled) {
semantic_listener_->OnSemanticsModeChanged(enabled, []() {});
}
fidl::InterfaceRequestHandler<fuchsia::accessibility::semantics::SemanticsManager>
FakeA11yManager::GetHandler() {
return semantics_manager_bindings_.GetHandler(this);
}
void FakeA11yManager::RegisterViewForSemantics(
fuchsia::ui::views::ViewRef view_ref,
fidl::InterfaceHandle<fuchsia::accessibility::semantics::SemanticListener> handle,
fidl::InterfaceRequest<fuchsia::accessibility::semantics::SemanticTree> semantic_tree_request) {
fuchsia::accessibility::semantics::SemanticListenerPtr semantic_listener;
semantic_listener.Bind(std::move(handle));
semantic_trees_.emplace_back(std::make_unique<FakeSemanticTree>(std::move(semantic_listener)));
semantic_trees_.back()->Bind(std::move(semantic_tree_request));
semantic_trees_.back()->SetSemanticsEnabled(false);
}
} // namespace a11y_testing
| 40.630435 | 100 | 0.797753 | fabio-d |
aa9964468d6aa4c54aaf83ac6e4a28db73680e87 | 11,531 | cpp | C++ | Benchmarks/leukocyte/lc_dilate/dilate_7_multiddr/src/dilate.cpp | LemonAndRabbit/rodinia-hls | 097e8cf572a9ab04403c4eb0cfdb042f233f4aea | [
"BSD-2-Clause"
] | 16 | 2020-12-28T15:07:53.000Z | 2022-02-16T08:55:40.000Z | Benchmarks/leukocyte/lc_dilate/dilate_7_multiddr/src/dilate.cpp | LemonAndRabbit/rodinia-hls | 097e8cf572a9ab04403c4eb0cfdb042f233f4aea | [
"BSD-2-Clause"
] | null | null | null | Benchmarks/leukocyte/lc_dilate/dilate_7_multiddr/src/dilate.cpp | LemonAndRabbit/rodinia-hls | 097e8cf572a9ab04403c4eb0cfdb042f233f4aea | [
"BSD-2-Clause"
] | 6 | 2020-12-28T07:33:08.000Z | 2022-01-13T16:31:22.000Z | #include "dilate.h"
extern "C" {
const int PARA_FACTOR=16;
float lc_dilate_stencil_core(float img_sample[STREL_ROWS * STREL_COLS])
{
float max = 0.0;
for (int i = 0; i < STREL_ROWS; i++)
#pragma HLS unroll
for (int j = 0; j < STREL_COLS; j++) {
#pragma HLS unroll
float temp = img_sample[i * STREL_COLS + j];
if (temp > max) max = temp;
}
return max;
}
void lc_dilate(int flag, float result[TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)],
float img [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)], int which_boundary)
{
if (flag){
bool strel[25] = { 0, 0, 1, 0, 0,
0, 1, 1, 1, 0,
1, 1, 1, 1, 1,
0, 1, 1, 1, 0,
0, 0, 1, 0, 0 };
int radius_p = STREL_ROWS / 2;
float img_rf[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2 + PARA_FACTOR];
#pragma HLS array_partition variable=img_rf complete dim=0
LOAD_WORKING_IMG_SET_BLANK : for (int i = 0; i < MAX_RADIUS; i++) {
#pragma HLS pipeline II=1
#pragma HLS unroll
img_rf[i] = 0.0;
}
LOAD_WORKING_IMG_SET : for (int i = 0; i < (TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS + PARA_FACTOR; i++) {
#pragma HLS pipeline II=1
#pragma HLS unroll
img_rf[i + MAX_RADIUS] = img[i];
}
COMPUTE_EACH_OUTPUT : for (int i = 0; i < ((TILE_COLS+2*MAX_RADIUS) * TILE_ROWS) / PARA_FACTOR ; i++) {
#pragma HLS pipeline II=1
UNROLL_PE : for (int k = 0; k < PARA_FACTOR; k++) {
#pragma HLS unroll
float img_sample[STREL_ROWS * STREL_COLS];
#pragma HLS array_partition variable=img_sample complete dim=0
FILTER_ROW : for (int m = 0; m < STREL_ROWS; m++) {
#pragma HLS unroll
FILTER_COL : for (int n = 0; n < STREL_COLS; n++) {
#pragma HLS unroll
if ( strel[m * STREL_COLS + n] != 1 )
{
img_sample[m * STREL_COLS + n] = 0;
}
else {
img_sample[m * STREL_COLS + n] = img_rf[(TILE_COLS+2*MAX_RADIUS) * m + n + k];
}
}
}
result[i * PARA_FACTOR + k] = lc_dilate_stencil_core(img_sample);
}
SHIFT_AHEAD_BODY_INDEX : for (int k = 0; k < (TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2; k++) {
#pragma HLS unroll
img_rf[k] = img_rf[k + PARA_FACTOR];
}
SHIFT_AHEAD_LAST_INDEX : for (int k = 0; k < PARA_FACTOR; k++) {
#pragma HLS unroll
if ((TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS + (i + 1) * PARA_FACTOR + k <
(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)){
img_rf[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2 + k] =
img[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS + (i + 1) * PARA_FACTOR + k];
}else{
img_rf[(TILE_COLS+2*MAX_RADIUS) * (2 * MAX_RADIUS) + MAX_RADIUS * 2 + k] = 0.0;
}
}
}
}
return;
}
void load_col_tile (int flag, int col_tile_idx,
float col_tile [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)],
float row_tile [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS])
{
if (flag){
int start_col = 0;
if (col_tile_idx == 0){
start_col = 0;
LOAD_IMG_ROW_LEFTMOST : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){
#pragma HLS PIPELINE II=1
LOAD_IMG_COL_LEFTMOST : for (int col=0; col<(TILE_COLS + MAX_RADIUS); ++col){
#pragma HLS UNROLL
col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+MAX_RADIUS+col] = row_tile[row*GRID_COLS+col];
}
}
LOAD_IMG_ROW_LEFTMOST_BLANK : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){
#pragma HLS PIPELINE II=1
LOAD_IMG_COL_LEFTMOST_BLANK : for (int col=0; col<MAX_RADIUS; ++col){
#pragma HLS UNROLL
col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+col] = 0.0;
}
}
}
else if (col_tile_idx == GRID_COLS / TILE_COLS-1){
start_col = col_tile_idx * TILE_COLS - MAX_RADIUS;
LOAD_IMG_ROW_RIGHTMOST : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){
#pragma HLS PIPELINE II=1
LOAD_IMG_COL_RIGHTMOST : for (int col=0; col<(TILE_COLS + MAX_RADIUS); ++col){
#pragma HLS UNROLL
col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+col] = row_tile[row*GRID_COLS+start_col+col];
}
}
LOAD_IMG_ROW_RIGHTMOST_BLANK : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){
#pragma HLS PIPELINE II=1
LOAD_IMG_COL_RIGHTMOST_BLANK : for (int col=0; col<MAX_RADIUS; ++col){
#pragma HLS UNROLL
col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+(TILE_COLS + MAX_RADIUS)+col] = 0.0;
}
}
}
else{
start_col = col_tile_idx * TILE_COLS - MAX_RADIUS;
LOAD_IMG_ROW_REST : for (int row=0; row<(TILE_ROWS + 2 * MAX_RADIUS); ++row){
#pragma HLS PIPELINE II=1
LOAD_IMG_COL_REST : for (int col=0; col<(TILE_COLS + 2 * MAX_RADIUS); ++col){
#pragma HLS UNROLL
col_tile[row*(TILE_COLS + 2 * MAX_RADIUS)+col] = row_tile[row*GRID_COLS+start_col+col];
}
}
}
}
}
void store_col_tile (int flag, int col_tile_idx,
float row_tile_result [TILE_ROWS * GRID_COLS],
float col_tile_result [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)])
{
if (flag){
int start_col = col_tile_idx * TILE_COLS;
STORE_RST_ROW : for (int row=0; row<TILE_ROWS; ++row){
#pragma HLS PIPELINE II=1
STORE_RST_COL : for (int col=0; col<TILE_COLS; ++col){
#pragma HLS UNROLL
row_tile_result[row*GRID_COLS+start_col+col] = col_tile_result[row*(TILE_COLS+2*MAX_RADIUS)+MAX_RADIUS+col];
}
}
}
}
void load_row_tile(int flag, float img_bram[(TILE_ROWS+2*MAX_RADIUS)*GRID_COLS], ap_uint<LARGE_BUS> *img, int tile_index)
{
if (flag){
int starting_index = tile_index * TILE_ROWS * GRID_COLS / 16;
// for (int row=0; row<TILE_ROWS+2*MAX_RADIUS; ++row){
// for (int col=0; col<GRID_COLS / 16; ++col){
// #pragma HLS PIPELINE II=1
// memcpy_wide_bus_read_float(img_bram+(row*GRID_COLS+col*16), (class ap_uint<LARGE_BUS> *)(img+(starting_index+row*GRID_COLS/16+col)), 0, sizeof(float) * 16);
// }
// }
memcpy_wide_bus_read_float(img_bram, (class ap_uint<LARGE_BUS> *)(img+starting_index), 0, sizeof(float) *((unsigned long)(TILE_ROWS+2*MAX_RADIUS)* GRID_COLS ));
}
}
void compute_row_tile(int flag, int row_tile_idx,
float row_tile_img [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS],
float row_tile_result [TILE_ROWS * GRID_COLS])
{
if (flag){
float col_tile_img_0 [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)];
#pragma HLS array_partition variable=col_tile_img_0 cyclic factor=PARA_FACTOR
float col_tile_result_0 [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)];
#pragma HLS array_partition variable=col_tile_result_0 cyclic factor=PARA_FACTOR
float col_tile_img_1 [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)];
#pragma HLS array_partition variable=col_tile_img_1 cyclic factor=PARA_FACTOR
float col_tile_result_1 [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)];
#pragma HLS array_partition variable=col_tile_result_1 cyclic factor=PARA_FACTOR
float col_tile_img_2 [(TILE_ROWS + 2 * MAX_RADIUS) * (TILE_COLS + 2 * MAX_RADIUS)];
#pragma HLS array_partition variable=col_tile_img_2 cyclic factor=PARA_FACTOR
float col_tile_result_2 [TILE_ROWS * (TILE_COLS+2*MAX_RADIUS)];
#pragma HLS array_partition variable=col_tile_result_2 cyclic factor=PARA_FACTOR
int NUM_COL_TILES = GRID_COLS / TILE_COLS;
COL_TILES : for (int j = 0; j < NUM_COL_TILES + 2; ++j)
{
int load_img_flag = j >= 0 && j < NUM_COL_TILES;
int compute_flag = j >= 1 && j < NUM_COL_TILES + 1;
int store_flag = j >= 2 && j < NUM_COL_TILES + 2;
if (j % 3 == 0){
load_col_tile(load_img_flag, j, col_tile_img_0, row_tile_img);
lc_dilate(compute_flag, col_tile_result_2, col_tile_img_2, row_tile_idx);
store_col_tile(store_flag, j-2, row_tile_result, col_tile_result_1);
}
else if (j % 3 == 1){
load_col_tile(load_img_flag, j, col_tile_img_1, row_tile_img);
lc_dilate(compute_flag, col_tile_result_0, col_tile_img_0, row_tile_idx);
store_col_tile(store_flag, j-2, row_tile_result, col_tile_result_2);
}
else{
load_col_tile(load_img_flag, j, col_tile_img_2, row_tile_img);
lc_dilate(compute_flag, col_tile_result_1, col_tile_img_1, row_tile_idx);
store_col_tile(store_flag, j-2, row_tile_result, col_tile_result_0);
}
}
}
}
void store_row_tile(int flag, float result_bram[TILE_ROWS * GRID_COLS], ap_uint<LARGE_BUS>* result, int tile_index)
{
if (flag){
int starting_index = tile_index * TILE_ROWS * GRID_COLS / 16;
// for (int row=0; row<TILE_ROWS; ++row){
// for (int col=0; col<GRID_COLS / 16; ++col){
// #pragma HLS PIPELINE II=1
// //memcpy_wide_bus_write_float((class ap_uint<LARGE_BUS> *)(result+(starting_index+row*GRID_COLS/16+col)), result_bram+(row*GRID_COLS+col*16), 0, 64);
// memcpy_wide_bus_write_float((class ap_uint<LARGE_BUS> *)(result+(starting_index+row*GRID_COLS/16+col)), result_bram+(row*GRID_COLS+col*16), 0, sizeof(float) * 16);
// }
// }
memcpy_wide_bus_write_float((class ap_uint<LARGE_BUS> *)(result+starting_index), result_bram, 0, sizeof(float) * ((unsigned long) TILE_ROWS * GRID_COLS));
}
}
void workload(ap_uint<LARGE_BUS> *result, ap_uint<LARGE_BUS>* img)
{
#pragma HLS INTERFACE m_axi port=result offset=slave bundle=result1
#pragma HLS INTERFACE m_axi port=img offset=slave bundle=img1
#pragma HLS INTERFACE s_axilite port=result bundle=control
#pragma HLS INTERFACE s_axilite port=img bundle=control
#pragma HLS INTERFACE s_axilite port=return bundle=control
float row_tile_img_0 [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS];
#pragma HLS array_partition variable=row_tile_img_0 cyclic factor=PARA_FACTOR
float row_tile_result_0 [TILE_ROWS * GRID_COLS];
#pragma HLS array_partition variable=row_tile_result_0 cyclic factor=PARA_FACTOR
float row_tile_img_1 [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS];
#pragma HLS array_partition variable=row_tile_img_1 cyclic factor=PARA_FACTOR
float row_tile_result_1 [TILE_ROWS * GRID_COLS];
#pragma HLS array_partition variable=row_tile_result_1 cyclic factor=PARA_FACTOR
float row_tile_img_2 [(TILE_ROWS + 2 * MAX_RADIUS) * GRID_COLS];
#pragma HLS array_partition variable=row_tile_img_2 cyclic factor=PARA_FACTOR
float row_tile_result_2 [TILE_ROWS * GRID_COLS];
#pragma HLS array_partition variable=row_tile_result_2 cyclic factor=PARA_FACTOR
int NUM_ROW_TILES = GRID_ROWS / TILE_ROWS;
ROW_TILES : for (int k = 0; k < NUM_ROW_TILES + 2; k++) {
int load_img_flag = k >= 0 && k < NUM_ROW_TILES;
int compute_flag = k >= 1 && k < NUM_ROW_TILES + 1;
int store_flag = k >= 2 && k < NUM_ROW_TILES + 2;
if (k % 3 == 0){
load_row_tile(load_img_flag, row_tile_img_0, img, k);
compute_row_tile(compute_flag, k-1, row_tile_img_2, row_tile_result_2);
store_row_tile(store_flag, row_tile_result_1, result, k-2);
}
else if (k % 3 == 1){
load_row_tile(load_img_flag, row_tile_img_1, img, k);
compute_row_tile(compute_flag, k-1, row_tile_img_0, row_tile_result_0);
store_row_tile(store_flag, row_tile_result_2, result, k-2);
}
else{
load_row_tile(load_img_flag, row_tile_img_2, img, k);
compute_row_tile(compute_flag, k-1, row_tile_img_1, row_tile_result_1);
store_row_tile(store_flag, row_tile_result_0, result, k-2);
}
}
return;
}
}
| 39.62543 | 170 | 0.66447 | LemonAndRabbit |
aa998be3d5886b10d7a197f61b4c004e56109d05 | 2,348 | cc | C++ | cetlib/test/PluginFactory_t.cc | jcfreeman2/cetlib | 2ad242f6d9ec99f23c9730c60ef84036a9b8d8ca | [
"BSD-3-Clause"
] | null | null | null | cetlib/test/PluginFactory_t.cc | jcfreeman2/cetlib | 2ad242f6d9ec99f23c9730c60ef84036a9b8d8ca | [
"BSD-3-Clause"
] | null | null | null | cetlib/test/PluginFactory_t.cc | jcfreeman2/cetlib | 2ad242f6d9ec99f23c9730c60ef84036a9b8d8ca | [
"BSD-3-Clause"
] | 1 | 2022-03-30T15:12:49.000Z | 2022-03-30T15:12:49.000Z | #define BOOST_TEST_MODULE (PluginFactory_t)
#include "boost/test/unit_test.hpp"
#include "cetlib/BasicPluginFactory.h"
#include "cetlib/PluginTypeDeducer.h"
#include "cetlib/test/TestPluginBase.h"
#include "cetlib_except/exception.h"
#include <memory>
#include <string>
using namespace cet;
// PluginFactory tests are independent of how its search path is
// constructed.
// Make test fixture creation compile time generated so we can
// generated one test for the system default, and one for a
// user-supplied search path.
#if defined(PLUGIN_FACTORY_SEARCH_PATH)
struct PluginFactoryTestFixture {
explicit PluginFactoryTestFixture() { pf.setDiagReleaseVersion("ETERNAL"); }
BasicPluginFactory pf{search_path{"PLUGIN_FACTORY_SEARCH_PATH"}};
};
#else
struct PluginFactoryTestFixture {
explicit PluginFactoryTestFixture() { pf.setDiagReleaseVersion("ETERNAL"); }
BasicPluginFactory pf{};
};
#endif
using namespace std::string_literals;
BOOST_FIXTURE_TEST_SUITE(PluginFactory_t, PluginFactoryTestFixture)
BOOST_AUTO_TEST_CASE(checkType)
{
BOOST_TEST_REQUIRE("TestPluginBase"s ==
PluginTypeDeducer_v<cettest::TestPluginBase>);
BOOST_TEST_REQUIRE(pf.pluginType("TestPlugin") ==
PluginTypeDeducer_v<cettest::TestPluginBase>);
}
BOOST_AUTO_TEST_CASE(checkMaker)
{
auto p = pf.makePlugin<std::unique_ptr<cettest::TestPluginBase>, std::string>(
"TestPlugin", "Hi");
BOOST_TEST_REQUIRE(p->message() == "Hi"s);
}
BOOST_AUTO_TEST_CASE(CheckFinder)
{
auto fptr = pf.find<std::string>(
"TestPlugin", "pluginType", cet::PluginFactory::nothrow);
BOOST_TEST_REQUIRE(fptr);
BOOST_TEST_REQUIRE(fptr() == PluginTypeDeducer_v<cettest::TestPluginBase>);
BOOST_TEST_REQUIRE(
pf.find<std::string>("TestPlugin", "oops", cet::PluginFactory::nothrow) ==
nullptr);
}
BOOST_AUTO_TEST_CASE(checkError)
{
BOOST_CHECK_EXCEPTION(pf.makePlugin<std::unique_ptr<cettest::TestPluginBase>>(
"TestPluginX"s, "Hi"s),
cet::exception,
[](cet::exception const& e) {
return e.category() == "Configuration" &&
std::string{e.what()}.find("ETERNAL") !=
std::string::npos;
});
}
BOOST_AUTO_TEST_SUITE_END()
| 31.306667 | 80 | 0.689097 | jcfreeman2 |
aa9ad566eb58d2ae6327fb53cf8ae1bef9696e24 | 1,859 | hpp | C++ | stapl_release/stapl/views/type_traits/is_identity.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/views/type_traits/is_identity.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | stapl_release/stapl/views/type_traits/is_identity.hpp | parasol-ppl/PPL_utils | 92728bb89692fda1705a0dee436592d97922a6cb | [
"BSD-3-Clause"
] | null | null | null | /*
// Copyright (c) 2000-2009, Texas Engineering Experiment Station (TEES), a
// component of the Texas A&M University System.
// All rights reserved.
// The information and source code contained herein is the exclusive
// property of TEES and may not be disclosed, examined or reproduced
// in whole or in part without explicit written authorization from TEES.
*/
#ifndef STAPL_VIEWS_TYPE_TRAITS_IS_IDENTITY_HPP
#define STAPL_VIEWS_TYPE_TRAITS_IS_IDENTITY_HPP
#include <boost/mpl/bool.hpp>
#include <stapl/views/mapping_functions/identity.hpp>
#include <stapl/views/type_traits/is_view.hpp>
namespace stapl {
//////////////////////////////////////////////////////////////////////
/// @brief Type checker to determine if a mapping function is an
/// identity mapping function.
//////////////////////////////////////////////////////////////////////
template <typename MF>
struct is_identity
: boost::mpl::false_
{ };
template <typename T>
struct is_identity<f_ident<T> >
: boost::mpl::true_
{ };
//////////////////////////////////////////////////////////////////////
/// @brief Metafunction to determine if a view has an identity mapping
/// function. Differs from @c has_identity in that if the type
/// is not a view, it defaults to false_type.
//////////////////////////////////////////////////////////////////////
template<typename View, bool IsView = is_view<View>::type::value>
struct has_identity_mf
: public std::false_type
{ };
//////////////////////////////////////////////////////////////////////
/// @brief Specialization for views
//////////////////////////////////////////////////////////////////////
template<typename View>
struct has_identity_mf<View, true>
: public is_identity<typename view_traits<View>::map_function>::type
{ };
} // stapl namespace
#endif /* STAPL_VIEWS_TYPE_TRAITS_IS_IDENTITY_HPP */
| 32.051724 | 74 | 0.579344 | parasol-ppl |
aa9bae64f9ed87d56bd491fa3f13db0fdbf1f1a9 | 8,786 | cc | C++ | chrome/browser/page_load_metrics/observers/use_counter_page_load_metrics_observer_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/page_load_metrics/observers/use_counter_page_load_metrics_observer_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/page_load_metrics/observers/use_counter_page_load_metrics_observer_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 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 "chrome/browser/page_load_metrics/observers/use_counter_page_load_metrics_observer.h"
#include <memory>
#include <vector>
#include "base/macros.h"
#include "base/metrics/histogram_base.h"
#include "base/test/histogram_tester.h"
#include "chrome/browser/page_load_metrics/observers/page_load_metrics_observer_test_harness.h"
#include "chrome/browser/page_load_metrics/page_load_tracker.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "third_party/blink/public/platform/web_feature.mojom.h"
#include "url/gurl.h"
namespace {
const char kTestUrl[] = "https://www.google.com";
using WebFeature = blink::mojom::WebFeature;
} // namespace
class UseCounterPageLoadMetricsObserverTest
: public page_load_metrics::PageLoadMetricsObserverTestHarness {
public:
UseCounterPageLoadMetricsObserverTest() {}
void HistogramBasicTest(
const page_load_metrics::mojom::PageLoadFeatures& first_features,
const page_load_metrics::mojom::PageLoadFeatures& second_features =
page_load_metrics::mojom::PageLoadFeatures()) {
NavigateAndCommit(GURL(kTestUrl));
SimulateFeaturesUpdate(first_features);
// Verify that kPageVisits is observed on commit.
histogram_tester().ExpectBucketCount(
internal::kFeaturesHistogramName,
static_cast<base::Histogram::Sample>(WebFeature::kPageVisits), 1);
// Verify that page visit is recorded for CSS histograms.
histogram_tester().ExpectBucketCount(
internal::kCssPropertiesHistogramName,
blink::mojom::kTotalPagesMeasuredCSSSampleId, 1);
histogram_tester().ExpectBucketCount(
internal::kAnimatedCssPropertiesHistogramName,
blink::mojom::kTotalPagesMeasuredCSSSampleId, 1);
for (auto feature : first_features.features) {
histogram_tester().ExpectBucketCount(
internal::kFeaturesHistogramName,
static_cast<base::Histogram::Sample>(feature), 1);
}
SimulateFeaturesUpdate(second_features);
for (auto feature : first_features.features) {
histogram_tester().ExpectBucketCount(
internal::kFeaturesHistogramName,
static_cast<base::Histogram::Sample>(feature), 1);
}
for (auto feature : second_features.features) {
histogram_tester().ExpectBucketCount(
internal::kFeaturesHistogramName,
static_cast<base::Histogram::Sample>(feature), 1);
}
}
void CssHistogramBasicTest(
const page_load_metrics::mojom::PageLoadFeatures& first_features,
const page_load_metrics::mojom::PageLoadFeatures& second_features =
page_load_metrics::mojom::PageLoadFeatures()) {
NavigateAndCommit(GURL(kTestUrl));
SimulateFeaturesUpdate(first_features);
// Verify that page visit is recorded for CSS histograms.
histogram_tester().ExpectBucketCount(
internal::kCssPropertiesHistogramName,
blink::mojom::kTotalPagesMeasuredCSSSampleId, 1);
for (auto feature : first_features.css_properties) {
histogram_tester().ExpectBucketCount(
internal::kCssPropertiesHistogramName, feature, 1);
}
SimulateFeaturesUpdate(second_features);
for (auto feature : first_features.css_properties) {
histogram_tester().ExpectBucketCount(
internal::kCssPropertiesHistogramName, feature, 1);
}
for (auto feature : second_features.css_properties) {
histogram_tester().ExpectBucketCount(
internal::kCssPropertiesHistogramName, feature, 1);
}
}
void AnimatedCssHistogramBasicTest(
const page_load_metrics::mojom::PageLoadFeatures& first_features,
const page_load_metrics::mojom::PageLoadFeatures& second_features =
page_load_metrics::mojom::PageLoadFeatures()) {
NavigateAndCommit(GURL(kTestUrl));
SimulateFeaturesUpdate(first_features);
// Verify that page visit is recorded for CSS histograms.
histogram_tester().ExpectBucketCount(
internal::kAnimatedCssPropertiesHistogramName,
blink::mojom::kTotalPagesMeasuredCSSSampleId, 1);
for (auto feature : first_features.animated_css_properties) {
histogram_tester().ExpectBucketCount(
internal::kAnimatedCssPropertiesHistogramName, feature, 1);
}
SimulateFeaturesUpdate(second_features);
for (auto feature : first_features.animated_css_properties) {
histogram_tester().ExpectBucketCount(
internal::kAnimatedCssPropertiesHistogramName, feature, 1);
}
for (auto feature : second_features.animated_css_properties) {
histogram_tester().ExpectBucketCount(
internal::kAnimatedCssPropertiesHistogramName, feature, 1);
}
}
protected:
void RegisterObservers(page_load_metrics::PageLoadTracker* tracker) override {
tracker->AddObserver(std::make_unique<UseCounterPageLoadMetricsObserver>());
}
private:
DISALLOW_COPY_AND_ASSIGN(UseCounterPageLoadMetricsObserverTest);
};
TEST_F(UseCounterPageLoadMetricsObserverTest, CountOneFeature) {
std::vector<WebFeature> features({WebFeature::kFetch});
page_load_metrics::mojom::PageLoadFeatures page_load_features;
page_load_features.features = features;
HistogramBasicTest(page_load_features);
}
TEST_F(UseCounterPageLoadMetricsObserverTest, CountFeatures) {
std::vector<WebFeature> features_0(
{WebFeature::kFetch, WebFeature::kFetchBodyStream});
std::vector<WebFeature> features_1({WebFeature::kWindowFind});
page_load_metrics::mojom::PageLoadFeatures page_load_features_0;
page_load_metrics::mojom::PageLoadFeatures page_load_features_1;
page_load_features_0.features = features_0;
page_load_features_1.features = features_1;
HistogramBasicTest(page_load_features_0, page_load_features_1);
}
TEST_F(UseCounterPageLoadMetricsObserverTest, CountDuplicatedFeatures) {
std::vector<WebFeature> features_0(
{WebFeature::kFetch, WebFeature::kFetch, WebFeature::kFetchBodyStream});
std::vector<WebFeature> features_1(
{WebFeature::kFetch, WebFeature::kWindowFind});
page_load_metrics::mojom::PageLoadFeatures page_load_features_0;
page_load_metrics::mojom::PageLoadFeatures page_load_features_1;
page_load_features_0.features = features_0;
page_load_features_1.features = features_1;
HistogramBasicTest(page_load_features_0, page_load_features_1);
}
TEST_F(UseCounterPageLoadMetricsObserverTest, RecordUkmUsage) {
std::vector<WebFeature> features_0(
{WebFeature::kFetch, WebFeature::kNavigatorVibrate});
std::vector<WebFeature> features_1(
{WebFeature::kTouchEventPreventedNoTouchAction});
page_load_metrics::mojom::PageLoadFeatures page_load_features_0;
page_load_metrics::mojom::PageLoadFeatures page_load_features_1;
page_load_features_0.features = features_0;
page_load_features_1.features = features_1;
HistogramBasicTest(page_load_features_0, page_load_features_1);
std::vector<const ukm::mojom::UkmEntry*> entries =
test_ukm_recorder().GetEntriesByName(
ukm::builders::Blink_UseCounter::kEntryName);
EXPECT_EQ(2ul, entries.size());
test_ukm_recorder().ExpectEntrySourceHasUrl(entries[0], GURL(kTestUrl));
test_ukm_recorder().ExpectEntryMetric(
entries[0], ukm::builders::Blink_UseCounter::kFeatureName,
static_cast<int64_t>(WebFeature::kNavigatorVibrate));
test_ukm_recorder().ExpectEntrySourceHasUrl(entries[1], GURL(kTestUrl));
test_ukm_recorder().ExpectEntryMetric(
entries[1], ukm::builders::Blink_UseCounter::kFeatureName,
static_cast<int64_t>(WebFeature::kTouchEventPreventedNoTouchAction));
}
TEST_F(UseCounterPageLoadMetricsObserverTest, RecordCSSProperties) {
// CSSPropertyFont (5), CSSPropertyZoom (19)
page_load_metrics::mojom::PageLoadFeatures page_load_features_0;
page_load_metrics::mojom::PageLoadFeatures page_load_features_1;
page_load_features_0.css_properties = {5, 19};
page_load_features_1.css_properties = {19};
CssHistogramBasicTest(page_load_features_0, page_load_features_1);
}
TEST_F(UseCounterPageLoadMetricsObserverTest, RecordAnimatedCSSProperties) {
// CSSPropertyFont (5), CSSPropertyZoom (19)
page_load_metrics::mojom::PageLoadFeatures page_load_features_0;
page_load_metrics::mojom::PageLoadFeatures page_load_features_1;
page_load_features_0.css_properties = {5, 19};
page_load_features_1.css_properties = {19};
AnimatedCssHistogramBasicTest(page_load_features_0, page_load_features_1);
}
TEST_F(UseCounterPageLoadMetricsObserverTest, RecordCSSPropertiesInRange) {
page_load_metrics::mojom::PageLoadFeatures page_load_features;
page_load_features.css_properties = {2, blink::mojom::kMaximumCSSSampleId};
CssHistogramBasicTest(page_load_features);
}
| 42.240385 | 95 | 0.773389 | zipated |
aa9dc223835335d51a820d67bf599c19e7106c78 | 861 | cpp | C++ | src/cpp/drawing/CanvasWithProfiler.cpp | Yukihito/alcube | 8aac4e2dd2cb3871b672d92902cf15150c430a56 | [
"MIT"
] | null | null | null | src/cpp/drawing/CanvasWithProfiler.cpp | Yukihito/alcube | 8aac4e2dd2cb3871b672d92902cf15150c430a56 | [
"MIT"
] | null | null | null | src/cpp/drawing/CanvasWithProfiler.cpp | Yukihito/alcube | 8aac4e2dd2cb3871b672d92902cf15150c430a56 | [
"MIT"
] | null | null | null | #include "CanvasWithProfiler.h"
namespace alcube::drawing {
CanvasWithProfiler::CanvasWithProfiler(Camera *camera, utils::Profiler *profiler) : Canvas(camera) {
this->profiler = profiler;
profilers.draw = profiler->create("draw");
profilers.drawAllDrawables = profiler->create("drawAllDrawables");
profilers.waitVSync = profiler->create("waitVSync");
}
void CanvasWithProfiler::draw() {
profiler->start(profilers.draw);
Canvas::draw();
profiler->stop(profilers.draw);
}
void CanvasWithProfiler::waitVSync() {
profiler->start(profilers.waitVSync);
Canvas::waitVSync();
profiler->stop(profilers.waitVSync);
}
void CanvasWithProfiler::drawAllDrawables() {
profiler->start(profilers.drawAllDrawables);
Canvas::drawAllDrawables();
glFinish();
profiler->stop(profilers.drawAllDrawables);
}
} | 29.689655 | 102 | 0.711963 | Yukihito |
aa9f3c50eba90d00a967fb0d858f6642eba3f888 | 4,169 | cpp | C++ | src/text/freetype/wrap.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/text/freetype/wrap.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | src/text/freetype/wrap.cpp | degarashi/revenant | 9e671320a5c8790f6bdd1b14934f81c37819f7b3 | [
"MIT"
] | null | null | null | #include "wrap.hpp"
#include "error.hpp"
#include "../../sdl/rw.hpp"
namespace rev {
namespace {
constexpr unsigned int FTUnit = 64;
}
// ---------------------- FTLibrary ----------------------
FTLibrary::FTLibrary() {
FTAssert(FT_Init_FreeType, &_lib);
}
FTLibrary::~FTLibrary() {
if(_lib)
D_FTAssert(FT_Done_FreeType, _lib);
}
HFT FTLibrary::newFace(const HRW& hRW, const int index) {
FT_Face face;
HRW ret;
// 中身がメモリじゃなければ一旦コピーする
if(!hRW->isMemory())
ret = mgr_rw.fromVector(hRW->readAll());
else
ret = hRW;
auto m = ret->getMemoryC();
FTAssert(FT_New_Memory_Face, _lib, reinterpret_cast<const uint8_t*>(m.data), m.length, index, &face);
return emplace(face, ret);
}
// ---------------------- FTFace ----------------------
FTFace::FTFace(const FT_Face face, const HRW& hRW):
_face(face),
_hRW(hRW)
{}
FTFace::FTFace(FTFace&& f):
_face(f._face),
_hRW(std::move(f._hRW)),
_faceInfo(f._faceInfo),
_glyphInfo(f._glyphInfo)
{
f._face = nullptr;
}
FTFace::~FTFace() {
if(_face)
D_FTAssert(FT_Done_Face, _face);
}
void FTFace::prepareGlyph(const char32_t code, const RenderMode::e mode, const bool bBold, const bool bItalic) {
uint32_t gindex = FT_Get_Char_Index(_face, code);
int loadflag = mode==RenderMode::Mono ? FT_LOAD_MONOCHROME : FT_LOAD_DEFAULT;
if(bBold || bItalic)
loadflag |= FT_LOAD_NO_BITMAP;
FTAssert(FT_Load_Glyph, _face, gindex, loadflag);
auto* slot = _face->glyph;
if(!bBold && !bItalic) {
if(slot->format != FT_GLYPH_FORMAT_BITMAP)
FTAssert(FT_Render_Glyph, slot, static_cast<FT_Render_Mode>(mode));
} else {
if(bBold) {
int strength = 1 * FTUnit;
FTAssert(FT_Outline_Embolden, &slot->outline, strength);
FTAssert(FT_Render_Glyph, slot, static_cast<FT_Render_Mode>(mode));
}
if(bItalic) {
FT_Matrix mat;
mat.xx = 1 << 16;
mat.xy = 0x5800;
mat.yx = 0;
mat.yy = 1 << 16;
FT_Outline_Transform(&slot->outline, &mat);
}
}
Assert0(slot->format == FT_GLYPH_FORMAT_BITMAP);
/*
met.width / FTUnit == bitmap.width
met.height / FTUnit == bitmap.height
met.horiBearingX / FTUnit == bitmap_left
met.horiBearingY / FTUnit == bitmap_top
assert(_info.width == _info.bmp_width &&
_info.height == _info.bmp_height &&
_info.horiBearingX == _info.bmp_left &&
_info.horiBearingY == _info.bmp_top);
*/
auto& met = slot->metrics;
auto& bm = slot->bitmap;
_glyphInfo.data = static_cast<const uint8_t*>(bm.buffer);
_glyphInfo.advanceX = slot->advance.x / FTUnit;
_glyphInfo.nlevel = mode==RenderMode::Mono ? 2 : bm.num_grays;
_glyphInfo.pitch = bm.pitch;
_glyphInfo.height = bm.rows;
_glyphInfo.width = bm.width;
_glyphInfo.horiBearingX = met.horiBearingX / FTUnit;
_glyphInfo.horiBearingY = met.horiBearingY / FTUnit;
}
const FTFace::GlyphInfo& FTFace::getGlyphInfo() const {
return _glyphInfo;
}
const FTFace::FaceInfo& FTFace::getFaceInfo() const {
return _faceInfo;
}
void FTFace::setPixelSizes(const lubee::SizeI s) {
FTAssert(FT_Set_Pixel_Sizes, _face, s.width, s.height);
_updateFaceInfo();
}
void FTFace::setCharSize(const lubee::SizeI s, const lubee::SizeI dpi) {
FTAssert(FT_Set_Char_Size,
_face,
s.width * FTUnit, s.height * FTUnit,
dpi.width, dpi.height
);
_updateFaceInfo();
}
void FTFace::setSizeFromLine(const unsigned int lineHeight) {
FT_Size_RequestRec req;
req.height = lineHeight * FTUnit;
req.width = 0;
req.type = FT_SIZE_REQUEST_TYPE_CELL;
req.horiResolution = 0;
req.vertResolution = 0;
FTAssert(FT_Request_Size, _face, &req);
_updateFaceInfo();
}
void FTFace::_updateFaceInfo() {
auto& met = _face->size->metrics;
_faceInfo.baseline = (_face->height + _face->descender) *
met.y_ppem / _face->units_per_EM;
_faceInfo.height = met.height / FTUnit;
_faceInfo.maxWidth = met.max_advance / FTUnit;
}
const char* FTFace::getFamilyName() const {
return _face->family_name;
}
const char* FTFace::getStyleName() const {
return _face->style_name;
}
size_t FTFace::getNFace() const {
return _face->num_faces;
}
int FTFace::getFaceIndex() const {
return _face->face_index;
}
}
| 28.751724 | 113 | 0.673063 | degarashi |
aaa0112e550b865ce0a2d2946b2ac2a5c9099c23 | 1,564 | cpp | C++ | snippets/cpp/VS_Snippets_Winforms/Classic DefaultEventAttribute Example/CPP/source.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 834 | 2017-06-24T10:40:36.000Z | 2022-03-31T19:48:51.000Z | snippets/cpp/VS_Snippets_Winforms/Classic DefaultEventAttribute Example/CPP/source.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 7,042 | 2017-06-23T22:34:47.000Z | 2022-03-31T23:05:23.000Z | snippets/cpp/VS_Snippets_Winforms/Classic DefaultEventAttribute Example/CPP/source.cpp | BohdanMosiyuk/samples | 59d435ba9e61e0fc19f5176c96b1cdbd53596142 | [
"CC-BY-4.0",
"MIT"
] | 1,640 | 2017-06-23T22:31:39.000Z | 2022-03-31T02:45:37.000Z | #using <System.dll>
#using <System.Windows.Forms.dll>
using namespace System;
using namespace System::ComponentModel;
using namespace System::Windows::Forms;
namespace DefaultEventAttributeExample
{
// <Snippet1>
[DefaultEvent("CollectionChanged")]
public ref class TestCollection: public BaseCollection
{
private:
CollectionChangeEventHandler^ onCollectionChanged;
public:
event CollectionChangeEventHandler^ CollectionChanged
{
public:
void add(CollectionChangeEventHandler^ eventHandler)
{
onCollectionChanged += eventHandler;
}
protected:
void remove(CollectionChangeEventHandler^ eventHandler)
{
onCollectionChanged -= eventHandler;
}
}
// Insert additional code.
};
// </Snippet1>
}
// <Snippet2>
int main()
{
// Creates a new collection.
DefaultEventAttributeExample::TestCollection^ newCollection =
gcnew DefaultEventAttributeExample::TestCollection;
// Gets the attributes for the collection.
AttributeCollection^ attributes =
TypeDescriptor::GetAttributes(newCollection);
// Prints the name of the default event by retrieving the
// DefaultEventAttribute from the AttributeCollection.
DefaultEventAttribute^ attribute = (DefaultEventAttribute^)
attributes[DefaultEventAttribute::typeid];
Console::WriteLine("The default event is: {0}", attribute->Name);
}
// </Snippet2>
| 27.928571 | 69 | 0.661765 | BohdanMosiyuk |
aaa247e81f79f2589581a3e0995f94ebcccca378 | 1,371 | cpp | C++ | src/parser/expression/lambda_expression.cpp | nbenn/duckdb | a7493fec044a3d652389039fc942a3d331cf2c16 | [
"MIT"
] | 1 | 2021-12-13T06:00:18.000Z | 2021-12-13T06:00:18.000Z | src/parser/expression/lambda_expression.cpp | nbenn/duckdb | a7493fec044a3d652389039fc942a3d331cf2c16 | [
"MIT"
] | 32 | 2021-09-24T23:50:09.000Z | 2022-03-29T09:37:26.000Z | src/parser/expression/lambda_expression.cpp | nbenn/duckdb | a7493fec044a3d652389039fc942a3d331cf2c16 | [
"MIT"
] | null | null | null | #include "duckdb/parser/expression/lambda_expression.hpp"
#include "duckdb/common/field_writer.hpp"
#include "duckdb/common/types/hash.hpp"
namespace duckdb {
LambdaExpression::LambdaExpression(unique_ptr<ParsedExpression> lhs, unique_ptr<ParsedExpression> rhs)
: ParsedExpression(ExpressionType::LAMBDA, ExpressionClass::LAMBDA), lhs(move(lhs)), rhs(move(rhs)) {
}
string LambdaExpression::ToString() const {
return lhs->ToString() + " -> " + rhs->ToString();
}
bool LambdaExpression::Equals(const LambdaExpression *a, const LambdaExpression *b) {
return a->lhs->Equals(b->lhs.get()) && a->rhs->Equals(b->rhs.get());
}
hash_t LambdaExpression::Hash() const {
hash_t result = lhs->Hash();
ParsedExpression::Hash();
result = CombineHash(result, rhs->Hash());
return result;
}
unique_ptr<ParsedExpression> LambdaExpression::Copy() const {
return make_unique<LambdaExpression>(lhs->Copy(), rhs->Copy());
}
void LambdaExpression::Serialize(FieldWriter &writer) const {
writer.WriteSerializable(*lhs);
writer.WriteSerializable(*rhs);
}
unique_ptr<ParsedExpression> LambdaExpression::Deserialize(ExpressionType type, FieldReader &reader) {
auto lhs = reader.ReadRequiredSerializable<ParsedExpression>();
auto rhs = reader.ReadRequiredSerializable<ParsedExpression>();
return make_unique<LambdaExpression>(move(lhs), move(rhs));
}
} // namespace duckdb
| 32.642857 | 105 | 0.757112 | nbenn |
aaa42d1f553c87847ffef92b7900d9d30b2d4ac2 | 21,482 | cpp | C++ | src/main.cpp | CrackerCat/Ponce | c065c984ae20c9e7c3540042c2d1202b5b0a6b6c | [
"BSL-1.0"
] | 1,270 | 2016-09-23T13:43:00.000Z | 2022-03-27T10:00:02.000Z | src/main.cpp | CrackerCat/Ponce | c065c984ae20c9e7c3540042c2d1202b5b0a6b6c | [
"BSL-1.0"
] | 87 | 2016-09-23T13:50:17.000Z | 2021-05-16T06:02:36.000Z | src/main.cpp | CrackerCat/Ponce | c065c984ae20c9e7c3540042c2d1202b5b0a6b6c | [
"BSL-1.0"
] | 232 | 2016-09-23T15:24:42.000Z | 2022-03-30T13:22:34.000Z | //! \file
/*
** Copyright (c) 2020 - Ponce
** Authors:
** Alberto Garcia Illera agarciaillera@gmail.com
** Francisco Oca francisco.oca.gonzalez@gmail.com
**
** This program is under the terms of the BSD License.
*/
//IDA
#include <idp.hpp>
#include <dbg.hpp>
#include <loader.hpp>
#include <kernwin.hpp>
//Triton
#include <triton/api.hpp>
//Ponce
#include "callbacks.hpp"
#include "actions.hpp"
#include "globals.hpp"
#include "trigger.hpp"
#include "context.hpp"
#include "utils.hpp"
#include "formConfiguration.hpp"
#include "triton_logic.hpp"
#include "actions.hpp"
#ifdef BUILD_HEXRAYS_SUPPORT
#include "ponce_hexrays.hpp"
#if IDA_SDK_VERSION < 760
// Hex-Rays API pointer
hexdsp_t* hexdsp = NULL;
#endif
#endif
bool idaapi run(size_t)
{
/*We shouldn't prompt for it if the user has a saved configuration*/
if (!load_options(&cmdOptions)) {
prompt_conf_window();
}
if (!hooked) {
//Registering action for the Ponce config
register_action(action_IDA_show_config);
attach_action_to_menu("Edit/Ponce/", action_IDA_show_config.name, SETMENU_APP);
//Registering action for the Ponce taint window
register_action(action_IDA_show_expressionsWindow);
attach_action_to_menu("Edit/Ponce/", action_IDA_show_expressionsWindow.name, SETMENU_APP);
//Registering action for the unload action
register_action(action_IDA_unload);
attach_action_to_menu("Edit/Ponce/", action_IDA_unload.name, SETMENU_APP);
register_action(action_IDA_clean);
attach_action_to_menu("Edit/Ponce/", action_IDA_clean.name, SETMENU_APP);
//Some actions needs to use the api and the api need to have the architecture set
if (!ponce_set_triton_architecture()) {
return false;
}
// Set the name for the action depending if using tainting or symbolic engine
if (cmdOptions.use_tainting_engine) {
action_list[3].menu_path = TAINT;
action_IDA_taint_symbolize_register.label = TAINT_REG;
action_IDA_taint_symbolize_register.tooltip = COMMENT_TAINT_REG;
action_list[4].menu_path = TAINT;
action_IDA_taint_symbolize_memory.label = TAINT_MEM;
action_IDA_taint_symbolize_memory.tooltip = COMMENT_TAINT_MEM;
}
else {
action_list[3].menu_path = SYMBOLIC;
action_IDA_taint_symbolize_register.label = symbolize_REG;
action_IDA_taint_symbolize_register.tooltip = COMMENT_SYMB_REG;
action_list[4].menu_path = SYMBOLIC;
action_IDA_taint_symbolize_memory.tooltip = COMMENT_SYMB_MEM;
action_IDA_taint_symbolize_memory.label = symbolize_MEM;
}
/* Init the IDA actions depending on the IDA SDK version we build with*/
std::copy(std::begin(ponce_banner_views), std::end(ponce_banner_views), std::begin(action_list[0].view_type));
std::copy(std::begin(ponce_taint_symbolize_reg_views), std::end(ponce_taint_symbolize_reg_views), std::begin(action_list[3].view_type));
std::copy(std::begin(ponce_taint_symbolize_mem_views), std::end(ponce_taint_symbolize_mem_views), std::begin(action_list[4].view_type));
//Loop to register all the actions used in the menus
for (int i = 0;; i++) {
if (action_list[i].action_decs == NULL) {
break;
}
//Here we register all the actions
if (!register_action(*action_list[i].action_decs)) {
warning("[!] Failed to register %s actions. Exiting Ponce plugin\n", action_list[i].action_decs->name);
return false;
}
}
// This is Ponce logo. I put it here so it's only loaded once
unsigned char ponce_icon[] = "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A\x00\x00\x00\x0D\x49\x48\x44\x52\x00\x00\x00\x20\x00\x00\x00\x20\x08\x06\x00\x00\x00\x73\x7A\x7A\xF4\x00\x00\x00\x01\x73\x52\x47\x42\x00\xAE\xCE\x1C\xE9\x00\x00\x00\x04\x67\x41\x4D\x41\x00\x00\xB1\x8F\x0B\xFC\x61\x05\x00\x00\x00\x09\x70\x48\x59\x73\x00\x00\x0E\xC4\x00\x00\x0E\xC4\x01\x95\x2B\x0E\x1B\x00\x00\x0C\xC4\x49\x44\x41\x54\x58\x47\x45\x97\x77\x54\x94\x69\x9A\xC5\x6B\xF7\x9C\xDD\xB3\x33\x67\x66\xDA\x2C\x92\xA1\x08\x05\x14\x59\x42\x21\x85\x04\x11\x49\x22\x2A\x51\x25\x08\x88\x0D\x8A\x28\x60\x00\xEC\x56\x51\x14\x23\x88\x82\xA0\x24\xC5\x00\x82\x80\x18\xDA\x00\x54\x51\x44\xC1\xD0\x3D\x1D\xB4\x1D\xDB\x9E\x99\xD3\xDB\x7B\xBA\x7B\x66\xCE\x9E\x8D\x67\xFE\xF9\xED\x53\x65\xDB\xFB\xC7\x3D\xDF\x57\x1F\x1F\x75\xEF\x7B\x9F\xE7\xBD\xEF\x53\x8A\x3A\xDD\xD7\xD4\x8D\x7C\xCD\xE9\xA1\xAF\x38\x33\xFC\x92\xDA\x91\x57\x72\xFF\xA5\x3C\x7B\xC5\xF9\xC9\x3F\x73\x4A\xFF\x86\xFD\x1D\x83\xEC\xD9\xB7\x8F\xAA\x82\x4D\xB4\xEC\xDB\x42\xAB\xA0\xAD\x3C\x9F\x96\xBD\x79\x9C\x2B\xC9\xA6\x66\x5B\x1A\x95\x39\xEB\x29\xCB\x4C\x64\x67\xC6\x3A\x2A\x2E\xF6\xD2\x30\xFE\x2D\xF5\xC3\x5F\x71\x4E\x27\xDF\xA3\xFF\xDA\x74\xAD\x1F\x79\xF9\xCB\x67\xE3\xFD\x59\x81\xC2\x48\x58\x27\x0F\x6B\xE5\xE5\x3A\xA3\x00\x11\x72\x61\xF2\x4F\x9C\xD6\xBD\xA6\xB2\xED\x36\xFB\x76\x97\x71\xFC\xC3\x54\x5A\xCB\xB2\xB8\x5C\x91\x6F\x22\x37\x12\x1B\x05\xBC\x17\xD2\x54\x96\x43\xED\x8E\x8D\x1C\xD8\x92\xC4\xB6\xA4\x28\x0A\xD2\x13\x38\x7E\x7B\x9A\x73\xFA\xD7\xD4\x3D\xFE\x82\xB3\xC3\x5F\x9A\xC4\x18\x51\x27\x8B\x3B\x6B\xBC\x17\x9E\x73\x46\x01\x46\x15\x26\xC8\x1F\xCE\x89\x1B\x17\xC6\xDF\x52\x5C\x7F\x83\xBC\x82\x02\x8A\x92\x57\x72\x7C\x4B\x22\x2D\xBB\x73\x68\xFD\x99\xF0\x3D\xE9\x7B\x21\xEF\x90\x2B\x22\x32\x39\x5B\xB4\x91\xC3\xF9\x29\x94\xA7\x47\x51\xB2\xAF\x82\x46\x71\xF0\x82\xE1\x1B\x9A\x26\xBE\xE5\xC2\x84\xF1\xFA\x96\xA6\xF1\x37\x72\x2F\xD0\xBD\xA4\x41\xF7\x25\x8A\xF7\xD6\x34\x18\xDE\x88\xBA\x2F\x88\xD9\x90\x8B\xD9\xA2\x85\xC4\x2F\xF7\x67\xB7\x58\x7A\xA2\x30\x9D\xA6\xD2\x6C\x93\xF5\xEF\x09\x2F\xED\x31\x22\x97\x36\x79\xD6\x21\xAE\xB4\x95\xE7\xD2\xB2\x27\x8B\x3A\x71\xA1\xA6\x20\x95\xED\xC9\xAB\xC8\x4C\x8C\xE2\x60\xCB\x4D\x8E\xB4\xDE\xE4\x70\xD3\x55\x8E\xB6\x76\x51\x71\xAE\x9D\x9D\x27\x9B\x39\xD8\x3E\xC0\xB9\xA1\xCF\x68\x99\xFA\x46\x04\x0C\x7F\x41\xE3\xE8\x2B\x6A\xFA\x27\xF0\x5F\x1E\xC1\xC2\x79\x73\xB0\xB6\xB6\xC1\xD5\xCD\x85\x1D\xE9\xF1\xD4\x6E\x4F\xA7\x71\x57\x26\xAD\x42\xFC\xCE\x81\x3C\xDA\x85\xB0\xAD\x3C\x87\x46\xA9\xFF\x89\xC2\x0D\x7C\x9C\xB3\x8E\xA2\xB4\x18\xB2\xE2\xC3\x49\x5A\x11\x44\x8C\x36\x80\x10\x3F\x6F\xB4\xBE\x1E\x84\xFB\x79\x10\xE6\xA7\x46\xEB\xE3\x46\x84\xAF\x2B\x81\xEE\x4E\x78\xB9\x3A\xE3\x17\x18\xC4\x8E\x93\x4D\x28\xEA\x1F\x3E\x17\x25\x6F\x49\x2A\x28\xC1\xCA\x6C\x3E\x16\x96\x96\x2C\x5C\xB4\x08\x17\x95\x23\x9B\x65\x15\xC6\xFA\x9F\x28\x4C\xA5\xAE\x78\xA3\x08\x31\xAE\x72\x13\xFB\x73\x12\xD9\x91\xB6\x8A\xDC\x35\x2B\x48\x89\xD2\x12\xAD\xF5\x43\xE3\xED\x8E\xD2\xDE\x0E\x4B\x2B\x2B\x59\x80\x35\xFE\x9E\xAE\xC4\x89\x8B\x61\x41\x4B\xD1\x88\x90\xE8\xE0\xA5\x04\xCA\x3B\x4E\x0E\xF6\xD8\xD9\x2B\xF9\xE0\xD7\xBF\x22\x3E\x6B\x2B\x8A\x06\xC3\xD7\xB4\x4E\xFF\x91\x8C\x9D\x15\x78\xAA\xEC\x59\x62\x66\xC6\xDC\xB9\x73\xB1\x92\x2F\x5A\x2E\xFF\xBC\x2B\x63\x0D\xE5\xD2\xE1\x25\x1B\xE2\xD9\x2A\x0D\xB6\x29\x36\x94\xF5\x11\x1A\x22\x35\x3E\xF8\xA8\x5D\x71\x72\x54\xCA\xBB\xD6\x38\x3B\x3A\xA0\x5D\xEA\x4E\xAC\x76\x29\x41\x42\xE8\xEF\xE3\x81\x8F\xA7\x1B\x3E\xEE\x6E\x78\xAA\x5D\x50\x3A\x38\x60\x2E\xEF\x2D\x59\xB2\x84\x79\xBF\xFB\x0D\xDA\xA8\x78\xCE\x3F\x7A\x8A\xA2\xB4\xA2\x92\xF3\xA3\x5F\xB1\xE5\xE3\xE3\xA8\x1D\x6D\x31\x33\x5B\xC2\x9C\x39\x73\x58\xB0\x60\x01\xF6\x4A\x3B\xD6\xAE\x0C\x21\x3B\x61\x85\x89\x38\x69\x65\x10\x11\x81\xDE\x78\xB8\x38\x61\x6B\x6B\x8B\xA3\x83\x12\xB5\x88\xF0\x70\x17\xB8\x09\x5C\x9C\xB1\xB7\xB5\x61\xF1\x12\x73\xEC\xEC\x6C\x70\x76\xB2\x47\xE5\xA4\xC4\xC1\xDE\x1E\x2B\x8B\x25\x2C\x5A\x30\x0F\x27\x95\x8A\x84\x8C\x2D\xD4\x7F\xF2\x84\xD6\xF1\x57\x28\xF6\xAD\x74\x61\x7F\xE5\x3E\x0A\x8E\x9C\x41\xED\xEC\x28\x0A\xCD\xF8\xC0\x28\x60\xE1\x22\xFC\xBD\x3D\x48\x8D\x0E\x25\x79\x65\x30\xA1\xFE\x5E\xB8\x38\x39\xE0\x2A\xEF\xA8\x1C\xED\x71\x50\x2A\xB1\x17\xCB\xCD\xCC\x2D\x04\xE6\xB8\xC8\xF3\xD8\xD0\x40\x4A\xB3\xD6\xD1\x71\xA8\x90\xD9\xCE\xA3\x18\xDA\x0F\xB3\x23\x7B\x35\x96\x36\xB6\x04\x48\x7F\xE5\x94\x1F\xA4\x76\x70\x94\xCB\x33\x7F\xA0\xD5\xF0\x39\x17\x75\x2F\x44\x40\xE2\x32\xAA\x37\xC7\x92\x97\xB6\x06\x57\x95\x13\x8B\x16\x2F\xC6\xC2\x7C\x89\xE9\xCB\xF2\xD6\x46\x4A\xED\xFC\xF1\x16\x0B\x7D\xA5\xA6\x4A\x5B\x6B\xDC\xE4\x1D\x07\x7B\x5B\xCC\x45\xA8\x9D\x08\xD8\x95\xB5\x9A\xBE\x33\x65\x7C\xDE\x73\x9A\xBF\xEA\x5B\xF9\xFB\x74\x17\x7F\x7F\x72\x93\xFF\x9C\xE8\xE2\x7F\x27\xBB\xE9\x39\x55\x4A\x55\xCB\x55\x3A\xA6\x5F\x73\x75\xF6\x0D\xAD\x63\x9F\xD3\x3C\xF2\x9C\x4B\xFA\x4F\xB9\x34\xFA\x19\x8A\xB8\x20\x6F\x76\xC9\x7E\x2F\xDD\x9C\x84\x9B\x94\xC0\xD3\x4D\x45\xD6\x6A\xE9\x66\x69\x2E\x3F\x2F\x35\x4B\x85\x38\xC0\x5B\x2D\x2B\xB6\x63\x91\x99\xF9\xBB\x15\x4B\x9F\x58\xDB\xDA\x71\x74\x77\x2E\x3F\x8E\x5C\xE2\xBF\xA7\x3A\xF9\xF7\xF1\xCB\xFC\x75\xB4\x83\x7F\x1B\x6A\xE5\x87\xE1\xCB\xFC\x4D\x7F\x85\xFF\x9A\xB8\x4A\xE7\xE1\x02\x4A\x8E\x1C\xA3\x63\xF2\x25\xCD\x43\xB3\xA6\x55\xB7\xEA\x9F\xD3\xA6\x97\xAB\xEE\x39\x8A\x98\x60\x1F\xE2\xFC\x5D\xA4\x8B\xD5\x44\x87\xF8\x89\xE5\xC1\xF8\x7B\xB9\xE2\x25\xAB\x0E\xD3\xF8\x8A\x00\x37\x53\xBD\x17\x2E\x32\xC3\xC3\xD9\x8A\x08\x3F\x3B\x1C\xA4\x04\x47\x64\x47\xFC\x20\xE4\x7F\x1B\x6D\xE3\xF5\x60\x3D\x2F\x07\xEA\x98\xBD\x7E\x9C\x9F\x74\x6D\xBC\xBD\xDB\x48\x7F\x5D\x19\x39\xA9\xB1\xAC\x8E\xD4\x50\x56\x52\xC0\xC5\x91\x67\xB4\xEB\x9F\x0A\xF1\x53\xDA\x47\xE5\x5E\xD0\x21\x50\x94\x94\xED\x22\x37\x7B\x13\xAB\x43\x7C\x09\x0E\xF0\x96\xC6\x92\xC6\x71\x76\x62\x79\xA0\x2F\x7E\xB2\x6D\x6C\x64\x4B\x59\x59\x5A\xB0\xC4\xC2\x92\xA4\x50\x47\x92\x42\xEC\xA4\xBB\x5D\x19\xBE\xB8\x9F\x4F\xBB\x6A\x28\xCD\x5D\xCB\x52\x79\x4F\x25\xFD\x61\x27\xCD\x76\xF7\xFC\x7E\xBE\x7F\xD8\xCC\x0E\xD9\xAA\xAE\x6E\x6E\xE4\xAD\x8B\x24\x3F\x2F\x53\x04\x3C\xA5\xC3\xF0\xDC\x84\xCB\x63\x2F\x7E\x81\xE2\x78\xC7\x0D\xB2\x32\xD2\x25\x1C\x9C\x70\x17\xFB\x97\x6B\xFC\x58\xA1\xF5\xC7\x41\x3A\xDC\xB8\x15\x9D\x1C\xAC\xB1\xB1\xB1\xC4\xDE\xCE\x9A\x60\x1F\x47\xC9\x07\xB9\xCA\x4E\x68\xAB\xDA\x46\x51\x66\x3C\x51\x2B\x82\x09\x09\x09\x20\x34\xD8\x8F\xD8\x88\x65\xAC\x08\x0B\xE2\xF5\x9D\x7A\x76\xE7\x26\xE3\xEB\x17\xC8\xFA\xC4\x04\xD6\xAF\x4F\x14\xE2\xFF\x17\x70\xE5\x67\x72\xE3\x55\xB1\x26\x71\x8D\x58\xAB\x24\x7C\x99\x2F\x51\x21\x12\x1C\x62\xBB\xB7\x5A\x85\xA3\x10\xAA\x55\x76\xB8\x3B\x5B\xBF\xAB\xB9\x38\xE1\xA6\xB2\xC5\xD5\xC5\x96\xEC\x94\x18\x9A\xAA\x77\x52\x55\x92\xC5\xCE\x9C\x64\x52\xD7\xC7\xA3\x09\x0A\xA2\xB7\xBE\x92\x4C\xF9\xDB\x09\x89\xE9\xBB\x8D\x15\x5C\xAC\xA9\x60\x57\x6E\x3A\x25\x5B\x33\x69\x1B\x9A\xE4\xAA\x88\xE8\x14\x5C\x1B\x7B\x66\x82\xF1\xB3\xC2\x58\xFB\xB0\x65\x01\xD2\xF5\x41\xAC\x92\xCE\xD7\xF8\x7A\x9A\xA2\x38\xD8\xDB\x1E\x27\x7B\x4B\x11\xE5\x63\x2A\x8D\xAD\x9D\x92\xA0\x40\x1F\x42\x24\xF5\xCE\x56\xE6\x33\x70\xBE\x9C\x03\x72\xF8\x6C\xCD\x4C\xE1\x64\x4D\x35\x9B\xD2\x53\xE9\xAD\x2D\xE7\xEC\xFE\x7C\x12\xE3\x56\xA2\x6B\x3F\x42\xCF\x99\x52\xEE\xD4\x16\xF3\x71\x69\x0E\xCD\xF7\x46\xE8\x9A\xFA\xCC\x44\x7A\x7D\xFC\xF9\x2F\x50\x68\xC5\xCE\x48\xC9\xEE\xE8\x50\x8D\xD4\xDD\xC7\x94\x5A\x8E\x0E\x12\xA9\x16\x16\xA6\xCE\x2F\xCA\x5A\xCB\xA9\x8A\x3C\x62\xC2\xB5\x04\x06\x06\x90\x9E\x12\xCF\x58\x7B\x15\xD3\x57\xAA\xD0\xB7\x1D\xA4\xAF\x76\x0F\xCF\xBA\x4E\xD2\x7E\xA4\x98\xE1\x96\xC3\xCC\x5C\x3F\xC6\x9A\x98\x08\x06\xCE\x55\x30\x75\xE3\x04\x23\x2D\x07\x38\x5A\xBE\x85\x0B\xB7\x1F\xD2\x3D\xF5\x29\xD7\x46\x67\xB8\x6E\x98\xE5\xC6\xD8\x53\xBA\xC6\xA5\x09\x3D\xE5\x60\x08\xF6\xF3\x42\xEB\xEF\x69\xEA\x01\x95\x44\xAB\xBB\xA3\xB9\xE4\xBA\xA5\xA4\x9B\x92\xED\x22\x60\x67\xF6\x1A\xB2\x52\xE3\x08\x08\xF0\xC3\xD7\xC7\x9B\x07\x4D\x07\xF8\x7E\xE8\x12\xFF\xFA\xA8\x99\xBF\x8C\xB4\xF3\xC3\x50\x1B\x6F\x06\x1B\x64\x47\x74\x32\x7B\xAD\x9A\x8C\x94\x38\xAA\x4B\x72\x4D\xB9\x70\x4B\x5C\x38\xBB\xFF\x43\xDA\xEE\x3E\xA2\x7B\xE2\x39\xD7\x74\xD3\x5C\x17\x11\x37\x44\x44\x97\x88\x50\xB8\x8B\x00\x6F\x89\x52\x3B\x3B\x5B\xE6\xCD\x9D\xC3\xFC\x79\xF3\x89\x88\x8E\xC6\x5D\x2D\xA9\x27\x0D\x98\x20\xF1\x1B\x1B\xA9\x25\x4D\xBA\x39\x2E\x26\x1C\x47\x95\x0B\x15\xDB\x36\xF2\xED\xBD\x06\x53\x06\x7C\xFF\xF8\x12\x3F\xE9\x2F\xF3\xDD\xE3\x16\xFE\xFC\xA0\x99\xE9\xCE\x6A\x8A\x73\x93\x4C\x22\xBE\x7B\x78\x89\xD1\xD6\x43\x9C\xAC\xFC\x90\xCB\x8F\x0C\x26\x01\x46\xE2\x6E\x59\xF9\x7B\x28\xAC\xCC\xCD\x30\x5F\xBC\x90\xC5\x92\x80\x01\xC1\x21\x94\x1D\x3D\xCD\x55\xFD\x13\xB2\xF3\xF3\xB0\xB7\x5A\x28\x2E\x48\xC4\x46\x85\xB1\x29\x25\x96\x84\xD8\x70\x3C\xBD\xBC\x49\x88\x5F\x49\xC3\xC7\xF9\xB2\x0D\x4F\xF0\xA3\xAE\x45\xF2\xA0\x4D\x4A\x72\x84\xD7\xB7\xEB\xA8\x96\x7C\xC8\xDF\xB4\x96\xC6\x83\x1F\xF2\xAA\xBF\x8E\x9F\x86\x9A\x68\x3B\xB9\x87\x8E\xC7\x93\xDC\x14\xC2\xAE\x51\x11\x20\x0D\xD8\x2D\xAB\xEF\x91\xAB\x62\xC3\xD6\x6D\xE4\x95\xEE\x93\xA1\xA1\x8D\x2B\xC3\x93\xF4\x4E\x7F\xCE\xB1\x86\x26\x34\xD2\x0F\x5E\xAE\x36\x12\x48\xF6\xA8\x5D\xE4\x50\x8A\xD1\xA2\x0D\xF2\xC1\xC3\xD3\x1D\xB5\xBB\x9A\x75\x72\x40\x55\x09\x59\x6F\xED\x5E\x06\xCF\xEE\x41\x77\xE9\x00\x53\x97\xAB\xE8\x3E\x59\xC2\x47\xC5\xD9\xEC\x93\x39\xA1\x54\x4E\xD1\x2B\x87\xC4\xFE\xC6\x1A\x6E\x48\x00\xF5\x88\xF5\x3D\xD2\x84\xBD\x46\x88\x80\x5B\xE3\x52\x82\x3E\x21\xEC\x17\xF4\x4E\xBC\xA0\xF3\xD1\x38\x37\x86\x9F\xD0\x78\xA3\x8F\x20\x1F\x3B\xBC\xDC\xAC\x25\xF7\xCD\xE5\x6A\x85\xB9\x85\xB9\xA4\xA5\x92\x15\xC1\x5E\x04\xF8\xFB\xE1\xE7\xE7\x4B\x8C\x34\x5B\x5A\x4A\x02\x97\x8F\x14\x99\xAC\x7F\xD8\xB4\x5F\x82\xA8\x9C\x63\xC5\x49\x6C\x88\xF3\x25\x73\x5D\x38\xBB\xD3\x34\xD4\xD4\x7C\x44\xFF\xCC\x17\xF4\x8D\xCD\x30\x20\xC4\xEF\xD1\x2F\x50\x5C\x13\xD2\xAB\x82\x6B\x8F\x85\x7C\x64\x92\xEB\xC3\x13\x74\xE9\xA7\x38\xDE\xD8\x44\x4C\xA4\x3F\x2B\x23\x03\x65\xEF\x3B\x31\x57\x7A\xC3\x43\x9C\xC8\x88\x72\x66\xDD\x4A\x1F\x34\x1A\x0D\xE1\xA1\x5A\xA2\xA2\x23\xE8\xAD\xDB\xCD\x84\xEC\x8C\x43\xDB\x92\xC9\x8C\x51\x11\x13\xA2\x22\x37\x29\x82\x03\xDB\x37\xB1\x76\xD5\x32\x7C\xBC\x1C\x68\xE9\xBD\xCB\x9D\xA9\x67\xF4\x8D\x4E\x30\x30\x3E\x25\x30\x5E\x27\x51\x74\xEB\xA7\xE9\xD6\x4D\xBD\xC3\x88\x40\xCA\x70\x43\xC4\xF4\xE8\x66\xE8\x1E\x1A\xA3\xBE\xF3\x2A\xB6\x36\x36\xCC\x9F\x3F\x9F\x25\x72\x10\x69\x97\x2A\x29\x8C\x73\x61\x5D\x94\x06\xFF\x40\x09\xAE\xD0\x60\xAE\x89\xED\xCD\x07\x0A\xD8\x93\xEC\x4E\x72\x98\x03\x07\x4B\xB6\xD0\x79\xBC\x8C\x43\xC5\x9B\xA9\x2C\xCA\x21\x5C\xE3\x4A\x55\xED\x69\x06\xA7\x9E\x70\x6B\x74\x94\xFE\xF1\x71\x6E\x4F\x4C\x32\x30\x31\x21\x25\x18\x9B\xA4\xDF\x30\xC9\x2D\x59\xF5\x2D\xFD\x18\xBD\x3A\x83\x09\xDD\x23\x06\xAE\xF4\xF5\x50\x98\x9F\xC6\xBC\xF9\x0B\x24\x8E\xAD\xB1\x94\x71\xCD\x41\x69\xC3\x72\x3F\x07\x8A\x13\x9C\x24\xB2\xDD\x88\x91\x06\xAD\x96\x71\x2D\x31\xC2\x9D\x8D\x51\x6E\xA4\xC4\x86\xF0\x3F\x72\x1C\x3F\xBD\x79\x46\xC8\x33\x88\x8F\x0A\x62\x43\x6A\xBC\xF4\x55\x1D\x57\x06\x6F\x9B\x56\x3E\x28\xE4\x83\x13\x53\xDC\x11\x28\xFA\x0D\x63\xA6\x87\xFD\x63\xE3\x52\xA3\x31\xFA\xE4\x73\x8F\x4E\xC7\x9D\x27\xB3\x14\x16\x17\x11\xA5\xF5\xC0\x5A\x1C\x30\x92\xAB\x64\x9A\xF1\xF6\x72\xC7\x41\xA2\x3B\x39\xD4\x8E\xDD\x89\x4E\x6C\x49\xF4\x65\xDB\x7A\x3F\x36\xAE\x52\xE3\x25\x56\x27\xAD\x0E\x61\x50\x42\xA8\xF9\xA3\x6C\x3E\xCE\x8F\x91\xF1\xCD\x85\x42\x99\x94\x6F\x1B\xC6\x19\x10\xDC\x11\xDB\x8D\xC4\x46\x0C\x1A\x4B\xD0\xAB\x17\x4B\x84\xBC\x5F\xFE\x78\x7B\x4C\xEA\x22\xD7\x5B\xF2\xAC\xF3\xDE\x7D\xD6\x27\x84\xCB\x19\x21\x93\x6D\xC8\x52\x71\x40\x46\x30\x39\x25\xA3\x65\xC5\x39\x9B\x8C\x53\x8E\x15\x61\xFE\xF6\xE4\xC7\xDB\x53\xBA\xD6\x91\xC2\x78\x27\x56\x87\x39\x91\x19\xAD\x22\x2F\xC1\x5D\xCA\xE1\x46\x4D\xA6\x27\xA7\xB2\x7D\x28\x5C\xA3\xA6\x43\xDC\xBC\x3F\x3D\x6B\xE2\x30\x12\x9B\x04\x88\xFB\x8A\x5B\xBA\x51\x13\xA1\xF1\xDA\xA7\x37\x98\x70\x57\x6A\x75\xAE\xF3\x1A\xF5\x87\xF3\xB9\x71\xBE\x84\x8C\xB5\xA1\xEC\x92\x1F\x1C\xC1\x32\xA4\xAA\x5C\x5D\x68\x39\xB6\xD3\x94\x90\x16\x32\x21\x69\x65\x3E\xD8\xB8\x42\xC9\xE6\x68\x41\x8C\x08\x88\x71\x23\x5D\xC6\xBC\x8D\xD1\x2E\x64\xC4\xA8\xC9\x58\xA5\x22\x25\xDC\x8A\x8A\xF2\x6D\x3C\x78\xF2\x8C\x41\x71\xF8\x9E\x34\xE1\x3D\x11\x70\xCF\xE8\x80\x49\x80\xA0\x77\x44\x4F\xF7\xA3\x21\x13\x1E\xCE\x3C\x23\x31\x6D\x3D\x21\x1A\x67\x7E\x3F\xD4\xC8\x27\x1D\x7B\xF9\xA8\x28\x81\xEA\xBD\x99\x64\x6E\x58\xC7\xF6\xBC\x14\xEE\x34\x54\x92\x91\x1C\xC3\x32\xAD\x0C\xAA\x72\x8E\x38\x39\xD9\x11\xE0\x65\x23\x3B\x40\xC9\xEA\xE5\x2A\x52\x57\xC9\x84\x1C\xA6\x26\x72\x55\x24\xDE\x32\x3F\x44\xAF\x5C\xC6\xDD\x89\x71\xEE\x8E\x8B\x80\xC9\x09\xEE\xFF\x0C\x45\xEF\x90\x8E\x9E\xA1\x11\x7A\x1E\x0F\x73\x6B\x58\xCF\xE3\xA7\x2F\x28\xDB\x5F\xC9\x6F\x7F\xA3\xE0\x57\xFF\xA2\x20\x54\x44\x4C\x0D\x9E\x64\xAA\xEF\x88\x4C\x41\x09\x34\x1F\x2B\xA0\xA1\xA6\x98\x6B\xB5\x15\x34\x1C\xDC\x4E\x9E\xA4\x5E\xE7\x89\x5D\x5C\x3B\xBE\x93\x9D\x12\xC1\x39\xA9\x31\xD2\x0B\xAE\xB8\xB9\x2A\x71\x71\xB0\x60\xCD\xDA\x38\xB6\x6E\x2F\x22\x6D\x63\x1A\xBA\x99\x59\xEE\x8B\xDB\x9F\x8C\x1A\x78\x20\x65\x7F\x20\x6E\x28\xFA\x47\x46\x18\x94\x87\x03\xD2\x78\x57\xFA\xFB\x38\x5C\x73\x02\x2B\xEB\xF9\xCC\xF9\x40\xC1\xE2\x85\xFF\x6C\x12\xB1\x54\x56\x76\xFB\xF2\x21\xFE\x38\x73\x95\xD9\x4F\x6A\x99\xB9\x7F\x96\xC7\x37\x6B\xB8\x79\xA9\x8A\x0B\x27\x4A\x68\xA9\x2E\xE6\x85\x9C\x88\xDF\xCB\xE1\xD4\x7B\x76\x2F\x99\x1B\x57\x13\xB8\xD4\x19\x5F\x0F\x67\x34\xCB\x34\x5C\xEF\xEF\xE5\xC1\xA8\x8E\x47\x63\xA3\x3C\x32\xC8\x22\xE5\xFA\x78\x5C\xEE\xC7\xF4\x28\x06\x86\x86\x68\x6C\x6D\x23\x76\x75\x82\xCC\xF8\x6A\x94\x8B\x2D\xF0\x97\x5F\x2E\x36\xE6\xBF\x63\xDE\xBC\x7F\x14\x11\xFF\x24\xBF\x13\xFE\x41\x0E\xAB\xDF\xD2\x78\x6A\x37\x7F\xF9\xC6\xC0\x7F\x7C\x37\xCB\x8F\x7F\x30\xF0\xA7\xDF\x3F\xE0\xED\xF3\x41\xA6\xEE\x5F\x60\xEC\x76\x03\x93\x3D\x75\x34\x4B\x2A\xE6\x65\xA7\x70\xAB\xFD\x38\x47\xF7\xA4\x73\xE2\xCC\x29\x0C\x4F\x9F\x88\x80\x11\x13\x1E\x1A\x74\x26\x72\x93\x80\x71\x3D\xFF\x07\xBC\x56\x64\x24\x3B\xC4\x6A\x82\x00\x00\x00\x00\x49\x45\x4E\x44\xAE\x42\x60\x82";
auto custom_ponce_icon = load_custom_icon(ponce_icon, sizeof(ponce_icon), "png");
update_action_icon(action_IDA_ponce_banner.name, custom_ponce_icon);
if (!hook_to_notification_point(HT_UI, ui_callback, NULL)) {
warning("[!] Could not hook ui callback");
return false;
}
if (!hook_to_notification_point(HT_DBG, tracer_callback, NULL)) {
warning("[!] Could not hook tracer callback");
return false;
}
msg("[+] Ponce plugin running!\n");
hooked = true;
}
return true;
}
//--------------------------------------------------------------------------
#if IDA_SDK_VERSION >= 760
plugmod_t* idaapi init(void)
#elif IDA_SDK_VERSION == 750
size_t idaapi init(void)
#else
int idaapi init(void)
#endif
{
char version[8];
//We do some checks with the versions...
if (get_kernel_version(version, sizeof(version))) {
#if IDA_SDK_VERSION == 760
if (strcmp(version, "7.6") != 0) {
#elif IDA_SDK_VERSION == 750
if (strcmp(version, "7.5") != 0) {
#elif IDA_SDK_VERSION == 740
if (strcmp(version, "7.4") != 0) {
#elif IDA_SDK_VERSION == 730
if (strcmp(version, "7.3") != 0) {
#elif IDA_SDK_VERSION == 720
if (strcmp(version, "7.2") != 0) {
#elif IDA_SDK_VERSION == 710
if (strcmp(version, "7.1") != 0) {
#elif IDA_SDK_VERSION == 700
if (strcmp(version, "7.00") != 0) {
#elif IDA_SDK_VERSION < 700
#error "Ponce does not support IDA < 7.0"
#endif
warning("[!] This Ponce plugin was built for IDA %d, you are using: %s\n", IDA_SDK_VERSION, version);
}
}
else {
error("Can't detect the IDA version you are running");
}
if (int(version[0]) < 7) {
warning("[!] Ponce plugin can't run with IDA version < 7. Please use a newer IDA version");
return PLUGIN_SKIP;
}
#ifdef BUILD_HEXRAYS_SUPPORT
/* try to use hexrays if possible*/
if (init_hexrays_plugin()) {
install_hexrays_callback(ponce_hexrays_callback, NULL);
msg("[+] Hex-rays version %s has been detected, Ponce will use it to provide more info\n", get_hexrays_version());
hexrays_present = true;
}
#endif
// Start Ponce when IDA starts
if(run(0))
return PLUGIN_KEEP;
else
return PLUGIN_SKIP;
}
//--------------------------------------------------------------------------
void idaapi term(void)
{
// remove snapshot if exists
snapshot.resetEngine();
// We want to delete Ponce comments and colours before terminating
delete_ponce_comments();
#ifdef BUILD_HEXRAYS_SUPPORT
remove_hexrays_callback(ponce_hexrays_callback, NULL);
#endif
// Unhook notifications
unhook_from_notification_point(HT_UI, ui_callback, NULL);
unhook_from_notification_point(HT_DBG, tracer_callback, NULL);
// Unregister and detach menus
unregister_action(action_IDA_show_config.name);
detach_action_from_menu("Edit/Ponce/", action_IDA_show_config.name);
unregister_action(action_IDA_show_expressionsWindow.name);
detach_action_from_menu("Edit/Ponce/", action_IDA_show_expressionsWindow.name);
unregister_action(action_IDA_unload.name);
detach_action_from_menu("Edit/Ponce/", action_IDA_unload.name);
unregister_action(action_IDA_clean.name);
detach_action_from_menu("Edit/Ponce/", action_IDA_clean.name);
detach_action_from_menu("Edit/Ponce/", "");
hooked = false;
}
//--------------------------------------------------------------------------
//
// PLUGIN DESCRIPTION BLOCK
//
//--------------------------------------------------------------------------
plugin_t PLUGIN =
{
IDP_INTERFACE_VERSION,
0, // plugin flags
init, // initialize
term, // terminate. this pointer may be NULL.
run, // invoke plugin
"Ponce, a concolic execution plugin for IDA", // long comment about the plugin
"", // multiline help about the plugin
"Ponce", // the preferred short name of the plugin
"" // the preferred hotkey to run the plugin
};
| 96.331839 | 13,540 | 0.707383 | CrackerCat |
aaa773dbc0c43b8c14227438b71557ccd8d501f6 | 6,932 | cc | C++ | src/apps/vod/VoDUDPServer.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 58 | 2021-04-15T09:20:26.000Z | 2022-03-31T08:52:23.000Z | src/apps/vod/VoDUDPServer.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 34 | 2021-05-14T15:05:36.000Z | 2022-03-31T20:51:33.000Z | src/apps/vod/VoDUDPServer.cc | talal00/Simu5G | ffbdda3e4cd873b49d7022912fe25e39d1a503e8 | [
"Intel"
] | 30 | 2021-04-16T05:46:13.000Z | 2022-03-28T15:26:29.000Z | //
// Simu5G
//
// Authors: Giovanni Nardini, Giovanni Stea, Antonio Virdis (University of Pisa)
//
// This file is part of a software released under the license included in file
// "license.pdf". Please read LICENSE and README files before using it.
// The above files and the present reference are part of the software itself,
// and cannot be removed from it.
//
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <inet/common/TimeTag_m.h>
#include "apps/vod/VoDUDPServer.h"
Define_Module(VoDUDPServer);
using namespace std;
using namespace inet;
VoDUDPServer::VoDUDPServer()
{
}
VoDUDPServer::~VoDUDPServer()
{
}
void VoDUDPServer::initialize(int stage)
{
cSimpleModule::initialize(stage);
if (stage != INITSTAGE_APPLICATION_LAYER)
return;
EV << "VoD Server initialize: stage " << stage << endl;
serverPort = par("localPort");
inputFileName = par("vod_trace_file").stringValue();
traceType = par("traceType").stringValue();
fps = par("fps");
double one = 1.0;
TIME_SLOT = one / fps;
numStreams = 0;
// set up Udp socket
socket.setOutputGate(gate("socketOut"));
socket.bind(serverPort);
int tos = par("tos");
if (tos != -1)
socket.setTos(tos);
if (!inputFileName.empty())
{
// Check whether string is empty
if (traceType.compare("SVC") != 0)
throw cRuntimeError("VoDUDPServer::initialize - only SVC trace is currently available. Abort.");
infile.open(inputFileName.c_str(), ios::in);
if (infile.bad()) /* Or file is bad */
throw cRuntimeError("Error while opening input file (File not found or incorrect type)");
infile.seekg(0, ios::beg);
long int i = 0;
while (!infile.eof())
{
svcPacket tmp;
tmp.index = i;
infile >> tmp.memoryAdd >> tmp.length >> tmp.lid >> tmp.tid >> tmp.qid >>
tmp.frameType >> tmp.isDiscardable >> tmp.isTruncatable >> tmp.frameNumber
>> tmp.timestamp >> tmp.isControl;
svcTrace_.push_back(tmp);
i++;
}
svcPacket tmp;
tmp.index = LONG_MAX;
svcTrace_.push_back(tmp);
}
/* Initialize parameters after the initialize() method */
EV << "VoD Server initialize: Trace: " << inputFileName << " trace type " << traceType << endl;
cMessage* timer = new cMessage("Timer");
double start = par("startTime");
double offset = (double) start + simTime().dbl();
scheduleAt(offset, timer);
}
void VoDUDPServer::finish()
{
if (infile.is_open())
infile.close();
}
void VoDUDPServer::handleMessage(cMessage *msg)
{
if (msg->isSelfMessage())
{
if (!strcmp(msg->getName(), "Timer"))
{
clientsPort = par("destPort");
// vclientsPort = cStringTokenizer(clientsPort).asIntVector();
clientsStartStreamTime = par("clientsStartStreamTime").doubleValue();
//vclientsStartStreamTime = cStringTokenizer(clientsStartStreamTime).asDoubleVector();
clientsReqTime = par("clientsReqTime");
vclientsReqTime = cStringTokenizer(clientsReqTime).asDoubleVector();
int size = 0;
const char *destAddrs = par("destAddresses");
cStringTokenizer tokenizer(destAddrs);
const char *token;
while ((token = tokenizer.nextToken()) != nullptr)
{
clientAddr.push_back(L3AddressResolver().resolve(token));
size++;
}
/* Register video streams*/
for (int i = 0; i < size; i++)
{
M1Message* M1 = new M1Message();
M1->setClientAddr(clientAddr[i]);
M1->setClientPort(clientsPort);
double npkt;
npkt = clientsStartStreamTime;
M1->setNumPkSent((int) (npkt * fps));
numStreams++;
EV << "VoD Server self message: Dest IP: " << clientAddr[i] << " port: " << clientsPort << " start stream: " << (int)(npkt* fps) << endl;
// scheduleAt(simTime() + vclientsReqTime[i], M1);
scheduleAt(simTime(), M1);
}
delete msg;
return;
}
else
handleSVCMessage(msg);
}
else
delete msg;
}
void VoDUDPServer::handleSVCMessage(cMessage *msg)
{
M1Message* msgNew = (M1Message*) msg;
long numPkSentApp = msgNew->getNumPkSent();
if (svcTrace_[numPkSentApp].index == LONG_MAX)
{
/* End of file, send finish packet */
Packet* fm = new Packet("VoDFinishPacket");
socket.sendTo(fm, msgNew->getClientAddr(), msgNew->getClientPort());
return;
}
else
{
int seq_num = numPkSentApp;
int currentFrame = svcTrace_[numPkSentApp].frameNumber;
Packet* packet = new Packet("VoDPacket");
auto frame = makeShared<VoDPacket>();
frame->setFrameSeqNum(seq_num);
frame->setPayloadTimestamp(simTime());
frame->setChunkLength(B(svcTrace_[numPkSentApp].length));
frame->setFrameLength(svcTrace_[numPkSentApp].length + 2 * sizeof(int)); /* Seq_num plus frame length plus payload */
frame->setTid(svcTrace_[numPkSentApp].tid);
frame->setQid(svcTrace_[numPkSentApp].qid);
frame->addTag<CreationTimeTag>()->setCreationTime(simTime());
packet->insertAtBack(frame);
socket.sendTo(packet, msgNew->getClientAddr(), msgNew->getClientPort());
numPkSentApp++;
while (1)
{
/* Get infos about the frame from file */
if (svcTrace_[numPkSentApp].index == LONG_MAX)
break;
int seq_num = numPkSentApp;
if (svcTrace_[numPkSentApp].frameNumber != currentFrame)
break; // Finish sending packets belonging to the current frame
Packet* packet = new Packet("VoDPacket");
auto frame = makeShared<VoDPacket>();
frame->setTid(svcTrace_[numPkSentApp].tid);
frame->setQid(svcTrace_[numPkSentApp].qid);
frame->setFrameSeqNum(seq_num);
frame->setPayloadTimestamp(simTime());
frame->setChunkLength(B(svcTrace_[numPkSentApp].length));
frame->setFrameLength(svcTrace_[numPkSentApp].length + 2 * sizeof(int)); /* Seq_num plus frame length plus payload */
frame->addTag<CreationTimeTag>()->setCreationTime(simTime());
packet->insertAtBack(frame);
socket.sendTo(packet, msgNew->getClientAddr(), msgNew->getClientPort());
EV << " VoDUDPServer::handleSVCMessage sending frame " << seq_num << std::endl;
numPkSentApp++;
}
msgNew->setNumPkSent(numPkSentApp);
scheduleAt(simTime() + TIME_SLOT, msgNew);
}
}
| 33.814634 | 153 | 0.594201 | talal00 |
aaa817e3d4addd5459537bd43baec980757528b9 | 7,027 | cpp | C++ | printscan/wia/drivers/util/gdipconv.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/wia/drivers/util/gdipconv.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/wia/drivers/util/gdipconv.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /****************************************************************************
*
* (C) COPYRIGHT 2000, MICROSOFT CORP.
*
* FILE: gdipconv.cpp
*
* VERSION: 1.0
*
* DATE: 11/10/2000
*
* AUTHOR: Dave Parsons
*
* DESCRIPTION:
* Helper functions for using GDI+ to convert image formats.
*
*****************************************************************************/
#include "pch.h"
using namespace Gdiplus;
CWiauFormatConverter::CWiauFormatConverter() :
m_Token(NULL),
m_EncoderCount(0),
m_pEncoderInfo(NULL)
{
memset(&m_guidCodecBmp, 0, sizeof(m_guidCodecBmp));
}
CWiauFormatConverter::~CWiauFormatConverter()
{
if (m_pEncoderInfo)
{
delete []m_pEncoderInfo;
m_pEncoderInfo = NULL;
}
if (m_Token)
{
GdiplusShutdown(m_Token);
m_Token = NULL;
}
}
HRESULT CWiauFormatConverter::Init()
{
HRESULT hr = S_OK;
GpStatus Status = Ok;
//
// Locals
//
GdiplusStartupInput gsi;
ImageCodecInfo *pEncoderInfo = NULL;
if (m_pEncoderInfo != NULL) {
wiauDbgError("Init", "Init has already been called");
goto Cleanup;
}
//
// Start up GDI+
//
Status = GdiplusStartup(&m_Token, &gsi, NULL);
if (Status != Ok)
{
wiauDbgError("Init", "GdiplusStartup failed");
hr = E_FAIL;
goto Cleanup;
}
UINT cbCodecs = 0;
Status = GetImageEncodersSize(&m_EncoderCount, &cbCodecs);
if (Status != Ok)
{
wiauDbgError("Init", "GetImageEncodersSize failed");
hr = E_FAIL;
goto Cleanup;
}
m_pEncoderInfo = new BYTE[cbCodecs];
REQUIRE_ALLOC(m_pEncoderInfo, hr, "Init");
pEncoderInfo = (ImageCodecInfo *) m_pEncoderInfo;
Status = GetImageEncoders(m_EncoderCount, cbCodecs, pEncoderInfo);
if (Ok != Status)
{
wiauDbgError("Init", "GetImageEncoders failed");
hr = E_FAIL;
goto Cleanup;
}
for (UINT count = 0; count < m_EncoderCount; count++)
{
if (pEncoderInfo[count].FormatID == ImageFormatBMP)
{
m_guidCodecBmp = pEncoderInfo[count].Clsid;
break;
}
}
Cleanup:
if (FAILED(hr)) {
if (m_pEncoderInfo)
delete []m_pEncoderInfo;
m_pEncoderInfo = NULL;
}
return hr;
}
BOOL CWiauFormatConverter::IsFormatSupported(const GUID *pguidFormat)
{
BOOL result = FALSE;
ImageCodecInfo *pEncoderInfo = (ImageCodecInfo *) m_pEncoderInfo;
for (UINT count = 0; count < m_EncoderCount; count++)
{
if (pEncoderInfo[count].FormatID == *pguidFormat)
{
result = TRUE;
break;
}
}
return result;
}
HRESULT CWiauFormatConverter::ConvertToBmp(BYTE *pSource, INT iSourceSize,
BYTE **ppDest, INT *piDestSize,
BMP_IMAGE_INFO *pBmpImageInfo, SKIP_AMOUNT iSkipAmt)
{
HRESULT hr = S_OK;
//
// Locals
//
GpStatus Status = Ok;
CImageStream *pInStream = NULL;
CImageStream *pOutStream = NULL;
Image *pSourceImage = NULL;
BYTE *pTempBuf = NULL;
SizeF gdipSize;
//
// Check args
//
REQUIRE_ARGS(!pSource || !ppDest || !piDestSize || !pBmpImageInfo, hr, "ConvertToBmp");
memset(pBmpImageInfo, 0, sizeof(BMP_IMAGE_INFO));
//
// Create a CImageStream from the source memory
//
pInStream = new CImageStream;
REQUIRE_ALLOC(pInStream, hr, "ConvertToBmp");
hr = pInStream->SetBuffer(pSource, iSourceSize);
REQUIRE_SUCCESS(hr, "ConvertToBmp", "SetBuffer failed");
//
// Create a GDI+ Image object from the IStream
//
pSourceImage = new Image(pInStream);
REQUIRE_ALLOC(pSourceImage, hr, "ConvertToBmp");
if (pSourceImage->GetLastStatus() != Ok)
{
wiauDbgError("ConvertToBmp", "Image constructor failed");
hr = E_FAIL;
goto Cleanup;
}
//
// Ask GDI+ for the image dimensions, and fill in the
// passed structure
//
Status = pSourceImage->GetPhysicalDimension(&gdipSize);
if (Status != Ok)
{
wiauDbgError("ConvertToBmp", "GetPhysicalDimension failed");
hr = E_FAIL;
goto Cleanup;
}
pBmpImageInfo->Width = (INT) gdipSize.Width;
pBmpImageInfo->Height = (INT) gdipSize.Height;
PixelFormat PixFmt = pSourceImage->GetPixelFormat();
DWORD PixDepth = (PixFmt & 0xFFFF) >> 8; // Cannot assume image is always 24bits/pixel
if( PixDepth < 24 )
PixDepth = 24;
pBmpImageInfo->ByteWidth = ((pBmpImageInfo->Width * PixDepth + 31) & ~31) / 8;
pBmpImageInfo->Size = pBmpImageInfo->ByteWidth * pBmpImageInfo->Height;
switch (iSkipAmt) {
case SKIP_OFF:
pBmpImageInfo->Size += sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);
break;
case SKIP_FILEHDR:
pBmpImageInfo->Size += sizeof(BITMAPINFOHEADER);
break;
case SKIP_BOTHHDR:
break;
default:
break;
}
if (pBmpImageInfo->Size == 0)
{
wiauDbgError("ConvertToBmp", "Size of image is zero");
hr = E_FAIL;
goto Cleanup;
}
//
// See if the caller passed in a destination buffer, and make sure
// it is big enough.
//
if (*ppDest) {
if (*piDestSize < pBmpImageInfo->Size) {
wiauDbgError("ConvertToBmp", "Passed buffer is too small");
hr = E_INVALIDARG;
goto Cleanup;
}
}
//
// Otherwise allocate memory for a buffer
//
else
{
pTempBuf = new BYTE[pBmpImageInfo->Size];
REQUIRE_ALLOC(pTempBuf, hr, "ConvertToBmp");
*ppDest = pTempBuf;
*piDestSize = pBmpImageInfo->Size;
}
//
// Create output IStream
//
pOutStream = new CImageStream;
REQUIRE_ALLOC(pOutStream, hr, "ConvertToBmp");
hr = pOutStream->SetBuffer(*ppDest, pBmpImageInfo->Size, iSkipAmt);
REQUIRE_SUCCESS(hr, "ConvertToBmp", "SetBuffer failed");
//
// Write the Image to the output IStream in BMP format
//
pSourceImage->Save(pOutStream, &m_guidCodecBmp, NULL);
if (pSourceImage->GetLastStatus() != Ok)
{
wiauDbgError("ConvertToBmp", "GDI+ Save failed");
hr = E_FAIL;
goto Cleanup;
}
Cleanup:
if (FAILED(hr)) {
if (pTempBuf) {
delete []pTempBuf;
pTempBuf = NULL;
*ppDest = NULL;
*piDestSize = 0;
}
}
if (pInStream) {
pInStream->Release();
}
if (pOutStream) {
pOutStream->Release();
}
if (pSourceImage) {
delete pSourceImage;
}
return hr;
}
| 24.742958 | 96 | 0.54931 | npocmaka |
aaacd4d00260bf51d9070e3beb6b473c489b7652 | 8,724 | cpp | C++ | core/ir/node.cpp | lqwang1025/Eutopia | 5ecb47805fd650bd7580cd3702032a98378e334f | [
"Apache-2.0"
] | 2 | 2021-08-29T00:22:23.000Z | 2021-09-13T13:16:52.000Z | core/ir/node.cpp | lqwang1025/Eutopia | 5ecb47805fd650bd7580cd3702032a98378e334f | [
"Apache-2.0"
] | null | null | null | core/ir/node.cpp | lqwang1025/Eutopia | 5ecb47805fd650bd7580cd3702032a98378e334f | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* License); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* (C) COPYRIGHT Daniel Wang Limited.
* File : node.cpp
* Authors : Daniel Wang
* Create Time: 2021-08-09:22:02:38
* Email : wangliquan21@qq.com
* Description:
*/
#include "core/ir/node.h"
#include "core/ir/tensor.h"
#include "op/op.h"
#include "op/ops_param.h"
#include "op/cpu/op_register.h"
#include "utils/filler.h"
#include <iostream>
namespace eutopia {
namespace core {
namespace ir {
using InputShapes = std::vector< std::vector<uint32_t> >;
Node::Node(Graph* graph): graph_(graph) {
op_ = nullptr;
name_ = "";
index_ = -1;
op_type_ = "";
output_shape_.resize(0);
is_trainning_ = false;
is_quantize_ = false;
weight_shared_ = false;
is_sparse_ = false;
is_first_node_ = false;
is_last_node_ = false;
dynamic_shape_ = false;
in_place_ = false;
device_ = "cpu";
producers_.resize(0);
consumers_.resize(0);
weight_ = nullptr;
bias_ = nullptr;
output_tensor_ = nullptr;
diff_tensor_ = nullptr;
weight_filler_ = nullptr;
bias_filler_ = nullptr;
set_is_trainning(false);
set_dynamic_shape(false);
}
Node::Node(Graph* graph, const op::BaseParam* param): Node(graph) {
setup(param);
}
void Node::setup(const op::BaseParam* param) {
set_op_type(param->op_type);
set_name(param->op_name);
set_is_sparse(param->sparse);
set_is_quantize(param->quantize);
set_weight_shared(param->weight_shared);
set_is_first_node(param->first_op);
set_is_last_node(param->last_op);
op_ = op::Holder::get_op_creator(op_type_)(param);
op_->set_node(this);
output_tensor_ = new Tensor;
CHECK(output_tensor_!=nullptr, "Alloc mem failed.")
output_tensor_->set_name(param->op_name);
diff_tensor_ = new Tensor;
CHECK(diff_tensor_!=nullptr, "Alloc mem failed.");
diff_tensor_->set_name(param->op_name);
}
void Node::infer_shape(const InputShapes& input_shapes) {
op_->infer_shape(input_shapes, output_shape_);
}
void Node::set_graph(Graph* graph) {
graph_ = graph;
}
const Graph* Node::get_graph(void) const {
return graph_;
}
void Node::set_weight_filler(utils::Filler* filler) {
weight_filler_ = filler;
}
void Node::set_bias_filler(utils::Filler* filler) {
bias_filler_ = filler;
}
const std::string& Node::get_name(void) const {
return name_;
}
void Node::set_name(const std::string& name) {
name_ = name;
}
const Tensor* Node::get_output_tensor(void) const {
return output_tensor_;
}
int32_t Node::get_index(void) const {
return index_;
}
void Node::set_index(const int32_t index) {
index_ = index;
}
const std::string& Node::get_op_type(void) const {
return op_type_;
}
void Node::set_op_type(const std::string& op_type) {
op_type_ = op_type;
}
void Node::set_output_shape(const std::vector<uint32_t>& output_shape) {
output_shape_ = output_shape;
}
const std::vector<uint32_t>& Node::get_output_shape(void) const {
return output_shape_;
}
void Node::add_producer(const std::string& producer) {
producers_.push_back(producer);
}
const std::vector<std::string>& Node::get_producers(void) const {
return producers_;
}
void Node::add_consumer(const std::string& consumer) {
consumers_.push_back(consumer);
}
const std::vector<std::string>& Node::get_consumers(void) const {
return consumers_;
}
void Node::set_is_first_node(bool is_first_node) {
is_first_node_ = is_first_node;
}
void Node::set_is_last_node(bool is_last_node) {
is_last_node_ = is_last_node;
}
bool Node::is_last_node(void) const {
return is_last_node_;
}
bool Node::is_first_node(void) const {
return is_first_node_;
}
void Node::set_dynamic_shape(bool dynamic_shape) {
dynamic_shape_ = dynamic_shape;
}
bool Node::dynamic_shape(void) const {
return dynamic_shape_;
}
void Node::set_is_sparse(bool is_sparse) {
is_sparse_ = is_sparse;
}
bool Node::is_sparse(void) const {
return is_sparse_;
}
void Node::set_is_quantize(bool is_quantize) {
is_quantize_ = is_quantize;
}
bool Node::is_quantize(void) const {
return is_quantize_;
}
void Node::set_in_place(bool in_place) {
in_place_ = in_place;
}
bool Node::in_place(void) const {
return in_place_;
}
void Node::set_weight_shared(bool weight_shared) {
weight_shared_ = weight_shared;
}
bool Node::weight_shared(void) const {
return weight_shared_;
}
bool Node::is_trainning(void) const {
return is_trainning_;
}
void Node::set_is_trainning(bool is_trainning) {
is_trainning_ = is_trainning;
}
void Node::set_weight(Tensor* weight) {
weight_ = weight;
}
Tensor* Node::get_weight(void) const {
return weight_;
}
void Node::set_bias(Tensor* bias) {
bias_ = bias;
}
Tensor* Node::get_bias(void) const {
return bias_;
}
void Node::set_input_shape(const std::vector<uint32_t>& input_shape) {
input_shapes_.push_back(input_shape);
}
const InputShapes& Node::get_input_shapes(void) const {
return input_shapes_;
}
void Node::_conv2d_filler() {
CHECK(weight_filler_!=nullptr, "Please assign weight filler.");
CHECK(bias_filler_!=nullptr, "Please assign bias filler.");
op::cpu::Convolution2DOperator* conv2d_op = static_cast<op::cpu::Convolution2DOperator*>(op_);
op::Convolution2DParam* op_param = conv2d_op->op_param_;
std::vector<uint32_t> kernel_shape = op_param->kernel_shape;
CHECK(kernel_shape.size() == 4, "");
if (kernel_shape[1] == 0) { // weight distribution: OcIcHW
uint32_t ic = 0;
for (int i = 0; i < input_shapes_.size(); ++i) {
CHECK(input_shapes_[i].size()==4,"");
ic += input_shapes_[i][1]; // feature distribution: NCHW
}
op_param->kernel_shape[1] = ic;
kernel_shape[1] = ic;
}
weight_ = new Tensor(kernel_shape, DataType::EUTOPIA_DT_FP32);
weight_->set_name(get_name()+"_const_1");
weight_filler_->fill(weight_);
delete weight_filler_;
bias_ = new Tensor({kernel_shape[0]}, DataType::EUTOPIA_DT_FP32);
bias_->set_name(get_name()+"_const_2");
bias_filler_->fill(bias_);
delete bias_filler_;
}
void Node::_fc_filler() {
CHECK(weight_filler_!=nullptr, "Please assign weight filler.");
CHECK(bias_filler_!=nullptr, "Please assign bias filler.");
op::cpu::FullyConnectedOperator* fc_op = static_cast<op::cpu::FullyConnectedOperator*>(op_);
op::FullyConnectedParam* op_param = fc_op->op_param_;
uint32_t num_outputs = op_param->num_outputs;
uint32_t num_inputs = 0;
for (int i = 0; i < (int)input_shapes_.size(); ++i) {
uint32_t flatten = 1;
for (int _i = 1; _i < (int)input_shapes_[i].size(); ++_i) {
flatten *= input_shapes_[i][_i];
}
num_inputs += flatten;
}
CHECK(num_inputs!=0,"");
std::vector<uint32_t> kernel_shape = {num_outputs, num_inputs, 1, 1}; // // weight distribution: OcIcHW
weight_ = new Tensor(kernel_shape, DataType::EUTOPIA_DT_FP32);
weight_->set_name(get_name()+"_const_1");
weight_filler_->fill(weight_);
delete weight_filler_;
bias_ = new Tensor({num_outputs}, DataType::EUTOPIA_DT_FP32);
bias_->set_name(get_name()+"_const_2");
bias_filler_->fill(bias_);
delete bias_filler_;
}
void Node::fill_weight_bias() {
if (fill_func_map_.count(op_type_) != 0) {
(this->*fill_func_map_[op_type_])();
}
}
void Node::forward(const std::vector<const Tensor*> input_tensors) {
op_->forward(input_tensors, output_tensor_);
}
void Node::backward(void) {
//TODO
}
void Node::update(void) {
//TODO
}
void Node::run(void) {
//todo
}
void Node::dump(void) {
//todo
}
Node::~Node(void) {
if (weight_ != nullptr) {
delete weight_;
}
if (bias_ != nullptr) {
delete bias_;
}
delete op_;
delete output_tensor_;
delete diff_tensor_;
}
} // namespace ir
} // namespace core
} // namespace eutopia
| 25.14121 | 107 | 0.685695 | lqwang1025 |
aab0b70d332efe7a18e716c2ad86348b07e41e71 | 805 | cpp | C++ | src/Tokenizer.cpp | eldermyoshida/Potato-Master | 31efa37b0f2cb4cbf44afda2b38b80053cc89d7f | [
"MIT"
] | null | null | null | src/Tokenizer.cpp | eldermyoshida/Potato-Master | 31efa37b0f2cb4cbf44afda2b38b80053cc89d7f | [
"MIT"
] | null | null | null | src/Tokenizer.cpp | eldermyoshida/Potato-Master | 31efa37b0f2cb4cbf44afda2b38b80053cc89d7f | [
"MIT"
] | null | null | null | //
// Tokenizer.cpp
// Potato-Master
//
// Created by Elder Yoshida on 4/23/15.
// Copyright (c) 2015 Elder Yoshida. All rights reserved.
//
#include "Tokenizer.h"
void Tokenize(const string& str,
vector<string>& tokens,
const string& delimiters = " ")
{
// Skip delimiters at beginning.
string::size_type lastPos = str.find_first_not_of(delimiters, 0);
// Find first "non-delimiter".
string::size_type pos = str.find_first_of(delimiters, lastPos);
while (string::npos != pos || string::npos != lastPos)
{
// Found a token, add it to the vector.
tokens.push_back(str.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = str.find_first_not_of(delimiters, pos);
// Find next "non-delimiter"
pos = str.find_first_of(delimiters, lastPos);
} | 29.814815 | 68 | 0.686957 | eldermyoshida |
aab155f3c6d981d9e9afb90b50db0b888f252313 | 445 | cpp | C++ | wwi-2019/choinka.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | 2 | 2019-05-04T09:37:09.000Z | 2019-05-22T18:07:28.000Z | wwi-2019/choinka.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | wwi-2019/choinka.cpp | Aleshkev/algoritmika | fc95b0c0f318d9eb4ef1fef4cc3c6e85d2417189 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef intmax_t I;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr), cout.tie(nullptr);
I n;
cin >> n;
for (I k = 0; k < 2; ++k)
for (I i = 0; i < n + k; ++i)
cout << string(n - i, ' ') << string(2 * i + 1, '*') << '\n';
for (I k = 0; k < 2; ++k) cout << string(n, ' ') << '*' << '\n';
#ifdef UNITEST
cout.flush();
system("pause");
#endif
return 0;
}
| 19.347826 | 67 | 0.501124 | Aleshkev |
82b457fc501bd9a5ffce50b88dee587bc5657254 | 1,734 | cpp | C++ | src/IO/gpio/PwmOutput.cpp | uorocketry/rocket-code-2020 | 06e3e56b79653f8c0c3af0cb422531d058a0f7ec | [
"MIT"
] | 8 | 2021-04-04T12:10:40.000Z | 2022-03-25T03:12:25.000Z | src/IO/gpio/PwmOutput.cpp | uorocketry/rocket-code-2020 | 06e3e56b79653f8c0c3af0cb422531d058a0f7ec | [
"MIT"
] | 104 | 2020-01-10T00:47:24.000Z | 2022-03-24T03:54:13.000Z | src/IO/gpio/PwmOutput.cpp | uorocketry/rocket-code-2020 | 06e3e56b79653f8c0c3af0cb422531d058a0f7ec | [
"MIT"
] | 4 | 2021-04-04T12:10:48.000Z | 2022-03-25T03:12:26.000Z | #include "config/config.h"
#if USE_GPIO == 1
#include "PwmOutput.h"
#include <iostream>
#include <spdlog/spdlog.h>
#include <utility>
#include <wiringSerial.h>
#if USE_WIRING_Pi == 1
#include <softPwm.h>
#include <wiringPi.h>
#endif
PwmOutput::PwmOutput(std::string name, const int pin, const int safePosition, bool softPWM)
: name(std::move(name)), pinNbr(pin), softPWM(softPWM), safePosition(safePosition)
{
logger = spdlog::default_logger();
SPDLOG_LOGGER_DEBUG(logger, "Created PwmOutput {}", name);
if (!softPWM)
{
#if USE_WIRING_Pi == 1
pinMode(pinNbr, PWM_OUTPUT);
pwmSetMode(PWM_MODE_MS);
pwmSetRange(256);
pwmSetClock(192);
#endif
}
else
{
#if USE_ARDUINO_PROXY == 1
arduinoProxy = ArduinoProxy::getInstance();
RocketryProto::ArduinoIn arduinoIn;
arduinoIn.mutable_servoinit()->set_pin(pinNbr);
arduinoIn.mutable_servoinit()->set_safeposition(safePosition);
arduinoProxy->send(arduinoIn);
#endif
}
}
bool PwmOutput::setValue(int value)
{
if (currentState != value)
{
currentState = value;
SPDLOG_LOGGER_INFO(logger, "PWM {} changed to {} on pin {}", name, currentState, pinNbr);
if (!softPWM)
{
#if USE_WIRING_Pi == 1
pwmWrite(pinNbr, value);
#endif
}
else
{
#if USE_ARDUINO_PROXY == 1
RocketryProto::ArduinoIn arduinoIn;
arduinoIn.mutable_servocontrol()->set_pin(pinNbr);
arduinoIn.mutable_servocontrol()->set_position(value);
arduinoProxy->send(arduinoIn);
#endif
}
}
return true;
}
#endif | 23.432432 | 98 | 0.60842 | uorocketry |
82b686cf7b10218ba123f71635a7a4dc38dddfaf | 2,834 | cpp | C++ | breeze/conversion/test/roman_test.cpp | gennaroprota/breeze | 7afe88a30dc8ac8b97a76a192dc9b189d9752e8b | [
"BSD-3-Clause"
] | 1 | 2021-04-03T22:35:52.000Z | 2021-04-03T22:35:52.000Z | breeze/conversion/test/roman_test.cpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | null | null | null | breeze/conversion/test/roman_test.cpp | gennaroprota/breeze | f1dfd7154222ae358f5ece936c2897a3ae110003 | [
"BSD-3-Clause"
] | 1 | 2021-10-01T04:26:48.000Z | 2021-10-01T04:26:48.000Z | // ===========================================================================
// Copyright 2016 Gennaro Prota
//
// Licensed under the 3-Clause BSD License.
// (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or
// <https://opensource.org/licenses/BSD-3-Clause>.)
// ___________________________________________________________________________
#include "breeze/conversion/roman.hpp"
#include "breeze/environment/get_environment_variable.hpp"
#include "breeze/testing/testing.hpp"
#include <algorithm>
#include <fstream>
#include <ios>
#include <iterator>
#include <locale>
#include <sstream>
#include <string>
int test_roman() ;
namespace {
std::string
classic_to_lower( std::string const & s )
{
std::locale const loc = std::locale::classic() ;
std::string result ;
std::transform( s.cbegin(), s.cend(),
std::back_inserter( result ),
[ &loc ]( char c )
{
return std::tolower( c, loc ) ;
} ) ;
return result ;
}
void
check()
{
std::string const breeze_root = breeze::get_environment_variable(
"BREEZE_ROOT" ).value() ;
std::ifstream is( breeze_root
+ "/breeze/conversion/test/a006968.txt" ) ;
BREEZE_CHECK( is.good() ) ;
// Skip the first lines.
// -----------------------------------------------------------------------
int const lines_to_skip = 14 ;
for ( int i = 0 ; i < lines_to_skip ; ++ i ) {
std::string line ;
std::getline( is, line ) ;
}
int const max_roman = 3999 ;
int n ;
do {
is >> n ;
char equal_sign ;
is >> equal_sign ;
std::string upper_expected ;
is >> upper_expected ;
BREEZE_CHECK( is.good() ) ;
std::ostringstream strm ;
breeze::roman const roman( n ) ;
strm << std::uppercase << roman ;
std::string const upper_actual = strm.str() ;
strm.str( "" ) ;
strm << std::nouppercase << roman ;
std::string const lower_actual = strm.str() ;
BREEZE_CHECK( upper_actual == upper_expected ) ;
BREEZE_CHECK( lower_actual == classic_to_lower( upper_expected ) ) ;
} while ( n != max_roman ) ;
}
void
out_of_range_integer_causes_assert()
{
BREEZE_CHECK_THROWS( breeze::assert_failure, breeze::roman( 0 ) ) ;
BREEZE_CHECK_THROWS( breeze::assert_failure, breeze::roman( 4000 ) ) ;
}
}
int
test_roman()
{
return breeze::test_runner::instance().run(
"roman",
{ check,
out_of_range_integer_causes_assert } ) ;
}
| 27.784314 | 78 | 0.51976 | gennaroprota |
82b6c82dd2b391f1568fd71f56c83159da297164 | 3,224 | cpp | C++ | Server/src/Services/Resource/ResourceDatabase.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 2 | 2017-04-19T01:38:30.000Z | 2020-07-31T03:05:32.000Z | Server/src/Services/Resource/ResourceDatabase.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | null | null | null | Server/src/Services/Resource/ResourceDatabase.cpp | achilex/MgDev | f7baf680a88d37659af32ee72b9a2046910b00d8 | [
"PHP-3.0"
] | 1 | 2021-12-29T10:46:12.000Z | 2021-12-29T10:46:12.000Z | //
// Copyright (C) 2004-2011 by Autodesk, Inc.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of version 2.1 of the GNU Lesser
// General Public License as published by the Free Software Foundation.
//
// 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 St, Fifth Floor, Boston, MA 02110-1301 USA
//
#include "ResourceServiceDefs.h"
#include "ResourceDatabase.h"
///----------------------------------------------------------------------------
/// <summary>
/// Constructs the object.
/// </summary>
///
/// <exceptions>
/// MgDbException
/// </exceptions>
///----------------------------------------------------------------------------
MgResourceDatabase::MgResourceDatabase(MgDbEnvironment& environment,
const string& fileName) :
MgDatabase(environment),
m_db(&environment.GetDbEnv(), 0)
{
assert(!fileName.empty());
DbTxn* dbTxn = NULL;
MG_RESOURCE_SERVICE_TRY()
#ifdef _DEBUG
m_db.set_error_stream(&std::cerr);
#endif
if (fileName.find(MG_WCHAR_TO_CHAR(MgRepositoryType::Session)) == fileName.npos)
{
m_db.set_pagesize(environment.getDBPageSize());
}
else
{
m_db.set_pagesize(environment.getSessionDBPageSize());
}
if (m_environment.IsTransacted())
{
m_environment.GetDbEnv().txn_begin(0, &dbTxn, 0);
assert(NULL != dbTxn);
}
u_int32_t flags = DB_CREATE|DB_THREAD;
m_db.open(dbTxn, fileName.c_str(), 0, DB_BTREE, flags, 0);
m_opened = true;
if (NULL != dbTxn)
{
dbTxn->commit(0);
dbTxn = NULL;
}
Reset();
MG_RESOURCE_SERVICE_CATCH(L"MgResourceDatabase.MgResourceDatabase")
if (mgException != NULL)
{
try
{
if (NULL != dbTxn)
{
dbTxn->abort();
}
}
catch (...)
{
assert(false);
}
}
MG_RESOURCE_SERVICE_THROW()
}
///----------------------------------------------------------------------------
/// <summary>
/// Destructs the object.
/// </summary>
///----------------------------------------------------------------------------
MgResourceDatabase::~MgResourceDatabase()
{
if (m_opened)
{
try
{
Reset();
m_db.close(0);
}
catch (...)
{
assert(false);
}
}
}
///////////////////////////////////////////////////////////////////////////////
/// \brief
/// Return the name of the database.
///
string MgResourceDatabase::GetName()
{
string name;
if (m_opened)
{
const char *fileName = NULL;
const char *dbName = NULL;
m_db.get_dbname(&fileName, &dbName);
CHECKNULL(fileName, L"MgResourceDatabase.GetName");
name = fileName;
}
return name;
}
| 23.532847 | 84 | 0.531638 | achilex |
82b82cd7ee2ee6bbb0c0be93f62c980894f13e20 | 239 | hpp | C++ | include/Node.hpp | behluluysal/sau-data-structures-2020-midterm | 39b21a77943dcdbc9223b8f22690bac766050861 | [
"MIT"
] | null | null | null | include/Node.hpp | behluluysal/sau-data-structures-2020-midterm | 39b21a77943dcdbc9223b8f22690bac766050861 | [
"MIT"
] | null | null | null | include/Node.hpp | behluluysal/sau-data-structures-2020-midterm | 39b21a77943dcdbc9223b8f22690bac766050861 | [
"MIT"
] | null | null | null | #ifndef Node_hpp
#define Node_hpp
#pragma once
#include "iostream"
class Node
{
public:
Node();
Node(int data, Node *prevnew, Node *nextnew);
int getData();
~Node();
Node *next;
Node *prev;
int data;
};
#endif | 13.277778 | 49 | 0.615063 | behluluysal |
82b9bb8fa03488e86044b2df5eeba361aec3b249 | 2,552 | cpp | C++ | Classic Algorithms/Columnar cypher/columnar.cpp | IulianOctavianPreda/EncryptionAlgorithms | 3cbaec3f5a6b9b7c615a20bfd3c6206469deb8f4 | [
"MIT"
] | null | null | null | Classic Algorithms/Columnar cypher/columnar.cpp | IulianOctavianPreda/EncryptionAlgorithms | 3cbaec3f5a6b9b7c615a20bfd3c6206469deb8f4 | [
"MIT"
] | null | null | null | Classic Algorithms/Columnar cypher/columnar.cpp | IulianOctavianPreda/EncryptionAlgorithms | 3cbaec3f5a6b9b7c615a20bfd3c6206469deb8f4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
std::map<int, int> keyMap;
void orderColumns(const std::string &key) {
for (unsigned int i = 0; i < key.length(); i++) {
keyMap[key[i]] = i;
}
}
std::string encrypt(std::string text, const std::string &key) {
unsigned int row, column;
std::string cipher;
column = key.length();
row = text.length() / column;
if (text.length() % column) {
row += 1;
}
char matrix[row][column];
for (unsigned int i = 0, k = 0; i < row; i++) {
for (unsigned int j = 0; j < column;) {
if (text[k] == '\0') {
matrix[i][j] = '_';
j++;
}
if (isalpha(text[k]) || text[k] == ' ') {
matrix[i][j] = text[k];
j++;
}
k++;
}
}
unsigned int j = 0;
for (auto &iterator : keyMap) {
j = iterator.second;
for (unsigned int i = 0; i < row; i++) {
if (isalpha(matrix[i][j]) || matrix[i][j] == ' ' || matrix[i][j] == '_')
cipher += matrix[i][j];
}
}
return cipher;
}
std::string decrypt(std::string encryptedText, const std::string &key) {
unsigned int column = key.length();
unsigned int row = encryptedText.length() / column;
char cipherMatrix[row][column];
for (unsigned int j = 0, k = 0; j < column; j++) {
for (unsigned int i = 0; i < row; i++) {
cipherMatrix[i][j] = encryptedText[k++];
}
}
int index = 0;
for (auto &iterator : keyMap) {
iterator.second = index++;
}
char decryptedText[row][column];
auto ii = keyMap.begin();
int k = 0;
for (int l = 0, j; key[l] != '\0'; k++) {
j = keyMap[key[l++]];
for (unsigned int i = 0; i < row; i++) {
decryptedText[i][k] = cipherMatrix[i][j];
}
}
std::string decrypted;
for (unsigned int i = 0; i < row; i++) {
for (unsigned int j = 0; j < column; j++) {
if (decryptedText[i][j] != '_') decrypted += decryptedText[i][j];
}
}
return decrypted;
}
int main() {
int choice;
std::string text;
std::string key;
std::cout << "1)Encrypt" << std::endl << "2)Decrypt";
std::cin >> choice;
std::cout << "Insert plaintext";
std::cin >> text;
std::cout << "Plain text: " << text << std::endl;
std::cout << "Insert key";
std::cin >> key;
std::cout << "key: " << key << std::endl;
orderColumns(key);
if (choice == 1) {
std::string cipher = encrypt(text, key);
std::cout << "Encrypted Message: " << cipher << std::endl;
} else {
std::string decryptedText = decrypt(text, key);
std::cout << "Decrypted Message: " << decryptedText << std::endl;
}
return 0;
} | 24.538462 | 78 | 0.53605 | IulianOctavianPreda |
82bbb41c98d85bcf17aeb6b4993071f13ad8339f | 2,932 | cc | C++ | jsp/rcm_denoising/horny_toad/examples/bicubic_example.cc | jeffsp/kaggle_denoising | ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27 | [
"MIT"
] | 1 | 2015-06-04T14:34:01.000Z | 2015-06-04T14:34:01.000Z | jsp/rcm_denoising/horny_toad/examples/bicubic_example.cc | jeffsp/kaggle_denoising | ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27 | [
"MIT"
] | null | null | null | jsp/rcm_denoising/horny_toad/examples/bicubic_example.cc | jeffsp/kaggle_denoising | ad0e86a34c8c0c98c95e3ec3fe791a6b75154a27 | [
"MIT"
] | null | null | null | // Bicubic Interpolation Example
//
// Copyright (C) 2004-2011
// Center for Perceptual Systems
// University of Texas at Austin
//
// contact: jeffsp@gmail.com
#include "horny_toad/horny_toad.h"
#include "jack_rabbit/jack_rabbit.h"
#include <cmath>
#include <iostream>
using namespace std;
using namespace horny_toad;
using namespace jack_rabbit;
int main ()
{
try
{
const size_t M = 16;
const size_t N = 16;
const size_t SCALE = 30;
raster<unsigned char> p (M, N);
generate (p.begin (), p.end (), rand);
raster<double> q (M * SCALE, N * SCALE);
bicubic_interp (p, q);
raster<unsigned char> u (q.rows (), q.cols ());
transform (q.begin (), q.end (), q.begin (), (double(*)(double))&round);
transform (q.begin (), q.end (), u.begin (), clip_functor<int> (0, 255));
raster<unsigned char> ind (u.rows () - 3 * SCALE * 2, u.cols () - 3 * SCALE * 2);
subregion s = { 3 * SCALE, 3 * SCALE, ind.rows (), ind.cols () };
copy (u.begin (s), u.end (s), ind.begin ());
double pal[96] = {
1.0000, 0, 0,
1.0000, 0.1875, 0,
1.0000, 0.3750, 0,
1.0000, 0.5625, 0,
1.0000, 0.7500, 0,
1.0000, 0.9375, 0,
0.8750, 1.0000, 0,
0.6875, 1.0000, 0,
0.5000, 1.0000, 0,
0.3125, 1.0000, 0,
0.1250, 1.0000, 0,
0, 1.0000, 0.0625,
0, 1.0000, 0.2500,
0, 1.0000, 0.4375,
0, 1.0000, 0.6250,
0, 1.0000, 0.8125,
0, 1.0000, 1.0000,
0, 0.8125, 1.0000,
0, 0.6250, 1.0000,
0, 0.4375, 1.0000,
0, 0.2500, 1.0000,
0, 0.0625, 1.0000,
0.1250, 0, 1.0000,
0.3125, 0, 1.0000,
0.5000, 0, 1.0000,
0.6875, 0, 1.0000,
0.8750, 0, 1.0000,
1.0000, 0, 0.9375,
1.0000, 0, 0.7500,
1.0000, 0, 0.5625,
1.0000, 0, 0.3750,
1.0000, 0, 0.1875
};
raster<unsigned char> c (ind.rows (), ind.cols () * 3);
for (size_t i = 0; i < ind.size (); ++i)
{
c[i * 3 + 0] = pal[ind[i]/8*3+0] * 255;
c[i * 3 + 1] = pal[ind[i]/8*3+1] * 255;
c[i * 3 + 2] = pal[ind[i]/8*3+2] * 255;
}
write_pnm (cout, c.cols () / 3, c.rows (), c, true);
return 0;
}
catch (const exception &e)
{
cerr << e.what () << endl;
return -1;
}
}
| 32.577778 | 89 | 0.398363 | jeffsp |
82bcba1f9f778d56dc28382e7a990618bdce2a5a | 4,171 | cpp | C++ | sdpsensor.cpp | dizcza/arduino-sdp | 6f4a74cbef4c35a9c8913a2cf51111299089b888 | [
"BSD-3-Clause"
] | null | null | null | sdpsensor.cpp | dizcza/arduino-sdp | 6f4a74cbef4c35a9c8913a2cf51111299089b888 | [
"BSD-3-Clause"
] | null | null | null | sdpsensor.cpp | dizcza/arduino-sdp | 6f4a74cbef4c35a9c8913a2cf51111299089b888 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2018, Sensirion AG <joahnnes.winkelmann@sensirion.com>
* 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 Sensirion AG 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Arduino.h>
#include "sdpsensor.h"
#include "i2chelper.h"
int SDPSensor::init()
{
// try to read product id
const uint8_t CMD_LEN = 2;
uint8_t cmd0[CMD_LEN] = { 0x36, 0x7C };
uint8_t cmd1[CMD_LEN] = { 0xE1, 0x02 };
const uint8_t DATA_LEN = 18;
uint8_t data[DATA_LEN] = { 0 };
uint8_t ret = I2CHelper::i2c_write(mI2CAddress, cmd0, CMD_LEN);
if (ret != 0) {
return 1;
}
ret = I2CHelper::i2c_write(mI2CAddress, cmd1, CMD_LEN);
if (ret != 0) {
return 2;
}
ret = I2CHelper::i2c_read(mI2CAddress, data, DATA_LEN);
if (ret != 0) {
return 3;
}
uint8_t cmd_write[CMD_LEN] = { 0x36, 0x2F };
const uint8_t DATA_LEN_WRITE = 9;
if (I2CHelper::i2c_write(mI2CAddress, cmd_write, CMD_LEN) != 0) {
return 4;
}
delay(45);
if (I2CHelper::i2c_read(mI2CAddress, data, DATA_LEN_WRITE) != 0) {
return 5;
}
mDiffPressureScale = ((int16_t)data[6]) << 8 | data[7];
// at this point, we don't really care about the data just yet, but
// we may use that in the future. Either way, the sensor responds, and
return 0;
}
int SDPSensor::startContinuous(bool averaging)
{
const uint8_t CMD_LEN = 2;
uint8_t cmd[CMD_LEN] = { 0x36 };
cmd[1] = (averaging) ? 0x15 : 0x1E;
int ret = I2CHelper::i2c_write(mI2CAddress, cmd, CMD_LEN);
// wait for sensor to start continuously making measurements
delay(20);
return ret;
}
int SDPSensor::reset()
{
const uint8_t CMD_LEN = 2;
uint8_t cmd[CMD_LEN] = { 0x00, 0x06 };
int ret = I2CHelper::i2c_write(mI2CAddress, cmd, CMD_LEN);
delay(20);
return ret;
}
int SDPSensor::readContinuous(float *diffPressure) {
const uint8_t DATA_LEN = 2;
uint8_t data[DATA_LEN] = { 0 };
if (I2CHelper::i2c_read(mI2CAddress, data, DATA_LEN) != 0) {
return 2;
}
int16_t dp_raw = ((int16_t)data[0]) << 8 | data[1];
*diffPressure = dp_raw / (float)mDiffPressureScale;
return 0;
}
int SDPSensor::stopContinuous()
{
const uint8_t CMD_LEN = 2;
uint8_t cmd[CMD_LEN] = { 0x3F, 0xF9 };
return I2CHelper::i2c_write(mI2CAddress, cmd, CMD_LEN);
}
int SDPSensor::readPressureAndTemperatureContinuous(float *diffPressure, float *temperature)
{
const uint8_t DATA_LEN = 5;
uint8_t data[DATA_LEN] = { 0 };
if (I2CHelper::i2c_read(mI2CAddress, data, DATA_LEN) != 0) {
return 2;
}
int16_t dp_raw = ((int16_t)data[0]) << 8 | data[1];
*diffPressure = dp_raw / (float)mDiffPressureScale;
int16_t temp_raw = ((int16_t)data[3]) << 8 | data[4];
*temperature = temp_raw / 200.0;
return 0;
}
| 30.896296 | 92 | 0.690961 | dizcza |
82bce099e057cee96fc162bb5fd79780a10a99fd | 2,273 | hh | C++ | include/xpgom/gomwrappedelement.hh | jberkman/gom | 4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5 | [
"MIT"
] | null | null | null | include/xpgom/gomwrappedelement.hh | jberkman/gom | 4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5 | [
"MIT"
] | null | null | null | include/xpgom/gomwrappedelement.hh | jberkman/gom | 4bccfec5e5ada830a4c5f076dfefb9ad9baab6a5 | [
"MIT"
] | null | null | null | /*
The MIT License
Copyright (c) 2008 jacob berkman <jacob@ilovegom.org>
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 GOM_WRAPPED_ELEMENT_HH
#define GOM_WRAPPED_ELEMENT_HH
#include <glib/gmacros.h>
G_BEGIN_DECLS
typedef struct _GomWrappedElement GomWrappedElement;
typedef struct _GomWrappedElementClass GomWrappedElementClass;
G_END_DECLS
#include <xpgom/gomwrappednode.hh>
G_BEGIN_DECLS
#define GOM_TYPE_WRAPPED_ELEMENT (gom_wrapped_element_get_type ())
#define GOM_WRAPPED_ELEMENT(i) (G_TYPE_CHECK_INSTANCE_CAST ((i), GOM_TYPE_WRAPPED_ELEMENT, GomWrappedElement))
#define GOM_WRAPPED_ELEMENT_CLASS(k) (G_TYPE_CHECK_CLASS_CAST ((k), GOM_TYPE_WRAPPED_ELEMENT, GomWrappedElementClass))
#define GOM_IS_WRAPPED_ELEMENT(i) (G_TYPE_CHECK_INSTANCE_TYPE ((i), GOM_TYPE_WRAPPED_ELEMENT))
#define GOM_IS_WRAPPED_ELEMENT_CLASS(k) (G_TYPE_CHECK_CLASS_TYPE ((k), GOM_TYPE_WRAPPED_ELEMENT))
#define GOM_WRAPPED_ELEMENT_GET_CLASS(i) (G_TYPE_INSTANCE_GET_CLASS ((i), GOM_TYPE_WRAPPED_ELEMENT, GomWrappedElementClass))
struct _GomWrappedElement {
GomWrappedNode parent;
};
struct _GomWrappedElementClass {
GomWrappedNodeClass parent_class;
};
GType gom_wrapped_element_get_type (void);
G_END_DECLS
#endif /* GOM_WRAPPED_ELEMENT_HH */
| 37.262295 | 125 | 0.805543 | jberkman |
82be9a432108b936dbab2c6ee1202c494cfb358e | 456 | cpp | C++ | essential/Exercise Files/Chap05/func-operator.cpp | disono/cp-cheat-sheet | 02edee3d822f56770e1a1a3cc4db6be3691a7a38 | [
"MIT"
] | null | null | null | essential/Exercise Files/Chap05/func-operator.cpp | disono/cp-cheat-sheet | 02edee3d822f56770e1a1a3cc4db6be3691a7a38 | [
"MIT"
] | null | null | null | essential/Exercise Files/Chap05/func-operator.cpp | disono/cp-cheat-sheet | 02edee3d822f56770e1a1a3cc4db6be3691a7a38 | [
"MIT"
] | null | null | null | // func-operator.cpp by Bill Weinman <http://bw.org/>
// updated for C++EssT 2018-08-08
#include <cstdio>
using namespace std;
class A {
int a;
public:
A ( const int &a ) : a(a) {}
const int & value() const { return a; }
};
int operator + (const A & lhs, const A & rhs ) {
puts("operator + for class A");
return lhs.value() + rhs.value();
}
int main() {
A a(7);
A b(42);
printf("add em up! %d\n", a + b);
return 0;
}
| 19 | 53 | 0.554825 | disono |
82c00462cd78a9c2103827adce5cbd9afc6bb797 | 2,359 | cpp | C++ | Uncategorized/hkccc15j5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/hkccc15j5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | Uncategorized/hkccc15j5.cpp | crackersamdjam/DMOJ-Solutions | 97992566595e2c7bf41b5da9217d8ef61bdd1d71 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int MM = 1005;
int n, m, vis[MM], ad = 1001, bt[MM][MM*2], pre, ass[MM], v1[MM], v2[MM];
bool dp[MM][MM*2], last[MM][MM*2], NO;
vector<int> adj[MM];
char out[MM];
vector<pair<int, int>> v[MM][2];
int dfs(int cur, int id, int val){
int ret = val ? 1 : -1;
ass[cur] = val;
vis[cur] = id;
v[pre][id-1].emplace_back(cur, val);
for(int u: adj[cur]){
if(vis[u] != id){
vis[u] = id;
ret += dfs(u, id, !val);
}
else if(ass[u] == ass[cur])
NO = 1;
}
return ret;
}
int main(){
cin >> n >> m;
for(int i = 0,a,b; i < m; i++){
cin >> a >> b;
adj[a].emplace_back(b);
adj[b].emplace_back(a);
}
for(int i = 1; i <= n; i++){
if(!vis[i]){
pre++;
v1[pre] = dfs(i, 1, 0), v2[pre] = dfs(i, 2, 1);
//so lex min is off
}
}
dp[pre+1][ad] = 1;
//dp backward to get lex min
for(int i = pre; i; i--){
for(int j = 0; j < 2000; j++){
if(j-v1[i] > 0 and j-v1[i] < 2000 and dp[i+1][j-v1[i]]){
dp[i][j] = 1;
last[i][j] = 0;
bt[i][j] = j-v1[i];
}
}
for(int j = 0; j < 2000; j++){
if(j-v2[i] > 0 and j-v2[i] < 2000 and dp[i+1][j-v2[i]] and !dp[i][j]){
dp[i][j] = 1;
last[i][j] = 1;
bt[i][j] = j-v2[i];
}
}
}
if(NO){
cout << "-1";
return 0;
}
int val = 1e9;
string best = "3";
for(int k = 0; k < 2000; k++){
if(dp[1][k]){
//get string and compare
int ans = k;
string s; s.resize(n);
for(int i = 1; i <= pre; i++){
for(auto p: v[i][last[i][ans]]){
s[p.first-1] = '1'+p.second;
}
ans = bt[i][ans];
}
if(abs(k-ad) < val){
val = abs(k-ad);
best = s;
}
else if(abs(k-ad) == val)
best = min(best, s);
}
}
cout << best << '\n';
return 0;
} | 24.831579 | 83 | 0.342942 | crackersamdjam |
82c0e01358964e038113049e99c8e730deac79da | 4,109 | cc | C++ | scratch/performance.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | 1 | 2022-03-22T08:08:35.000Z | 2022-03-22T08:08:35.000Z | scratch/performance.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | null | null | null | scratch/performance.cc | Marquez607/Wireless-Perf-Sim | 1086759b6dbe7da192225780d5fe6a3da0c5eb07 | [
"MIT"
] | null | null | null |
// Performance calculation in NS3 without using software
SentPackets
ReceivedPackets
LostPackets
Packet Loss ratio << "%"
Packet delivery ratio << "%"
AvgThroughput<< "Kbps"
End to End Delay <<"ns"
End to End Jitter delay <<"ns"
// OS : ubuntu 16.04 LTS
// NS version ns-3.29
//Explain example with MANET-routing-compare.cc which is available in the /home/logu/ns-allinone-3.29/ns-3.29/examples/routing/
//step 1:Add header file
#include "ns3/flow-monitor-module.h"
//step 2: variable declaration after m_protocolName = "protocol" in the
//void RoutingExperiment::Run (int nSinks, double txp, std::string CSVfileName)
uint32_t SentPackets = 0;
uint32_t ReceivedPackets = 0;
uint32_t LostPackets = 0;
//step 3:Install FlowMonitor on all nodes
FlowMonitorHelper flowmon;
Ptr<FlowMonitor> monitor = flowmon.InstallAll();
// step 4: Add below code after Simulator::Run ();
///////////////////////////////////// Network Perfomance Calculation /////////////////////////////////////
int j=0;
float AvgThroughput = 0;
Time Jitter;
Time Delay;
Ptr<Ipv4FlowClassifier> classifier = DynamicCast<Ipv4FlowClassifier> (flowmon.GetClassifier ());
std::map<FlowId, FlowMonitor::FlowStats> stats = monitor->GetFlowStats ();
for (std::map<FlowId, FlowMonitor::FlowStats>::const_iterator iter = stats.begin (); iter != stats.end (); ++iter)
{
Ipv4FlowClassifier::FiveTuple t = classifier->FindFlow (iter->first);
NS_LOG_UNCOND("----Flow ID:" <<iter->first);
NS_LOG_UNCOND("Src Addr" <<t.sourceAddress << "Dst Addr "<< t.destinationAddress);
NS_LOG_UNCOND("Sent Packets=" <<iter->second.txPackets);
NS_LOG_UNCOND("Received Packets =" <<iter->second.rxPackets);
NS_LOG_UNCOND("Lost Packets =" <<iter->second.txPackets-iter->second.rxPackets);
NS_LOG_UNCOND("Packet delivery ratio =" <<iter->second.rxPackets*100/iter->second.txPackets << "%");
NS_LOG_UNCOND("Packet loss ratio =" << (iter->second.txPackets-iter->second.rxPackets)*100/iter->second.txPackets << "%");
NS_LOG_UNCOND("Delay =" <<iter->second.delaySum);
NS_LOG_UNCOND("Jitter =" <<iter->second.jitterSum);
NS_LOG_UNCOND("Throughput =" <<iter->second.rxBytes * 8.0/(iter->second.timeLastRxPacket.GetSeconds()-iter->second.timeFirstTxPacket.GetSeconds())/1024<<"Kbps");
SentPackets = SentPackets +(iter->second.txPackets);
ReceivedPackets = ReceivedPackets + (iter->second.rxPackets);
LostPackets = LostPackets + (iter->second.txPackets-iter->second.rxPackets);
AvgThroughput = AvgThroughput + (iter->second.rxBytes * 8.0/(iter->second.timeLastRxPacket.GetSeconds()-iter->second.timeFirstTxPacket.GetSeconds())/1024);
Delay = Delay + (iter->second.delaySum);
Jitter = Jitter + (iter->second.jitterSum);
j = j + 1;
}
AvgThroughput = AvgThroughput/j;
NS_LOG_UNCOND("--------Total Results of the simulation----------"<<std::endl);
NS_LOG_UNCOND("Total sent packets =" << SentPackets);
NS_LOG_UNCOND("Total Received Packets =" << ReceivedPackets);
NS_LOG_UNCOND("Total Lost Packets =" << LostPackets);
NS_LOG_UNCOND("Packet Loss ratio =" << ((LostPackets*100)/SentPackets)<< "%");
NS_LOG_UNCOND("Packet delivery ratio =" << ((ReceivedPackets*100)/SentPackets)<< "%");
NS_LOG_UNCOND("Average Throughput =" << AvgThroughput<< "Kbps");
NS_LOG_UNCOND("End to End Delay =" << Delay);
NS_LOG_UNCOND("End to End Jitter delay =" << Jitter);
NS_LOG_UNCOND("Total Flod id " << j);
monitor->SerializeToXmlFile("manet-routing.xml", true, true);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Step 5: Run the program
$ cd ns-allinone-3.29/ns-3.29/
$ ./waf --run scratch/manet-routing-compare
// you can get the following results//
//--------Total Results of the simulation----------//
Total sent packets =1649
Total Received Packets =1377
Total Lost Packets =272
Packet Loss ratio =16%
Packet delivery ratio =83%
Average Throughput =5.56209Kbps
End to End Delay =+110104125435.0ns
End to End Jitter delay =+43338866355.0ns
Total Flod id 182
////////////////////////////////////////////////////////
Thank you... subcribe channel... //Technosilent
| 36.6875 | 161 | 0.681188 | Marquez607 |
82c2f5b6572143f3919473671e6ed190fcc7e086 | 2,729 | cc | C++ | emplnofusion/employee2.cc | jorgeventura/spirit | 3ad8ebee54bb294486fe8eead44691bec89532e6 | [
"BSL-1.0"
] | null | null | null | emplnofusion/employee2.cc | jorgeventura/spirit | 3ad8ebee54bb294486fe8eead44691bec89532e6 | [
"BSL-1.0"
] | null | null | null | emplnofusion/employee2.cc | jorgeventura/spirit | 3ad8ebee54bb294486fe8eead44691bec89532e6 | [
"BSL-1.0"
] | null | null | null | #define BOOST_SPIRIT_X3_DEBUG
#include <iostream>
#include <boost/spirit/home/x3.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <string>
#include <vector>
#include <variant>
namespace x3 = boost::spirit::x3;
namespace ast {
struct employee
{
int age;
std::string gname;
std::string sname;
float sal;
employee() : age(0), sal(0.0) {}
friend std::ostream& operator<<(std::ostream& os, employee const& e)
{
os << "[ " << e.age << ", \"" << e.gname << "\", \"" << e.sname << "\", " << float(e.sal) << " ]" << std::endl;
return os;
}
};
}
BOOST_FUSION_ADAPT_STRUCT(ast::employee, age, gname, sname, sal);
namespace parser {
namespace x3 = boost::spirit::x3;
x3::rule<struct employee_class, ast::employee> const employee_ = "employee";
x3::real_parser<float, x3::strict_real_policies<float> > float_;
auto const quoted_string = x3::lexeme['"' >> +(x3::char_ - '"') >> '"'];
const auto employee__def =
x3::lit("employee")
>> '{'
>> (x3::int_ >> ',')
>> (quoted_string >> ',')
>> (quoted_string >> ',')
>> float_
>> '}'
;
BOOST_SPIRIT_DEFINE(employee_)
const auto entry_point = x3::skip(x3::space) [ employee_ ];
}
int main()
{
namespace x3 = boost::spirit::x3;
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout << "\t\tAn employee parser for Spirit...\n\n";
std::cout << "/////////////////////////////////////////////////////////\n\n";
std::cout
<< "Give me an employee of the form :"
<< "employee{age, \"forename\", \"surname\", salary } \n";
std::cout << "Type [q or Q] to quit\n\n";
using iterator_type = std::string::const_iterator;
std::string str;
while (getline(std::cin, str))
{
if (str.empty() || str[0] == 'q' || str[0] == 'Q')
break;
ast::employee emp;
iterator_type iter = str.begin();
iterator_type const end = str.end();
bool r = phrase_parse(iter, end, parser::entry_point, x3::space, emp);
if (r && iter == end)
{
std::cout << "-------------------------\n";
std::cout << "Parsing succeeded\n";
std::cout << "got: " << emp << std::endl;
std::cout << "\n-------------------------\n";
}
else
{
std::cout << "-------------------------\n";
std::cout << "Parsing failed\n";
std::cout << "-------------------------\n";
}
}
std::cout << "Bye... :-) \n\n";
return 0;
}
| 25.036697 | 115 | 0.45841 | jorgeventura |