blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c9d17397d082756fe02189a735a71179167dd415 | ac0642759c121158cbf00e2c8b08530b03337260 | /src/PdnPinDumper/src/db/obj/frBlockObject.h | 1f4e6953ddb0e460e93907a849296efbe268b8cd | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ax3ghazy/pdn | 6dc1c594bc47be701b51cde24c812050586cfac0 | a53aaf9620654fc799227f2f48d61eceb0322b36 | refs/heads/master | 2020-11-27T03:21:44.720248 | 2019-10-24T13:11:53 | 2019-10-24T13:11:53 | 229,285,794 | 0 | 0 | BSD-3-Clause | 2019-12-20T15:06:52 | 2019-12-20T15:06:51 | null | UTF-8 | C++ | false | false | 2,425 | h | /* Authors: Lutong Wang and Bangqi Xu */
/*
* Copyright (c) 2019, The Regents of the University of California
* 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 University nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _FR_BLOCKOBJECT_H_
#define _FR_BLOCKOBJECT_H_
#include "frBaseTypes.h"
namespace fr {
class frBlockObject {
public:
// constructors
//frBlockObject() {}
frBlockObject(): id(-1) {}
frBlockObject(const frBlockObject &in): id(in.id) {}
virtual ~frBlockObject() {}
// getters
int getId() const {
return id;
}
// setters
void setId(int in) {
id = in;
}
// others
virtual frBlockObjectEnum typeId() const {
return frcBlockObject;
}
bool operator<(const frBlockObject &rhs) const {
return id < rhs.id;
}
protected:
int id;
};
struct frBlockObjectComp {
bool operator()(const frBlockObject* lhs, const frBlockObject* rhs) const {
return *lhs < *rhs;
}
};
}
#endif
| [
"mgwoo@unist.ac.kr"
] | mgwoo@unist.ac.kr |
0828011928d0150867d216437bb11b8a9f474691 | 4f307eb085ad9f340aaaa2b6a4aa443b4d3977fe | /Bakaleinik.David/assignment5/Game.cpp | 03c65fe9051a65a7b1eb430a80b6237ab0b60796 | [] | no_license | Connellj99/GameArch | 034f4a0f52441d6dde37956a9662dce452a685c7 | 5c95e9bdfce504c02c73a0c3cb566a010299a9b8 | refs/heads/master | 2020-12-28T10:29:19.935573 | 2020-02-04T19:41:09 | 2020-02-04T19:41:09 | 238,286,390 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,572 | cpp | #include "Game.h"
#include "Unit.h"
#include "System.h"
#include "Timer.h"
#include "GraphicsBuffer.h"
#include "PerformanceTracker.h"
#include "Animation.h"
#include "GBufferManager.h"
#include "UnitManager.h"
#include "InputSystem.h"
#include "EventSystem.h"
#include "Event.h" //May be not needed
#include "GameEvent.h"
#include "CreateUnit.h"
#include "DeleteUnit.h"
#include "ExitGame.h"
#include "SwitchHead.h"
#include "StopAnim.h"
Game * Game::mpGameInstance = nullptr;
const string ASSET_PATH = "..\\..\\shared\\assets\\";
const string DEANS = "dean_sprites.png";
const string SMURFS = "smurf_sprites.png";
using namespace std;
Game* gpGame = nullptr;
Game::Game(EventSystem* pEventSystem)
:EventListener(pEventSystem)
{
pEventSystem->addListener((EventType)STOP_ANIMATION, this);
pEventSystem->addListener((EventType)HEAD_SWITCH, this);
pEventSystem->addListener((EventType)CREATE_UNIT, this);
pEventSystem->addListener((EventType)DELETE_UNIT, this);
pEventSystem->addListener((EventType)EXIT_GAME, this);
}
Game::Game(double fps, EventSystem* pEventSystem)
:EventListener(pEventSystem)
{
mTargetTime = fps;
pEventSystem->addListener((EventType)STOP_ANIMATION, this);
pEventSystem->addListener((EventType)HEAD_SWITCH, this);
pEventSystem->addListener((EventType)CREATE_UNIT, this);
pEventSystem->addListener((EventType)DELETE_UNIT, this);
pEventSystem->addListener((EventType)EXIT_GAME, this);
}
Game::~Game()
{
}
void Game::handleEvent(const Event& theEvent)
{
if (theEvent.getType() == STOP_ANIMATION)
{
//Stop Animation
mpUnitManager->disableAnimation();
}
else if (theEvent.getType() == HEAD_SWITCH)
{
//Change heads
mpUnitManager->switchHead(mpDeanSmurf, mpNormalSmurf);
}
else if (theEvent.getType() == EXIT_GAME)
{
//Exit the game loop
mShouldRunLoop = false;
}
else if (theEvent.getType() == DELETE_UNIT)
{
const DeleteUnit& removeUnit = static_cast<const DeleteUnit&>(theEvent);
//Delete unit
mpUnitManager->deleteUnit(removeUnit.getX(), removeUnit.getY(), 60);
}
else if (theEvent.getType() == CREATE_UNIT)
{
const CreateUnit& newUnit = static_cast<const CreateUnit&>(theEvent);
//Spawn unit
mpUnitManager->createNewUnit(mpNormalSmurf, newUnit.getX(), newUnit.getY());
}
//For later implementation:
//mpPlayerUnit->mUnitAnimation->speedUp();
//mpPlayerUnit->mUnitAnimation->slowDown();
}
void Game::initGame(int screenX, int screenY, string filename, EventSystem* eventSystem)
{
//Init system (including screen size + FPS)
//Have system init GraphicsLib
mDisplayX = screenX;
mDisplayY = screenY;
mpGameSystem = new System(mDisplayX, mDisplayY);
mpBufferManager = new GBufferManager();
mpUnitManager = new UnitManager();
mpGameSystem->initSystem();
mpInputSystem = new InputSystem();
mpInputSystem->init(mpGameSystem, eventSystem);
mpBufferManager->createNewBuffer("BG", ASSET_PATH, filename);
mpBufferManager->createNewBuffer("Smurfs", ASSET_PATH, SMURFS);
mpBufferManager->createNewBuffer("Deans", ASSET_PATH, DEANS);
//Backgound conversion for drawing
mpGameBackground = new Sprite(mpBufferManager->getBuffer("BG"),0, 0, mDisplayX, mDisplayY);
//new smurf animation
mpNormalSmurf = new Animation(mpBufferManager->getBuffer("Smurfs"), 100.0, true);
mpNormalSmurf->setAnimID(1);
//new dean animation
mpDeanSmurf = new Animation(mpBufferManager->getBuffer("Deans"), 100.0, true);
mpDeanSmurf->setAnimID(2);
}
void Game::cleanupGame()
{
delete mpInputSystem;
delete mpGameBackground;
delete mpNormalSmurf;
delete mpDeanSmurf;
//call system cleanup
delete mpUnitManager;
//mpBufferManager->clearAllBuffers();
delete mpBufferManager;
delete mpGameSystem;
}
void Game::runGameLoop()
{
mShouldRunLoop = true;
PerformanceTracker loopTracker;
Timer mGameTimer;
while (mShouldRunLoop)
{
loopTracker.clearTracker("GameLoop");
loopTracker.startTracking("GameLoop");
mGameTimer.start();
// Process user input
mpInputSystem->update();
//Update
mpUnitManager->update(16.7);
//Draw
mpGameSystem->getDisplay()->draw(0, 0, mpGameBackground, 1);
mpUnitManager->draw(mpGameSystem);
//Display picture
mpGameSystem->getDisplay()->flipDispaly();
//get current time again
double postTime = mGameTimer.getElapsedTime();
//sleep time = target time - elapsed time
double sleepTime = mTargetTime;
//sleep for (sleep time) - al_rest
mGameTimer.sleepUntilElapsed(sleepTime);
loopTracker.stopTracking("GameLoop");
cout << loopTracker.getElapsedTime("GameLoop") << endl;
}
} | [
"john.connelly@mymail.champlain.edu"
] | john.connelly@mymail.champlain.edu |
254d758e1100f6b9182c87e3ca2e8dd0ee1ccb82 | 1c6c1b7f8ea652bed1a38306933f3bb115f4e94a | /examples/sycamore/sycamore_circ_slice_samples.cpp | 007366b95c7191c70bd6cc27f1ef863c9da180fc | [
"BSD-3-Clause"
] | permissive | ORNL-QCI/tnqvm | 67dd1dc48aecd482ed06ef83fe5e9df15aa79173 | 68a03ddce7bab7a584ab4f29ad30182607a25bf5 | refs/heads/master | 2022-11-04T23:51:08.823729 | 2022-10-21T05:31:32 | 2022-10-21T05:31:32 | 73,201,965 | 35 | 9 | null | 2022-05-20T03:28:28 | 2016-11-08T15:53:45 | C++ | UTF-8 | C++ | false | false | 2,869 | cpp | // Computes a single amplitude from a Sycamore circuit via full tensor contraction
#include "xacc.hpp"
#include <iostream>
#include <fstream>
#include <numeric>
#include <cassert>
// Initial state:
const std::vector<int> INITIAL_STATE_BIT_STRING(53, 0);
std::string bitStringVecToString(const std::vector<int>& in_vec)
{
std::stringstream s;
for (const auto& bit: in_vec) s << bit;
return s.str();
}
int main(int argc, char **argv)
{
xacc::Initialize();
xacc::set_verbose(true);
xacc::logToFile(true);
xacc::setLoggingLevel(1);
// Options: 4, 5, 6, 8, 10, 12, 14, 16, 18, 20
const int CIRCUIT_DEPTH = 4;
// Construct the full path to the XASM source file
const std::string XASM_SRC_FILE = std::string(RESOURCE_DIR) + "/sycamore_53_" + std::to_string(CIRCUIT_DEPTH) + "_0.xasm";
// Read XASM source
std::ifstream inFile;
inFile.open(XASM_SRC_FILE);
std::stringstream strStream;
strStream << inFile.rdbuf();
const std::string kernelName = "sycamoreCirc";
std::string xasmSrcStr = strStream.str();
// Construct a unique kernel name:
const std::string newKernelName = kernelName + "_" + std::to_string(CIRCUIT_DEPTH);
xasmSrcStr.replace(xasmSrcStr.find(kernelName), kernelName.length(), newKernelName);
const int NB_OPEN_QUBITS = 21;
// The bitstring to calculate amplitude
// Example: bitstring = 000000000...00 (-1 -1)
// there are NB_OPEN_QUBITS open legs at the end (-1) values
std::vector<int> BIT_STRING(53, 0);
std::fill_n(BIT_STRING.begin() + (BIT_STRING.size() - NB_OPEN_QUBITS),
NB_OPEN_QUBITS, -1);
// ExaTN visitor:
// Note:
// (1) "exatn" == "exatn:double" uses double (64-bit) type.
// (1) "exatn:float" uses float (32-bit) type.
const std::string OPTIMIZER_NAME = "cotengra"; // "cotengra"
auto qpu = xacc::getAccelerator("tnqvm", {
std::make_pair("tnqvm-visitor", "exatn"),
std::make_pair("bitstring", BIT_STRING),
std::make_pair("exatn-buffer-size-gb", 2),
std::make_pair("exatn-contract-seq-optimizer", OPTIMIZER_NAME)
});
// Allocate a register of 53 qubits
auto qubitReg = xacc::qalloc(53);
// Compile the XASM program
auto xasmCompiler = xacc::getCompiler("xasm");
auto ir = xasmCompiler->compile(xasmSrcStr, qpu);
auto program = ir->getComposites()[0];
qpu->execute(qubitReg, program);
// qubitReg->print();
const auto realAmpl = (*qubitReg)["amplitude-real-vec"].as<std::vector<double>>();
const auto imagAmpl = (*qubitReg)["amplitude-imag-vec"].as<std::vector<double>>();
// Open 21 legs
assert(realAmpl.size() == (1ULL << NB_OPEN_QUBITS));
assert(imagAmpl.size() == (1ULL << NB_OPEN_QUBITS));
std::cout << "Slice vector of size: " << realAmpl.size() << "\n";
xacc::Finalize();
return 0;
}
| [
"nguyentm@ornl.gov"
] | nguyentm@ornl.gov |
c41e95ac2ffbf325a553d78ece698a1c29c94410 | b71b8bd385c207dffda39d96c7bee5f2ccce946c | /testcases/CWE401_Memory_Leak/s02/CWE401_Memory_Leak__new_array_struct_twoIntsStruct_14.cpp | 457b5e71c5352444d0f775bb9ef89330e9669979 | [] | no_license | Sporknugget/Juliet_prep | e9bda84a30bdc7938bafe338b4ab2e361449eda5 | 97d8922244d3d79b62496ede4636199837e8b971 | refs/heads/master | 2023-05-05T14:41:30.243718 | 2021-05-25T16:18:13 | 2021-05-25T16:18:13 | 369,334,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,309 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE401_Memory_Leak__new_array_struct_twoIntsStruct_14.cpp
Label Definition File: CWE401_Memory_Leak__new_array.label.xml
Template File: sources-sinks-14.tmpl.cpp
*/
/*
* @description
* CWE: 401 Memory Leak
* BadSource: Allocate data using new[]
* GoodSource: Point data to a stack buffer
* Sinks:
* GoodSink: call delete[] on data
* BadSink : no deallocation of data
* Flow Variant: 14 Control flow: if(globalFive==5) and if(globalFive!=5)
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
namespace CWE401_Memory_Leak__new_array_struct_twoIntsStruct_14
{
#ifndef OMITBAD
void bad()
{
struct _twoIntsStruct * data;
data = NULL;
{
/* POTENTIAL FLAW: Allocate memory on the heap */
data = new struct _twoIntsStruct[100];
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
}
{
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second globalFive==5 to globalFive!=5 */
static void goodB2G1()
{
struct _twoIntsStruct * data;
data = NULL;
{
/* POTENTIAL FLAW: Allocate memory on the heap */
data = new struct _twoIntsStruct[100];
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
}
{
/* FIX: Deallocate memory */
delete[] data;
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
struct _twoIntsStruct * data;
data = NULL;
{
/* POTENTIAL FLAW: Allocate memory on the heap */
data = new struct _twoIntsStruct[100];
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
}
{
/* FIX: Deallocate memory */
delete[] data;
}
}
/* goodG2B1() - use goodsource and badsink by changing the first globalFive==5 to globalFive!=5 */
static void goodG2B1()
{
struct _twoIntsStruct * data;
data = NULL;
{
/* FIX: Use memory allocated on the stack */
struct _twoIntsStruct dataGoodBuffer[100];
data = dataGoodBuffer;
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
}
{
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
struct _twoIntsStruct * data;
data = NULL;
{
/* FIX: Use memory allocated on the stack */
struct _twoIntsStruct dataGoodBuffer[100];
data = dataGoodBuffer;
/* Initialize and make use of data */
data[0].intOne = 0;
data[0].intTwo = 0;
printStructLine((twoIntsStruct *)&data[0]);
}
{
/* POTENTIAL FLAW: No deallocation */
; /* empty statement needed for some flow variants */
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE401_Memory_Leak__new_array_struct_twoIntsStruct_14; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"jaredzap@rams.colostate.edu"
] | jaredzap@rams.colostate.edu |
1efe9cebf2b76644ab1bab84bb94897935ab05ef | a37963cee6a482275b089922375a60b3819d8072 | /tdw/SupportTDW/TiledDisplayWallTag.h | 074f2513fb49ceae17f6d6703377efa432480bf6 | [] | no_license | njun-git/kvs | f639ab36df290d308531d1538066739b8ca265e6 | ae15b5dc2b50f9ff8fb5090bdd41fc1b496cada3 | refs/heads/master | 2021-01-23T07:03:20.287011 | 2012-02-14T06:53:59 | 2012-02-14T06:53:59 | 2,502,777 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,435 | h | /*
* TiledDisplayWallTag.h
*
*
* Created by njun on 11/07/09.
* Copyright 2011 Jun Nishimura. All rights reserved.
*
*/
#ifndef KVS__KVSML__TILED_DISPLAY_WALL_TAG_H_INCLUDE
#define KVS__KVSML__TILED_DISPLAY_WALL_TAG_H_INCLUDE
#include <kvs/XMLNode>
#include <Core/FileFormat/KVSML/TagBase.h>
#include <kvs/Vector2>
namespace kvs
{
namespace kvsml
{
class TiledDisplayWallTag : public kvs::kvsml::TagBase
{
public:
typedef kvs::kvsml::TagBase BaseClass;
protected:
bool m_has_nrenderers;
int m_nrenderers;
bool m_has_full_resolution;
kvs::Vector2i m_full_resolution;
bool m_is_fullscreen;
bool m_is_sync;
public:
TiledDisplayWallTag( void );
virtual ~TiledDisplayWallTag( void );
public:
const bool hasNRenderers( void ) const;
const int nrenderers( void ) const;
const bool hasFullResolution( void ) const;
const kvs::Vector2i fullResolution( void ) const;
const bool isFullscreen( void ) const;
const bool isSync( void ) const;
public:
void setNRenderers( const int nrenderers );
void setFullResolution( const kvs::Vector2i& full_resolution );
void setFullscreen( const bool fullscreen );
void setSync( const bool sync );
public:
const bool read( const kvs::XMLNode::SuperClass* parent );
const bool write( kvs::XMLNode::SuperClass* parent );
};
} // end of namespace kvsml
} // end of namespace kvs
#endif
| [
"njun3196@gmail.com"
] | njun3196@gmail.com |
0979f92e8bc336cf398875f5635b9834484e7b05 | 9a455973f60ce048eed15d3c71f60e81161a09c7 | /src/common/conparser/implementations/jiangming/rules/csubjpass.cpp | 540aa9026532c4ba654da3a9908500ce7dfe5bde | [] | no_license | SUTDNLP/ZPar | 4e2e87b874a2d2ca8c1f8aec854698d35ed3b307 | 0d07078be45151b4dfc5cda82cfd16c9765f0b63 | refs/heads/master | 2021-05-04T10:33:24.955650 | 2016-10-15T10:28:06 | 2016-10-15T10:28:06 | 45,964,664 | 11 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 6,348 | cpp |
//"S < (SBAR|S=target !$+ /^,$/ $++ (VP < (VP < VBN|VBD) < (/^(?:VB|AUXG?)/ < " + passiveAuxWordRegex + ") !$-- NP))",
bool csubjpass1(const unsigned long &cons){
if (cons==PENN_CON_S){
CStateNodeList* childs=node.m_umbinarizedSubNodes;
while(childs!=0){
const CStateNode* targ=childs->node;
if (CConstituent::clearTmp(CConstituent::clearTmp(targ->constituent.code())==PENN_CON_SBAR
|| CConstituent::clearTmp(targ->constituent.code())==PENN_CON_S)){
bool commaCond=true;
CStateNodeList* rightSisters=childs->next;
if (rightSisters!=0){
if ((*words)[rightSisters->node->lexical_head].word==g_word_comma){
commaCond=false;
}
}
if (commaCond){
while(rightSisters!=0){
if (CConstituent::clearTmp(rightSisters->node->constituent.code())==PENN_CON_VP){
bool leftSisCond=true;
CStateNodeList* leftSisters=rightSisters->previous;
while(leftSisters!=0){
if (CConstituent::clearTmp(leftSisters->node->constituent.code())==PENN_CON_NP){
leftSisCond=false;
}
leftSisters=leftSisters->previous;
}
if (leftSisCond){
CStateNodeList* childsVp=rightSisters->node->m_umbinarizedSubNodes;
bool firstCond=false;
bool secCond=false;
//< (VP < VBN|VBD) < (/^(?:VB|AUXG?)/ < " + passiveAuxWordRegex + ")
while(childsVp!=0){
if (CConstituent::clearTmp(childsVp->node->constituent.code())==PENN_CON_VP){
CStateNodeList* childsVpIn=childsVp->node->m_umbinarizedSubNodes;
while(childsVpIn!=0){
if ((*words)[childsVpIn->node->lexical_head].tag.code()==PENN_TAG_VERB_PAST
|| (*words)[childsVpIn->node->lexical_head].tag.code()==PENN_TAG_VERB_PAST_PARTICIPATE){
firstCond=true;
}
childsVpIn=childsVpIn->next;
}
}
if ((*words)[childsVp->node->lexical_head].tag.code()==PENN_TAG_VERB){
if (compareWordToPassiveAuxWordRegex((*words)[childsVp->node->lexical_head].word)) {
secCond=true;
}
}
childsVp=childsVp->next;
}
if (firstCond && secCond){
// CDependencyLabel* label=new CDependencyLabel(STANFORD_DEP_NN);
if (buildStanfordLink(STANFORD_DEP_CSUBJPASS, targ->lexical_head, node.lexical_head)) {
addLinked(&node,targ);
return true;
}
}
}
}
rightSisters=rightSisters->next;
}
}
}
childs=childs->next;
}
}
return false;
}
//"S < (SBAR|S=target !$+ /^,$/ $++ (VP <+(VP) (VP < VBN|VBD > (VP < (/^(?:VB|AUX)/ < " + passiveAuxWordRegex + "))) !$-- NP))"
bool csubjpass2(const unsigned long &cons){
if (cons==PENN_CON_S){
CStateNodeList* childs=node.m_umbinarizedSubNodes;
while(childs!=0){
const CStateNode* targ=childs->node;
if ((CConstituent::clearTmp(targ->constituent.code())==PENN_CON_SBAR || CConstituent::clearTmp(targ->constituent.code())==PENN_CON_S) && !isLinked(&node,targ)){
bool commaCond=true;
bool npCond=true;
CStateNodeList* leftSisters=childs->previous;
while(leftSisters!=0){
if (CConstituent::clearTmp(leftSisters->node->constituent.code())==PENN_CON_NP){
npCond=false;
}
leftSisters=leftSisters->previous;
}
if (npCond&& childs->next!=0){
if ((*words)[childs->next->node->lexical_head].word==g_word_comma){
commaCond=false;
}
}
if (commaCond && npCond){
CStateNodeList* rightSisters=childs->next;
while(rightSisters!=0){
if (CConstituent::clearTmp(rightSisters->node->constituent.code())==PENN_CON_VP){
CStateNodeList* vpsChain=new CStateNodeList();
//std::cout<<"findingchain\n";
findChain(PENN_CON_VP,PENN_CON_VP, rightSisters->node, vpsChain);
if (vpsChain->node==0) {
vpsChain->clear();
vpsChain=0;
}
while(vpsChain!=0){
CStateNodeList* childsOfAVp=vpsChain->node->m_umbinarizedSubNodes;
while(childsOfAVp!=0){
if ((*words)[childsOfAVp->node->lexical_head].tag.code()==PENN_TAG_VERB_PAST_PARTICIPATE || (*words)[childsOfAVp->node->lexical_head].tag.code()==PENN_TAG_VERB_PAST){
const CStateNode* parent=findParent(rightSisters->node, childsOfAVp->node);
if (parent!=0 && CConstituent::clearTmp(parent->constituent.code())==PENN_CON_VP){
CStateNodeList* childsVp=parent->m_umbinarizedSubNodes;
while(childsVp!=0){
if ((*words)[childsVp->node->lexical_head].tag.code()==PENN_TAG_VERB){
//CStateNodeList* childsVb=childsVp->node->m_umbinarizedSubNodes;
//while(childsVb!=0){
if (compareWordToPassiveAuxWordRegex((*words)[childsVp->node->lexical_head].word)) {
// CDependencyLabel* label=new CDependencyLabel(STANFORD_DEP_NN);
if (buildStanfordLink(STANFORD_DEP_CSUBJPASS, targ->lexical_head, node.lexical_head)) {
addLinked(&node,targ);
return true;
}
}
//childsVb=childsVb->next;
//}
}
childsVp=childsVp->next;
}
}
}
childsOfAVp=childsOfAVp->next;
}
vpsChain=vpsChain->next;
}
}
rightSisters=rightSisters->next;
}
}
}
childs=childs->next;
}
}
return false;
}
| [
"jmliunlp@gmail.com"
] | jmliunlp@gmail.com |
14d61b0b2edbfff5e86104944f894d1b24c37535 | c744852d48fa2be04d0ff8b0aa25f01bbcd4f585 | /PowerController.h | 2e4b871959e2249fff9c3305c1bf49d9c0b810be | [] | no_license | minxiviii/gppc | 3e10d8fa58ac09e45f3464743c9a6a4b22bafee5 | a0d54a3afcecaf6c1bd671dcabd3d938a7c0d14b | refs/heads/master | 2023-03-02T04:59:51.687459 | 2021-01-26T02:22:10 | 2021-01-26T02:22:10 | 324,851,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,790 | h | #pragma once
#include ".\serial\CSerial.h"
#include "CommandModel.h"
/********************* PowerPort *********************/
class PowerPort
{
private:
PowerPort();
uint32_t m_dwPortNumber;
vector<CommandModel> m_schedule;
HANDLE m_hScheduleThread;
HANDLE m_hSemaphore;
BOOL m_bThreadRun;
BOOL m_bStart;
string current;
int step;
void* m_handle;
CtrlCommand_CB m_callback;
static DWORD WINAPI ScheduleThread(void* data);
public:
PowerPort(uint32_t dwPortNumber, CtrlCommand_CB callback, void* handle);
~PowerPort();
void InitSchedule();
void AddSchedule(const string& action, const string& value, int step = 0);
void ClearSchedule();
void StartSchedule();
void ThreadClose();
string GetCurrent();
void SetCurrent(const string& current);
int GetStep();
BOOL isRun();
};
/********************* PowerController *********************/
class PowerController : public CSerial
{
private:
int id;
void* context;
CallbackFunc callbackfunc;
vector<PowerPort> powerport;
static void Command_CB(char* buffer, int len, void* handle);
public:
PowerController();
~PowerController();
void Init(int id, int port_count, CallbackFunc cb, void* ctx);
void Deinit();
int GetID();
int GetPortCount();
BOOL ConnectSerial(CString port, CString buadrate = _T("57600"));
BOOL DisconnectSerial();
void SendCommand(const int port_index, const string& action, const string& value);
void SendCommand(const string& command);
void SendCommand(BYTE* buffer, int len);
void StartScheduler(int port_index);
BOOL isScheduling(int port_index);
BOOL AddSchedule(int port_index, const string& action, const string& value, int step = 0);
void ResetSchedule();
void ResetSchedule(int port_index);
string GetCurrent(int port_index);
int GetStep(int port_index);
}; | [
"minxiviii@gmail.com"
] | minxiviii@gmail.com |
1041c7d0cb1cc87240b9361208cba21b0ecb699b | 49d55bf89ed481762dd7ad07627ea56147e12f22 | /Command.h | 9729f9cd533d8264eb1608055c61d022e6981efe | [] | no_license | renanaMalkiel/millStone | 44291192b1029c9aed3bc950714c23b00ca67423 | 363567b31d1152b2827eb6ba4c5fd3eb73206d03 | refs/heads/master | 2020-04-11T08:37:35.196011 | 2018-12-17T17:01:56 | 2018-12-17T17:01:56 | 161,650,123 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 260 | h | //
// Created by renana on 12/13/18.
//
#ifndef MILLSTONE_COMMAND_H
#define MILLSTONE_COMMAND_H
#include <iostream>
#include <vector>
using namespace std;
class Command{
public:
virtual void doCommand(vector<string>) = 0;
};
#endif //MILLSTONE_COMMAND_H
| [
"8renana@gmail.com"
] | 8renana@gmail.com |
65d1271fe2ab5c4fc8297c1f86b6cefb0e499dcb | 5db22247ed9ee65139b87c1ed28108cd4b1ac6e5 | /Classes/Native/mscorlib_System_Console3734986830.h | 29b0bd4ebdf7a8111632cea3d3ff23d999ec5bd6 | [] | no_license | xubillde/JLMC | fbb1a80dc9bbcda785ccf7a85eaf9228f3388aff | 408af89925c629a4d0828d66f6ac21e14e78d3ec | refs/heads/master | 2023-07-06T00:44:22.164698 | 2016-11-25T05:01:16 | 2016-11-25T05:01:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,500 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.IO.TextWriter
struct TextWriter_t1448322145;
// System.IO.TextReader
struct TextReader_t657369457;
// System.Text.Encoding
struct Encoding_t2125916575;
#include "mscorlib_System_Object707969140.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Console
struct Console_t3734986830 : public Il2CppObject
{
public:
public:
};
struct Console_t3734986830_StaticFields
{
public:
// System.IO.TextWriter System.Console::stdout
TextWriter_t1448322145 * ___stdout_0;
// System.IO.TextWriter System.Console::stderr
TextWriter_t1448322145 * ___stderr_1;
// System.IO.TextReader System.Console::stdin
TextReader_t657369457 * ___stdin_2;
// System.Text.Encoding System.Console::inputEncoding
Encoding_t2125916575 * ___inputEncoding_3;
// System.Text.Encoding System.Console::outputEncoding
Encoding_t2125916575 * ___outputEncoding_4;
public:
inline static int32_t get_offset_of_stdout_0() { return static_cast<int32_t>(offsetof(Console_t3734986830_StaticFields, ___stdout_0)); }
inline TextWriter_t1448322145 * get_stdout_0() const { return ___stdout_0; }
inline TextWriter_t1448322145 ** get_address_of_stdout_0() { return &___stdout_0; }
inline void set_stdout_0(TextWriter_t1448322145 * value)
{
___stdout_0 = value;
Il2CppCodeGenWriteBarrier(&___stdout_0, value);
}
inline static int32_t get_offset_of_stderr_1() { return static_cast<int32_t>(offsetof(Console_t3734986830_StaticFields, ___stderr_1)); }
inline TextWriter_t1448322145 * get_stderr_1() const { return ___stderr_1; }
inline TextWriter_t1448322145 ** get_address_of_stderr_1() { return &___stderr_1; }
inline void set_stderr_1(TextWriter_t1448322145 * value)
{
___stderr_1 = value;
Il2CppCodeGenWriteBarrier(&___stderr_1, value);
}
inline static int32_t get_offset_of_stdin_2() { return static_cast<int32_t>(offsetof(Console_t3734986830_StaticFields, ___stdin_2)); }
inline TextReader_t657369457 * get_stdin_2() const { return ___stdin_2; }
inline TextReader_t657369457 ** get_address_of_stdin_2() { return &___stdin_2; }
inline void set_stdin_2(TextReader_t657369457 * value)
{
___stdin_2 = value;
Il2CppCodeGenWriteBarrier(&___stdin_2, value);
}
inline static int32_t get_offset_of_inputEncoding_3() { return static_cast<int32_t>(offsetof(Console_t3734986830_StaticFields, ___inputEncoding_3)); }
inline Encoding_t2125916575 * get_inputEncoding_3() const { return ___inputEncoding_3; }
inline Encoding_t2125916575 ** get_address_of_inputEncoding_3() { return &___inputEncoding_3; }
inline void set_inputEncoding_3(Encoding_t2125916575 * value)
{
___inputEncoding_3 = value;
Il2CppCodeGenWriteBarrier(&___inputEncoding_3, value);
}
inline static int32_t get_offset_of_outputEncoding_4() { return static_cast<int32_t>(offsetof(Console_t3734986830_StaticFields, ___outputEncoding_4)); }
inline Encoding_t2125916575 * get_outputEncoding_4() const { return ___outputEncoding_4; }
inline Encoding_t2125916575 ** get_address_of_outputEncoding_4() { return &___outputEncoding_4; }
inline void set_outputEncoding_4(Encoding_t2125916575 * value)
{
___outputEncoding_4 = value;
Il2CppCodeGenWriteBarrier(&___outputEncoding_4, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"zhaolibo@zhaolibodeiMac.local"
] | zhaolibo@zhaolibodeiMac.local |
ac26858fd0a4f5734733778df566d3723f34a5f7 | be8e47adaf8f46248b4d1887ba235733c2e45879 | /incdec.cpp | f86002c962529c4bd618944d9c5a1b9df10ff492 | [
"MIT"
] | permissive | riyadhalnur/C-plusplus-codes | 7137bf8348e8b2927f50b274d86dc039da6ad616 | 662f5f4be5fb73f1c8d3f4c370093997c9289dc7 | refs/heads/master | 2016-09-06T00:21:49.957768 | 2015-12-05T10:28:39 | 2015-12-05T10:28:39 | 40,323,682 | 0 | 0 | null | 2015-12-05T10:28:39 | 2015-08-06T19:45:07 | C++ | UTF-8 | C++ | false | false | 292 | cpp | #include <iostream>
using namespace std;
int main()
{
int a, b=0, c=0;
a = b++ + c++;
cout << a << ", " << b << ", " << c << "\n";
a = ++b + c++;
cout << a << ", " << b << ", " << c << "\n";
a = --b + c--;
cout << a << ", " << b << ", " << c << "\n";
return 0;
} | [
"riyadhalnur@verticalaxisbd.com"
] | riyadhalnur@verticalaxisbd.com |
a545f234bee929cfbedc29e56ce17a01f1dd1766 | 1fa9bcfa1f366af818cbd474e0339965d849b51f | /src/util/dilate_erode.hh | 1b5880748aac7beee3f6552b829ae0d5bab12c6e | [] | no_license | stanford-stagecast/compositor | a092d3c2c6ac34ffd2d0f5a25ccd53a828691136 | 29d4a47a86655128ae094b8e66e709ee69d7d5fa | refs/heads/master | 2023-04-09T16:52:44.472853 | 2021-04-22T19:57:01 | 2021-04-22T19:57:01 | 298,700,836 | 0 | 1 | null | 2021-02-13T00:16:04 | 2020-09-25T23:38:42 | C++ | UTF-8 | C++ | false | false | 1,139 | hh | /* -*-mode:c++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
#ifndef DILATE_ERODE_HH
#define DILATE_ERODE_HH
#include "util/raster.hh"
class DilateErodeOperation
{
private:
uint16_t width_, height_;
int distance_ {};
bool is_dilation_ { distance_ > 0 };
TwoD<uint8_t> intermediate_mask_ { width_, height_ };
double process_pixel_intermediate( TwoD<uint8_t>& mask, int x, int y );
double process_pixel_final( int x, int y );
public:
DilateErodeOperation( const uint16_t width,
const uint16_t height,
const int distance );
void set_distance( const int distance );
// The kernel is separable, so the convolution is done in two steps for speed
void process_rows_intermediate( TwoD<uint8_t>& mask,
const uint16_t row_start_idx,
const uint16_t row_end_idx );
void process_rows_final( TwoD<uint8_t>& mask,
const uint16_t row_start_idx,
const uint16_t row_end_idx );
};
#endif /* DILATE_ERODE_HH */
| [
"yifengl@stanford.edu"
] | yifengl@stanford.edu |
b79ad0baede9265e9598eb53695f838b0b591bef | 1ed5f26b3e24e566f2e402503eff841c8ada70de | /Module-3/light-controlled-blink.ino | 5f4df0b60488b523e95fd3fc7afa4848602941d9 | [] | no_license | GalileoWorkshop/IESC | c9abbbd42f9b2fcd30eff7113bc0e7ef564d0cbc | 4afc840bcb00d1805d5efcdf69dcef8d2fc2b85f | refs/heads/master | 2021-01-20T10:06:33.603480 | 2014-07-28T23:22:25 | 2014-07-28T23:22:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | ino | /* Analog InputDemonstrates analog input by reading an analog sensor on analog pin 0 and turning on and off a light emitting diode(LED) connected to digital pin 13. The amount of time the LED will be on and off depends on the value obtained by analogRead(). */
int photo = A0; // select the input pin for the potentiometer
int led = 8; // select the pin for the LED
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
// declare the ledPin as an OUTPUT:
pinMode(led, OUTPUT);
}
void loop() {
// read the value from the sensor:
sensorValue = analogRead(photo);
// turn the ledPin on
digitalWrite(led, HIGH);
// stop the program for <sensorValue> milliseconds:
delay(sensorValue);
// turn the ledPin off:
digitalWrite(led, LOW);
// stop the program for for <sensorValue> milliseconds:
delay(sensorValue);
}
| [
"sherwin.remo@gmail.com"
] | sherwin.remo@gmail.com |
a4dba0375624de90bfb0f66a2085a1193daad39e | df6a7072020c0cce62a2362761f01c08f1375be7 | /include/oglplus/texture_target.hpp | a656abad6f2147b9a54e564534fcacf68d3f0215 | [
"BSL-1.0"
] | permissive | matus-chochlik/oglplus | aa03676bfd74c9877d16256dc2dcabcc034bffb0 | 76dd964e590967ff13ddff8945e9dcf355e0c952 | refs/heads/develop | 2023-03-07T07:08:31.615190 | 2021-10-26T06:11:43 | 2021-10-26T06:11:43 | 8,885,160 | 368 | 58 | BSL-1.0 | 2018-09-21T16:57:52 | 2013-03-19T17:52:30 | C++ | UTF-8 | C++ | false | false | 775 | hpp | /**
* @file oglplus/texture_target.hpp
* @brief Texture target enumeration
*
* @author Matus Chochlik
*
* Copyright 2010-2019 Matus Chochlik. Distributed under the Boost
* Software License, Version 1.0. (See accompanying file
* LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
*/
#pragma once
#ifndef OGLPLUS_TEXTURE_TARGET_1107121519_HPP
#define OGLPLUS_TEXTURE_TARGET_1107121519_HPP
#include <oglplus/config/enums.hpp>
#include <oglplus/enums/texture_target.hpp>
#include <oglplus/fwd.hpp>
namespace oglplus {
#if !OGLPLUS_NO_ENUM_VALUE_CLASSES
#include <oglplus/enums/texture_target_class.ipp>
#endif
template <>
struct ObjectTargetTag<TextureTarget> {
using Type = tag::Texture;
};
} // namespace oglplus
#endif // include guard
| [
"chochlik@gmail.com"
] | chochlik@gmail.com |
71988f8c6ddb118ad8a6d12d7b46e42d3b0a99e3 | 8a9de9939503b1f75aa744382935663c3d6e63c2 | /Kids With the Greatest Number of Candies.cpp | 6875d53baf5468fefb5e4c09b884fa5b9c8ca33b | [] | no_license | eecheng87/LeetCode | cd9d91178a3feeb6aa2cd961c568d2369832b6a6 | 768537fcf4d7567fd7f7755424b5cb0779addbaa | refs/heads/master | 2021-07-11T21:19:31.420880 | 2020-07-25T03:14:54 | 2020-07-25T03:14:54 | 175,143,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | class Solution
{
public:
vector<bool> kidsWithCandies(vector<int> &candies, int extraCandies)
{
int m = -1;
for (auto i : candies)
m = max(m, i);
vector<bool> ans(candies.size(), false);
for (int i = 0; i < ans.size(); i++)
{
if (candies[i] + extraCandies >= m)
ans[i] = true;
}
return ans;
}
}; | [
"yucheng871011@gmail.com"
] | yucheng871011@gmail.com |
c80aa12b5700dfca0421f48c298a1f544857c68d | d754ba23c8ff391ce9dcefcfae3b90cef16ecde0 | /DMOJ/BackToSchool/bts19p4.cpp | 6a74be629357edab5751a8be626e9ef718da72b2 | [] | no_license | TruVortex/Competitive-Programming | 3edc0838aef41128a27fdc7f47d704adbf2c3f38 | 3812ff630488d7589754ff25a3eefd8898226301 | refs/heads/master | 2023-05-10T01:48:00.996120 | 2021-06-02T03:36:35 | 2021-06-02T03:36:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 845 | cpp | // full solution
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, m;
scanf("%i%i", &n, &m);
assert(1 <= n && n <= 100000);
assert(1 <= m && m <= 1000000000);
vector<long long> arr(n);
for (auto &x : arr)
scanf("%lli", &x), assert(1 <= x && x <= m);
sort(arr.begin(), arr.end());
for (int x = 0; x < n; x++)
arr.push_back(arr[x] + m);
long long cur = 0;
for (int x = 0; x < n; x++)
cur += abs(arr[x] - arr[0]);
int l = 0, r = 0;
long long mi = cur;
while (l < n)
{
while (r < l + n/2)
{
r++;
cur += abs(arr[r] - arr[r-1]) * (2 * r - 2 * l - n);
}
mi = min(mi, cur);
cur -= abs(arr[l] - arr[r]);
cur += abs(arr[l + n] - arr[r]);
l++;
}
printf("%lli\n", mi);
}
| [
"evanzhang1028@hotmail.com"
] | evanzhang1028@hotmail.com |
dbd20a431c30911c883cee103de558af1141bc2e | feabb02a9f72d59935fb9dffa73d0a926c0d4072 | /source/anim.h | f10d39c03babf7474c615f624892694f64282d07 | [] | no_license | titangate/SEttlers-of-Apocalypse | 3b007de5b1aba02f18b2662fa13f3e94fae385bc | fdd30c5a4de1260b4ef842253f43d2edca53c023 | refs/heads/master | 2020-04-27T04:44:53.929091 | 2013-01-12T23:41:14 | 2013-01-12T23:41:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,137 | h | #ifndef ANIMATION_H
#define ANIMATION_H
#include "widget.h"
#include <string>
#include <vector>
template <class T>
class Anim;
using namespace std;
typedef double (*STYLEFUNC)(double time_e,double start,double interval,double time) ;
extern map<string, STYLEFUNC> stylefs;
double linear(double t,double b, double c, double d);
double quadIn(double t,double b, double c, double d);
double quadOut(double t,double b, double c, double d);
template <class T>
class Animation{
public:
void (T::*setter)(double value);
T* obj;
double start,finish;
double time,delay,current;
double time_eplapsed;
std::string style;
Animation(void (T::*_setter)(double value),T* _obj,
double _start,double _finish,double _time,
const std::string& _style):
setter(_setter),obj(_obj),
start(_start),finish(_finish),time(_time),style(_style),current(_start),time_eplapsed(0)
{}
bool update (double dt){
time_eplapsed+=dt;
if (time_eplapsed < time) {
current = (*stylefs[style])(time_eplapsed,start,finish-start,time);
(obj->*setter)(current);
}
else{
(obj->*setter)(finish);
//vector < Animation<T> > & anim = Anim<T>::getInstance().anims;
return true;
//anim.erase(find(anim.begin(), anim.end(), *this));
}
return false;
}
};
template <class T>
class Anim{
friend class Animation<T>;
protected:
vector<Animation<T> > anims;
public:
static Anim & getInstance(){
static Anim instance;
return instance;
}
void animate(T * w,void (T::*_setter)(double value),double start,double finish,double time,string style = "linear"){
anims.push_back(Animation<T>(_setter,w,start,finish,time,style));
}
void update(double dt){
for (unsigned int i=0; i<anims.size(); i++) {
if(anims[i].update(dt)) anims.erase(anims.begin()+i);
}
}
Anim(){
stylefs["linear"] = &linear;
stylefs["quadIn"] = &quadIn;
stylefs["quadOut"] = &quadIn;
}
};
#endif | [
"titangate1202@gmail.com"
] | titangate1202@gmail.com |
2f70b521ccdcca8d45ba7b29550449838f173d5d | 09a20466c1650ab4beb6554ceabc8649a7540c06 | /core/src/api/BoolCallback.hpp | 54dd069cf99763e66fb754a3bbdd806fbe0ffe6d | [
"MIT"
] | permissive | LedgerHQ/lib-ledger-core | 2f1153655ed7c116b866d2b21920a8a3017f5d96 | ad1e271b5f61e92f663ff08c337acc8b107fc85f | refs/heads/main | 2023-07-09T18:24:41.408616 | 2023-07-06T13:09:06 | 2023-07-06T13:09:06 | 68,716,694 | 99 | 99 | MIT | 2023-06-30T08:36:20 | 2016-09-20T13:51:06 | C++ | UTF-8 | C++ | false | false | 1,003 | hpp | // AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from callback.djinni
#ifndef DJINNI_GENERATED_BOOLCALLBACK_HPP
#define DJINNI_GENERATED_BOOLCALLBACK_HPP
#include "../utils/optional.hpp"
#ifndef LIBCORE_EXPORT
#if defined(_MSC_VER)
#include <libcore_export.h>
#else
#define LIBCORE_EXPORT
#endif
#endif
namespace ledger { namespace core { namespace api {
struct Error;
/** Callback triggered by main completed task, returning optional result of template type T. */
class BoolCallback {
public:
virtual ~BoolCallback() {}
/**
* Method triggered when main task complete.
* @params result optional of type T, non null if main task failed
* @params error optional of type Error, non null if main task succeeded
*/
virtual void onCallback(std::experimental::optional<bool> result, const std::experimental::optional<Error> & error) = 0;
};
} } } // namespace ledger::core::api
#endif //DJINNI_GENERATED_BOOLCALLBACK_HPP
| [
"khalil.bellakrid@ledger.fr"
] | khalil.bellakrid@ledger.fr |
3053c0eeed5e12bba33ef2628beabc32f0563ca6 | ef25bd96604141839b178a2db2c008c7da20c535 | /src/src/Engine/Core/Math.h | dbe1915e821ff2ee32a64b485ecbf3bae4301227 | [] | no_license | OtterOrder/crock-rising | fddd471971477c397e783dc6dd1a81efb5dc852c | 543dc542bb313e1f5e34866bd58985775acf375a | refs/heads/master | 2020-12-24T14:57:06.743092 | 2009-07-15T17:15:24 | 2009-07-15T17:15:24 | 32,115,272 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,566 | h | #ifndef _CROCKENGINE_MATH_H_
#define _CROCKENGINE_MATH_H_
//******************************************************************
#include <math.h>
#include <d3dx9math.h>
#include "Types/Types.h"
#include "Types/Crc32.h"
#include "Types/Vector.h"
#include "Types/Color.h"
//******************************************************************
// Ne pas mettre n'importe quoi "pour tester", car ce fichier
// est amené à être inclus dans plein d'autres ; toute modification
// devrait pourrir le temps de compilation, donc ça a intéret de
// valoire le coup..
// Merci de respecter la même syntaxe pour les macros et
// fonctions de math, à savoir : MATH_MyFunction().
template< typename T >
inline const T& MATH_Clamp( const T& x, const T& min, const T& max )
{
return ( x < min ) ? min : ( x > max ) ? max : x;
}
//******************************************************************
// Manipulation de flags facile
// @param field : champs de flag sur lequel on travaille
// @param flag : flag à activer, désactiver, tester, etc.
// Note: pour faire des flags simplement, il suffit de
// définir des constantes qui sont des puissances de 2 :
// MY_FLAG_A = 1<<0 (->001)
// MY_FLAG_B = 1<<1 (->010)
// MY_FLAG_C = 1<<2 (->100)
// etc.
#define FLAG_Set( field, flag ) ((field)|=(flag))
#define FLAG_Unset( field, flag ) ((field)^=(flag))
#define FLAG_IsSet( field, flag ) (((field)&(flag))==(flag))
//******************************************************************
#endif //_CROCKENGINE_MATH_H_
| [
"mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b"
] | mathieu.chabanon@7c6770cc-a6a4-11dd-91bf-632da8b6e10b |
d4b820979a41daec69d97dfc9f218af5b3b12bac | 9ca51d1ee38b5157c11685b348ba58602c837d6a | /ch03/ex03_03.cpp | e8d3a2eca6253baf8ca1ff774fa01b50ba5fe0d2 | [] | no_license | HLPJay/C-PrimerPlusTest | 54fdc41e809e0bd707bc430b1dca3ade2faee6bc | bd08d23210b1947c7dd24d5ae974df5ec1136b6a | refs/heads/master | 2020-06-29T14:21:34.451932 | 2019-09-19T09:30:32 | 2019-09-19T09:30:32 | 200,559,949 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 827 | cpp | /***********************************
输入:纬度,(度,分,秒)
1度 = 60 分
1分 = 60 秒
输出:以度为单位表示输出
************************************/
#include <iostream>
using namespace std;
const int degrees_to_minute = 60;
const int min_to_second = 60;
int main(void)
{
float degrees;
float minutes;
float seconds;
float result_degrees;
cout<<"Enter a latitude in degrees, minutes, and seconds"<<endl;
cout<<"First, enter the degrees:";
cin >> degrees;
cout<<"Nect, enter the minutes of arc:";
cin >> minutes;
cout<<"Finally, enter the seconds of arc:";
cin >> seconds;
result_degrees = (seconds/min_to_second+minutes)/degrees_to_minute + degrees;
cout<<degrees<<" degrees,"<<minutes <<" minutes," <<seconds<<" seconds, = "<<result_degrees<<" degrees."<<endl;
return 0;
} | [
"yun6853992@163.com"
] | yun6853992@163.com |
c2ba930978d6c2703fba0a5548a729a13ce88b78 | 25b4dd9f69cf72b33ce6ce90319b9071fbb82122 | /neuron.h | 6f1c04b35e19fba2eac39ddaaccf95ba5282ee13 | [] | no_license | Noorquacker/ScratchNN | 659d376fadc890388d4cbe52a5f588057841ea6c | 4d79d0deaf67bce273ffaba5804d973340698de7 | refs/heads/main | 2023-08-11T20:01:17.642436 | 2021-09-23T04:39:07 | 2021-09-23T04:39:07 | 409,446,173 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | h | #ifndef NEURON_H
#define NEURON_H
class Neuron {
public:
Neuron(Neuron* inputs, unsigned int size_inputs);
float (*Activate)(float in);
void Compute();
static float sigmoid(float in);
float getOutput();
float* getWeights();
float getWeight(unsigned int n);
void setWeight(unsigned int n, float w);
void setWeights(float* weights);
float getBias();
void setBias(float b);
float getInput(unsigned int n);
protected:
float output;
private:
Neuron* inputs;
float* weights;
unsigned int inputCount; //Swear on Jah if one y'all connect more than 4,294,whatever,000 neurons imma make this closed source
float bias;
};
#endif // NEURON_H
//qt creator adding auto comments like "the volume up button increases volume
| [
"noorquacker@nqind.com"
] | noorquacker@nqind.com |
aba0d155814867d42807bb7318fc426bf9b25542 | 9f08a953fb4eb719fd003221640165ee4074973d | /Validation/MuonCSCDigis/src/CSCCorrelatedLCTDigiValidation.cc | c609e959b5caadd59e2d77bb953a802844ddc827 | [
"Apache-2.0"
] | permissive | suhokimHEP/cmssw | 5270877fe2be2b1ac9c137cda041d797e96cd129 | 4102974e760db0f758efcb696b2d3e5c10d52058 | refs/heads/master | 2021-11-23T06:46:55.465132 | 2021-11-18T21:09:42 | 2021-11-18T21:09:42 | 158,607,069 | 0 | 0 | Apache-2.0 | 2019-06-04T19:24:42 | 2018-11-21T21:16:19 | C++ | UTF-8 | C++ | false | false | 5,352 | cc | #include "DataFormats/Common/interface/Handle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "Validation/MuonCSCDigis/interface/CSCCorrelatedLCTDigiValidation.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "Geometry/CSCGeometry/interface/CSCGeometry.h"
#include "Geometry/CSCGeometry/interface/CSCLayerGeometry.h"
CSCCorrelatedLCTDigiValidation::CSCCorrelatedLCTDigiValidation(const edm::ParameterSet &ps, edm::ConsumesCollector &&iC)
: CSCBaseValidation(ps),
theNDigisPerChamberPlots(),
chambers_(ps.getParameter<std::vector<std::string>>("chambers")),
chambersRun3_(ps.getParameter<std::vector<unsigned>>("chambersRun3")),
// variables
lctVars_(ps.getParameter<std::vector<std::string>>("lctVars")),
// binning
lctNBin_(ps.getParameter<std::vector<unsigned>>("lctNBin")),
lctMinBin_(ps.getParameter<std::vector<double>>("lctMinBin")),
lctMaxBin_(ps.getParameter<std::vector<double>>("lctMaxBin")),
isRun3_(ps.getParameter<bool>("isRun3")) {
const auto &pset = ps.getParameterSet("cscMPLCT");
inputTag_ = pset.getParameter<edm::InputTag>("inputTag");
lcts_Token_ = iC.consumes<CSCCorrelatedLCTDigiCollection>(inputTag_);
}
CSCCorrelatedLCTDigiValidation::~CSCCorrelatedLCTDigiValidation() {}
void CSCCorrelatedLCTDigiValidation::bookHistograms(DQMStore::IBooker &iBooker) {
iBooker.setCurrentFolder("MuonCSCDigisV/CSCDigiTask/LCT/Occupancy/");
theNDigisPerEventPlot =
iBooker.book1D("CSCCorrelatedLCTDigisPerEvent",
"CorrelatedLCT trigger primitives per event; Number of CorrelatedLCTs; Entries",
100,
0,
100);
for (int i = 1; i <= 10; ++i) {
const std::string t2("CSCCorrelatedLCTDigisPerChamber_" + CSCDetId::chamberName(i));
theNDigisPerChamberPlots[i - 1] =
iBooker.book1D(t2,
"Number of CorrelatedLCTs per chamber " + CSCDetId::chamberName(i) +
";Number of CorrelatedLCTs per chamber;Entries",
4,
0,
4);
}
// do not analyze Run-3 properties in Run-1 and Run-2 eras
if (!isRun3_) {
lctVars_.resize(6);
}
// chamber type
for (unsigned iType = 0; iType < chambers_.size(); iType++) {
// consider CSC+ and CSC- separately
for (unsigned iEndcap = 0; iEndcap < 2; iEndcap++) {
const std::string eSign(iEndcap == 0 ? "+" : "-");
// lct variable
for (unsigned iVar = 0; iVar < lctVars_.size(); iVar++) {
if (std::find(chambersRun3_.begin(), chambersRun3_.end(), iType) == chambersRun3_.end()) {
if (iVar > 5)
continue;
}
const std::string key("lct_" + lctVars_[iVar]);
const std::string histName(key + "_" + chambers_[iType] + eSign);
const std::string histTitle(chambers_[iType] + eSign + " LCT " + lctVars_[iVar]);
const unsigned iTypeCorrected(iEndcap == 0 ? iType : iType + chambers_.size());
chamberHistos[iTypeCorrected][key] =
iBooker.book1D(histName, histTitle, lctNBin_[iVar], lctMinBin_[iVar], lctMaxBin_[iVar]);
chamberHistos[iTypeCorrected][key]->getTH1()->SetMinimum(0);
}
}
}
}
void CSCCorrelatedLCTDigiValidation::analyze(const edm::Event &e, const edm::EventSetup &) {
edm::Handle<CSCCorrelatedLCTDigiCollection> lcts;
e.getByToken(lcts_Token_, lcts);
if (!lcts.isValid()) {
edm::LogError("CSCDigiDump") << "Cannot get CorrelatedLCTs by label " << inputTag_.encode();
}
unsigned nDigisPerEvent = 0;
for (auto j = lcts->begin(); j != lcts->end(); j++) {
auto beginDigi = (*j).second.first;
auto endDigi = (*j).second.second;
const CSCDetId &detId((*j).first);
int chamberType = detId.iChamberType();
int nDigis = endDigi - beginDigi;
nDigisPerEvent += nDigis;
theNDigisPerChamberPlots[chamberType - 1]->Fill(nDigis);
auto range = lcts->get((*j).first);
// 1=forward (+Z); 2=backward (-Z)
const unsigned typeCorrected(detId.endcap() == 1 ? chamberType - 2 : chamberType - 2 + chambers_.size());
for (auto lct = range.first; lct != range.second; lct++) {
if (lct->isValid()) {
chamberHistos[typeCorrected]["lct_pattern"]->Fill(lct->getPattern());
chamberHistos[typeCorrected]["lct_quality"]->Fill(lct->getQuality());
chamberHistos[typeCorrected]["lct_wiregroup"]->Fill(lct->getKeyWG());
chamberHistos[typeCorrected]["lct_halfstrip"]->Fill(lct->getStrip());
chamberHistos[typeCorrected]["lct_bend"]->Fill(lct->getBend());
chamberHistos[typeCorrected]["lct_bx"]->Fill(lct->getBX());
if (isRun3_) {
// ignore these fields for chambers that do not enable the Run-3 algorithm
if (std::find(chambersRun3_.begin(), chambersRun3_.end(), chamberType - 2) == chambersRun3_.end())
continue;
chamberHistos[typeCorrected]["lct_run3pattern"]->Fill(lct->getRun3Pattern());
chamberHistos[typeCorrected]["lct_slope"]->Fill(lct->getSlope());
chamberHistos[typeCorrected]["lct_quartstrip"]->Fill(lct->getStrip(4));
chamberHistos[typeCorrected]["lct_eighthstrip"]->Fill(lct->getStrip(8));
}
}
}
}
theNDigisPerEventPlot->Fill(nDigisPerEvent);
}
| [
"sven.dildick@cern.ch"
] | sven.dildick@cern.ch |
bd27e3d61eed45f02610be79bae8619d76f1528f | 46bf7c5fcdfdf69c6ea70c170dad286a4b327149 | /KMPAL/kaml.cpp | ac1d21fd0521865bc01ce6f887b21883eeb80f68 | [] | no_license | Arbusz/Data-Structure-C | 37cdf045851119f11f2bcba10a0560d4e8826699 | 310860b74dab18c3549cb97bcf0350696eb8344f | refs/heads/master | 2021-08-29T23:15:50.732986 | 2017-12-15T07:50:58 | 2017-12-15T07:50:58 | 103,737,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,743 | cpp | ////
//// Created by arbus on 2017/10/25.
////
//
//#include <iostream>
//using namespace std;
//
//void getNext(string pat, int next[]){
// int q,k;
// int m = pat.size();
// next[0]=0;
// for(q=1,k=0;q<m;++q){
// while(k>0&&pat[q]!=pat[k])
// k=next[k-1];
// if(pat[q]==pat[k])
// k++;
// next[q]=k;
// }
//}
//int kmp(const string &txt,const string &pat, int next[]){
// int lenT=txt.size(),lenP=pat.size();
// int i,q;
// getNext(pat,next);
// for(i=0,q=0;i<lenT;++i){
// while(q>0 && pat[q]!=txt[i])
// q=next[q-1];
// if(pat[q]==txt[i])
// q++;
// if(q==lenT)
// { cout<<"Pattern found at index"<<(i-lenP+1);
// q=next[q-1];
// }
// }
//
//}
//
//int main(){
// string T="ababaabbabab";
// string P="abbab";
// int next[20]={0};
// kmp(T,P,next);
// for(int i=0;i<P.length();++i){
// cout<<next[i];
// }
// return 0;
//}
#include "vector"
#include "string"
#include <iostream>
using namespace std;
//计算模式P的部分匹配值,保存在next数组中
void getNext(const string &P, vector<int> &next)
{
int q,k;//k记录所有前缀的对称值
int m = P.size();//模式字符串的长度
next[0] = 0;//首字符的对称值肯定为0
for (q = 1, k = 0; q < m; ++q)//计算每一个位置的对称值
{
//k总是用来记录上一个前缀的最大对称值
while (k > 0 && P[q] != P[k])
k = next[k - 1];//k将循环递减,值得注意的是next[k]<k总是成立
if (P[q] == P[k])
k++;//增加k的唯一方法
next[q] = k;//获取最终值
}
}
void KmpMatch(const string &T, const string &P, vector<int> &next)
{
int n, m;
n = T.size();
m = P.size();
getNext(P, next);
for (int i = 0, q = 0; i < n; ++i)
{
while (q > 0 && P[q] != T[i])
q = next[q - 1];
if (P[q] == T[i])
q++;
if (q == m)
{
cout << "Index:" << (i - m + 1) << endl;
q = next[q - 1];//寻找下一个匹配
}
}
}
int main()
{
//system("color 0A");
vector<int> next(20,0);//保存待搜索字符串的部分匹配表(所有前缀函数的对称值)
string T = "aabbababcabacababca";//文本
string P = "ababca";//待搜索字符串
cout <<"text:"<< T << endl;
cout <<"pattern:"<< P << endl;
KmpMatch(T, P, next);
cout << "Next array:"<< endl;
for (int i = 0; i < P.size(); i++)
cout<< next[i];
cout << endl;
system("pause");
return 0;
} | [
"arbuszg@gmail.com"
] | arbuszg@gmail.com |
1fab0291e2754878d0abb2a9e360c3fa9bde5abe | 2bf6bb1fc700405bf9c050163328f74bb814f109 | /src/activemasternode.cpp | 3af9db7e9ac339ea2427d99fa692de018ee19dc5 | [
"MIT"
] | permissive | trepcorick/trepco | 76a1e543f228fd741c7917f3bbf9f321f2c61a34 | e3d6deb833c9ee44eb717ae73887f99d72f277e4 | refs/heads/master | 2020-03-28T17:33:46.936919 | 2018-09-15T07:11:28 | 2018-09-15T07:11:28 | 148,801,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,391 | cpp | // Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Trepco developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "activemasternode.h"
#include "addrman.h"
#include "masternode.h"
#include "masternodeconfig.h"
#include "masternodeman.h"
#include "protocol.h"
#include "spork.h"
//
// Bootup the Masternode, look for a TREP input and register on the network
//
void CActiveMasternode::ManageStatus()
{
std::string errorMessage;
if (!fMasterNode) return;
if (fDebug) LogPrintf("CActiveMasternode::ManageStatus() - Begin\n");
//need correct blocks to send ping
if (Params().NetworkID() != CBaseChainParams::REGTEST && !masternodeSync.IsBlockchainSynced()) {
status = ACTIVE_MASTERNODE_SYNC_IN_PROCESS;
LogPrintf("CActiveMasternode::ManageStatus() - %s\n", GetStatus());
return;
}
if (status == ACTIVE_MASTERNODE_SYNC_IN_PROCESS) status = ACTIVE_MASTERNODE_INITIAL;
if (status == ACTIVE_MASTERNODE_INITIAL) {
CMasternode* pmn;
pmn = mnodeman.Find(pubKeyMasternode);
if (pmn != NULL) {
pmn->Check();
if (pmn->IsEnabled() && pmn->protocolVersion == PROTOCOL_VERSION) EnableHotColdMasterNode(pmn->vin, pmn->addr);
}
}
if (status != ACTIVE_MASTERNODE_STARTED) {
// Set defaults
status = ACTIVE_MASTERNODE_NOT_CAPABLE;
notCapableReason = "";
if (pwalletMain->IsLocked()) {
notCapableReason = "Wallet is locked.";
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
if (pwalletMain->GetBalance() == 0) {
notCapableReason = "Hot node, waiting for remote activation.";
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
if (strMasterNodeAddr.empty()) {
if (!GetLocal(service)) {
notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option.";
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
} else {
service = CService(strMasterNodeAddr);
}
// The service needs the correct default port to work properly
if(!CMasternodeBroadcast::CheckDefaultPort(strMasterNodeAddr, errorMessage, "CActiveMasternode::ManageStatus()"))
return;
LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString());
CNode* pnode = ConnectNode((CAddress)service, NULL, false);
if (!pnode) {
notCapableReason = "Could not connect to " + service.ToString();
LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason);
return;
}
pnode->Release();
// Choose coins to use
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
if (GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) {
if (GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS) {
status = ACTIVE_MASTERNODE_INPUT_TOO_NEW;
notCapableReason = strprintf("%s - %d confirmations", GetStatus(), GetInputAge(vin));
LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
return;
}
LOCK(pwalletMain->cs_wallet);
pwalletMain->LockCoin(vin.prevout);
// send to all nodes
CPubKey pubKeyMasternode;
CKey keyMasternode;
if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {
notCapableReason = "Error upon calling SetKey: " + errorMessage;
LogPrintf("Register::ManageStatus() - %s\n", notCapableReason);
return;
}
if (!Register(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage)) {
notCapableReason = "Error on Register: " + errorMessage;
LogPrintf("Register::ManageStatus() - %s\n", notCapableReason);
return;
}
LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n");
status = ACTIVE_MASTERNODE_STARTED;
return;
} else {
notCapableReason = "Could not find suitable coins!";
LogPrintf("CActiveMasternode::ManageStatus() - %s\n", notCapableReason);
return;
}
}
//send to all peers
if (!SendMasternodePing(errorMessage)) {
LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s\n", errorMessage);
}
}
std::string CActiveMasternode::GetStatus()
{
switch (status) {
case ACTIVE_MASTERNODE_INITIAL:
return "Node just started, not yet activated";
case ACTIVE_MASTERNODE_SYNC_IN_PROCESS:
return "Sync in progress. Must wait until sync is complete to start Masternode";
case ACTIVE_MASTERNODE_INPUT_TOO_NEW:
return strprintf("Masternode input must have at least %d confirmations", MASTERNODE_MIN_CONFIRMATIONS);
case ACTIVE_MASTERNODE_NOT_CAPABLE:
return "Not capable masternode: " + notCapableReason;
case ACTIVE_MASTERNODE_STARTED:
return "Masternode successfully started";
default:
return "unknown";
}
}
bool CActiveMasternode::SendMasternodePing(std::string& errorMessage)
{
if (status != ACTIVE_MASTERNODE_STARTED) {
errorMessage = "Masternode is not in a running status";
return false;
}
CPubKey pubKeyMasternode;
CKey keyMasternode;
if (!obfuScationSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) {
errorMessage = strprintf("Error upon calling SetKey: %s\n", errorMessage);
return false;
}
LogPrintf("CActiveMasternode::SendMasternodePing() - Relay Masternode Ping vin = %s\n", vin.ToString());
CMasternodePing mnp(vin);
if (!mnp.Sign(keyMasternode, pubKeyMasternode)) {
errorMessage = "Couldn't sign Masternode Ping";
return false;
}
// Update lastPing for our masternode in Masternode list
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
if (pmn->IsPingedWithin(MASTERNODE_PING_SECONDS, mnp.sigTime)) {
errorMessage = "Too early to send Masternode Ping";
return false;
}
pmn->lastPing = mnp;
mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp));
//mnodeman.mapSeenMasternodeBroadcast.lastPing is probably outdated, so we'll update it
CMasternodeBroadcast mnb(*pmn);
uint256 hash = mnb.GetHash();
if (mnodeman.mapSeenMasternodeBroadcast.count(hash)) mnodeman.mapSeenMasternodeBroadcast[hash].lastPing = mnp;
mnp.Relay();
/*
* IT'S SAFE TO REMOVE THIS IN FURTHER VERSIONS
* AFTER MIGRATION TO V12 IS DONE
*/
if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return true;
// for migration purposes ping our node on old masternodes network too
std::string retErrorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
int64_t masterNodeSignatureTime = GetAdjustedTime();
std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + boost::lexical_cast<std::string>(false);
if (!obfuScationSigner.SignMessage(strMessage, retErrorMessage, vchMasterNodeSignature, keyMasternode)) {
errorMessage = "dseep sign message failed: " + retErrorMessage;
return false;
}
if (!obfuScationSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, retErrorMessage)) {
errorMessage = "dseep verify message failed: " + retErrorMessage;
return false;
}
LogPrint("masternode", "dseep - relaying from active mn, %s \n", vin.ToString().c_str());
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
pnode->PushMessage("dseep", vin, vchMasterNodeSignature, masterNodeSignatureTime, false);
/*
* END OF "REMOVE"
*/
return true;
} else {
// Seems like we are trying to send a ping while the Masternode is not registered in the network
errorMessage = "Obfuscation Masternode List doesn't include our Masternode, shutting down Masternode pinging service! " + vin.ToString();
status = ACTIVE_MASTERNODE_NOT_CAPABLE;
notCapableReason = errorMessage;
return false;
}
}
bool CActiveMasternode::Register(std::string strService, std::string strKeyMasternode, std::string strTxHash, std::string strOutputIndex, std::string& errorMessage)
{
CTxIn vin;
CPubKey pubKeyCollateralAddress;
CKey keyCollateralAddress;
CPubKey pubKeyMasternode;
CKey keyMasternode;
//need correct blocks to send ping
if (!masternodeSync.IsBlockchainSynced()) {
errorMessage = GetStatus();
LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage);
return false;
}
if (!obfuScationSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) {
errorMessage = strprintf("Can't find keys for masternode %s - %s", strService, errorMessage);
LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage);
return false;
}
if (!GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, strTxHash, strOutputIndex)) {
errorMessage = strprintf("Could not allocate vin %s:%s for masternode %s", strTxHash, strOutputIndex, strService);
LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage);
return false;
}
CService service = CService(strService);
// The service needs the correct default port to work properly
if(!CMasternodeBroadcast::CheckDefaultPort(strService, errorMessage, "CActiveMasternode::Register()"))
return false;
addrman.Add(CAddress(service), CNetAddr("127.0.0.1"), 2 * 60 * 60);
return Register(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage);
}
bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& errorMessage)
{
CMasternodeBroadcast mnb;
CMasternodePing mnp(vin);
if (!mnp.Sign(keyMasternode, pubKeyMasternode)) {
errorMessage = strprintf("Failed to sign ping, vin: %s", vin.ToString());
LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage);
return false;
}
mnodeman.mapSeenMasternodePing.insert(make_pair(mnp.GetHash(), mnp));
LogPrintf("CActiveMasternode::Register() - Adding to Masternode list\n service: %s\n vin: %s\n", service.ToString(), vin.ToString());
mnb = CMasternodeBroadcast(service, vin, pubKeyCollateralAddress, pubKeyMasternode, PROTOCOL_VERSION);
mnb.lastPing = mnp;
if (!mnb.Sign(keyCollateralAddress)) {
errorMessage = strprintf("Failed to sign broadcast, vin: %s", vin.ToString());
LogPrintf("CActiveMasternode::Register() - %s\n", errorMessage);
return false;
}
mnodeman.mapSeenMasternodeBroadcast.insert(make_pair(mnb.GetHash(), mnb));
masternodeSync.AddedMasternodeList(mnb.GetHash());
CMasternode* pmn = mnodeman.Find(vin);
if (pmn == NULL) {
CMasternode mn(mnb);
mnodeman.Add(mn);
} else {
pmn->UpdateFromNewBroadcast(mnb);
}
//send to all peers
LogPrintf("CActiveMasternode::Register() - RelayElectionEntry vin = %s\n", vin.ToString());
mnb.Relay();
/*
* IT'S SAFE TO REMOVE THIS IN FURTHER VERSIONS
* AFTER MIGRATION TO V12 IS DONE
*/
if (IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES)) return true;
// for migration purposes inject our node in old masternodes' list too
std::string retErrorMessage;
std::vector<unsigned char> vchMasterNodeSignature;
int64_t masterNodeSignatureTime = GetAdjustedTime();
std::string donationAddress = "";
int donationPercantage = 0;
std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end());
std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end());
std::string strMessage = service.ToString() + boost::lexical_cast<std::string>(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast<std::string>(PROTOCOL_VERSION) + donationAddress + boost::lexical_cast<std::string>(donationPercantage);
if (!obfuScationSigner.SignMessage(strMessage, retErrorMessage, vchMasterNodeSignature, keyCollateralAddress)) {
errorMessage = "dsee sign message failed: " + retErrorMessage;
LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str());
return false;
}
if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, retErrorMessage)) {
errorMessage = "dsee verify message failed: " + retErrorMessage;
LogPrintf("CActiveMasternode::Register() - Error: %s\n", errorMessage.c_str());
return false;
}
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
pnode->PushMessage("dsee", vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION, donationAddress, donationPercantage);
/*
* END OF "REMOVE"
*/
return true;
}
bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey)
{
return GetMasterNodeVin(vin, pubkey, secretKey, "", "");
}
bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex)
{
// Find possible candidates
TRY_LOCK(pwalletMain->cs_wallet, fWallet);
if (!fWallet) return false;
vector<COutput> possibleCoins = SelectCoinsMasternode();
COutput* selectedOutput;
// Find the vin
if (!strTxHash.empty()) {
// Let's find it
uint256 txHash(strTxHash);
int outputIndex;
try {
outputIndex = std::stoi(strOutputIndex.c_str());
} catch (const std::exception& e) {
LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what());
return false;
}
bool found = false;
BOOST_FOREACH (COutput& out, possibleCoins) {
if (out.tx->GetHash() == txHash && out.i == outputIndex) {
selectedOutput = &out;
found = true;
break;
}
}
if (!found) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate valid vin\n");
return false;
}
} else {
// No output specified, Select the first one
if (possibleCoins.size() > 0) {
selectedOutput = &possibleCoins[0];
} else {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate specified vin from possible list\n");
return false;
}
}
// At this point we have a selected output, retrieve the associated info
return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey);
}
// Extract Masternode vin information from output
bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey)
{
CScript pubScript;
vin = CTxIn(out.tx->GetHash(), out.i);
pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey
CTxDestination address1;
ExtractDestination(pubScript, address1);
CBitcoinAddress address2(address1);
CKeyID keyID;
if (!address2.GetKeyID(keyID)) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Address does not refer to a key\n");
return false;
}
if (!pwalletMain->GetKey(keyID, secretKey)) {
LogPrintf("CActiveMasternode::GetMasterNodeVin - Private key for address is not known\n");
return false;
}
pubkey = secretKey.GetPubKey();
return true;
}
// get all possible outputs for running Masternode
vector<COutput> CActiveMasternode::SelectCoinsMasternode()
{
vector<COutput> vCoins;
vector<COutput> filteredCoins;
vector<COutPoint> confLockedCoins;
// Temporary unlock MN coins from masternode.conf
if (GetBoolArg("-mnconflock", true)) {
uint256 mnTxHash;
BOOST_FOREACH (CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) {
mnTxHash.SetHex(mne.getTxHash());
int nIndex;
if(!mne.castOutputIndex(nIndex))
continue;
COutPoint outpoint = COutPoint(mnTxHash, nIndex);
confLockedCoins.push_back(outpoint);
pwalletMain->UnlockCoin(outpoint);
}
}
// Retrieve all possible outputs
pwalletMain->AvailableCoins(vCoins);
// Lock MN coins from masternode.conf back if they where temporary unlocked
if (!confLockedCoins.empty()) {
BOOST_FOREACH (COutPoint outpoint, confLockedCoins)
pwalletMain->LockCoin(outpoint);
}
// Filter
BOOST_FOREACH (const COutput& out, vCoins) {
if (out.tx->vout[out.i].nValue == Params().MasternodeCollateral() * COIN) { //exactly
filteredCoins.push_back(out);
}
}
return filteredCoins;
}
// when starting a Masternode, this can enable to run as a hot wallet with no funds
bool CActiveMasternode::EnableHotColdMasterNode(CTxIn& newVin, CService& newService)
{
if (!fMasterNode) return false;
status = ACTIVE_MASTERNODE_STARTED;
//The values below are needed for signing mnping messages going forward
vin = newVin;
service = newService;
LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n");
return true;
}
| [
"support@trepco.io"
] | support@trepco.io |
979b45a6b9290742351a311484959858520311fe | f0d902356e4cc914337892194079fee52410838a | /src/signet.cpp | a29f89b58e7b9c773dcd20aa78c2f6a3d9baa2f1 | [
"MIT"
] | permissive | thebevrishot/bitcoin | 9061d74fecb198e9d9d67ff4a6b6e46ece57752b | d692d192cda37fda6359ad0736b85de20383db73 | refs/heads/master | 2021-07-04T08:55:27.794876 | 2020-09-22T15:08:00 | 2020-09-22T15:08:08 | 175,374,217 | 0 | 0 | MIT | 2019-03-13T08:04:59 | 2019-03-13T08:04:58 | null | UTF-8 | C++ | false | false | 5,567 | cpp | // Copyright (c) 2019-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <signet.h>
#include <array>
#include <cstdint>
#include <vector>
#include <consensus/merkle.h>
#include <consensus/params.h>
#include <consensus/validation.h>
#include <core_io.h>
#include <hash.h>
#include <primitives/block.h>
#include <primitives/transaction.h>
#include <span.h>
#include <script/interpreter.h>
#include <script/standard.h>
#include <streams.h>
#include <util/strencodings.h>
#include <util/system.h>
#include <uint256.h>
static constexpr uint8_t SIGNET_HEADER[4] = {0xec, 0xc7, 0xda, 0xa2};
static constexpr unsigned int BLOCK_SCRIPT_VERIFY_FLAGS = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_WITNESS | SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_NULLDUMMY;
static bool FetchAndClearCommitmentSection(const Span<const uint8_t> header, CScript& witness_commitment, std::vector<uint8_t>& result)
{
CScript replacement;
bool found_header = false;
result.clear();
opcodetype opcode;
CScript::const_iterator pc = witness_commitment.begin();
std::vector<uint8_t> pushdata;
while (witness_commitment.GetOp(pc, opcode, pushdata)) {
if (pushdata.size() > 0) {
if (!found_header && pushdata.size() > (size_t) header.size() && Span<const uint8_t>(pushdata.data(), header.size()) == header) {
// pushdata only counts if it has the header _and_ some data
result.insert(result.end(), pushdata.begin() + header.size(), pushdata.end());
pushdata.erase(pushdata.begin() + header.size(), pushdata.end());
found_header = true;
}
replacement << pushdata;
} else {
replacement << opcode;
}
}
if (found_header) witness_commitment = replacement;
return found_header;
}
static uint256 ComputeModifiedMerkleRoot(const CMutableTransaction& cb, const CBlock& block)
{
std::vector<uint256> leaves;
leaves.resize(block.vtx.size());
leaves[0] = cb.GetHash();
for (size_t s = 1; s < block.vtx.size(); ++s) {
leaves[s] = block.vtx[s]->GetHash();
}
return ComputeMerkleRoot(std::move(leaves));
}
SignetTxs SignetTxs::Create(const CBlock& block, const CScript& challenge)
{
CMutableTransaction tx_to_spend;
tx_to_spend.nVersion = 0;
tx_to_spend.nLockTime = 0;
tx_to_spend.vin.emplace_back(COutPoint(), CScript(OP_0), 0);
tx_to_spend.vout.emplace_back(0, challenge);
CMutableTransaction tx_spending;
tx_spending.nVersion = 0;
tx_spending.nLockTime = 0;
tx_spending.vin.emplace_back(COutPoint(), CScript(), 0);
tx_spending.vout.emplace_back(0, CScript(OP_RETURN));
// can't fill any other fields before extracting signet
// responses from block coinbase tx
// find and delete signet signature
if (block.vtx.empty()) return invalid(); // no coinbase tx in block; invalid
CMutableTransaction modified_cb(*block.vtx.at(0));
const int cidx = GetWitnessCommitmentIndex(block);
if (cidx == NO_WITNESS_COMMITMENT) {
return invalid(); // require a witness commitment
}
CScript& witness_commitment = modified_cb.vout.at(cidx).scriptPubKey;
std::vector<uint8_t> signet_solution;
if (!FetchAndClearCommitmentSection(SIGNET_HEADER, witness_commitment, signet_solution)) {
// no signet solution -- allow this to support OP_TRUE as trivial block challenge
} else {
try {
VectorReader v(SER_NETWORK, INIT_PROTO_VERSION, signet_solution, 0);
v >> tx_spending.vin[0].scriptSig;
v >> tx_spending.vin[0].scriptWitness.stack;
if (!v.empty()) return invalid(); // extraneous data encountered
} catch (const std::exception&) {
return invalid(); // parsing error
}
}
uint256 signet_merkle = ComputeModifiedMerkleRoot(modified_cb, block);
std::vector<uint8_t> block_data;
CVectorWriter writer(SER_NETWORK, INIT_PROTO_VERSION, block_data, 0);
writer << block.nVersion;
writer << block.hashPrevBlock;
writer << signet_merkle;
writer << block.nTime;
tx_to_spend.vin[0].scriptSig << block_data;
tx_spending.vin[0].prevout = COutPoint(tx_to_spend.GetHash(), 0);
return {tx_to_spend, tx_spending};
}
// Signet block solution checker
bool CheckSignetBlockSolution(const CBlock& block, const Consensus::Params& consensusParams)
{
if (block.GetHash() == consensusParams.hashGenesisBlock) {
// genesis block solution is always valid
return true;
}
const CScript challenge(consensusParams.signet_challenge.begin(), consensusParams.signet_challenge.end());
const SignetTxs signet_txs(block, challenge);
if (!signet_txs.m_valid) {
LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution parse failure)\n");
return false;
}
const CScript& scriptSig = signet_txs.m_to_sign.vin[0].scriptSig;
const CScriptWitness& witness = signet_txs.m_to_sign.vin[0].scriptWitness;
TransactionSignatureChecker sigcheck(&signet_txs.m_to_sign, /*nIn=*/ 0, /*amount=*/ signet_txs.m_to_spend.vout[0].nValue);
if (!VerifyScript(scriptSig, signet_txs.m_to_spend.vout[0].scriptPubKey, &witness, BLOCK_SCRIPT_VERIFY_FLAGS, sigcheck)) {
LogPrint(BCLog::VALIDATION, "CheckSignetBlockSolution: Errors in block (block solution invalid)\n");
return false;
}
return true;
}
| [
"karljohan-alm@garage.co.jp"
] | karljohan-alm@garage.co.jp |
bef74489439d5bd0676cdf15b4496a6b112fc737 | 5e6910a3e9a20b15717a88fd38d200d962faedb6 | /AtCoder/nomura2020/a.cpp | 3e4c299fc99aa19335419b1d0e25370a434040ce | [] | no_license | khaledsliti/CompetitiveProgramming | f1ae55556d744784365bcedf7a9aaef7024c5e75 | 635ef40fb76db5337d62dc140f38105595ccd714 | refs/heads/master | 2023-08-29T15:12:04.935894 | 2023-08-15T13:27:12 | 2023-08-15T13:27:12 | 171,742,989 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | cpp | // We only fail when we stop trying
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define endl '\n'
#define D(x) cerr << #x << " = " << (x) << '\n'
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
typedef long long ll;
int main()
{
int H1, M1, H2, M2, P;
cin >> H1 >> M1 >> H2 >> M2 >> P;
int a = H1 * 60 + M1;
int b = H2 * 60 + M2;
cout << b - a - P << endl;
return 0;
}
| [
"khaled.sliti@supcom.tn"
] | khaled.sliti@supcom.tn |
f1d33a39a2f09fae8490320733389ad1b0a3fb48 | eca262d076c873069d536011970d5a85d6a59405 | /core/sample-vpDebug.cpp | b6cb91e7ba26621abd27f2000b23a66672dbb9b3 | [] | no_license | lagadic/visp_sample | b2ed331f4a3e97f42e30eaf2677f10d06090f80e | 021d1c2435c38491407b687f35ba3c8858a77019 | refs/heads/master | 2023-07-10T05:17:07.106467 | 2023-07-01T06:31:55 | 2023-07-01T06:31:55 | 238,434,368 | 2 | 2 | null | 2023-07-01T06:45:22 | 2020-02-05T11:28:26 | C++ | UTF-8 | C++ | false | false | 1,205 | cpp | #ifndef VP_DEBUG
# define VP_DEBUG // Activate the debug mode
#endif
#define VP_DEBUG_MODE 2 // Activate debug level 1 and 2
#include <visp3/core/vpDebug.h>
int main()
{
vpIN_FCT("main()");
// Check the active debug levels
std::cout << "Debug level 1 active: " << vpDEBUG_ENABLE(1) << std::endl;
std::cout << "Debug level 2 active: " << vpDEBUG_ENABLE(2) << std::endl;
std::cout << "Debug level 3 active: " << vpDEBUG_ENABLE(3) << std::endl;
// C-like debug printings
vpTRACE("C-like trace"); // stdout
// Printing depend only VP_DEBUG_MODE value is >= 1
vpTRACE(1, "C-like trace level 1"); // stdout
vpERROR_TRACE(1, "C-like error trace level 1"); // stderr
// Printing if VP_DEBUG defined and VP_DEBUG_MODE value >= 2
vpDEBUG_TRACE(2, "C-like debug trace level 2"); // stdout
vpDERROR_TRACE(2, "C-like error trace level 2"); // stderr
// C++-like debug printings
vpCTRACE << "C++-like debug trace" << std::endl; // stdout
vpCERROR << "C++-like error trace" << std::endl; // stderr
// Printing if VP_DEBUG defined and VP_DEBUG_MODE value >= 2
vpCDEBUG(2) << "C++-like debug trace level 2" << std::endl; // stdout
vpOUT_FCT("main()");
}
| [
"Fabien.Spindler@inria.fr"
] | Fabien.Spindler@inria.fr |
bb7bc2b28a015441a296862b3dd1bdc90617a22a | 03ba325820c997599beff5add437d35347a953aa | /source/utopian/core/renderer/jobs/GeometryThicknessJob.h | 428fee7f1e0edf93c9d5139cfa13b3ab2d8b226d | [
"MIT"
] | permissive | simplerr/UtopianEngine | cc13a43279bd49f55136120cf75c8c8d5fcff705 | b7c38df663a4b6b2fa1d7c9f1f83dfc661de1a9a | refs/heads/master | 2022-10-12T12:03:19.166812 | 2022-09-28T05:48:31 | 2022-09-28T05:48:31 | 77,483,702 | 64 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 826 | h | #pragma once
#include "core/renderer/jobs/BaseJob.h"
namespace Utopian
{
/* Renders copies of the deferred job output images needed by other jobs, transparency for example. */
class GeometryThicknessJob : public BaseJob
{
public:
GeometryThicknessJob(Vk::Device* device, uint32_t width, uint32_t height);
~GeometryThicknessJob();
void LoadResources() override;
void Init(const std::vector<BaseJob*>& jobs, const GBuffer& gbuffer) override;
void PostInit(const std::vector<BaseJob*>& jobs, const GBuffer& gbuffer) override;
void Render(const JobInput& jobInput) override;
SharedPtr<Vk::Image> geometryThicknessImage;
private:
SharedPtr<Vk::Effect> mEffect;
SharedPtr<Vk::RenderTarget> mRenderTarget;
const float DEFAULT_THICKNESS = 1.0f;
};
}
| [
"axel.blackert@gmail.com"
] | axel.blackert@gmail.com |
2993755e833a1f553de5b80c0ce71aa28ea14e28 | 4cc18df781a2ffac6be612f04834f02fccfa7e31 | /20170510/bo/threadpool/testThreadpool.cc | ce6fed0d99c788ac27de1cd841821d634ec8cd33 | [] | no_license | heartinharbin/learncpp | db5e616a3727376ca6370044b2b99d2f7e3b92e5 | 5d2cddc069b0c5b1342041388121776e3e0239b5 | refs/heads/master | 2021-01-19T11:09:26.626356 | 2017-05-16T14:22:34 | 2017-05-16T14:22:34 | 87,933,541 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 485 | cc | ///
/// @file testThreadpool.cc
/// @author heartinharbin
/// @date 2017-05-13 15:14:05
///
#include "Threadpool.h"
#include "Buffer.h"
#include "Task.h"
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
using std::cout;
using std::endl;
int main(void){
wd::Threadpool threadpool(10, 4);
threadpool.start();
size_t cnt = 20;
while(cnt--){
threadpool.addTask(std::bind(&Task::execute, Task()));
}
threadpool.stop();
return 0;
}
| [
"791365914@qq.com"
] | 791365914@qq.com |
8ff4baed26c298541e2b05429bc7dd0e15acb22e | 6b03fa64ebaf51f4ba45ef325deff5ecaddded9f | /softlight/src/SL_BoundingBox.cpp | 61508829ba7369d65c2db846d942e9ec3a2d25ad | [
"MIT"
] | permissive | hamsham/SoftLight | e28219ab57c992573477166100ec3ae259b94a1e | b1f7ae60ee9e9cbf38473912757e0fbc569474c3 | refs/heads/master | 2023-07-27T06:29:04.699524 | 2023-07-18T07:14:37 | 2023-07-18T07:14:37 | 148,108,300 | 34 | 5 | MIT | 2021-12-03T05:03:07 | 2018-09-10T06:21:23 | C++ | UTF-8 | C++ | false | false | 61 | cpp |
#include <utility>
#include "softlight/SL_BoundingBox.hpp"
| [
"mileslacey@gmail.com"
] | mileslacey@gmail.com |
3eaec138a64dfa1330d0273a0248370aad434aff | 269e13a077d3ef90d4c352249fb6e32d2360a4ec | /leetcode/string/1529-Bulb-Switcher-IV.cpp | f56b13b6fca9d79eb42840f36ee85eefb0208bc7 | [] | no_license | luckyzahuo/Snorlax | d3df462ee484ecd338cde05869006f907e684153 | 51cf7e313fddee6fd00c2a276b43c48013375618 | refs/heads/master | 2023-08-21T11:02:01.975516 | 2021-10-10T08:50:40 | 2021-10-10T08:50:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,201 | cpp |
#include <string>
using namespace std;
/*
* 挺有意思的一道题目。从初始化状态 "00000" 进行翻转,直到等于 target。翻转是指从第 i 个元素开始,一直到字符串的末尾,'0' 变成 '1','1' 变成 '0'。
*
* 当 target 为 "10111" 时,我们可以这样进行翻转:
*
* "00000" => "00111",翻转索引为 2 后面的所有字符。
* "00111" => "11000",翻转索引为 2 后面的所有字符。
* "11000" => "10111",翻转索引为 1 后面的所有字符。
*
* 1 <= target.length <= 10^5,因此,我们必须在 O(n) 的时间复杂度内完成。如果不考虑 target 的长度的话,BFS 有可能完成。
*
* 因为我们每次翻转都是针对 [i...n-1] 这个区间的,也就是说,假设 [x..i] 以及 [i...k] 这一块儿区间的值不一样的话,我们一定需要一次翻转来完成。
*/
class Solution {
public:
int minFlips(string target) {
int result = 0, current = 0;
for (int i = 0; i < target.size(); i++) {
if (target[i] - '0' != current) {
result ++;
current = target[i] - '0';
}
}
return result;
}
}; | [
"smartkeyerror@gmail.com"
] | smartkeyerror@gmail.com |
6586a3f7d42d16a01f7cf9197fc9ef4314490eec | 394b831ad755a197975e9195b28902cd634b3d28 | /common_src/common_socket_exception.h | 7c1a493e41c0b5e47e29d2a678274554d1eedda6 | [] | no_license | German-Rotili/tpGrupal | 68a58762d7247b9f79a98d9b3f7fe8c95760694b | 941642621b3c2468c240cf7fc10ff792083c6df2 | refs/heads/main | 2023-03-09T19:02:08.771718 | 2021-02-23T20:59:19 | 2021-02-23T20:59:19 | 314,632,892 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 209 | h | #ifndef SOCKET_EX
#define SOCKET_EX
#include <exception>
class CloseSocketException : public std::exception{
public:
CloseSocketException();
~CloseSocketException();
const char *what();
};
#endif
| [
"atvisciglio@gmail.com"
] | atvisciglio@gmail.com |
13b1bb1b43008f67e2e7cd0783713d3d7ca2dfc2 | 2fde10b5519cdda785ba91cbea8b11d5d66dc018 | /tests/jStringTestRunner.cpp | 5be33cf18888ccd71330accfb91db7dc4cbb3f3e | [
"MIT"
] | permissive | juliaclement/jclib | b0acef277f7407a8e06e0a4fc1908a463bd17f5a | 85cdb78fac275d450dd157138d190feebbe3397d | refs/heads/master | 2022-12-23T06:39:38.612336 | 2022-12-12T07:29:23 | 2022-12-12T07:29:23 | 106,623,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,360 | cpp | /*
Copyright (c) 2022 Julia Ingleby Clement
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.
*/
/*
* File: jStringTestRunner.cpp
* Author: Julia Clement <Julia at Clement dot nz>
*
* Created on 25/10/2022, 5:15:39 PM
*/
// CppUnit site http://sourceforge.net/projects/cppunit/files
#include <cppunit/BriefTestProgressListener.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/TestResult.h>
#include <cppunit/TestResultCollector.h>
#include <cppunit/TestRunner.h>
#include <cppunit/Test.h>
#include <cppunit/TestFailure.h>
#include <cppunit/portability/Stream.h>
class ProgressListener : public CPPUNIT_NS::TestListener {
public:
ProgressListener()
: m_lastTestFailed(false) {
}
~ProgressListener() {
}
void startTest(CPPUNIT_NS::Test *test) {
CPPUNIT_NS::stdCOut() << test->getName();
CPPUNIT_NS::stdCOut() << "\n";
CPPUNIT_NS::stdCOut().flush();
m_lastTestFailed = false;
}
void addFailure(const CPPUNIT_NS::TestFailure &failure) {
CPPUNIT_NS::stdCOut() << " : " << (failure.isError() ? "error" : "assertion");
m_lastTestFailed = true;
}
void endTest(CPPUNIT_NS::Test *test) {
if (!m_lastTestFailed)
CPPUNIT_NS::stdCOut() << " : OK";
CPPUNIT_NS::stdCOut() << "\n";
}
private:
/// Prevents the use of the copy constructor.
ProgressListener(const ProgressListener ©);
/// Prevents the use of the copy operator.
void operator=(const ProgressListener ©);
private:
bool m_lastTestFailed;
};
int main(int argc, char* argv[]) {
// Create the event manager and test controller
CPPUNIT_NS::TestResult controller;
// Add a listener that colllects test result
CPPUNIT_NS::TestResultCollector result;
controller.addListener(&result);
// Add a listener that print dots as test run.
ProgressListener progress;
controller.addListener(&progress);
// Add the top suite to the test runner
CPPUNIT_NS::TestRunner runner;
runner.addTest(CPPUNIT_NS::TestFactoryRegistry::getRegistry().makeTest());
runner.run(controller);
// Print test in a compiler compatible format.
CPPUNIT_NS::CompilerOutputter outputter(&result, CPPUNIT_NS::stdCOut());
outputter.write();
return result.wasSuccessful() ? 0 : 1;
}
| [
"32722175+juliaclement@users.noreply.github.com"
] | 32722175+juliaclement@users.noreply.github.com |
0b82c9ae783851b14b93b20067be65421f406b74 | 03387c6544f1837822cfc6c47e93abe79b6c3b9e | /diamond-0.8.26/src/dp/smith_waterman.cpp | f58c456e19662e244790531ef589955bbdb8443f | [
"BSD-3-Clause"
] | permissive | gsmith98/ComputationalGenomicsProject | 0b7614080fa6b73979d70423c2e5d127911ea179 | 62f2ce6fb65cdcf87d4841529b248c508f3430ba | refs/heads/master | 2020-07-04T08:40:44.501102 | 2016-12-10T00:13:48 | 2016-12-10T00:13:48 | 73,863,759 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,024 | cpp | /****
Copyright (c) 2016, University of Tuebingen, Benjamin Buchfink
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
****/
#include <vector>
#include "dp.h"
#include "../util/double_buffer.h"
#include "growing_buffer.h"
#include "../util/util.h"
using std::vector;
using std::pair;
template<typename _t>
struct Fixed_score_buffer
{
inline void init(size_t col_size, size_t cols, _t init)
{
col_size_ = size;
data_.reserve(col_size * cols);
data_.resize(col_size);
for (size_t i = 0; i<col_size; ++i)
data_[i] = init;
}
inline pair<_t*, _t*> get()
{
data_.resize(data_.size() + col_size_);
_t* ptr = last();
return pair<_t*, _t*>(ptr - col_size_, ptr);
}
inline _t* last()
{
return &*(data_.end() - col_size_);
}
const _t* column(int col) const
{
return &data_[col_size_*col];
}
private:
vector<_t> data_;
size_t col_size_;
};
template<typename _score>
struct Dp_matrix
{
struct Column_iterator
{
inline Column_iterator(const pair<_score*, _score*> &score, const pair<_score*, _score*> &hgap, int query_len):
score_(score),
hgap_(hgap),
end_(score_.second + query_len),
i_(0)
{
*score_.first = 0;
++score_.second;
}
inline int row() const
{
return i_;
}
inline bool valid() const
{
return score_.second < end_;
}
inline _score& score()
{
return *score_.second;
}
inline _score diag() const
{
return *score_.first;
}
inline _score hgap_in() const
{
return *hgap_.first;
}
inline _score& hgap_out()
{
return *hgap_.second;
}
inline void operator++()
{
++i_;
++score_.first;
++score_.second;
++hgap_.first;
++hgap_.second;
}
private:
pair<_score*, _score*> score_, hgap_;
const _score* const end_;
int i_;
};
inline Column_iterator column(int j)
{
return Column_iterator(score_.get(), hgap_.get(int()), query_len_);
}
inline Dp_matrix(int query_len, int subject_len):
query_len_(query_len),
score_(TLS::get(score_ptr)),
hgap_(TLS::get(hgap_ptr))
{
score_.init(query_len+1, subject_len+1, 0);
hgap_.init(query_len, 0, 0, 0);
}
const Fixed_score_buffer<_score>& score_buffer() const
{
return score_;
}
private:
const int query_len_;
Fixed_score_buffer<_score> &score_;
Double_buffer<_score> &hgap_;
static TLS_PTR Fixed_score_buffer<_score> *score_ptr;
static TLS_PTR Double_buffer<_score> *hgap_ptr;
};
template<typename _score>
void smith_waterman(const Letter *query, unsigned query_len, local_match &hssp, _score gap_open, _score gap_extend, vector<char> &transcript_buf, const _score& = int())
{
using std::max;
_score max_score = 0, column_max = 0;
int j = 0, i_max = -1, j_best = -1, i_best = -1;
Dp_matrix<_score> mtx(query_len, hssp.total_subject_len_);
const Letter *subject = hssp.subject_;
while (*subject != '\xff') {
typename Dp_matrix<_score>::Column_iterator it = mtx.column(j);
_score vgap = 0;
for (; it.valid(); ++it) {
const _score match_score = score_matrix(mask_critical(*subject), query[it.row()]);
const _score s = max(max(it.diag() + match_score, vgap), it.hgap_in());
s = max(s, 0);
if (s > column_max) {
column_max = s;
i_max = it.row();
}
const _score open = s - gap_open;
vgap = max(vgap - gap_extend, open);
it.hgap_out() = max(it.hgap_in() - gap_extend, open);
it.score() = s;
}
if (column_max > max_score) {
max_score = column_max;
j_best = j;
i_best = i_max;
}
++subject;
++j;
}
return traceback<_dir, _score>(query, subject, mtx.score_buffer(), band, gap_open, gap_extend, j_best, i_best, max_score, transcript_buf);
}
| [
"ubuntu@ip-172-31-49-101.ec2.internal"
] | ubuntu@ip-172-31-49-101.ec2.internal |
b5d46858ccdeaeb929576074d2e55c0d3523ebf7 | 47794800f5cb8f303106457739cec548a140b3a0 | /Examples/RFM69-gw-session/RFM69-gw-session.ino | e7c6038b05448d06a83de01399b48e2202b0a4d0 | [] | no_license | rrobinet/RFM69_SessionKey | 8368676660a70aa487b7367d4e16cba198b8b782 | cfb6602ccb571a68822915c174fe7de15de5748d | refs/heads/master | 2021-01-19T03:18:11.189177 | 2017-10-04T14:43:16 | 2017-10-04T14:43:16 | 49,140,691 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,310 | ino | // Sample RFM69 receiver/gateway sketch, with Session Key library
#include <RFM69_SessionKey.h> // enable session key support extension for RFM69 base library
#include <RFM69.h> //get it here: https://www.github.com/lowpowerlab/rfm69
#include <SPI.h>
#define NODEID 1 //unique for each node on same network
#define NETWORKID 110 //the same on all nodes that talk to each other
//Match frequency to the hardware version of the radio on your Moteino (uncomment one):
#define FREQUENCY RF69_433MHZ
//#define FREQUENCY RF69_868MHZ
//#define FREQUENCY RF69_915MHZ
#define ENCRYPTKEY "sampleEncryptKey" //exactly the same 16 characters/bytes on all nodes!
//#define IS_RFM69HW //uncomment only for RFM69HW! Leave out if you have RFM69W!
#define SERIAL_BAUD 115200
#ifdef __AVR_ATmega1284P__
#define LED 15 // Moteino MEGA have LED on D15
#define FLASH_SS 23 // and FLASH SS on D23
#else
#define LED 9 // Moteino has LEDs on D9
#define FLASH_SS 8 // and FLASH SS on D8
#endif
long int NOANS = 0; // used to count the answer errors
RFM69_SessionKey radio; // create radio instance
bool promiscuousMode = false; //set to 'true' to sniff all packets on the same network
bool SESSION_KEY = true; // set usage of session mode (or not)
bool SESSION_3ACKS = false; // set 3 acks at the end of a session transfer (or not)
unsigned long SESSION_WAIT_TIME = 40; // adjust wait time of data recption in session mode (default is 40ms)
byte ackCount=0; // use to count
uint32_t packetCount = 0; // use to count the received packets
void setup()
{
Serial.begin(SERIAL_BAUD);
delay(10);
radio.initialize(FREQUENCY,NODEID,NETWORKID);
#ifdef IS_RFM69HW
radio.setHighPower(); //only for RFM69HW!
#endif
radio.encrypt(ENCRYPTKEY); // set encryption
radio.useSessionKey(SESSION_KEY); // set session mode
radio.promiscuous(promiscuousMode); // set promiscuous mode
radio.sessionWaitTime(40); // adjust wait time of data recption in session mode (default is 40ms)
char buff[50];
sprintf(buff, "\nListening at %d Mhz...", FREQUENCY==RF69_433MHZ ? 433 : FREQUENCY==RF69_868MHZ ? 868 : 915);
Serial.println(buff);
}
void loop() {
//process any serial input
if (Serial.available() > 0)
{
char input = Serial.read();
if (input == 't')
{
byte temperature = radio.readTemperature(-1); // -1 = user cal factor, adjust for correct ambient
byte fTemp = 1.8 * temperature + 32; // 9/5=1.8
Serial.print( "Radio Temp is ");
Serial.print(temperature);
Serial.print("C, ");
Serial.print(fTemp); //converting to F loses some resolution, obvious when C is on edge between 2 values (ie 26C=78F, 27C=80F)
Serial.println('F');
}
}
if (radio.receiveDone())
{
Serial.print("#[");
Serial.print(++packetCount);
Serial.print(']');
Serial.print('[');Serial.print(radio.SENDERID, DEC);Serial.print("] ");
if (promiscuousMode)
{
Serial.print("to [");Serial.print(radio.TARGETID, DEC);Serial.print("] ");
}
for (byte i = 0; i < radio.DATALEN; i++)
Serial.print((char)radio.DATA[i]);
Serial.print(" [RX_RSSI:");Serial.print(radio.RSSI);Serial.print("]");
if (radio.ACKRequested())
{
byte theNodeID = radio.SENDERID;
radio.sendACK();
Serial.print(" - ACK sent.");
// When a node requests an ACK, respond to the ACK
// and also send a packet requesting an ACK (every 3rd one only)
// This way both TX/RX NODE functions are tested on 1 end at the GATEWAY
if (ackCount++%3==0)
{
Serial.print("\n\rPinging node ");
Serial.print(theNodeID);
Serial.print(" - ACK...");
delay(3); //need this when sending right after reception .. ?
if (radio.sendWithRetry(theNodeID, "ACK TEST", 8, 0)) // 0 = only 1 attempt, no retries
{
Serial.println (" SEND OK");
if (SESSION_KEY)
{
Serial.print("Session key receive status: ");
switch (RFM69_SessionKey::SESSION_KEY_RCV_STATUS)
{
case (0):
Serial.println ("Receiver: The received session key DO match with the expected one");
break;
case (1):
Serial.println ("Receiver: A session key is requested and send");
break;
case (2):
Serial.println ("Sender: A session key is received and computed");
break;
case (3):
Serial.println ("Receiver: The received session key DO NOT match with the expected one");
break;
case (4):
Serial.println ("Receiver: No Data received (time-out) or Data without Session Key received");
break;
default:
break;
}
}
}
else
{
Serial.print (" !!! NO ANSWER COUNT: "); Serial.println (++NOANS);
if (SESSION_KEY)
{
Serial.print("Last Received status is: ");
switch (RFM69_SessionKey::SESSION_KEY_RCV_STATUS)
{
case (0):
Serial.println ("Receiver: The received session key DO match with the expected one");
break;
case (1):
Serial.println ("Receiver: A session key is requested and send");
break;
case (2):
Serial.println ("Sender: A session key is received and computed");
break;
case (3):
Serial.println ("Receiver: The received session key DO NOT match with the expected one");
break;
case (4):
Serial.println ("Receiver: No Data received (time-out) or Data without Session Key received");
break;
default:
break;
}
}
}
}
}
Serial.println();
Blink(LED,3);
}
}
void Blink(byte PIN, int DELAY_MS)
{
pinMode(PIN, OUTPUT);
digitalWrite(PIN,HIGH);
delay(DELAY_MS);
digitalWrite(PIN,LOW);
}
| [
"rrobinet@hotmail.com"
] | rrobinet@hotmail.com |
9b24c80a3f275718a5c58a68bfe25f119101ceb9 | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/gil/color_base_algorithm.hpp | 07e6e9806f18a7bb80167777d2301153bc4ac17f | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 70 | hpp | #include "thirdparty/boost_1_58_0/boost/gil/color_base_algorithm.hpp"
| [
"qinzuoyan@xiaomi.com"
] | qinzuoyan@xiaomi.com |
6aa865f8b2f147c1c7d8f634d22782c62cab0816 | b1964e1c170ca6920c1f7ec3c86327608346b306 | /Domino/Core/Input.h | 1196515c912d6c58df46a399f21a0bf892db3fc5 | [] | no_license | hyf042/Domino | f711c6ebb89225f35f89054647f2faa3bc379e22 | f0160188c9c8d3ec58cd5de045cc965583e19837 | refs/heads/master | 2016-08-03T12:52:04.545541 | 2015-01-14T17:14:19 | 2015-01-14T17:14:19 | 28,511,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,055 | h | #ifndef __INPUT_H__
#include <set>
#include "../Domino.h"
namespace Domino {
class Input {
friend Application;
int mouseX;
int mouseY;
std::set<unsigned char> keyDown;
std::set<unsigned char> keyPress;
Input() {}
public:
static shared_ptr<Input> instance() {
static shared_ptr<Input> m_instance(new Input());
return m_instance;
}
int getMouseX() const {
return mouseX;
}
int getMouseY() const {
return mouseY;
}
bool getKeyDown(unsigned char key) const {
return keyDown.find(key) != keyDown.end();
}
bool getKeyPressed(unsigned char key) const {
return keyPress.find(key) != keyPress.end();
}
void afterUpdate() {
keyPress.clear();
}
private:
void mouseCB(int button, int state, int x, int y) {
mouseX = x;
mouseY = y;
}
void keyboardCB(unsigned char key, int x, int y) {
if (keyDown.find(key) == keyDown.end()) {
keyPress.insert(key);
}
keyDown.insert(key);
}
void keyboardUpCB(unsigned char key, int x, int y) {
keyDown.erase(key);
}
};
}
#endif | [
"hyf042@gmail.com"
] | hyf042@gmail.com |
2a2b8d06d1b8f8d94fe2629d4eb77c2fc00a5caa | dc489858f8001a905350be6d0d20cbd18d830273 | /_/Source code/CoherentBank/cpp/include/seovic/samples/bank/domain/Account.hpp | d29f9399be8c8418ce56c90310adb2292e3175cd | [
"Apache-2.0"
] | permissive | paullewallencom/oracle-coherence-978-1-8471-9612-5 | a652841b2a5ba4ad74eb1dfcdda255748c8594c4 | 32fbf9889210188c7e41102480690692ce0dbdc0 | refs/heads/main | 2023-02-07T11:12:48.975841 | 2021-01-01T01:22:15 | 2021-01-01T01:22:15 | 319,492,626 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,777 | hpp | #ifndef BANK_ACCOUNT_HPP
#define BANK_ACCOUNT_HPP
#include "Money.hpp"
#include <iostream>
#include <string>
class Account
{
// ----- constructors ---------------------------------------------------
public:
Account(long long lId, const std::string& sDesc,
const Money& balance, long long lLastTransId,
long long lCustomerId);
Account();
// ----- accessors ------------------------------------------------------
public:
long long getId() const;
std::string getDescription() const;
void setDescription(const std::string& sDesc);
Money getBalance() const;
long long getLastTransactionId() const;
long long getCustomerId() const;
// ----- data members ---------------------------------------------------
private:
const long long m_lId;
std::string m_sDescription;
Money m_balance;
long long m_lLastTransactionId;
const long long m_lCustomerId;
};
// ----- free functions -----------------------------------------------------
/**
* Output this Account to the stream
*
* @param out the stream to output to
*
* @return the stream
*/
std::ostream& operator<<(std::ostream& out, const Account& account);
/**
* Perform an equality test on two Account objects
*
* @param accountA the first Account
* @param accountB the second Account
*
* @return true if the objects are equal
*/
bool operator==(const Account& accountA, const Account& accountB);
/**
* Return the hash for the Account.
*
* @param account the Account to hash
*
* @return the hash for the Account
*/
size_t hash_value(const Account& account);
#endif // BAND_ACCOUNT_HPP
| [
"paullewallencom@users.noreply.github.com"
] | paullewallencom@users.noreply.github.com |
315867e60b8c235fb1211be0e581090affe5dccd | 2c7d768786f849584c6f0074cc46c0d561b832f1 | /20160422/queue/queue.cc | ac86930d86b168eb40dd0716b6da4d3099bf8b31 | [] | no_license | LoydChen/Cplusplus | f074a2441cdd0c95a303a58a789f04cf03af784c | c12970e7b0041d40c6054ebc45b07f503fd9b37f | refs/heads/master | 2021-01-01T05:28:41.168749 | 2016-04-25T13:36:22 | 2016-04-25T13:36:22 | 56,554,905 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,960 | cc | ///
/// @file stack.cc
/// @author loydchen(loydchen729@gmail.com)
/// @date 2016-04-23 16:20:28
///
#include "func.h"
Node::Node()
: _value(0)
, _next(NULL)
{
cout << "Node(int)" << endl;
}
Link::Link(int MaxSize)
: _head(NULL)
, _tail(NULL)
, _size(0)
{
int i;
for(i=0;i<MaxSize;i++){
Node * newNode = new Node;
newNode->_next = _head;
_head = newNode;
}
}
void Link::Insert(int value){
if(_size == 0){
cout << "insert " << value << endl;
_head->_value = value;
_tail = _head;
_size++;
}else if(_tail->_next == NULL){
cout << "insert fail" << endl;
}else{
cout << "insert " << value << endl;
_tail = _head ->_next;
_tail->_value = value;
_size++;
}
}
void Link::Delete(){
if(_size == 0){
cout << "delete fail" << endl;
}else if(_size == 1){
cout << "delete" << endl;
_head->_value = 0;
_tail = _head;
_size--;
}else{
cout << "delete" << endl;
Node * p1 = _head;
Node * p2 = _head;
while(p1 ->_next != _tail){
p2 = p1;
p1 = p1->_next;
}
_tail->_value = 0;
_tail = p2;
_size--;
}
}
int Link::ReadTail(){
return _tail->_value;
}
int Link::ReadHead(){
return _head->_value;
}
int Link::Size(){
return _size;
}
bool Link::Full(){
if(_tail->_next == NULL){
return true;
}else{
return false;
}
}
Queue::Queue(int MaxSize){
_link = new Link(MaxSize);
}
void Queue::push(int value){
_link->Insert(value);
}
void Queue::pop(){
_link->Delete();
}
int Queue::readTail(){
return _link->ReadTail();
}
int Queue::readHead(){
return _link->ReadHead();
}
bool Queue::empty(){
if(_link->Size() == 0){
return true;
}else{
return false;
}
}
bool Queue::full(){
return _link->Full();
}
int main(){
Queue st1(5);
cout << "empty = " << st1.empty() << endl;
st1.push(3);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
cout << "empty = " << st1.empty() << endl;
st1.push(4);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
st1.pop();
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
st1.pop();
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
cout << "empty = " << st1.empty() << endl;
st1.push(5);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
st1.push(6);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
st1.push(7);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
st1.push(8);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
st1.push(9);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
cout << "full = " << st1.full() << endl;
st1.push(10);
cout << "head = " << st1.readHead() << endl;
cout << "tail = " << st1.readTail() << endl;
return 0;
}
| [
"loydchen729@gmail.com"
] | loydchen729@gmail.com |
b71b9ee516b401d1c211f57adf86876055590a4f | ee9d134f818dcccbbaaa19475497dce0cc1deca9 | /Algoritmos Busqueda/A_estrella.cpp | 9dcd342ac4beafb0f271ad9c608cbf808aaa64dd | [] | no_license | pakejo/Practicas-IA-UGR | 89a8748292af35238d5e00541e788e2f7be13dc5 | 0768cbe10919358845c11d3ba4017a0c7569a5de | refs/heads/master | 2020-04-03T23:50:45.033684 | 2018-10-31T22:42:36 | 2018-10-31T22:42:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,173 | cpp | /*
Como todo algoritmo de búsqueda en amplitud, A* es un algoritmo completo:
en caso de existir una solución, siempre dará con ella.
Si para todo nodo n del grafo se cumple g(n)=0 nos encontramos ante una búsqueda voraz.
Si para todo nodo n del grafo se cumple h(n)=0, A* pasa a ser una búsqueda de coste uniforme no informada.
Para garantizar la optimización del algoritmo, la función h(n) debe ser heurística admisible,
esto es, que no sobrestime el coste real de alcanzar el nodo objetivo.
De no cumplirse dicha condición, el algoritmo pasa a denominarse simplemente A,
y a pesar de seguir siendo completo, no se asegura que el resultado obtenido sea
el camino de coste mínimo. Asimismo, si garantizamos que h(n) es consistente, es decir,
que para cualquier nodo n y cualquiera de sus sucesores, el coste estimado de alcanzar
el objetivo desde n no es mayor que el de alcanzar el sucesor más el coste de alcanzar
el objetivo desde el sucesor.
La complejidad computacional del algoritmo está íntimamente relacionada con la
calidad de la heurística que se utilice en el problema. En el caso peor,
con una heurística de pésima calidad, la complejidad será exponencial,
mientras que en el caso mejor, con una buena h(n), el algoritmo se ejecutará en tiempo lineal.
*/
#include <iostream>
#include <list>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
#include <cmath>
using namespace std;
enum Action {actFORWARD, actTURN_L, actTURN_R, actIDLE};
struct nodo
{
int fila;
int col;
int orientacion;
double g = 0.0;
double h = 0.0;
double f = 0.0;
nodo *padre;
bool operator<(const nodo &b) { return f < b.f; }
bool operator==(const nodo &b) { return (fila == b.fila) && (col == b.col); }
void CalculaF(nodo destino)
{
g = sqrt(pow((fila - padre->fila), 2) + pow((col - padre->col), 2)) + padre->g;
//h = sqrt(pow((fila - destino.fila), 2) + pow((col - destino.col), 2));
h = abs(fila - destino.fila) + abs(col - destino.col);
f = g + h;
}
};
void construyePlan(vector<nodo> camino, list<Action> plan)
{
int i = 1;
int j = 0;
while (j < camino.size())
{
//El vecino esta al norte
if ((camino[i].fila + 1 == camino[j].fila) && (camino[i].col == camino[j].col))
{
switch (camino[j].orientacion)
{
case 0:
plan.push_back(actFORWARD);
break;
case 1:
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 2:
plan.push_back(actTURN_R);
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 3:
plan.push_back(actTURN_L);
plan.push_back(actFORWARD);
break;
}
camino[i].orientacion = 0;
}
//El vecino esta al sur
if ((camino[i].fila - 1 == camino[j].fila) && (camino[i].col == camino[j].col))
{
switch (camino[j].orientacion)
{
case 0:
plan.push_back(actTURN_R);
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 1:
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 2:
plan.push_back(actFORWARD);
break;
case 3:
plan.push_back(actTURN_L);
plan.push_back(actFORWARD);
break;
}
camino[i].orientacion = 2;
}
//El vecino esta al este
if ((camino[i].fila == camino[j].fila) && (camino[i].col - 1 == camino[j].col))
{
switch (camino[j].orientacion)
{
case 0:
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 1:
plan.push_back(actFORWARD);
break;
case 2:
plan.push_back(actTURN_L);
plan.push_back(actFORWARD);
break;
case 3:
plan.push_back(actTURN_R);
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
}
camino[i].orientacion = 2;
}
//El vecino esta al oeste
if ((camino[i].fila == camino[j].fila) && (camino[i].col + 1 == camino[j].col))
{
switch (camino[j].orientacion)
{
case 0:
plan.push_back(actTURN_L);
plan.push_back(actFORWARD);
break;
case 1:
plan.push_back(actTURN_R);
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 2:
plan.push_back(actTURN_R);
plan.push_back(actFORWARD);
break;
case 3:
plan.push_back(actFORWARD);
break;
}
camino[i].orientacion = 3;
}
i++, j++;
}
}
bool esObstaculo(nodo nodo, vector<vector<char>> mapa)
{
if ((mapa[nodo.fila][nodo.col] == 'B') || (mapa[nodo.fila][nodo.col] == 'A') ||
(mapa[nodo.fila][nodo.col] == 'P') || (mapa[nodo.fila][nodo.col] == 'M') ||
(mapa[nodo.fila][nodo.col] == 'D'))
return true;
return false;
}
bool buscaEnLista(list<nodo> &lista, nodo &estado)
{
for (auto it = lista.begin(); it != lista.end(); ++it)
{
if ((it->col == estado.col) && (it->fila == estado.fila))
{
return true;
}
}
return false;
}
vector<nodo> obtenVecinos(nodo &actual)
{
vector<nodo> salida;
nodo norte;
norte.fila = actual.fila - 1;
norte.col = actual.col;
salida.push_back(norte);
nodo sur;
sur.fila = actual.fila + 1;
sur.col = actual.col;
salida.push_back(sur);
nodo este;
este.fila = actual.fila;
este.col = actual.col + 1;
salida.push_back(este);
nodo oeste;
oeste.fila = actual.fila;
oeste.col = actual.col - 1;
salida.push_back(oeste);
return salida;
}
vector<vector<char>> cargaMapa(std::string nombre)
{
vector<vector<char>> mapa;
ifstream file;
std::string linea;
string n, m;
int filas, cols;
file.open(nombre);
std::getline(file, n);
std::getline(file, m);
filas = std::stoi(n);
cols = std::stoi(m);
mapa.resize(filas);
for (int i = 0; i < filas; i++)
mapa[i].resize(cols);
for (int fila = 0; fila < filas; fila++)
{
std::getline(file, linea);
for (int i = 0; i < linea.length(); i++)
{
mapa[fila][i] = linea[i];
}
}
return mapa;
}
bool pathfinding(nodo &origen, nodo &destino, vector<vector<char>> mapa)
{
list<nodo> abierta;
list<nodo> cerrada;
list<Action> plan;
abierta.push_back(origen);
if (esObstaculo(destino, mapa))
return false;
while (!abierta.empty())
{
nodo actual = abierta.front();
camino.push_back(actual);
if (actual == destino)
{
cout << "Destino encotrado" << endl;
cout << "Construyendo plan" << endl;
construyePlan(camino,plan);
return true;
}
abierta.pop_front();
cerrada.push_back(actual);
vector<nodo> vecinos = obtenVecinos(actual);
vector<nodo> vecinosNoObstaculos;
for (int i = 0; i < vecinos.size(); i++)
{
vecinos[i].padre = &actual;
if (!esObstaculo(vecinos[i], mapa))
{
vecinosNoObstaculos.push_back(vecinos[i]);
}
else
cerrada.push_back(vecinos[i]);
}
for (int i = 0; i < vecinosNoObstaculos.size(); i++)
{
vecinosNoObstaculos[i].CalculaF(destino);
if (!buscaEnLista(abierta, vecinosNoObstaculos[i]))
{
abierta.push_back(vecinosNoObstaculos[i]);
}
else
{
for (auto it = abierta.begin(); it != abierta.end(); ++it)
{
if (*it == vecinosNoObstaculos[i])
{
if (it->g > vecinosNoObstaculos[i].g)
{
*it = vecinosNoObstaculos[i];
}
}
}
}
}
abierta.sort();
}
return false;
}
int main()
{
vector<vector<char>> mapa;
mapa = cargaMapa("mapas/cuadricula.map");
nodo origen;
origen.fila = 96;
origen.col = 15;
origen.orientacion = 0;
nodo destino;
destino.fila = 91;
destino.col = 45;
bool hayPlan = pathfinding(origen, destino, mapa);
cout << hayPlan;
} | [
"paco1998@hotmail.es"
] | paco1998@hotmail.es |
432d6aa5c36f2c6a36d042c217daa1ec339370a4 | c067b496e3273dff4d9ff048764601a3d10e7db0 | /corobot_state_tf/cfg/cpp/corobot_state_tf/corobot_state_tfConfig.h | 23bf55643281b03d4d35db80f2a1649c6a0f594c | [] | no_license | CoroBot/CoroBot_ROS_Stack | 5de88d3c11b65b0ca6f64cf2f532d7e416d8bb77 | b9cfa77faca01cd0af856d3e61074b7f2c96d8e4 | refs/heads/master | 2021-01-20T00:41:39.583559 | 2014-12-11T15:32:44 | 2014-12-11T15:32:44 | 27,877,941 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 21,037 | h | //#line 2 "/opt/ros/hydro/share/dynamic_reconfigure/templates/ConfigType.h.template"
// *********************************************************
//
// File autogenerated for the corobot_state_tf package
// by the dynamic_reconfigure package.
// Please do not edit.
//
// ********************************************************/
/***********************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Willow Garage, Inc.
* 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 Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
***********************************************************/
// Author: Blaise Gassend
#ifndef __corobot_state_tf__COROBOT_STATE_TFCONFIG_H__
#define __corobot_state_tf__COROBOT_STATE_TFCONFIG_H__
#include <dynamic_reconfigure/config_tools.h>
#include <limits>
#include <ros/node_handle.h>
#include <dynamic_reconfigure/ConfigDescription.h>
#include <dynamic_reconfigure/ParamDescription.h>
#include <dynamic_reconfigure/Group.h>
#include <dynamic_reconfigure/config_init_mutex.h>
#include <boost/any.hpp>
namespace corobot_state_tf
{
class corobot_state_tfConfigStatics;
class corobot_state_tfConfig
{
public:
class AbstractParamDescription : public dynamic_reconfigure::ParamDescription
{
public:
AbstractParamDescription(std::string n, std::string t, uint32_t l,
std::string d, std::string e)
{
name = n;
type = t;
level = l;
description = d;
edit_method = e;
}
virtual void clamp(corobot_state_tfConfig &config, const corobot_state_tfConfig &max, const corobot_state_tfConfig &min) const = 0;
virtual void calcLevel(uint32_t &level, const corobot_state_tfConfig &config1, const corobot_state_tfConfig &config2) const = 0;
virtual void fromServer(const ros::NodeHandle &nh, corobot_state_tfConfig &config) const = 0;
virtual void toServer(const ros::NodeHandle &nh, const corobot_state_tfConfig &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, corobot_state_tfConfig &config) const = 0;
virtual void toMessage(dynamic_reconfigure::Config &msg, const corobot_state_tfConfig &config) const = 0;
virtual void getValue(const corobot_state_tfConfig &config, boost::any &val) const = 0;
};
typedef boost::shared_ptr<AbstractParamDescription> AbstractParamDescriptionPtr;
typedef boost::shared_ptr<const AbstractParamDescription> AbstractParamDescriptionConstPtr;
template <class T>
class ParamDescription : public AbstractParamDescription
{
public:
ParamDescription(std::string name, std::string type, uint32_t level,
std::string description, std::string edit_method, T corobot_state_tfConfig::* f) :
AbstractParamDescription(name, type, level, description, edit_method),
field(f)
{}
T (corobot_state_tfConfig::* field);
virtual void clamp(corobot_state_tfConfig &config, const corobot_state_tfConfig &max, const corobot_state_tfConfig &min) const
{
if (config.*field > max.*field)
config.*field = max.*field;
if (config.*field < min.*field)
config.*field = min.*field;
}
virtual void calcLevel(uint32_t &comb_level, const corobot_state_tfConfig &config1, const corobot_state_tfConfig &config2) const
{
if (config1.*field != config2.*field)
comb_level |= level;
}
virtual void fromServer(const ros::NodeHandle &nh, corobot_state_tfConfig &config) const
{
nh.getParam(name, config.*field);
}
virtual void toServer(const ros::NodeHandle &nh, const corobot_state_tfConfig &config) const
{
nh.setParam(name, config.*field);
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, corobot_state_tfConfig &config) const
{
return dynamic_reconfigure::ConfigTools::getParameter(msg, name, config.*field);
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const corobot_state_tfConfig &config) const
{
dynamic_reconfigure::ConfigTools::appendParameter(msg, name, config.*field);
}
virtual void getValue(const corobot_state_tfConfig &config, boost::any &val) const
{
val = config.*field;
}
};
class AbstractGroupDescription : public dynamic_reconfigure::Group
{
public:
AbstractGroupDescription(std::string n, std::string t, int p, int i, bool s)
{
name = n;
type = t;
parent = p;
state = s;
id = i;
}
std::vector<AbstractParamDescriptionConstPtr> abstract_parameters;
bool state;
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &config) const = 0;
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &config) const =0;
virtual void updateParams(boost::any &cfg, corobot_state_tfConfig &top) const= 0;
virtual void setInitialState(boost::any &cfg) const = 0;
void convertParams()
{
for(std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = abstract_parameters.begin(); i != abstract_parameters.end(); ++i)
{
parameters.push_back(dynamic_reconfigure::ParamDescription(**i));
}
}
};
typedef boost::shared_ptr<AbstractGroupDescription> AbstractGroupDescriptionPtr;
typedef boost::shared_ptr<const AbstractGroupDescription> AbstractGroupDescriptionConstPtr;
template<class T, class PT>
class GroupDescription : public AbstractGroupDescription
{
public:
GroupDescription(std::string name, std::string type, int parent, int id, bool s, T PT::* f) : AbstractGroupDescription(name, type, parent, id, s), field(f)
{
}
GroupDescription(const GroupDescription<T, PT>& g): AbstractGroupDescription(g.name, g.type, g.parent, g.id, g.state), field(g.field), groups(g.groups)
{
parameters = g.parameters;
abstract_parameters = g.abstract_parameters;
}
virtual bool fromMessage(const dynamic_reconfigure::Config &msg, boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
if(!dynamic_reconfigure::ConfigTools::getGroupState(msg, name, (*config).*field))
return false;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
if(!(*i)->fromMessage(msg, n))
return false;
}
return true;
}
virtual void setInitialState(boost::any &cfg) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* group = &((*config).*field);
group->state = state;
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = boost::any(&((*config).*field));
(*i)->setInitialState(n);
}
}
virtual void updateParams(boost::any &cfg, corobot_state_tfConfig &top) const
{
PT* config = boost::any_cast<PT*>(cfg);
T* f = &((*config).*field);
f->setParams(top, abstract_parameters);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
boost::any n = &((*config).*field);
(*i)->updateParams(n, top);
}
}
virtual void toMessage(dynamic_reconfigure::Config &msg, const boost::any &cfg) const
{
const PT config = boost::any_cast<PT>(cfg);
dynamic_reconfigure::ConfigTools::appendGroup<T>(msg, name, id, parent, config.*field);
for(std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = groups.begin(); i != groups.end(); ++i)
{
(*i)->toMessage(msg, config.*field);
}
}
T (PT::* field);
std::vector<corobot_state_tfConfig::AbstractGroupDescriptionConstPtr> groups;
};
class DEFAULT
{
public:
DEFAULT()
{
state = true;
name = "Default";
}
void setParams(corobot_state_tfConfig &config, const std::vector<AbstractParamDescriptionConstPtr> params)
{
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = params.begin(); i != params.end(); ++i)
{
boost::any val;
(*i)->getValue(config, val);
if("camera_state_tf"==(*i)->name){camera_state_tf = boost::any_cast<bool>(val);}
}
}
bool camera_state_tf;
bool state;
std::string name;
}groups;
//#line 259 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
bool camera_state_tf;
//#line 255 "/opt/ros/hydro/share/dynamic_reconfigure/templates/ConfigType.h.template"
bool __fromMessage__(dynamic_reconfigure::Config &msg)
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
int count = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
if ((*i)->fromMessage(msg, *this))
count++;
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i ++)
{
if ((*i)->id == 0)
{
boost::any n = boost::any(this);
(*i)->updateParams(n, *this);
(*i)->fromMessage(msg, n);
}
}
if (count != dynamic_reconfigure::ConfigTools::size(msg))
{
ROS_ERROR("corobot_state_tfConfig::__fromMessage__ called with an unexpected parameter.");
ROS_ERROR("Booleans:");
for (unsigned int i = 0; i < msg.bools.size(); i++)
ROS_ERROR(" %s", msg.bools[i].name.c_str());
ROS_ERROR("Integers:");
for (unsigned int i = 0; i < msg.ints.size(); i++)
ROS_ERROR(" %s", msg.ints[i].name.c_str());
ROS_ERROR("Doubles:");
for (unsigned int i = 0; i < msg.doubles.size(); i++)
ROS_ERROR(" %s", msg.doubles[i].name.c_str());
ROS_ERROR("Strings:");
for (unsigned int i = 0; i < msg.strs.size(); i++)
ROS_ERROR(" %s", msg.strs[i].name.c_str());
// @todo Check that there are no duplicates. Make this error more
// explicit.
return false;
}
return true;
}
// This version of __toMessage__ is used during initialization of
// statics when __getParamDescriptions__ can't be called yet.
void __toMessage__(dynamic_reconfigure::Config &msg, const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__, const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__) const
{
dynamic_reconfigure::ConfigTools::clear(msg);
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toMessage(msg, *this);
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
if((*i)->id == 0)
{
(*i)->toMessage(msg, *this);
}
}
}
void __toMessage__(dynamic_reconfigure::Config &msg) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
__toMessage__(msg, __param_descriptions__, __group_descriptions__);
}
void __toServer__(const ros::NodeHandle &nh) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->toServer(nh, *this);
}
void __fromServer__(const ros::NodeHandle &nh)
{
static bool setup=false;
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->fromServer(nh, *this);
const std::vector<AbstractGroupDescriptionConstPtr> &__group_descriptions__ = __getGroupDescriptions__();
for (std::vector<AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); i++){
if (!setup && (*i)->id == 0) {
setup = true;
boost::any n = boost::any(this);
(*i)->setInitialState(n);
}
}
}
void __clamp__()
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
const corobot_state_tfConfig &__max__ = __getMax__();
const corobot_state_tfConfig &__min__ = __getMin__();
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->clamp(*this, __max__, __min__);
}
uint32_t __level__(const corobot_state_tfConfig &config) const
{
const std::vector<AbstractParamDescriptionConstPtr> &__param_descriptions__ = __getParamDescriptions__();
uint32_t level = 0;
for (std::vector<AbstractParamDescriptionConstPtr>::const_iterator i = __param_descriptions__.begin(); i != __param_descriptions__.end(); ++i)
(*i)->calcLevel(level, config, *this);
return level;
}
static const dynamic_reconfigure::ConfigDescription &__getDescriptionMessage__();
static const corobot_state_tfConfig &__getDefault__();
static const corobot_state_tfConfig &__getMax__();
static const corobot_state_tfConfig &__getMin__();
static const std::vector<AbstractParamDescriptionConstPtr> &__getParamDescriptions__();
static const std::vector<AbstractGroupDescriptionConstPtr> &__getGroupDescriptions__();
private:
static const corobot_state_tfConfigStatics *__get_statics__();
};
template <> // Max and min are ignored for strings.
inline void corobot_state_tfConfig::ParamDescription<std::string>::clamp(corobot_state_tfConfig &config, const corobot_state_tfConfig &max, const corobot_state_tfConfig &min) const
{
return;
}
class corobot_state_tfConfigStatics
{
friend class corobot_state_tfConfig;
corobot_state_tfConfigStatics()
{
corobot_state_tfConfig::GroupDescription<corobot_state_tfConfig::DEFAULT, corobot_state_tfConfig> Default("Default", "", 0, 0, true, &corobot_state_tfConfig::groups);
//#line 259 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
__min__.camera_state_tf = 0;
//#line 259 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
__max__.camera_state_tf = 1;
//#line 259 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
__default__.camera_state_tf = 1;
//#line 259 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
Default.abstract_parameters.push_back(corobot_state_tfConfig::AbstractParamDescriptionConstPtr(new corobot_state_tfConfig::ParamDescription<bool>("camera_state_tf", "bool", 0, "Activate the odometry calculation", "", &corobot_state_tfConfig::camera_state_tf)));
//#line 259 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
__param_descriptions__.push_back(corobot_state_tfConfig::AbstractParamDescriptionConstPtr(new corobot_state_tfConfig::ParamDescription<bool>("camera_state_tf", "bool", 0, "Activate the odometry calculation", "", &corobot_state_tfConfig::camera_state_tf)));
//#line 233 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
Default.convertParams();
//#line 233 "/opt/ros/hydro/lib/python2.7/dist-packages/dynamic_reconfigure/parameter_generator.py"
__group_descriptions__.push_back(corobot_state_tfConfig::AbstractGroupDescriptionConstPtr(new corobot_state_tfConfig::GroupDescription<corobot_state_tfConfig::DEFAULT, corobot_state_tfConfig>(Default)));
//#line 390 "/opt/ros/hydro/share/dynamic_reconfigure/templates/ConfigType.h.template"
for (std::vector<corobot_state_tfConfig::AbstractGroupDescriptionConstPtr>::const_iterator i = __group_descriptions__.begin(); i != __group_descriptions__.end(); ++i)
{
__description_message__.groups.push_back(**i);
}
__max__.__toMessage__(__description_message__.max, __param_descriptions__, __group_descriptions__);
__min__.__toMessage__(__description_message__.min, __param_descriptions__, __group_descriptions__);
__default__.__toMessage__(__description_message__.dflt, __param_descriptions__, __group_descriptions__);
}
std::vector<corobot_state_tfConfig::AbstractParamDescriptionConstPtr> __param_descriptions__;
std::vector<corobot_state_tfConfig::AbstractGroupDescriptionConstPtr> __group_descriptions__;
corobot_state_tfConfig __max__;
corobot_state_tfConfig __min__;
corobot_state_tfConfig __default__;
dynamic_reconfigure::ConfigDescription __description_message__;
static const corobot_state_tfConfigStatics *get_instance()
{
// Split this off in a separate function because I know that
// instance will get initialized the first time get_instance is
// called, and I am guaranteeing that get_instance gets called at
// most once.
static corobot_state_tfConfigStatics instance;
return &instance;
}
};
inline const dynamic_reconfigure::ConfigDescription &corobot_state_tfConfig::__getDescriptionMessage__()
{
return __get_statics__()->__description_message__;
}
inline const corobot_state_tfConfig &corobot_state_tfConfig::__getDefault__()
{
return __get_statics__()->__default__;
}
inline const corobot_state_tfConfig &corobot_state_tfConfig::__getMax__()
{
return __get_statics__()->__max__;
}
inline const corobot_state_tfConfig &corobot_state_tfConfig::__getMin__()
{
return __get_statics__()->__min__;
}
inline const std::vector<corobot_state_tfConfig::AbstractParamDescriptionConstPtr> &corobot_state_tfConfig::__getParamDescriptions__()
{
return __get_statics__()->__param_descriptions__;
}
inline const std::vector<corobot_state_tfConfig::AbstractGroupDescriptionConstPtr> &corobot_state_tfConfig::__getGroupDescriptions__()
{
return __get_statics__()->__group_descriptions__;
}
inline const corobot_state_tfConfigStatics *corobot_state_tfConfig::__get_statics__()
{
const static corobot_state_tfConfigStatics *statics;
if (statics) // Common case
return statics;
boost::mutex::scoped_lock lock(dynamic_reconfigure::__init_mutex__);
if (statics) // In case we lost a race.
return statics;
statics = corobot_state_tfConfigStatics::get_instance();
return statics;
}
}
#endif // __COROBOT_STATE_TFRECONFIGURATOR_H__
| [
"cowens@coroware.com"
] | cowens@coroware.com |
f363989e53e9644f469dbe4fb0d60a9ae13a362b | 228e15141dfd53f3f3bf3a9e4fdd81989186e681 | /Kiwano/ui/Button.cpp | 29923e486e65892506aa83c4755a901ae9e85dc5 | [
"MIT"
] | permissive | nomango96/Kiwano | 796936e5fc3bf3bd5a670d58fb70c188d778cfc7 | 51b4078624fcd6370aa9c30eb5048a538cd1877c | refs/heads/master | 2020-06-21T01:13:51.529700 | 2019-07-08T09:23:49 | 2019-07-08T09:23:49 | 197,307,231 | 1 | 0 | MIT | 2019-07-17T03:20:19 | 2019-07-17T03:20:19 | null | UTF-8 | C++ | false | false | 3,689 | cpp | // Copyright (c) 2016-2018 Kiwano - Nomango
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include "Button.h"
#include "../2d/Scene.h"
namespace kiwano
{
Button::Button()
: enabled_(true)
, is_selected_(false)
, click_callback_(nullptr)
, status_(Status::Normal)
{
SetResponsible(true);
AddListener(Event::MouseHover, MakeClosure(this, &Button::UpdateStatus));
AddListener(Event::MouseOut, MakeClosure(this, &Button::UpdateStatus));
AddListener(Event::MouseBtnDown, MakeClosure(this, &Button::UpdateStatus));
AddListener(Event::MouseBtnUp, MakeClosure(this, &Button::UpdateStatus));
}
Button::Button(const Callback& click)
: Button()
{
this->SetClickCallback(click);
}
Button::Button(Callback const & click, Callback const & pressed, Callback const & mouse_over, Callback const & mouse_out)
: Button()
{
this->SetClickCallback(click);
this->SetPressedCallback(pressed);
this->SetMouseOverCallback(mouse_over);
this->SetMouseOutCallback(mouse_out);
}
Button::~Button()
{
}
bool Button::IsEnable() const
{
return enabled_;
}
void Button::SetEnabled(bool enabled)
{
if (enabled_ != enabled)
{
enabled_ = enabled;
}
}
void Button::SetClickCallback(const Callback& func)
{
click_callback_ = func;
}
void Button::SetPressedCallback(const Callback & func)
{
pressed_callback_ = func;
}
void Button::SetReleasedCallback(const Callback& func)
{
released_callback_ = func;
}
void Button::SetMouseOverCallback(const Callback & func)
{
mouse_over_callback_ = func;
}
void Button::SetMouseOutCallback(const Callback & func)
{
mouse_out_callback_ = func;
}
void Button::SetStatus(Status status)
{
if (status_ != status)
{
status_ = status;
}
}
void Button::UpdateStatus(Event const& evt)
{
KGE_ASSERT(MouseEvent::Check(evt.type));
if (enabled_ && (evt.target == this))
{
if (evt.type == Event::MouseHover)
{
SetStatus(Status::Hover);
GetScene()->SetMouseCursor(MouseCursor::Hand);
if (mouse_over_callback_)
mouse_over_callback_();
}
else if (evt.type == Event::MouseOut)
{
SetStatus(Status::Normal);
GetScene()->SetMouseCursor(MouseCursor::Arrow);
if (mouse_out_callback_)
mouse_out_callback_();
}
else if (evt.type == Event::MouseBtnDown && status_ == Status::Hover)
{
SetStatus(Status::Pressed);
if (pressed_callback_)
pressed_callback_();
}
else if (evt.type == Event::MouseBtnUp && status_ == Status::Pressed)
{
SetStatus(Status::Hover);
if (released_callback_)
released_callback_();
if (click_callback_)
click_callback_();
}
}
}
} | [
"569629550@qq.com"
] | 569629550@qq.com |
5bd529bf7f2162c1ad5c5d5f37df34cda447faf0 | ab2a37a7b4747f6c5877041799257b5421c59e1f | /src/blend2d/pixelconverter_avx2.cpp | c00daaeda91f2ccc574107ac8bf31fd8558abdaf | [
"Zlib",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | ursine/blend2d | 527e2a27543a7f08286ae1fb827fdb3b98abeaca | b694944dd0322019b807e702413e6ea4fa3354f6 | refs/heads/master | 2020-12-04T03:55:25.689666 | 2020-02-25T08:52:44 | 2020-03-12T14:58:50 | 231,600,035 | 0 | 0 | Zlib | 2020-03-12T14:58:52 | 2020-01-03T14:01:31 | null | UTF-8 | C++ | false | false | 25,597 | cpp | // [Blend2D]
// 2D Vector Graphics Powered by a JIT Compiler.
//
// [License]
// Zlib - See LICENSE.md file in the package.
#include "./api-build_p.h"
#ifdef BL_BUILD_OPT_AVX2
#include "./pixelconverter_p.h"
#include "./simd_p.h"
#include "./support_p.h"
using namespace SIMD;
// ============================================================================
// [BLPixelConverter - Utilities (AVX2)]
// ============================================================================
static BL_INLINE I128 vpshufb_or(const I128& x, const I128& predicate, const I128& or_mask) noexcept {
return vor(vpshufb(x, predicate), or_mask);
}
static BL_INLINE I256 vpshufb_or(const I256& x, const I256& predicate, const I256& or_mask) noexcept {
return vor(vpshufb(x, predicate), or_mask);
}
// ============================================================================
// [BLPixelConverter - Copy (AVX2)]
// ============================================================================
BLResult bl_convert_copy_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
const size_t bytesPerPixel = blPixelConverterGetData(self)->memCopyData.bytesPerPixel;
const size_t byteWidth = size_t(w) * bytesPerPixel;
// Use a generic copy if `byteWidth` is small as we would not be able to
// utilize SIMD properly - in general we want to use at least 16-byte RW.
if (byteWidth < 16)
return bl_convert_copy(self, dstData, dstStride, srcData, srcStride, w, h, options);
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= intptr_t(byteWidth) + gap;
srcStride -= intptr_t(byteWidth);
for (uint32_t y = h; y != 0; y--) {
size_t i = byteWidth;
while_nounroll (i >= 64) {
I256 p0 = vloadi256u(srcData + 0);
I256 p1 = vloadi256u(srcData + 32);
vstorei256u(dstData + 0, p0);
vstorei256u(dstData + 32, p1);
dstData += 64;
srcData += 64;
i -= 64;
}
while_nounroll (i >= 16) {
vstorei128u(dstData, vloadi128u(srcData));
dstData += 16;
srcData += 16;
i -= 16;
}
if (i) {
dstData += i;
srcData += i;
vstorei128u(dstData - 16, vloadi128u(srcData - 16));
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
// ============================================================================
// [BLPixelConverter - Copy|Or (AVX2)]
// ============================================================================
BLResult bl_convert_copy_or_8888_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= uintptr_t(w) * 4 + gap;
srcStride -= uintptr_t(w) * 4;
I256 fillMask = vseti256u32(blPixelConverterGetData(self)->memCopyData.fillMask);
const BLCommonTable::LoadStoreM32* loadStoreM32 = blCommonTable.load_store_m32;
for (uint32_t y = h; y != 0; y--) {
uint32_t i = w;
while_nounroll (i >= 32) {
I256 p0 = vloadi256u(srcData + 0);
I256 p1 = vloadi256u(srcData + 32);
I256 p2 = vloadi256u(srcData + 64);
I256 p3 = vloadi256u(srcData + 96);
vstorei256u(dstData + 0, vor(p0, fillMask));
vstorei256u(dstData + 32, vor(p1, fillMask));
vstorei256u(dstData + 64, vor(p2, fillMask));
vstorei256u(dstData + 96, vor(p3, fillMask));
dstData += 128;
srcData += 128;
i -= 32;
}
while_nounroll (i >= 8) {
I256 p0 = vloadi256u(srcData);
vstorei256u(dstData, vor(p0, fillMask));
dstData += 32;
srcData += 32;
i -= 8;
}
if (i) {
I256 msk = loadStoreM32[i].as<I256>();
I256 p0 = vloadi256_mask32(srcData, msk);
vstorei256_mask32(dstData, vor(p0, fillMask), msk);
dstData += i * 4;
srcData += i * 4;
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
// ============================================================================
// [BLPixelConverter - Copy|Shufb (AVX2)]
// ============================================================================
BLResult bl_convert_copy_shufb_8888_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= uintptr_t(w) * 4 + gap;
srcStride -= uintptr_t(w) * 4;
const BLPixelConverterData::ShufbData& d = blPixelConverterGetData(self)->shufbData;
const BLCommonTable::LoadStoreM32* loadStoreM32 = blCommonTable.load_store_m32;
I256 fillMask = vseti256u32(d.fillMask);
I256 predicate = vdupli128(vloadi128u(d.shufbPredicate));
for (uint32_t y = h; y != 0; y--) {
uint32_t i = w;
while_nounroll (i >= 32) {
I256 p0 = vloadi256u(srcData + 0);
I256 p1 = vloadi256u(srcData + 32);
I256 p2 = vloadi256u(srcData + 64);
I256 p3 = vloadi256u(srcData + 96);
p0 = vpshufb_or(p0, predicate, fillMask);
p1 = vpshufb_or(p1, predicate, fillMask);
p2 = vpshufb_or(p2, predicate, fillMask);
p3 = vpshufb_or(p3, predicate, fillMask);
vstorei256u(dstData + 0, p0);
vstorei256u(dstData + 32, p1);
vstorei256u(dstData + 64, p2);
vstorei256u(dstData + 96, p3);
dstData += 128;
srcData += 128;
i -= 32;
}
while_nounroll (i >= 8) {
I256 p0 = vloadi256u(srcData);
p0 = vpshufb(p0, predicate);
p0 = vor(p0, fillMask);
vstorei256u(dstData, p0);
dstData += 32;
srcData += 32;
i -= 8;
}
if (i) {
I256 msk = loadStoreM32[i].as<I256>();
I256 p0 = vloadi256_mask32(srcData, msk);
p0 = vpshufb(p0, predicate);
p0 = vor(p0, fillMask);
vstorei256_mask32(dstData, p0, msk);
dstData += i * 4;
srcData += i * 4;
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
// ============================================================================
// [BLPixelConverter - RGB32 <- RGB24 (AVX2)]
// ============================================================================
BLResult bl_convert_rgb32_from_rgb24_shufb_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= uintptr_t(w) * 4 + gap;
srcStride -= uintptr_t(w) * 3;
const BLPixelConverterData::ShufbData& d = blPixelConverterGetData(self)->shufbData;
const BLCommonTable::LoadStoreM32* loadStoreM32 = blCommonTable.load_store_m32;
I256 fillMask = vseti256u32(d.fillMask);
I256 predicate = vdupli128(vloadi128u(d.shufbPredicate));
for (uint32_t y = h; y != 0; y--) {
uint32_t i = w;
while_nounroll (i >= 32) {
I256 p0, p1, p2, p3;
I256 q0, q1, q2, q3;
p0 = vloadi256_128u(srcData + 0); // [x5|z4 y4 x4|z3 y3 x3 z2|y2 x2 z1 y1|x1 z0 y0 x0]
p1 = vloadi256_128u(srcData + 16); // [yA|xA|z9 y9|x9 z8 y8 x8|z7 y7 x7 z6|y6 x6 z5 y5]
p3 = vloadi256_128u(srcData + 32); // [zF yF xF zE|yE xE zD yD|xD zC yC xC|zB yB xB zA]
p2 = vpalignr<8>(p3, p1); // [-- -- -- --|zB yB xB zA|yA|xA|z9 y9|x9 z8 y8 x8]
p1 = vpalignr<12>(p1, p0); // [-- -- -- --|z7 y7 x7 z6|y6 x6 z5 y5|x5|z4 y4 x4]
p3 = vsrli128b<4>(p3); // [-- -- -- --|zF yF xF zE|yE xE zD yD|xD zC yC xC]
p0 = vunpackli128(p0, p1);
p2 = vunpackli128(p2, p3);
q0 = vloadi256_128u(srcData + 48); // [x5|z4 y4 x4|z3 y3 x3 z2|y2 x2 z1 y1|x1 z0 y0 x0]
q1 = vloadi256_128u(srcData + 64); // [yA|xA|z9 y9|x9 z8 y8 x8|z7 y7 x7 z6|y6 x6 z5 y5]
q3 = vloadi256_128u(srcData + 80); // [zF yF xF zE|yE xE zD yD|xD zC yC xC|zB yB xB zA]
q2 = vpalignr<8>(q3, q1); // [-- -- -- --|zB yB xB zA|yA|xA|z9 y9|x9 z8 y8 x8]
q1 = vpalignr<12>(q1, q0); // [-- -- -- --|z7 y7 x7 z6|y6 x6 z5 y5|x5|z4 y4 x4]
q3 = vsrli128b<4>(q3); // [-- -- -- --|zF yF xF zE|yE xE zD yD|xD zC yC xC]
q0 = vunpackli128(q0, q1);
q2 = vunpackli128(q2, q3);
p0 = vpshufb_or(p0, predicate, fillMask);
p2 = vpshufb_or(p2, predicate, fillMask);
q0 = vpshufb_or(q0, predicate, fillMask);
q2 = vpshufb_or(q2, predicate, fillMask);
vstorei256u(dstData + 0, p0);
vstorei256u(dstData + 32, p2);
vstorei256u(dstData + 64, q0);
vstorei256u(dstData + 96, q2);
dstData += 128;
srcData += 96;
i -= 32;
}
while_nounroll (i >= 8) {
I128 p0, p1;
p0 = vloadi128u(srcData); // [x5|z4 y4 x4|z3 y3 x3 z2|y2 x2 z1 y1|x1 z0 y0 x0]
p1 = vloadi128_64(srcData + 16); // [-- -- -- --|-- -- -- --|z7 y7 x7 z6|y6 x6 z5 y5]
p1 = vpalignr<12>(p1, p0); // [-- -- -- --|z7 y7 x7 z6|y6 x6 z5 y5|x5|z4 y4 x4]
p0 = vpshufb_or(p0, vcast<I128>(predicate), vcast<I128>(fillMask));
p1 = vpshufb_or(p1, vcast<I128>(predicate), vcast<I128>(fillMask));
vstorei128u(dstData + 0, p0);
vstorei128u(dstData + 16, p1);
dstData += 32;
srcData += 24;
i -= 8;
}
if (i >= 4) {
I128 p0;
p0 = vloadi128_64(srcData); // [-- -- -- --|-- -- -- --|y2 x2 z1 y1|x1 z0 y0 x0]
p0 = vinsertm32<2>(p0, srcData + 8); // [-- -- -- --|z3 y3 x3 z2|y2 x2 z1 y1|x1 z0 y0 x0]
p0 = vpshufb_or(p0, vcast<I128>(predicate), vcast<I128>(fillMask));
vstorei128u(dstData, p0);
dstData += 16;
srcData += 12;
i -= 4;
}
if (i) {
I128 p0 = vzeroi128();
I128 msk = loadStoreM32[i].as<I128>();
p0 = vinsertm24<0>(p0, srcData + 0); // [-- -- -- --|-- -- -- z2|y2 x2 z1 y1|x1 z0 y0 x0]
if (i >= 2) {
p0 = vinsertm24<3>(p0, srcData + 3); // [-- -- -- --|-- -- -- --|-- -- z1 y1|x1 z0 y0 x0]
if (i >= 3) {
p0 = vinsertm24<6>(p0, srcData + 6); // [-- -- -- --|-- -- -- z2|y2 x2 z1 y1|x1 z0 y0 x0]
}
}
p0 = vpshufb_or(p0, vcast<I128>(predicate), vcast<I128>(fillMask));
vstorei128_mask32(dstData, p0, msk);
dstData += i * 4;
srcData += i * 3;
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
// ============================================================================
// [BLPixelConverter - Premultiply (AVX2)]
// ============================================================================
template<uint32_t A_Shift, bool UseShufB>
static BL_INLINE BLResult bl_convert_premultiply_8888_template_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= uintptr_t(w) * 4 + gap;
srcStride -= uintptr_t(w) * 4;
const BLPixelConverterData::PremultiplyData& d = blPixelConverterGetData(self)->premultiplyData;
const BLCommonTable::LoadStoreM32* loadStoreM32 = blCommonTable.load_store_m32;
I256 zero = vzeroi256();
I256 a255 = vseti256u64(uint64_t(0xFFu) << (A_Shift * 2));
I256 fillMask = vseti256u32(d.fillMask);
I256 predicate;
if (UseShufB)
predicate = vdupli128(vloadi128u(d.shufbPredicate));
// Alpha byte-index that can be used by instructions that perform shuffling.
constexpr uint32_t AI = A_Shift / 8u;
for (uint32_t y = h; y != 0; y--) {
uint32_t i = w;
while_nounroll (i >= 16) {
I256 p0, p1, p2, p3;
p0 = vloadi256u(srcData + 0);
p2 = vloadi256u(srcData + 32);
if (UseShufB) p0 = vpshufb(p0, predicate);
if (UseShufB) p2 = vpshufb(p2, predicate);
p1 = vunpackhi8(p0, zero);
p0 = vunpackli8(p0, zero);
p3 = vunpackhi8(p2, zero);
p2 = vunpackli8(p2, zero);
p0 = vmuli16(vor(p0, a255), vswizi16<AI, AI, AI, AI>(p0));
p1 = vmuli16(vor(p1, a255), vswizi16<AI, AI, AI, AI>(p1));
p2 = vmuli16(vor(p2, a255), vswizi16<AI, AI, AI, AI>(p2));
p3 = vmuli16(vor(p3, a255), vswizi16<AI, AI, AI, AI>(p3));
p0 = vdiv255u16(p0);
p1 = vdiv255u16(p1);
p2 = vdiv255u16(p2);
p3 = vdiv255u16(p3);
p0 = vpacki16u8(p0, p1);
p2 = vpacki16u8(p2, p3);
p0 = vor(p0, fillMask);
p2 = vor(p2, fillMask);
vstorei256u(dstData + 0, p0);
vstorei256u(dstData + 32, p2);
dstData += 64;
srcData += 64;
i -= 16;
}
while_nounroll (i) {
uint32_t n = blMin(i, uint32_t(8));
I256 p0, p1;
I256 msk = loadStoreM32[n].as<I256>();
p0 = vloadi256_mask32(srcData, msk);
if (UseShufB) p0 = vpshufb(p0, predicate);
p1 = vunpackhi8(p0, zero);
p0 = vunpackli8(p0, zero);
p0 = vmuli16(vor(p0, a255), vswizi16<AI, AI, AI, AI>(p0));
p1 = vmuli16(vor(p1, a255), vswizi16<AI, AI, AI, AI>(p1));
p0 = vdiv255u16(p0);
p1 = vdiv255u16(p1);
p0 = vpacki16u8(p0, p1);
p0 = vor(p0, fillMask);
vstorei256_mask32(dstData, p0, msk);
dstData += n * 4;
srcData += n * 4;
i -= n;
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
BLResult bl_convert_premultiply_8888_leading_alpha_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_premultiply_8888_template_avx2<24, false>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
BLResult bl_convert_premultiply_8888_trailing_alpha_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_premultiply_8888_template_avx2<0, false>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
BLResult bl_convert_premultiply_8888_leading_alpha_shufb_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_premultiply_8888_template_avx2<24, true>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
BLResult bl_convert_premultiply_8888_trailing_alpha_shufb_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_premultiply_8888_template_avx2<0, true>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
// ============================================================================
// [BLPixelConverter - Unpremultiply (PMULLD) (AVX2)]
// ============================================================================
template<uint32_t A_Shift>
static BL_INLINE BLResult bl_convert_unpremultiply_8888_pmulld_template_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
BL_UNUSED(self);
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= uintptr_t(w) * 4u + gap;
srcStride -= uintptr_t(w) * 4u;
const uint32_t* rcpTable = blCommonTable.unpremultiplyRcp;
const BLCommonTable::LoadStoreM32* loadStoreM32 = blCommonTable.load_store_m32;
I256 alphaMask = vseti256u32(0xFFu << A_Shift);
I256 componentMask = vseti256u32(0xFFu);
I256 rnd = vseti256u32(0x8000u);
// Alpha byte-index that can be used by instructions that perform shuffling.
constexpr uint32_t AI = A_Shift / 8u;
constexpr uint32_t RI = (AI + 1) % 4;
constexpr uint32_t GI = (AI + 2) % 4;
constexpr uint32_t BI = (AI + 3) % 4;
for (uint32_t y = h; y != 0; y--) {
uint32_t i = w;
while_nounroll (i >= 8) {
I256 pix = vloadi256u(srcData);
I256 rcp0 = vloadi256_32(rcpTable + srcData[0 * 4 + AI]);
I256 rcp4 = vloadi256_32(rcpTable + srcData[4 * 4 + AI]);
rcp0 = vinsertum32<1>(rcp0, rcpTable + srcData[1 * 4 + AI]);
rcp4 = vinsertum32<1>(rcp4, rcpTable + srcData[5 * 4 + AI]);
rcp0 = vinsertum32<2>(rcp0, rcpTable + srcData[2 * 4 + AI]);
rcp4 = vinsertum32<2>(rcp4, rcpTable + srcData[6 * 4 + AI]);
rcp0 = vinsertum32<3>(rcp0, rcpTable + srcData[3 * 4 + AI]);
rcp4 = vinsertum32<3>(rcp4, rcpTable + srcData[7 * 4 + AI]);
rcp0 = vunpackli128(rcp0, rcp4);
I256 pr = vsrli32<RI * 8>(pix);
I256 pg = vsrli32<GI * 8>(pix);
I256 pb = vsrli32<BI * 8>(pix);
if (RI != 3) pr = vand(pr, componentMask);
if (GI != 3) pg = vand(pg, componentMask);
if (BI != 3) pb = vand(pb, componentMask);
pr = vmulu32(pr, rcp0);
pg = vmulu32(pg, rcp0);
pb = vmulu32(pb, rcp0);
pix = vand(pix, alphaMask);
pr = vslli32<RI * 8>(vsrli32<16>(vaddi32(pr, rnd)));
pg = vslli32<GI * 8>(vsrli32<16>(vaddi32(pg, rnd)));
pb = vslli32<BI * 8>(vsrli32<16>(vaddi32(pb, rnd)));
pix = vor(pix, pr);
pix = vor(pix, pg);
pix = vor(pix, pb);
vstorei256u(dstData, pix);
dstData += 32;
srcData += 32;
i -= 8;
}
if (i) {
I256 msk = loadStoreM32[i].as<I256>();
I256 pix = vloadi256_mask32(srcData, msk);
I256 pixHi = vpermi128<1, 1>(pix);
size_t idx0 = vextractu8<0 * 4 + AI>(pix);
size_t idx4 = vextractu8<0 * 4 + AI>(pixHi);
I256 rcp0 = vloadi256_32(rcpTable + idx0);
I256 rcp4 = vloadi256_32(rcpTable + idx4);
size_t idx1 = vextractu8<1 * 4 + AI>(pix);
size_t idx5 = vextractu8<1 * 4 + AI>(pixHi);
rcp0 = vinsertum32<1>(rcp0, rcpTable + idx1);
rcp4 = vinsertum32<1>(rcp4, rcpTable + idx5);
size_t idx2 = vextractu8<2 * 4 + AI>(pix);
size_t idx6 = vextractu8<2 * 4 + AI>(pixHi);
rcp0 = vinsertum32<2>(rcp0, rcpTable + idx2);
rcp4 = vinsertum32<2>(rcp4, rcpTable + idx6);
size_t idx3 = vextractu8<3 * 4 + AI>(pix);
size_t idx7 = vextractu8<3 * 4 + AI>(pixHi);
rcp0 = vinsertum32<3>(rcp0, rcpTable + idx3);
rcp4 = vinsertum32<3>(rcp4, rcpTable + idx7);
rcp0 = vunpackli128(rcp0, rcp4);
I256 pr = vsrli32<RI * 8>(pix);
I256 pg = vsrli32<GI * 8>(pix);
I256 pb = vsrli32<BI * 8>(pix);
if (RI != 3) pr = vand(pr, componentMask);
if (GI != 3) pg = vand(pg, componentMask);
if (BI != 3) pb = vand(pb, componentMask);
pr = vmulu32(pr, rcp0);
pg = vmulu32(pg, rcp0);
pb = vmulu32(pb, rcp0);
pix = vand(pix, alphaMask);
pr = vslli32<RI * 8>(vsrli32<16>(vaddi32(pr, rnd)));
pg = vslli32<GI * 8>(vsrli32<16>(vaddi32(pg, rnd)));
pb = vslli32<BI * 8>(vsrli32<16>(vaddi32(pb, rnd)));
pix = vor(pix, pr);
pix = vor(pix, pg);
pix = vor(pix, pb);
vstorei256_mask32(dstData, pix, msk);
dstData += i * 4;
srcData += i * 4;
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
BLResult bl_convert_unpremultiply_8888_leading_alpha_pmulld_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_unpremultiply_8888_pmulld_template_avx2<24>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
BLResult bl_convert_unpremultiply_8888_trailing_alpha_pmulld_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_unpremultiply_8888_pmulld_template_avx2<0>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
// ============================================================================
// [BLPixelConverter - Unpremultiply (FLOAT) (AVX2)]
// ============================================================================
template<uint32_t A_Shift>
static BL_INLINE BLResult bl_convert_unpremultiply_8888_float_template_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
BL_UNUSED(self);
if (!options)
options = &blPixelConverterDefaultOptions;
const size_t gap = options->gap;
dstStride -= uintptr_t(w) * 4u + gap;
srcStride -= uintptr_t(w) * 4u;
const BLCommonTable::LoadStoreM32* loadStoreM32 = blCommonTable.load_store_m32;
I256 alphaMask = vseti256u32(0xFFu << A_Shift);
I256 componentMask = vseti256u32(0xFFu);
F256 const255 = vsetf256(255.0001f);
F256 lessThanOne = vsetf256(0.1f);
// Alpha byte-index that can be used by instructions that perform shuffling.
constexpr uint32_t AI = A_Shift / 8u;
constexpr uint32_t RI = (AI + 1) % 4;
constexpr uint32_t GI = (AI + 2) % 4;
constexpr uint32_t BI = (AI + 3) % 4;
for (uint32_t y = h; y != 0; y--) {
uint32_t i = w;
while_nounroll (i >= 8) {
I256 pix = vloadi256u(srcData);
I256 pa = vsrli32<AI * 8>(pix);
I256 pr = vsrli32<RI * 8>(pix);
if (AI != 3) pa = vand(pa, componentMask);
if (RI != 3) pr = vand(pr, componentMask);
F256 fa = vcvti256f256(pa);
F256 fr = vcvti256f256(pr);
fa = vdivps(const255, vmaxps(fa, lessThanOne));
I256 pg = vsrli32<GI * 8>(pix);
I256 pb = vsrli32<BI * 8>(pix);
if (GI != 3) pg = vand(pg, componentMask);
if (BI != 3) pb = vand(pb, componentMask);
F256 fg = vcvti256f256(pg);
F256 fb = vcvti256f256(pb);
fr = vmulps(fr, fa);
fg = vmulps(fg, fa);
fb = vmulps(fb, fa);
pix = vand(pix, alphaMask);
pr = vcvtf256i256(fr);
pg = vcvtf256i256(fg);
pb = vcvtf256i256(fb);
pr = vslli32<RI * 8>(pr);
pg = vslli32<GI * 8>(pg);
pb = vslli32<BI * 8>(pb);
pix = vor(pix, pr);
pix = vor(pix, pg);
pix = vor(pix, pb);
vstorei256u(dstData, pix);
dstData += 32;
srcData += 32;
i -= 8;
}
if (i) {
I256 msk = loadStoreM32[i].as<I256>();
I256 pix = vloadi256_mask32(srcData, msk);
I256 pa = vsrli32<AI * 8>(pix);
I256 pr = vsrli32<RI * 8>(pix);
if (AI != 3) pa = vand(pa, componentMask);
if (RI != 3) pr = vand(pr, componentMask);
F256 fa = vcvti256f256(pa);
F256 fr = vcvti256f256(pr);
fa = vdivps(const255, vmaxps(fa, lessThanOne));
I256 pg = vsrli32<GI * 8>(pix);
I256 pb = vsrli32<BI * 8>(pix);
if (GI != 3) pg = vand(pg, componentMask);
if (BI != 3) pb = vand(pb, componentMask);
F256 fg = vcvti256f256(pg);
F256 fb = vcvti256f256(pb);
fr = vmulps(fr, fa);
fg = vmulps(fg, fa);
fb = vmulps(fb, fa);
pix = vand(pix, alphaMask);
pr = vcvtf256i256(fr);
pg = vcvtf256i256(fg);
pb = vcvtf256i256(fb);
pr = vslli32<RI * 8>(pr);
pg = vslli32<GI * 8>(pg);
pb = vslli32<BI * 8>(pb);
pix = vor(pix, pr);
pix = vor(pix, pg);
pix = vor(pix, pb);
vstorei256_mask32(dstData, pix, msk);
dstData += i * 4;
srcData += i * 4;
}
dstData = blPixelConverterFillGap(dstData, gap);
dstData += dstStride;
srcData += srcStride;
}
return BL_SUCCESS;
}
BLResult bl_convert_unpremultiply_8888_leading_alpha_float_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_unpremultiply_8888_float_template_avx2<24>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
BLResult bl_convert_unpremultiply_8888_trailing_alpha_float_avx2(
const BLPixelConverterCore* self,
uint8_t* dstData, intptr_t dstStride,
const uint8_t* srcData, intptr_t srcStride, uint32_t w, uint32_t h, const BLPixelConverterOptions* options) noexcept {
return bl_convert_unpremultiply_8888_float_template_avx2<0>(self, dstData, dstStride, srcData, srcStride, w, h, options);
}
#endif
| [
"kobalicek.petr@gmail.com"
] | kobalicek.petr@gmail.com |
e4de49c736490473b1217cf94992696d5a25a56a | 3841f7991232e02c850b7e2ff6e02712e9128b17 | /小浪底泥沙三维/EV_Xld/jni/src/EV_Spatial3DAnalysisObject_CSharp/wrapper/math3dareameasure_wrapper.cpp | 5f71262a43e45c4c6e4d8033ea2733deb906fb19 | [] | no_license | 15831944/BeijingEVProjects | 62bf734f1cb0a8be6fed42cf6b207f9dbdf99e71 | 3b5fa4c4889557008529958fc7cb51927259f66e | refs/heads/master | 2021-07-22T14:12:15.106616 | 2017-10-15T11:33:06 | 2017-10-15T11:33:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,784 | cpp | /* This file is produced by the P/Invoke AutoWrapper Utility
Copyright (c) 2012 by EarthView Image Inc */
#include "spatial3danalysisobject/math3dareameasure.h"
namespace EarthView
{
namespace World
{
namespace Spatial3D
{
namespace Analysis
{
typedef const EarthView::World::Spatial3D::Analysis::CAltitude3DListener* ( _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback)();
typedef void ( _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback)(_in EarthView::World::Spatial3D::Analysis::CAltitude3DListener* ref_pListener);
class CMath3DMeasureAreaProxy : public EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea
{
private:
EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback* m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback;
EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback* m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback;
public:
CMath3DMeasureAreaProxy(EarthView::World::Core::CNameValuePairList *pList) : CMath3DMeasureArea(pList)
{
m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback = NULL;
m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback = NULL;
}
public:
ev_void registerCallback_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener(EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback* pCallback)
{
m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback = pCallback;
}
ev_void registerCallback_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener(EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback* pCallback)
{
m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback = pCallback;
}
virtual const EarthView::World::Spatial3D::Analysis::CAltitude3DListener* getAltitude3DListener() const
{
if(m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback != NULL && this->isCustomExtend())
{
const EarthView::World::Spatial3D::Analysis::CAltitude3DListener* returnValue = m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback();
return returnValue;
}
else
return this->CMath3DMeasureArea::getAltitude3DListener();
}
virtual void setAltitude3DListener(_in EarthView::World::Spatial3D::Analysis::CAltitude3DListener* ref_pListener)
{
if(m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback != NULL && this->isCustomExtend())
{
m_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback(ref_pListener);
}
else
return this->CMath3DMeasureArea::setAltitude3DListener(ref_pListener);
}
};
REGISTER_FACTORY_CLASS(CMath3DMeasureAreaProxy);
extern "C" EV_DLL_EXPORT ev_real64 _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getInterval_ev_real64(void *pObjectXXXX )
{
const EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea* ptrNativeObject = (EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX;
ev_real64 objXXXX = ptrNativeObject->getInterval();
return objXXXX;
}
extern "C" EV_DLL_EXPORT void _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setInterval_void_ev_real64(void *pObjectXXXX, _in const ev_real64& value )
{
EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea* ptrNativeObject = (EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX;
ptrNativeObject->setInterval(value);
}
extern "C" EV_DLL_EXPORT ev_real64 _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_calcuPolygonArea_ev_real64_VertexList_ev_bool_ev_real64(void *pObjectXXXX, _in void* inpoints, _in ev_bool calcuClampedArea, _out ev_real64& clampedArea )
{
EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea* ptrNativeObject = (EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX;
ev_real64 objXXXX = ptrNativeObject->calcuPolygonArea(*(EarthView::World::Spatial::Math::VertexList*)inpoints, calcuClampedArea, clampedArea);
return objXXXX;
}
extern "C" EV_DLL_EXPORT ev_real64 _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_calcuClampedArea_ev_real64_VertexList(void *pObjectXXXX, _in void* inpoints )
{
EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea* ptrNativeObject = (EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX;
ev_real64 objXXXX = ptrNativeObject->calcuClampedArea(*(EarthView::World::Spatial::Math::VertexList*)inpoints);
return objXXXX;
}
extern "C" EV_DLL_EXPORT ev_real64 _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_calcuProjectArea_ev_real64_VertexList(void *pObjectXXXX, _in void* inpoints )
{
EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea* ptrNativeObject = (EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX;
ev_real64 objXXXX = ptrNativeObject->calcuProjectArea(*(EarthView::World::Spatial::Math::VertexList*)inpoints);
return objXXXX;
}
extern "C" EV_DLL_EXPORT void _stdcall EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_calculateOnServer_void_VertexList_ev_real64_ev_real64(void *pObjectXXXX, _in void* inpoints, _out ev_real64& clampArea, _out ev_real64& projArea )
{
EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea* ptrNativeObject = (EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX;
ptrNativeObject->calculateOnServer(*(EarthView::World::Spatial::Math::VertexList*)inpoints, clampArea, projArea);
}
extern "C" EV_DLL_EXPORT ev_void _stdcall EV_RegisterCallback_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener( void *pObjectXXXX, EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener_Callback* pCallback )
{
CMath3DMeasureAreaProxy* ptr = dynamic_cast<CMath3DMeasureAreaProxy*>((EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX);
if(ptr != NULL)
{
ptr->registerCallback_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_getAltitude3DListener_CAltitude3DListener(pCallback);
}
}
extern "C" EV_DLL_EXPORT ev_void _stdcall EV_RegisterCallback_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener( void *pObjectXXXX, EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener_Callback* pCallback )
{
CMath3DMeasureAreaProxy* ptr = dynamic_cast<CMath3DMeasureAreaProxy*>((EarthView::World::Spatial3D::Analysis::CMath3DMeasureArea*) pObjectXXXX);
if(ptr != NULL)
{
ptr->registerCallback_EarthView_World_Spatial3D_Analysis_CMath3DMeasureArea_setAltitude3DListener_void_CAltitude3DListener(pCallback);
}
}
}
}
}
}
| [
"yanguanqi@aliyun.com"
] | yanguanqi@aliyun.com |
30e851de5638bf5c8bf7dd915fe45f8ed0e65b2d | 56ba2984d5f47c13ebb3ded8a041d43f9522e27f | /inexlib/ourex/SOPHYA/src/SkyMap/imgphotband.cc | 5e20349a9e5cfc63d77e167ad2a2260e65781dbe | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | gbarrand/TouchSky | 2ad7ec6eef209a8319698829877c20469857dbe1 | a6216fb20fbcf9e38ac62a81cef8c4f053a07b8c | refs/heads/master | 2021-09-11T07:25:41.523286 | 2021-08-31T09:29:39 | 2021-08-31T09:29:39 | 133,839,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,560 | cc | /*
------------------------------------------------------------------------------------
SOPHYA class library - (C) UPS+LAL IN2P3/CNRS , CEA-Irfu
Ancillary classes for Image<T> class
Jan 2015 - R. Ansari, J.E.Campagne, C. Magneville
------------------------------------------------------------------------------------
*/
#include "machdefs.h"
#include "imgphotband.h"
#include <sstream>
#include <iomanip>
using namespace std;
namespace SOPHYA {
/*!
\class ImgPhotometricBand
\ingroup SkyMap
*/
/*!
Subset of standard photometric bands defined through the central wavelength (lambda0),
and bandwidth (Delta-lambda) - See the reference below for more information.
\verbatim
--------------------------------------------------
FilterId lambda0 (A) Delta-lambda (A)
--------------------------------------------------
Johnson-Cousin
--------------------------------------------------
U_Filter 3663 A 650 A
B_Filter 4361 A 890 A
V_Filter 5448 A 840 A
R_Filter 6407 A 1580 A
I_Filter 7980 A 1540 A
--------------------------------------------------
Michael S. Bessell , STANDARD PHOTOMETRIC SYSTEMS
Annual Review of Astronomy and Astrophysics
Vol. 43: 293-336 (Volume publication date August 2005)
DOI: 10.1146/annurev.astro.41.082801.100251
\endverbatim
*/
/* --Methode-- */
ImgPhotometricBand::ImgPhotometricBand(StandardPhotometricFilterId fid)
{
// Johnson-Cousins central wavelength in Angstrom
double jc_lambda0[5]={3663., 4361., 5448., 6407., 7980.};
// Johnson-Cousins wavelength width in Angstrom
double jc_delta_lambda[5]={650., 890., 840., 1580., 1540.};
PhysQty lambda(Units::meter().micro(), 1.);
double relbw=0.1;
double maxtr=1.;
PassBandType pbt=kSquarePassBand;
switch (fid) {
case NonStandardFilter:
pbt=kSquarePassBand;
break;
// Johnson-Cousins filters
case U_Filter:
lambda.setValue(jc_lambda0[0]/1.e4);
relbw=jc_delta_lambda[0]/jc_lambda0[0];
break;
case B_Filter:
lambda.setValue(jc_lambda0[1]/1.e4);
relbw=jc_delta_lambda[1]/jc_lambda0[1];
break;
case V_Filter:
lambda.setValue(jc_lambda0[2]/1.e4);
relbw=jc_delta_lambda[2]/jc_lambda0[2];
break;
case R_Filter:
lambda.setValue(jc_lambda0[3]/1.e4);
relbw=jc_delta_lambda[3]/jc_lambda0[3];
break;
case I_Filter:
lambda.setValue(jc_lambda0[4]/1.e4);
relbw=jc_delta_lambda[4]/jc_lambda0[4];
break;
default:
break;
}
defineFilter(fid, lambda, relbw, maxtr, pbt);
}
/* --Methode-- */
ImgPhotometricBand::ImgPhotometricBand(PhysQty const& lambda_nu_0, double relbandw, double mxtrans, PassBandType typ)
{
StandardPhotometricFilterId fid=NonStandardFilter;
if (lambda_nu_0.getUnit().isSameDimension(Units::meter()))
defineFilter(fid, lambda_nu_0, relbandw, mxtrans, typ);
else {
if (lambda_nu_0.getUnit().isSameDimension(Units::hertz())) {
PhysQty lambda0 = PhysQty::SpeedofLight()/lambda_nu_0;
defineFilter(fid, lambda0, relbandw, mxtrans, typ);
}
else {
ParmError("ImgPhotometricBand::ImgPhotometricBand(lambda_nu_0 ...): lambda_nu_0 not a wavelength or frequency");
}
}
}
/* --Methode-- */
/* --Methode--
ImgPhotometricBand::~ImgPhotometricBand()
{
}
*/
/* --Methode-- */
string ImgPhotometricBand::getFilterName() const
{
switch (stdfilterid_) {
case NonStandardFilter:
return "NonStandardFilter";
break;
// Johnson-Cousins filters
case U_Filter:
return "U_Filter";
break;
case B_Filter:
return "B_Filter";
break;
case V_Filter:
return "V_Filter";
break;
case R_Filter:
return "R_Filter";
break;
case I_Filter:
return "I_Filter";
break;
default:
return "????_Filter";
break;
}
return "";
}
/* --Methode-- */
ostream& ImgPhotometricBand::Print(ostream& os) const
{
os << "ImgPhotometricBand["<<getFilterName()<<" , lambda0="<<lambda0_<<" relBW="<<relbandwidth_<<" MaxTr="<<maxtrans_<<"]";
return os;
}
//----------------------------------------------------------
// Classe pour la gestion de persistance de ImgPhotometricBand
// ObjFileIO<ImgPhotometricBand>
//----------------------------------------------------------
/* --Methode-- */
DECL_TEMP_SPEC /* equivalent a template <> , pour SGI-CC en particulier */
void ObjFileIO<ImgPhotometricBand>::WriteSelf(POutPersist& s) const
{
if (dobj == NULL)
throw NullPtrError("ObjFileIO<ImgPhotometricBand>::WriteSelf() dobj=NULL");
int_4 ver;
ver = 1;
s.Put(ver); // ecriture numero de version PPF
uint_2 fid = dobj->stdfilterid_;
uint_2 pbt = dobj->pbtype_;
s << fid << dobj->lambda0_ << dobj->relbandwidth_ << dobj->maxtrans_ << pbt;
}
/* --Methode-- */
DECL_TEMP_SPEC /* equivalent a template <> , pour SGI-CC en particulier */
void ObjFileIO<ImgPhotometricBand>::ReadSelf(PInPersist& s)
{
int_4 ver;
s.Get(ver); // Lecture numero de version PPF
uint_2 fid;
uint_2 pbt;
s >> fid >> dobj->lambda0_ >> dobj->relbandwidth_ >> dobj->maxtrans_ >> pbt;
dobj->stdfilterid_ = ImgPhotometricBand::StandardPhotometricFilterId(fid);
dobj->pbtype_ = ImgPhotometricBand::PassBandType(pbt);
}
/* --Methode-- */
#ifdef __CXX_PRAGMA_TEMPLATES__
#pragma define_template ObjFileIO<ImgPhotometricBand>
#endif
#if defined(ANSI_TEMPLATES) || defined(GNU_TEMPLATES)
template class ObjFileIO<ImgPhotometricBand>;
#endif
} // FIN namespace SOPHYA
| [
"guy.barrand@gmail.com"
] | guy.barrand@gmail.com |
c4c516eca01fea913b45f6bd7db114ec0e442eaa | ceb2a3d736e0c187eb67b064697409e919660e5a | /src/qt/bitcoinunits.h | ffd50efa01314a98c7cb7744bcff74bade557e6f | [
"MIT"
] | permissive | ARMROfficial/armr | 6405117c8ad936985ff71397a9dc0e65d37c1357 | 6bc69a9dcb3ae6b26de435c1906681b3a7dd4ad4 | refs/heads/master | 2021-06-11T05:30:08.314912 | 2020-01-24T03:45:33 | 2020-01-24T03:45:33 | 128,578,630 | 4 | 5 | MIT | 2020-01-21T21:12:19 | 2018-04-07T23:57:59 | C | UTF-8 | C++ | false | false | 2,005 | h | #ifndef BITCOINUNITS_H
#define BITCOINUNITS_H
#include <QString>
#include <QAbstractListModel>
/** Bitcoin unit definitions. Encapsulates parsing and formatting
and serves as list model for drop-down selection boxes.
*/
class BitcoinUnits: public QAbstractListModel
{
public:
explicit BitcoinUnits(QObject *parent);
/** Bitcoin units.
@note Source: https://en.bitcoin.it/wiki/Units . Please add only sensible ones
*/
enum Unit
{
BTC,
mBTC,
uBTC
};
//! @name Static API
//! Unit conversion and formatting
///@{
//! Get list of units, for drop-down box
static QList<Unit> availableUnits();
//! Is unit ID valid?
static bool valid(int unit);
//! Short name
static QString name(int unit);
//! Longer description
static QString description(int unit);
//! Number of Satoshis (1e-8) per unit
static qint64 factor(int unit);
//! Number of amount digits (to represent max number of coins)
static int amountDigits(int unit);
//! Number of decimals left
static int decimals(int unit);
//! Format as string
static QString format(int unit, qint64 amount, bool plussign=false);
//! Format as string (with unit)
static QString formatWithUnit(int unit, qint64 amount, bool plussign=false);
//! Format as string (without unit)
static QString formatWithoutUnit(int unit, qint64 amount, bool plussign=false);
//! Parse string to coin amount
static bool parse(int unit, const QString &value, qint64 *val_out);
///@}
//! @name AbstractListModel implementation
//! List model for unit drop-down selection box.
///@{
enum RoleIndex {
/** Unit identifier */
UnitRole = Qt::UserRole
};
int rowCount(const QModelIndex &parent) const;
QVariant data(const QModelIndex &index, int role) const;
///@}
private:
QList<BitcoinUnits::Unit> unitlist;
};
typedef BitcoinUnits::Unit BitcoinUnit;
#endif // BITCOINUNITS_H
| [
"info@armr.network"
] | info@armr.network |
484e2399d0b85a22ded4e610548067c106b0feb9 | 50b413dc554ba778a5e4f59fa8e458e598cd95b0 | /test/081_search_in_rotated_sorted_array_2_test.cpp | 55a7c19e29092f2b9fca29f12f6ccd9274f7d10d | [] | no_license | Mstoned/leetcode-solutions | fc794b690280fde6e5869dcaa1e9e6717644117b | 2b1465df29e3fae0cdba90d9b0733c138721dea6 | refs/heads/master | 2022-01-06T19:37:52.835243 | 2018-10-06T12:59:18 | 2018-10-06T12:59:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,625 | cpp | #include "081_search_in_rotated_sorted_array_2.h"
#include "gtest/gtest.h"
using namespace std;
SearchRotatedSortedArray2Solution *solution081 = new SearchRotatedSortedArray2Solution;
TEST(SearchRotatedSortedArray2, Test0) {
vector<int> nums = { 2,5,6,0,0,1,2 };
int target = 0;
bool result = solution081->search(nums, target);
EXPECT_TRUE(result);
}
TEST(SearchRotatedSortedArray2, Test1) {
vector<int> nums = { 2,5,6,0,0,1,2 };
int target = 3;
bool result = solution081->search(nums, target);
EXPECT_FALSE(result);
}
bool contains(vector<int> v, int t) {
for (int i = 0; i < v.size(); i++) {
if (v[i] == t) {
return true;
}
}
return false;
}
vector<int> shift081(vector<int> nums, int size) {
vector<int> copy(nums);
rotate(copy.begin(), copy.begin() + size, copy.end());
return copy;
}
TEST(SearchRotatedSortedArray2, Test4) {
vector<int> nums = { 0, 0, 10, 10, 10, 20, 20, 30, 40, 40, 40,
50, 50, 50, 60, 70, 70, 70 };
for (int s = 0; s < 18; s++) {
vector<int> nums_shifted = shift081(nums, s);
for (int i = 0; i < nums_shifted.size(); i++) {
printf("%d, ", nums_shifted[i]);
}
printf("\n");
for (int i = -10; i <= 80; i++) {
bool expected = contains(nums_shifted, i);
bool actual = solution081->search(nums_shifted, i);
printf("target=%d, outcome=%d\n", i, actual == expected);
EXPECT_EQ(actual, expected);
}
}
}
TEST(SearchRotatedSortedArray2, Test5) {
vector<int> nums = { 10, 10, 10, 20, 20, 30, 40, 40, 40, 50, 50, 50, 60,
70, 70, 70, 0, 0 };
bool expected = true;
bool actual = solution081->search(nums, 10);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test6) {
vector<int> nums = { 10, 10, 10, 20, 20, 30, 40, 40, 40, 50, 50, 50, 60,
70, 70, 70, 0, 0 };
bool expected = true;
bool actual = solution081->search(nums, 0);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test7) {
vector<int> nums = { 20, 20, 30, 40, 40, 40, 50, 50, 50, 60, 70, 70, 70,
0, 0, 10, 10, 10,};
bool expected = true;
bool actual = solution081->search(nums, 0);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test8) {
vector<int> nums = { 70, 70, 0, 0, 10, 10, 10, 20, 20, 30, 40, 40, 40, 50,
50, 50, 60, 70};
bool expected = true;
bool actual = solution081->search(nums, 0);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test9) {
vector<int> nums = { 1, 3, 3, 0, 0, 0 };
bool expected = false;
bool actual = solution081->search(nums, -1);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test10) {
vector<int> nums = { 3, 0, 0, 1, 1, 1 };
bool expected = true;
bool actual = solution081->search(nums, 0);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test11) {
vector<int> nums = { 1,2,2,2,0,1,1 };
bool expected = true;
bool actual = solution081->search(nums, 0);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test12) {
vector<int> nums = { 2,2,2,2,2,2,2 };
bool expected = true;
bool actual = solution081->search(nums, 2);
EXPECT_EQ(actual, expected);
}
TEST(SearchRotatedSortedArray2, Test13) {
vector<int> nums = { 2,2,2,2,2,2,2 };
bool expected = false;
bool actual = solution081->search(nums, 1);
EXPECT_EQ(actual, expected);
} | [
"alexey.s.grigoriev@gmail.com"
] | alexey.s.grigoriev@gmail.com |
c073ca9af55f1acb62ee55bf0ea47f5847522734 | 070ce743a5bb01852fb3f79ba07a20091157e630 | /code/src/align/src/general/indelHash_info.h | c203d6b029e4d61a53e009e455f5dd2a11c28c0c | [] | no_license | LiuBioinfo/iMapSplice | f4d641ade9aa882cb4cdec5efd3d21daea83b2ae | ecf2b1b79014e8a5f3ba8ee19ce5aa833ac292dd | refs/heads/master | 2020-03-22T00:06:42.136338 | 2019-02-08T04:17:05 | 2019-02-08T04:17:05 | 139,225,150 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,015 | h | // This file is a part of iMapSplice. Please refer to LICENSE.TXT for the LICENSE
#ifndef INDELHASH_INFO_H
#define INDELHAHS_INFO_H
#ifndef SPLICEJUNCTIONHASH_INFO_H
#define SPLICEJUNCTIONHASH_INFO_H
#include <string>
#include <string.h>
#include <map>
#include <set>
using namespace std;
typedef map<string, set<int> > SpliceEndStrHash; // SJ hash (in 2nd hash, key = anchor string)
typedef map<int, SpliceEndStrHash> SplicePosHash;
typedef SplicePosHash::iterator SplicePosHashIter;
typedef SpliceEndStrHash::iterator SpliceEndStrHashIter;
typedef map<int, set<int> > SJintHash; // InDel hash (only 1 hash, value is all possible splice junction positions in the other side)
typedef SJintHash::iterator InDelIntHashIter;
typedef map<int, set<int> > InDelAreaHash; //( areaNO = pos/100 ) intermediate hash to directly get the genomic positions in front of all InDels
typedef InDelAreaHash::iterator InDelAreaHashIter;
class InDelHash_Info
{
public:
vector<SplicePosHash> spliceJunctionNormal; // size = chromNum in index_info file
vector<SplicePosHash> spliceJunctionReverse; // size = chromNum in index_info file
int anchorStringLength;
//vector<SJintHash> SJintHashNormal;
//vector<SJintHash> SJintHashReverse;
int areaSize;
vector<SJareaHash> SJstartPosAreaHash;
vector<SJareaHash> SJendPosAreaHash;
SJhash_Info()
{
areaSize = 1000;
anchorStringLength = 3;
}
//////////////////////////////////////////////////////////////
///////////////////// SJintHash ///////////////////////////
//////////////////////////////////////////////////////////////
/*
void insert2SJintHash(
int chrInt, int spliceStartPos, int spliceEndPos)
{
SJintHashIter foundIntHashIter;
// insert to SJintHashNormal
foundIntHashIter = SJintHashNormal[chrInt].find(spliceStartPos);
if(foundIntHashIter == SJintHashNormal[chrInt].end())
{
set<int> newPosSet;
newPosSet.insert(spliceEndPos);
SJintHashNormal[chrInt].insert(pair<int, set<int> > (spliceStartPos, newPosSet));
}
else
{
if((foundIntHashIter->second).find(spliceEndPos) == (foundIntHashIter->second).end())
{
(foundIntHashIter->second).insert(spliceEndPos);
}
else
{}
}
//insert to SJintHashReverse
foundIntHashIter = SJintHashReverse[chrInt].find(spliceEndPos);
if(foundIntHashIter == SJintHashReverse[chrInt].end())
{
set<int> newPosSet;
newPosSet.insert(spliceStartPos);
SJintHashReverse[chrInt].insert(pair<int, set<int> > (spliceEndPos, newPosSet));
}
else
{
if((foundIntHashIter->second).find(spliceStartPos) == (foundIntHashIter->second).end())
{
(foundIntHashIter->second).insert(spliceStartPos);
}
else
{}
}
}
void initiateSJintHash(int chromNum)
{
for(int tmp = 0; tmp < chromNum; tmp++)
{
SJintHash newSJintHash;
SJintHashNormal.push_back(newSJintHash);
}
for(int tmp = 0; tmp < chromNum; tmp++)
{
SJintHash newSJintHash;
SJintHashReverse.push_back(newSJintHash);
}
}
*/
//////////////////////////////////////////////////////////////////////////
// 1. AreadHash: area - SJendSite hash ///////////////////////////////
// 2. StringHash: SJendSite - SJotherEndString - SJotherEndSite hash //
//////////////////////////////////////////////////////////////////////////
void initiateSpliceJunctionAreaHash(int chromNum)
{
for(int tmp = 0; tmp < chromNum; tmp++)
{
//SplicePosHash newSplicePosHash;
//spliceJunctionNormal.push_back(newSplicePosHash);
SJareaHash newSJareaHash;
SJstartPosAreaHash.push_back(newSJareaHash);
}
for(int tmp = 0; tmp < chromNum; tmp++)
{
//SplicePosHash newSplicePosHash;
//spliceJunctionReverse.push_back(newSplicePosHash);
SJareaHash newSJareaHash;
SJendPosAreaHash.push_back(newSJareaHash);
}
}
void initiateSpliceJunctionStringHash(int chromNum)
{
for(int tmp = 0; tmp < chromNum; tmp++)
{
SplicePosHash newSplicePosHash;
spliceJunctionNormal.push_back(newSplicePosHash);
}
for(int tmp = 0; tmp < chromNum; tmp++)
{
SplicePosHash newSplicePosHash;
spliceJunctionReverse.push_back(newSplicePosHash);
}
}
void initiateAreaAndStringHash(int chromNum)
{
this->initiateSpliceJunctionStringHash(chromNum);
this->initiateSpliceJunctionAreaHash(chromNum);
}
void insert2AreaHash(int chrInt,
int spliceStartPos, int spliceEndPos)
{
int spliceStartPosAreaNO = (int)(spliceStartPos/areaSize);
int spliceEndPosAreaNO = (int)(spliceEndPos/areaSize);
SJareaHashIter foundAreaHashIter;
// insert to SJstartPosAreaHash
foundAreaHashIter = SJstartPosAreaHash[chrInt].find(spliceStartPosAreaNO);
if(foundAreaHashIter == SJstartPosAreaHash[chrInt].end())
{
set<int> newPosSet;
newPosSet.insert(spliceStartPos);
SJstartPosAreaHash[chrInt].insert(pair<int, set<int> > (spliceStartPosAreaNO, newPosSet));
}
else
{
if( (foundAreaHashIter->second).find(spliceStartPos) == (foundAreaHashIter->second).end() )
{
(foundAreaHashIter->second).insert(spliceStartPos);
}
else
{}
}
// insert to SJendPosAreaHash
foundAreaHashIter = SJendPosAreaHash[chrInt].find(spliceEndPosAreaNO);
if(foundAreaHashIter == SJendPosAreaHash[chrInt].end())
{
set<int> newPosSet;
newPosSet.insert(spliceEndPos);
SJendPosAreaHash[chrInt].insert(pair<int, set<int> > (spliceEndPosAreaNO, newPosSet));
}
else
{
if( (foundAreaHashIter->second).find(spliceEndPos) == (foundAreaHashIter->second).end() )
{
(foundAreaHashIter->second).insert(spliceEndPos);
}
else
{}
}
}
void insert2StringHash(int chrInt,
int spliceStartPos, int spliceEndPos, Index_Info* indexInfo)
{
//string anchorString_doner = (indexInfo->chromStr)[chrInt].substr(spliceStartPos - anchorStringLength, anchorStringLength);
string anchorString_doner = indexInfo->returnChromStrSubstr(chrInt, spliceStartPos - anchorStringLength + 1, anchorStringLength);
//string anchorString_acceptor = (indexInfo->chromStr)[chrInt].substr(spliceEndPos - 1, anchorStringLength);
string anchorString_acceptor = indexInfo->returnChromStrSubstr(chrInt, spliceEndPos, anchorStringLength);
//insert to spliceJunctionNormal
SplicePosHashIter foundPosHashIter;
foundPosHashIter = spliceJunctionNormal[chrInt].find(spliceStartPos);
if(foundPosHashIter != spliceJunctionNormal[chrInt].end())
{
SpliceEndStrHashIter foundEndStrHashIter
= (foundPosHashIter->second).find(anchorString_acceptor);
if(foundEndStrHashIter != (foundPosHashIter->second).end())
{
set<int>::iterator intSetIter = (foundEndStrHashIter->second).find(spliceEndPos);
if(intSetIter != (foundEndStrHashIter->second).end())
{}
else
{
(foundEndStrHashIter->second).insert(spliceEndPos);
}
}
else
{
set<int> newAcceptorPosSet;
newAcceptorPosSet.insert(spliceEndPos);
(foundPosHashIter->second).insert(
pair<string, set<int> > (anchorString_acceptor, newAcceptorPosSet) );
//(foundPosHashIter->second).insert( pairn<string, set<int> > ("*", newDonerPosSet) );
}
SpliceEndStrHashIter foundEndStrHashIter_star = (foundPosHashIter->second).find("*");
if(foundEndStrHashIter_star != (foundPosHashIter->second).end() )
{
set<int>::iterator intSetIter
= (foundEndStrHashIter_star->second).find(spliceEndPos);
if(intSetIter != (foundEndStrHashIter_star->second).end())
{}
else
{
(foundEndStrHashIter_star->second).insert(spliceEndPos);
}
}
else
{
cout << "key value = * cannot be found !!! in spliceJunction_info.h" << endl;
}
}
else
{
set<int> newSpliceEndPosSet;
newSpliceEndPosSet.insert(spliceEndPos);
SpliceEndStrHash newSpliceEndStrHash;
newSpliceEndStrHash.insert(
pair<string, set<int> > (anchorString_acceptor, newSpliceEndPosSet) );
newSpliceEndStrHash.insert(
pair<string, set<int> > ("*", newSpliceEndPosSet) );
spliceJunctionNormal[chrInt].insert(
pair<int, SpliceEndStrHash> (spliceStartPos, newSpliceEndStrHash) );
}
foundPosHashIter = spliceJunctionReverse[chrInt].find(spliceEndPos);
if(foundPosHashIter != spliceJunctionReverse[chrInt].end())
{
SpliceEndStrHashIter foundEndStrHashIter
= (foundPosHashIter->second).find(anchorString_doner);
if(foundEndStrHashIter != (foundPosHashIter->second).end())
{
set<int>::iterator intSetIter = (foundEndStrHashIter->second).find(spliceStartPos);
if(intSetIter != (foundEndStrHashIter->second).end())
{}
else
{
(foundEndStrHashIter->second).insert(spliceStartPos);
}
}
else
{
set<int> newDonerPosSet;
newDonerPosSet.insert(spliceStartPos);
(foundPosHashIter->second).insert(
pair<string, set<int> > (anchorString_doner, newDonerPosSet) );
}
SpliceEndStrHashIter foundEndStrHashIter_star = (foundPosHashIter->second).find("*");
if(foundEndStrHashIter_star != (foundPosHashIter->second).end() )
{
set<int>::iterator intSetIter
= (foundEndStrHashIter_star->second).find(spliceStartPos);
if(intSetIter != (foundEndStrHashIter_star->second).end() )
{}
else
{
(foundEndStrHashIter_star->second).insert(spliceStartPos);
}
}
else
{
cout << "key value = * cannot be found !!! in spliceJunction_info.h" << endl;
}
}
else
{
set<int> newSpliceStartPosSet;
newSpliceStartPosSet.insert(spliceStartPos);
SpliceEndStrHash newSpliceEndStrHash;
newSpliceEndStrHash.insert(
pair<string, set<int> > (anchorString_doner, newSpliceStartPosSet) );
newSpliceEndStrHash.insert(
pair<string, set<int> > ("*", newSpliceStartPosSet) );
spliceJunctionReverse[chrInt].insert(
pair<int, SpliceEndStrHash> (spliceEndPos, newSpliceEndStrHash) );
}
}
void insert2AreaAndStringHash(int chrInt,
int spliceStartPos, int spliceEndPos, Index_Info* indexInfo)
{
this->insert2AreaHash(chrInt, spliceStartPos, spliceEndPos);
this->insert2StringHash(chrInt, spliceStartPos, spliceEndPos, indexInfo);
}
};
#endif | [
"Jinze.liu@uky.edu"
] | Jinze.liu@uky.edu |
78f198bf048be5edc706c9fe1020e0bba84a7248 | 2c96f14c2894b8b6c77c2c805e144990d6dee037 | /programitasC/serieRara.cpp | ac1db4c6605f8c8306de6dab5518eed3c4407253 | [] | no_license | JulioConchas/C-C- | c1473d804689e3f6f0e446cd5a8e054991b89683 | 3dab33e3998275f283c38b56b9d70557b589f06a | refs/heads/master | 2021-01-10T16:40:01.468226 | 2016-03-05T23:59:41 | 2016-03-05T23:59:41 | 47,792,779 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 334 | cpp | #include <iostream>
/**Realizar un programa que imprima 25 términos de la serie 11 - 22 - 33 - 44, etc.
(No se ingresan valores por teclado)*/
using namespace std;
int main(){
int cont,termino;
cont = 0;
termino = 11;
while(cont < 25){
cout <<termino<<"\n";
termino += 11;
cont++;
}
cin.get();
return 0;
} | [
"JulioConchas@Macbooks-MBP.lan"
] | JulioConchas@Macbooks-MBP.lan |
385191bbb51fa3aff2761571a212d1433260e08d | 461d6be1ea4d34858c6f08047aa6e21ebea3dcbe | /velodyne/velodyne_laserscan/include/velodyne_laserscan/velodyne_laserscan.h | fd2b619db2a3384cf900e4c3267701e26e46aac8 | [
"MIT",
"BSD-3-Clause"
] | permissive | runeg96/Velodyne-ROS-Windows | c5d52837ca35d20910795da72879cd3579d35a59 | 9dd883822eabaf143338fffe16424e3a3a0ae3e2 | refs/heads/main | 2023-05-02T03:47:41.512801 | 2021-05-25T08:02:21 | 2021-05-25T08:02:21 | 370,612,168 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,703 | h | // Copyright (C) 2018, 2019 Kevin Hallenbeck, Joshua Whitley
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// 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 {copyright_holder} nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#ifndef VELODYNE_LASERSCAN_VELODYNE_LASERSCAN_H
#define VELODYNE_LASERSCAN_VELODYNE_LASERSCAN_H
#include <ros/ros.h>
#include <sensor_msgs/PointCloud2.h>
#include <sensor_msgs/LaserScan.h>
#include <boost/thread/mutex.hpp>
#include <boost/thread/lock_guard.hpp>
#include <dynamic_reconfigure/server.h>
#include <velodyne_laserscan/VelodyneLaserScanConfig.h>
namespace velodyne_laserscan
{
class VelodyneLaserScan
{
public:
VelodyneLaserScan(ros::NodeHandle &nh, ros::NodeHandle &nh_priv);
private:
boost::mutex connect_mutex_;
void connectCb();
void recvCallback(const sensor_msgs::PointCloud2ConstPtr& msg);
ros::NodeHandle nh_;
ros::Subscriber sub_;
ros::Publisher pub_;
VelodyneLaserScanConfig cfg_;
dynamic_reconfigure::Server<VelodyneLaserScanConfig> srv_;
void reconfig(VelodyneLaserScanConfig& config, uint32_t level);
unsigned int ring_count_;
};
} // namespace velodyne_laserscan
#endif // VELODYNE_LASERSCAN_VELODYNE_LASERSCAN_H
| [
"runeg96@hotmail.com"
] | runeg96@hotmail.com |
f6ea4c5d6f7589afb911ea691b2a7e53374bac29 | c28ea5bdf8f0e08cec0dd0ff862775a347cace1e | /src/Fluid.cpp | 778695d4f981f4fa7e4a94b5707b5bda8035ffb7 | [] | no_license | NASGregorio/2DFluidNavierStokes | cca33fb331239aaae64c7a3e71e6baf375c1489f | 67ff54725bf34952c4bb1e757bb0bdb247de97d4 | refs/heads/master | 2020-04-23T05:03:11.925049 | 2019-02-17T23:13:03 | 2019-02-17T23:13:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,974 | cpp | #include "Fluid.h"
using namespace std;
#define IX(x, y) (x + y * N)
static void set_bnd(int b, float *x, int N)
{
for (int i = 1; i < N - 1; i++)
{
x[IX(i, 0)] = b == 2 ? -x[IX(i, 1)] : x[IX(i, 1)];
x[IX(i, N - 1)] = b == 2 ? -x[IX(i, N - 2)] : x[IX(i, N - 2)];
}
for (int j = 1; j < N - 1; j++)
{
x[IX(0, j)] = b == 1 ? -x[IX(1, j)] : x[IX(1, j)];
x[IX(N - 1, j)] = b == 1 ? -x[IX(N - 2, j)] : x[IX(N - 2, j)];
}
//for (int i = 1; i <= N; i++)
//{
// x[IX(i, 0)] = b == 2 ? -x[IX(i, 1)] : x[IX(i, 1)];
// x[IX(i, N - 1)] = b == 2 ? -x[IX(i, N - 2)] : x[IX(i, N - 2)];
// x[IX(0, i)] = b == 1 ? -x[IX(1, i)] : x[IX(1, i)];
// x[IX(N - 1, i)] = b == 1 ? -x[IX(N - 2, i)] : x[IX(N - 2, i)];
//}
x[IX(0, 0)] = 0.5f * (x[IX(1, 0)] + x[IX(0, 1)]);
x[IX(0, N - 1)] = 0.5f * (x[IX(1, N - 1)] + x[IX(0, N - 2)]);
x[IX(N - 1, 0)] = 0.5f * (x[IX(N - 2, 0)] + x[IX(N - 1, 1)]);
x[IX(N - 1, N - 1)] = 0.5f * (x[IX(N - 2, N - 1)] + x[IX(N - 1, N - 2)]);
}
static void lin_solve(int b, float *x, float *x0, float a, float c, int iter, int N)
{
float cRecip = 1.0f / c;
for (int k = 0; k < iter; k++)
{
for (int j = 1; j < N - 1; j++)
{
for (int i = 1; i < N - 1; i++)
{
x[IX(i, j)] = (x0[IX(i, j)] + a * (x[IX(i + 1, j)] + x[IX(i - 1, j)] + x[IX(i, j + 1)] + x[IX(i, j - 1)])) * cRecip; // Gauss-Seidel
}
}
set_bnd(b, x, N);
}
}
static void diffuse(int b, float *x, float *x0, float diff, float dt, int iter, int N)
{
float a = dt * diff * (N - 2) * (N - 2);
lin_solve(b, x, x0, a, 1 + 4 * a, iter, N);
}
static void advect(int b, float *d, float *d0, float *velocX, float *velocY, float dt, int N)
{
int i0, i1, j0, j1;
float dtx = dt * (N - 2);
float dty = dt * (N - 2);
float s0, s1, t0, t1;
float tmp1, tmp2, x, y;
float Nfloat = (float)N;
float ifloat, jfloat;
int i, j;
for (j = 1, jfloat = 1; j < N - 1; j++, jfloat++)
{
for (i = 1, ifloat = 1; i < N - 1; i++, ifloat++)
{
tmp1 = dtx * velocX[IX(i, j)];
tmp2 = dty * velocY[IX(i, j)];
x = ifloat - tmp1;
y = jfloat - tmp2;
if (x < 0.5f) x = 0.5f;
if (x > Nfloat + 0.5f) x = Nfloat + 0.5f;
i0 = static_cast<int>(floorf(x));
i1 = i0 + 1;
if (y < 0.5f) y = 0.5f;
if (y > Nfloat + 0.5f) y = Nfloat + 0.5f;
j0 = static_cast<int>(floorf(y));
j1 = j0 + 1;
s1 = x - i0;
s0 = 1.0f - s1;
t1 = y - j0;
t0 = 1.0f - t1;
d[IX(i, j)] = s0 * (t0 * d0[IX(i0, j0)] + t1 * d0[IX(i0, j1)]) +
s1 * (t0 * d0[IX(i1, j0)] + t1 * d0[IX(i1, j1)]);
}
}
set_bnd(b, d, N);
}
static void project(float *velocX, float *velocY, float *p, float *div, int iter, int N)
{
for (int j = 1; j < N - 1; j++)
{
for (int i = 1; i < N - 1; i++)
{
div[IX(i, j)] = -0.5f * (velocX[IX(i + 1, j)] - velocX[IX(i - 1, j)] + velocY[IX(i, j + 1)] - velocY[IX(i, j - 1)]) / N;
p[IX(i, j)] = 0;
}
}
set_bnd(0, div, N);
set_bnd(0, p, N);
lin_solve(0, p, div, 1, 4, iter, N);
for (int j = 1; j < N - 1; j++)
{
for (int i = 1; i < N - 1; i++)
{
velocX[IX(i, j)] -= 0.5f * (p[IX(i + 1, j)] - p[IX(i - 1, j)]) * N;
velocY[IX(i, j)] -= 0.5f * (p[IX(i, j + 1)] - p[IX(i, j - 1)]) * N;
}
}
set_bnd(1, velocX, N);
set_bnd(2, velocY, N);
}
Fluid::Fluid() {}
Fluid::~Fluid() {}
void Fluid::Clear(FluidGrid *square)
{
free(square->s);
free(square->density);
free(square->Vx);
free(square->Vy);
free(square->Vx0);
free(square->Vy0);
free(square);
}
void Fluid::Step(FluidGrid *square)
{
int N = square->size;
float visc = square->visc;
float diff = square->diff;
float dt = square->dt;
float *Vx = square->Vx;
float *Vy = square->Vy;
float *Vx0 = square->Vx0;
float *Vy0 = square->Vy0;
float *s = square->s;
float *density = square->density;
diffuse(1, Vx0, Vx, visc, dt, 4, N);
diffuse(2, Vy0, Vy, visc, dt, 4, N);
project(Vx0, Vy0, Vx, Vy, 4, N);
advect(1, Vx, Vx0, Vx0, Vy0, dt, N);
advect(2, Vy, Vy0, Vx0, Vy0, dt, N);
project(Vx, Vy, Vx0, Vy0, 4, N);
diffuse(0, s, density, diff, dt, 4, N);
advect(0, density, s, Vx, Vy, dt, N);
}
void Fluid::AddDensity(FluidGrid *square, int x, int y, float amount)
{
int N = square->size;
square->density[IX(x, y)] += amount;
}
void Fluid::AddVelocity(FluidGrid *square, int x, int y, float amountX, float amountY)
{
int N = square->size;
int index = IX(x, y);
square->Vx[index] += amountX;
square->Vy[index] += amountY;
}
Fluid::FluidGrid *Fluid::Create(int size, float diffusion, float viscosity, float dt)
{
FluidGrid *square = (FluidGrid*)malloc(sizeof(*square));
int N = size;
square->size = size;
square->dt = dt;
square->diff = diffusion;
square->visc = viscosity;
square->s = (float*)calloc(N * N, sizeof(float));
square->density = (float*)calloc(N * N, sizeof(float));
square->Vx = (float*)calloc(N * N, sizeof(float));
square->Vy = (float*)calloc(N * N, sizeof(float));
square->Vx0 = (float*)calloc(N * N, sizeof(float));
square->Vy0 = (float*)calloc(N * N, sizeof(float));
return square;
}
| [
"nelson.gregorio@live.com.pt"
] | nelson.gregorio@live.com.pt |
ad5df562fdff288ba6572fc7a8dadddc50b6627e | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/geometry/srs/projections/impl/pj_inv.hpp | 105e89de091f42f1c2031bce91d844301f220750 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,304 | hpp | // Boost.Geometry (aka GGL, Generic Geometry Library)
// This file is manually converted from PROJ4
// Copyright (c) 2008-2012 Barend Gehrels, Amsterdam, the Netherlands.
// This file was modified by Oracle on 2017.
// Modifications copyright (c) 2017, Oracle and/or its affiliates.
// Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle
// Use, modification and distribution is subject to 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)
// This file is converted from PROJ4, http://trac.osgeo.org/proj
// PROJ4 is originally written by Gerald Evenden (then of the USGS)
// PROJ4 is maintained by Frank Warmerdam
// PROJ4 is converted to Geometry Library by Barend Gehrels (Geodan, Amsterdam)
// Original copyright notice:
// 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 BOOST_GEOMETRY_PROJECTIONS_PJ_INV_HPP
#define BOOST_GEOMETRY_PROJECTIONS_PJ_INV_HPP
#include <sstd/boost/geometry/srs/projections/impl/adjlon.hpp>
#include <sstd/boost/geometry/core/radian_access.hpp>
#include <sstd/boost/geometry/util/math.hpp>
/* general inverse projection */
namespace boost { namespace geometry { namespace projections
{
namespace detail
{
/* inverse projection entry */
template <typename PRJ, typename LL, typename XY, typename PAR>
inline void pj_inv(PRJ const& prj, PAR const& par, XY const& xy, LL& ll)
{
typedef typename PAR::type calc_t;
static const calc_t EPS = 1.0e-12;
/* can't do as much preliminary checking as with forward */
/* descale and de-offset */
calc_t xy_x = (geometry::get<0>(xy) * par.to_meter - par.x0) * par.ra;
calc_t xy_y = (geometry::get<1>(xy) * par.to_meter - par.y0) * par.ra;
calc_t lon = 0, lat = 0;
prj.inv(xy_x, xy_y, lon, lat); /* inverse project */
lon += par.lam0; /* reduce from del lp.lam */
if (!par.over)
lon = adjlon(lon); /* adjust longitude to CM */
if (par.geoc && geometry::math::abs(geometry::math::abs(lat)-geometry::math::half_pi<calc_t>()) > EPS)
lat = atan(par.one_es * tan(lat));
geometry::set_from_radian<0>(ll, lon);
geometry::set_from_radian<1>(ll, lat);
}
} // namespace detail
}}} // namespace boost::geometry::projections
#endif
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
fc6959ecc8d2261048b8a9bc2f3539d79979c524 | 310d566e838c6c2fbac9864cab092be17b1ca37e | /C++/Pràctiques de laboratori/sequencies_II(1)/main.cpp | 0ad9de6df03d80c2bddc0102ab867b6630a05a32 | [] | no_license | MrRobertStark/C-plus-plus-codes | 1c6cad9af853964400d7b3b087e4f22ae9e351d7 | 4d968184eccd54cdd67ff3c5eec552fcc442177e | refs/heads/master | 2022-12-01T10:04:55.383249 | 2020-08-24T19:34:55 | 2020-08-24T19:34:55 | 290,140,151 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 2,027 | cpp | #include <iostream>
#include<string>
#include<fstream>
using namespace std;
const int PRECISIO=3;
//Entrada: Nom de fitxer
//Sortida: Retorna la mitjana de la longitud dels mots (3 decimals). Altrament missatge "cap mot!" si no existiex cap mot en el fitxer. O bé "Error d'apertura fitxer." si escau.
bool es_lletra(char c){
//Pre: C no ha de representar el final del fitxerr
//Post: Retorna cert si c és una lletra o no
bool resultat=false;
if(((c>='a') && (c<='z')) or ((c>='A')&&(c<='Z')))resultat=true;
return resultat;
}
char passa_separadors(char c,ifstream& nom_fitxer){
while(not es_lletra(c)&& not nom_fitxer.eof()){
nom_fitxer.get(c);
}
return c;
}
char passa_paraula(char& c, double& comptador_paraules, double& comptador_lletres,ifstream& nom_fitxer){
if(es_lletra(c)&& not nom_fitxer.eof()){
comptador_paraules++;
while(es_lletra(c)&& not nom_fitxer.eof()){
comptador_lletres++;
c=nom_fitxer.get();
}
}
return c;
}
void analisi_frase(ifstream& fitxer_principal){
//Pre: cert
//Post: calcula la mitjana de lletres en les paraules escrites en un fitxer
char c;
double comptador_paraules,comptador_lletres,mitjana;
comptador_paraules=comptador_lletres=0;
if(not fitxer_principal.fail()){
c=fitxer_principal.get();
while(not fitxer_principal.eof()){
passa_separadors(c,fitxer_principal);
passa_paraula(c,comptador_paraules,comptador_lletres,fitxer_principal);
}
mitjana=comptador_lletres/comptador_paraules;
if(comptador_paraules==0)cout<<"cap mot!"<<endl;
else cout<<mitjana<<endl;
}
else{
cout<<"Error d'apertura fitxer."<<endl;
}
}
int main(){
cout.setf(ios::fixed);
cout.precision(PRECISIO);
cout<<"Fitxer:"<<endl;
string nom;
cin>>nom;
ifstream fitxer_principal(nom.c_str());
cout<< "Mitjana longitud mot: ";
analisi_frase(fitxer_principal);
return 0;
}
| [
"69302922+MrRobertStark@users.noreply.github.com"
] | 69302922+MrRobertStark@users.noreply.github.com |
6581a17b1e70274c94080d7e5841838ad3516ee9 | f1bfee9c5583a356b4078755c2e664f8cbdca7e2 | /Shooting Balls 2016 (v 2.1)/Temp/StagingArea/Data/il2cppOutput/GeneratedGenericVirtualInvokers.h | ac8ceca0ea5d1892fb09f8dcfe4e80e4e3b73f12 | [] | no_license | MarckyMarc27/New | 6644fa7051df2e5bf2f59c1ef82b0a37b2fc26a0 | 2533b87c2ff89a7153724a176a1b67305c7b3053 | refs/heads/master | 2021-01-11T09:15:50.288935 | 2016-12-22T20:24:01 | 2016-12-22T20:24:01 | 77,173,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,643 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#pragma once
template <typename R>
struct GenericVirtFuncInvoker0
{
typedef R (*Func)(void*, const MethodInfo*);
static inline R Invoke (const MethodInfo* method, void* obj)
{
VirtualInvokeData invokeData;
il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData);
return ((Func)invokeData.methodPtr)(obj, invokeData.method);
}
};
template <typename T1>
struct GenericVirtActionInvoker1
{
typedef void (*Action)(void*, T1, const MethodInfo*);
static inline void Invoke (const MethodInfo* method, void* obj, T1 p1)
{
VirtualInvokeData invokeData;
il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData);
((Action)invokeData.methodPtr)(obj, p1, invokeData.method);
}
};
template <typename R, typename T1>
struct GenericVirtFuncInvoker1
{
typedef R (*Func)(void*, T1, const MethodInfo*);
static inline R Invoke (const MethodInfo* method, void* obj, T1 p1)
{
VirtualInvokeData invokeData;
il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData);
return ((Func)invokeData.methodPtr)(obj, p1, invokeData.method);
}
};
template <typename R, typename T1, typename T2, typename T3>
struct GenericVirtFuncInvoker3
{
typedef R (*Func)(void*, T1, T2, T3, const MethodInfo*);
static inline R Invoke (const MethodInfo* method, void* obj, T1 p1, T2 p2, T3 p3)
{
VirtualInvokeData invokeData;
il2cpp_codegen_get_generic_virtual_invoke_data(method, obj, &invokeData);
return ((Func)invokeData.methodPtr)(obj, p1, p2, p3, invokeData.method);
}
};
| [
"cournoyermarc2013@gmail.com"
] | cournoyermarc2013@gmail.com |
520aeb95096b5a45dfea9fed42804c54ef80446f | 861a09717edea2fbda93945af0a5962fcfa3a75e | /main.cc | 7cd3bd5eec75d63d893bde02c6399157beb25e05 | [] | no_license | AUTinker/blahblah | cffbf601716b23dbecb490a31eb77a53db8d039e | 557cc1e1f32eed7cc86abe15ed0eed01ef7b41be | refs/heads/master | 2021-01-23T07:08:44.615506 | 2013-09-27T20:43:00 | 2013-09-27T20:43:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84 | cc | #include <iostream>
int main() {
// hahah
std::cout<<"lalala"<<std:endl;
}
| [
"song@gao.io"
] | song@gao.io |
99816f1d2044903aa45b5f911962f3eedc65620f | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_repos_function_3959_git-2.14.0.cpp | b952d3071beb72f5bee7f329907f9a829c730abc | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | cpp | static void process_ls_object(struct remote_ls_ctx *ls)
{
unsigned int *parent = (unsigned int *)ls->userData;
const char *path = ls->dentry_name;
struct object_id oid;
if (!strcmp(ls->path, ls->dentry_name) && (ls->flags & IS_DIR)) {
remote_dir_exists[*parent] = 1;
return;
}
if (!skip_prefix(path, "objects/", &path) ||
get_oid_hex_from_objpath(path, &oid))
return;
one_remote_object(&oid);
} | [
"993273596@qq.com"
] | 993273596@qq.com |
bf41fcefd988cc233b8cdac3a06075411d110170 | dca653bb975528bd1b8ab2547f6ef4f48e15b7b7 | /tags/wxPy-2.9.5.0/src/gtk/font.cpp | e078010efa6dff4faa57ab017ab106bacd18e5e3 | [] | no_license | czxxjtu/wxPython-1 | 51ca2f62ff6c01722e50742d1813f4be378c0517 | 6a7473c258ea4105f44e31d140ea5c0ae6bc46d8 | refs/heads/master | 2021-01-15T12:09:59.328778 | 2015-01-05T20:55:10 | 2015-01-05T20:55:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,050 | cpp | /////////////////////////////////////////////////////////////////////////////
// Name: src/gtk/font.cpp
// Purpose: wxFont for wxGTK
// Author: Robert Roebling
// Id: $Id$
// Copyright: (c) 1998 Robert Roebling and Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#include "wx/font.h"
#ifndef WX_PRECOMP
#include "wx/log.h"
#include "wx/utils.h"
#include "wx/settings.h"
#include "wx/gdicmn.h"
#endif
#include "wx/fontutil.h"
#include "wx/tokenzr.h"
#include "wx/gtk/private.h"
// ----------------------------------------------------------------------------
// constants
// ----------------------------------------------------------------------------
// the default size (in points) for the fonts
static const int wxDEFAULT_FONT_SIZE = 12;
// ----------------------------------------------------------------------------
// wxFontRefData
// ----------------------------------------------------------------------------
class wxFontRefData : public wxGDIRefData
{
public:
// from broken down font parameters, also default ctor
wxFontRefData(int size = -1,
wxFontFamily family = wxFONTFAMILY_DEFAULT,
wxFontStyle style = wxFONTSTYLE_NORMAL,
wxFontWeight weight = wxFONTWEIGHT_NORMAL,
bool underlined = false,
bool strikethrough = false,
const wxString& faceName = wxEmptyString,
wxFontEncoding encoding = wxFONTENCODING_DEFAULT);
wxFontRefData(const wxString& nativeFontInfoString);
// copy ctor
wxFontRefData( const wxFontRefData& data );
virtual ~wxFontRefData();
// setters: all of them also take care to modify m_nativeFontInfo if we
// have it so as to not lose the information not carried by our fields
void SetPointSize(int pointSize);
void SetFamily(wxFontFamily family);
void SetStyle(wxFontStyle style);
void SetWeight(wxFontWeight weight);
void SetUnderlined(bool underlined);
void SetStrikethrough(bool strikethrough);
bool SetFaceName(const wxString& facename);
void SetEncoding(wxFontEncoding encoding);
// and this one also modifies all the other font data fields
void SetNativeFontInfo(const wxNativeFontInfo& info);
protected:
// common part of all ctors
void Init(int pointSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined,
bool strikethrough,
const wxString& faceName,
wxFontEncoding encoding);
// set all fields from (already initialized and valid) m_nativeFontInfo
void InitFromNative();
private:
// The native font info: basically a PangoFontDescription, plus
// 'underlined' and 'strikethrough' attributes not supported by Pango.
wxNativeFontInfo m_nativeFontInfo;
friend class wxFont;
};
#define M_FONTDATA ((wxFontRefData*)m_refData)
// ----------------------------------------------------------------------------
// wxFontRefData
// ----------------------------------------------------------------------------
void wxFontRefData::Init(int pointSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined,
bool strikethrough,
const wxString& faceName,
wxFontEncoding WXUNUSED(encoding))
{
if (family == wxFONTFAMILY_DEFAULT)
family = wxFONTFAMILY_SWISS;
// Create native font info
m_nativeFontInfo.description = pango_font_description_new();
// And set its values
if (!faceName.empty())
{
pango_font_description_set_family( m_nativeFontInfo.description,
wxGTK_CONV_SYS(faceName) );
}
else
{
SetFamily(family);
}
SetStyle( style == wxDEFAULT ? wxFONTSTYLE_NORMAL : style );
SetPointSize( (pointSize == wxDEFAULT || pointSize == -1)
? wxDEFAULT_FONT_SIZE
: pointSize );
SetWeight( weight == wxDEFAULT ? wxFONTWEIGHT_NORMAL : weight );
SetUnderlined( underlined );
SetStrikethrough( strikethrough );
}
void wxFontRefData::InitFromNative()
{
// Get native info
PangoFontDescription *desc = m_nativeFontInfo.description;
// Pango sometimes needs to have a size
int pango_size = pango_font_description_get_size( desc );
if (pango_size == 0)
m_nativeFontInfo.SetPointSize(wxDEFAULT_FONT_SIZE);
}
wxFontRefData::wxFontRefData( const wxFontRefData& data )
: wxGDIRefData()
{
// Forces a copy of the internal data. wxNativeFontInfo should probably
// have a copy ctor and assignment operator to fix this properly but that
// would break binary compatibility...
m_nativeFontInfo.FromString(data.m_nativeFontInfo.ToString());
}
wxFontRefData::wxFontRefData(int size, wxFontFamily family, wxFontStyle style,
wxFontWeight weight, bool underlined, bool strikethrough,
const wxString& faceName,
wxFontEncoding encoding)
{
Init(size, family, style, weight, underlined, strikethrough, faceName, encoding);
}
wxFontRefData::wxFontRefData(const wxString& nativeFontInfoString)
{
m_nativeFontInfo.FromString( nativeFontInfoString );
InitFromNative();
}
wxFontRefData::~wxFontRefData()
{
}
// ----------------------------------------------------------------------------
// wxFontRefData SetXXX()
// ----------------------------------------------------------------------------
void wxFontRefData::SetPointSize(int pointSize)
{
m_nativeFontInfo.SetPointSize(pointSize);
}
/*
NOTE: disabled because pango_font_description_set_absolute_size() and
wxDC::GetCharHeight() do not mix well: setting with the former a pixel
size of "30" makes the latter return 36...
Besides, we need to return GetPointSize() a point size value even if
SetPixelSize() was used and this would require further changes
(and use of pango_font_description_get_size_is_absolute in some places).
bool wxFontRefData::SetPixelSize(const wxSize& pixelSize)
{
wxCHECK_MSG( pixelSize.GetWidth() >= 0 && pixelSize.GetHeight() > 0, false,
"Negative values for the pixel size or zero pixel height are not allowed" );
if (wx_pango_version_check(1,8,0) != NULL ||
pixelSize.GetWidth() != 0)
{
// NOTE: pango_font_description_set_absolute_size() only sets the font height;
// if the user set the pixel width of the font explicitly or the pango
// library is too old, we cannot proceed
return false;
}
pango_font_description_set_absolute_size( m_nativeFontInfo.description,
pixelSize.GetHeight() * PANGO_SCALE );
return true;
}
*/
void wxFontRefData::SetFamily(wxFontFamily family)
{
m_nativeFontInfo.SetFamily(family);
}
void wxFontRefData::SetStyle(wxFontStyle style)
{
m_nativeFontInfo.SetStyle(style);
}
void wxFontRefData::SetWeight(wxFontWeight weight)
{
m_nativeFontInfo.SetWeight(weight);
}
void wxFontRefData::SetUnderlined(bool underlined)
{
m_nativeFontInfo.SetUnderlined(underlined);
}
void wxFontRefData::SetStrikethrough(bool strikethrough)
{
m_nativeFontInfo.SetStrikethrough(strikethrough);
}
bool wxFontRefData::SetFaceName(const wxString& facename)
{
return m_nativeFontInfo.SetFaceName(facename);
}
void wxFontRefData::SetEncoding(wxFontEncoding WXUNUSED(encoding))
{
// with GTK+ 2 Pango always uses UTF8 internally, we cannot change it
}
void wxFontRefData::SetNativeFontInfo(const wxNativeFontInfo& info)
{
m_nativeFontInfo = info;
// set all the other font parameters from the native font info
InitFromNative();
}
// ----------------------------------------------------------------------------
// wxFont creation
// ----------------------------------------------------------------------------
wxFont::wxFont(const wxNativeFontInfo& info)
{
Create( info.GetPointSize(),
info.GetFamily(),
info.GetStyle(),
info.GetWeight(),
info.GetUnderlined(),
info.GetFaceName(),
info.GetEncoding() );
if ( info.GetStrikethrough() )
SetStrikethrough(true);
}
wxFont::wxFont(const wxFontInfo& info)
{
m_refData = new wxFontRefData(info.GetPointSize(),
info.GetFamily(),
info.GetStyle(),
info.GetWeight(),
info.IsUnderlined(),
info.IsStrikethrough(),
info.GetFaceName(),
info.GetEncoding());
wxSize pixelSize = info.GetPixelSize();
if ( pixelSize != wxDefaultSize )
SetPixelSize(pixelSize);
}
bool wxFont::Create( int pointSize,
wxFontFamily family,
wxFontStyle style,
wxFontWeight weight,
bool underlined,
const wxString& face,
wxFontEncoding encoding )
{
UnRef();
m_refData = new wxFontRefData(pointSize, family, style, weight,
underlined, false, face, encoding);
return true;
}
bool wxFont::Create(const wxString& fontname)
{
// VZ: does this really happen?
if ( fontname.empty() )
{
*this = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
return true;
}
m_refData = new wxFontRefData(fontname);
return true;
}
wxFont::~wxFont()
{
}
// ----------------------------------------------------------------------------
// accessors
// ----------------------------------------------------------------------------
int wxFont::GetPointSize() const
{
wxCHECK_MSG( IsOk(), 0, wxT("invalid font") );
return M_FONTDATA->m_nativeFontInfo.GetPointSize();
}
wxString wxFont::GetFaceName() const
{
wxCHECK_MSG( IsOk(), wxEmptyString, wxT("invalid font") );
return M_FONTDATA->m_nativeFontInfo.GetFaceName();
}
wxFontFamily wxFont::DoGetFamily() const
{
return M_FONTDATA->m_nativeFontInfo.GetFamily();
}
wxFontStyle wxFont::GetStyle() const
{
wxCHECK_MSG( IsOk(), wxFONTSTYLE_MAX, wxT("invalid font") );
return M_FONTDATA->m_nativeFontInfo.GetStyle();
}
wxFontWeight wxFont::GetWeight() const
{
wxCHECK_MSG( IsOk(), wxFONTWEIGHT_MAX, wxT("invalid font") );
return M_FONTDATA->m_nativeFontInfo.GetWeight();
}
bool wxFont::GetUnderlined() const
{
wxCHECK_MSG( IsOk(), false, wxT("invalid font") );
return M_FONTDATA->m_nativeFontInfo.GetUnderlined();
}
bool wxFont::GetStrikethrough() const
{
wxCHECK_MSG( IsOk(), false, wxT("invalid font") );
return M_FONTDATA->m_nativeFontInfo.GetStrikethrough();
}
wxFontEncoding wxFont::GetEncoding() const
{
wxCHECK_MSG( IsOk(), wxFONTENCODING_SYSTEM, wxT("invalid font") );
return wxFONTENCODING_UTF8;
// Pango always uses UTF8... see also SetEncoding()
}
const wxNativeFontInfo *wxFont::GetNativeFontInfo() const
{
wxCHECK_MSG( IsOk(), NULL, wxT("invalid font") );
return &(M_FONTDATA->m_nativeFontInfo);
}
bool wxFont::IsFixedWidth() const
{
wxCHECK_MSG( IsOk(), false, wxT("invalid font") );
return wxFontBase::IsFixedWidth();
}
// ----------------------------------------------------------------------------
// change font attributes
// ----------------------------------------------------------------------------
void wxFont::SetPointSize(int pointSize)
{
AllocExclusive();
M_FONTDATA->SetPointSize(pointSize);
}
void wxFont::SetFamily(wxFontFamily family)
{
AllocExclusive();
M_FONTDATA->SetFamily(family);
}
void wxFont::SetStyle(wxFontStyle style)
{
AllocExclusive();
M_FONTDATA->SetStyle(style);
}
void wxFont::SetWeight(wxFontWeight weight)
{
AllocExclusive();
M_FONTDATA->SetWeight(weight);
}
bool wxFont::SetFaceName(const wxString& faceName)
{
AllocExclusive();
return M_FONTDATA->SetFaceName(faceName) &&
wxFontBase::SetFaceName(faceName);
}
void wxFont::SetUnderlined(bool underlined)
{
AllocExclusive();
M_FONTDATA->SetUnderlined(underlined);
}
void wxFont::SetStrikethrough(bool strikethrough)
{
AllocExclusive();
M_FONTDATA->SetStrikethrough(strikethrough);
}
void wxFont::SetEncoding(wxFontEncoding encoding)
{
AllocExclusive();
M_FONTDATA->SetEncoding(encoding);
}
void wxFont::DoSetNativeFontInfo( const wxNativeFontInfo& info )
{
AllocExclusive();
M_FONTDATA->SetNativeFontInfo( info );
}
wxGDIRefData* wxFont::CreateGDIRefData() const
{
return new wxFontRefData;
}
wxGDIRefData* wxFont::CloneGDIRefData(const wxGDIRefData* data) const
{
return new wxFontRefData(*static_cast<const wxFontRefData*>(data));
}
bool wxFont::GTKSetPangoAttrs(PangoLayout* layout) const
{
if (!IsOk() || !(GetUnderlined() || GetStrikethrough()))
return false;
PangoAttrList* attrs = pango_attr_list_new();
PangoAttribute* a;
if (wx_pango_version_check(1,16,0))
{
// a PangoLayout which has leading/trailing spaces with underlined font
// is not correctly drawn by this pango version: Pango won't underline the spaces.
// This can be a problem; e.g. wxHTML rendering of underlined text relies on
// this behaviour. To workaround this problem, we use a special hack here
// suggested by pango maintainer Behdad Esfahbod: we prepend and append two
// empty space characters and give them a dummy colour attribute.
// This will force Pango to underline the leading/trailing spaces, too.
const char* text = pango_layout_get_text(layout);
const size_t n = strlen(text);
if ((n > 0 && text[0] == ' ') || (n > 1 && text[n - 1] == ' '))
{
wxCharBuffer buf(n + 6);
// copy the leading U+200C ZERO WIDTH NON-JOINER encoded in UTF8 format
memcpy(buf.data(), "\342\200\214", 3);
// copy the user string
memcpy(buf.data() + 3, text, n);
// copy the trailing U+200C ZERO WIDTH NON-JOINER encoded in UTF8 format
memcpy(buf.data() + 3 + n, "\342\200\214", 3);
pango_layout_set_text(layout, buf, n + 6);
// Add dummy attributes (use colour as it's invisible anyhow for 0
// width spaces) to ensure that the spaces in the beginning/end of the
// string are underlined too.
a = pango_attr_foreground_new(0x0057, 0x52A9, 0xD614);
a->start_index = 0;
a->end_index = 3;
pango_attr_list_insert(attrs, a);
a = pango_attr_foreground_new(0x0057, 0x52A9, 0xD614);
a->start_index = n + 3;
a->end_index = n + 6;
pango_attr_list_insert(attrs, a);
}
}
if (GetUnderlined())
{
a = pango_attr_underline_new(PANGO_UNDERLINE_SINGLE);
pango_attr_list_insert(attrs, a);
}
if (GetStrikethrough())
{
a = pango_attr_strikethrough_new(true);
pango_attr_list_insert(attrs, a);
}
pango_layout_set_attributes(layout, attrs);
pango_attr_list_unref(attrs);
return true;
}
| [
"RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775"
] | RD@c3d73ce0-8a6f-49c7-b76d-6d57e0e08775 |
d990d6612c8d5dcbc081a32214eaa00340058445 | 89db51e6d6efb9d8f28271bb3364749093055818 | /src/qt/pivx/dashboardwidget.h | 454fe1fd6be88c250793de0c8fe45283fac0f23d | [
"MIT"
] | permissive | theabundancecoin/TACC | 3b194dc27b7f745d2a9562c0101521441eb09774 | fd7d38c6a04dcb2da3b2755879b153b4731cddb2 | refs/heads/master | 2023-08-16T04:46:13.970622 | 2021-10-02T19:35:04 | 2021-10-02T19:35:04 | 389,910,291 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,804 | h | // Copyright (c) 2019-2020 The TaccCoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DASHBOARDWIDGET_H
#define DASHBOARDWIDGET_H
#include "qt/pivx/pwidget.h"
#include "qt/pivx/furabstractlistitemdelegate.h"
#include "qt/pivx/furlistrow.h"
#include "transactiontablemodel.h"
#include "qt/pivx/txviewholder.h"
#include "transactionfilterproxy.h"
#include <atomic>
#include <cstdlib>
#include <QWidget>
#include <QLineEdit>
#include <QMap>
#if defined(HAVE_CONFIG_H)
#include "config/pivx-config.h" /* for USE_QTCHARTS */
#endif
#ifdef USE_QTCHARTS
#include <QtCharts/QChartView>
#include <QtCharts/QBarSeries>
#include <QtCharts/QBarCategoryAxis>
#include <QtCharts/QBarSet>
#include <QtCharts/QChart>
#include <QtCharts/QValueAxis>
QT_CHARTS_USE_NAMESPACE
using namespace QtCharts;
#endif
class PIVXGUI;
class WalletModel;
namespace Ui {
class DashboardWidget;
}
class SortEdit : public QLineEdit{
Q_OBJECT
public:
explicit SortEdit(QWidget* parent = nullptr) : QLineEdit(parent){}
inline void mousePressEvent(QMouseEvent *) override{
Q_EMIT Mouse_Pressed();
}
~SortEdit() override{}
Q_SIGNALS:
void Mouse_Pressed();
};
enum SortTx {
DATE_DESC = 0,
DATE_ASC = 1,
AMOUNT_DESC = 2,
AMOUNT_ASC = 3
};
enum ChartShowType {
ALL,
YEAR,
MONTH,
DAY
};
class ChartData {
public:
ChartData() {}
QMap<int, std::pair<qint64, qint64>> amountsByCache;
qreal maxValue = 0;
qint64 totalPiv = 0;
qint64 totalZpiv = 0;
QList<qreal> valuesPiv;
QList<qreal> valueszPiv;
QStringList xLabels;
};
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
class DashboardWidget : public PWidget
{
Q_OBJECT
public:
explicit DashboardWidget(PIVXGUI* _window);
~DashboardWidget();
void loadWalletModel() override;
void loadChart();
void run(int type) override;
void onError(QString error, int type) override;
public Q_SLOTS:
void walletSynced(bool isSync);
/**
* Show incoming transaction notification for new transactions.
* The new items are those between start and end inclusive, under the given parent item.
*/
void processNewTransaction(const QModelIndex& parent, int start, int /*end*/);
Q_SIGNALS:
/** Notify that a new transaction appeared */
void incomingTransaction(const QString& date, int unit, const CAmount& amount, const QString& type, const QString& address);
private Q_SLOTS:
void handleTransactionClicked(const QModelIndex &index);
void changeTheme(bool isLightTheme, QString &theme) override;
void onSortChanged(const QString&);
void onSortTypeChanged(const QString& value);
void updateDisplayUnit();
void showList();
void onTxArrived(const QString& hash, const bool& isCoinStake, const bool& isCSAnyType);
#ifdef USE_QTCHARTS
void windowResizeEvent(QResizeEvent* event);
void changeChartColors();
void onChartYearChanged(const QString&);
void onChartMonthChanged(const QString&);
void onChartArrowClicked(bool goLeft);
#endif
private:
Ui::DashboardWidget *ui{nullptr};
FurAbstractListItemDelegate* txViewDelegate{nullptr};
TransactionFilterProxy* filter{nullptr};
TxViewHolder* txHolder{nullptr};
TransactionTableModel* txModel{nullptr};
int nDisplayUnit{-1};
bool isSync{false};
void changeSort(int nSortIndex);
#ifdef USE_QTCHARTS
int64_t lastRefreshTime{0};
std::atomic<bool> isLoading;
// Chart
TransactionFilterProxy* stakesFilter{nullptr};
bool isChartInitialized{false};
QChartView *chartView{nullptr};
QBarSeries *series{nullptr};
QBarSet *set0{nullptr};
QBarSet *set1{nullptr};
QBarCategoryAxis *axisX{nullptr};
QValueAxis *axisY{nullptr};
QChart *chart{nullptr};
bool isChartMin{false};
ChartShowType chartShow{YEAR};
int yearFilter{0};
int monthFilter{0};
int dayStart{1};
bool hasZpivStakes{false};
ChartData* chartData{nullptr};
bool hasStakes{false};
bool fShowCharts{true};
std::atomic<bool> filterUpdateNeeded{false};
void initChart();
void showHideEmptyChart(bool show, bool loading, bool forceView = false);
bool refreshChart();
void tryChartRefresh();
void updateStakeFilter();
const QMap<int, std::pair<qint64, qint64>> getAmountBy();
bool loadChartData(bool withMonthNames);
void updateAxisX(const QStringList *arg = nullptr);
void setChartShow(ChartShowType type);
std::pair<int, int> getChartRange(QMap<int, std::pair<qint64, qint64>> amountsBy);
private Q_SLOTS:
void onChartRefreshed();
void onHideChartsChanged(bool fHide);
#endif
};
#endif // DASHBOARDWIDGET_H
| [
"alexdevchain@yandex.com"
] | alexdevchain@yandex.com |
f435fd63b272345cf6b682c937e5692e6aa599ca | 710ecac0f3c5d2dc9c8bbea729f88c88d80b572e | /examples/Trace/Trace.ino | 5fd75629959cefaa733c17aea45eb100bbdcbffc | [
"MIT"
] | permissive | Qiyd81/MultiPing | 54d71e69c32390f7285b49f477fcb7f52e69e094 | db61b37defd278af07ca96c4e40b02f28177a705 | refs/heads/master | 2022-04-26T21:18:16.232459 | 2020-04-29T15:06:41 | 2020-04-29T15:06:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 631 | ino | #include <PrintEx.h>
//#include "avrheap.h"
#include <MultiPingTrace.h>
//Avrheap myheap;
StreamEx out(Serial);
using namespace MultiPing;
void afterDump() {
//myheap.heapWalk();
while(true) ;
}
void setup() {
Serial.begin(115200);
while (!Serial) ;
delay(500);
Serial.println("Trace_example");
TRACE_START(&out)
TRACE_STOPAFTERDUMP(afterDump)
TRACE_TIMESTAMP(0,1)
TRACE_VALUE(0,10,1234)
TRACE_POINTER(0,20,&out)
TRACE_TIMESTAMP(0,2)
// TRACE_DUMP
// TRACE_STOP
//myheap.heapWalk();
}
void loop() {
TRACE_TIMESTAMP(0,1)
TRACE_VALUE(0,10,1234)
TRACE_POINTER(0,20,&out)
TRACE_TIMESTAMP(0,2)
}
| [
"lintond@gmail.com"
] | lintond@gmail.com |
d9c3eb3b4ef31cb78d3a4382379559eb76aa5ed7 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_2449486_0/C++/emaxx/B.cpp | 3eb9555af9f82d3119e837237d8bc8ee626d13cd | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,756 | cpp | #define _CRT_SECURE_NO_DEPRECATE
#define _SECURE_SCL 0
#pragma comment (linker, "/STACK:200000000")
#include <algorithm>
#include <bitset>
#include <cmath>
#include <ctime>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <stack>
#include <sstream>
#include <vector>
using namespace std;
typedef long long int64;
//typedef double old_double;
//#define double long double
const int INF = (int) 1E9;
const int64 INF64 = (int64) 1E18;
const double EPS = 1E-9;
const double PI = acos((double)0) * 2;
#define forn(i,n) for (int i=0; i<int(n); ++i)
#define ford(i,n) for (int i=int(n)-1; i>=0; --i)
#define fore(i,l,n) for (int i=int(l); i<int(n); ++i)
#define all(a) a.begin(), a.end()
#define fs first
#define sc second
#define pb push_back
#define mp make_pair
const int MAXN = 110;
int n, m, a[MAXN][MAXN], row[MAXN], col[MAXN];
void read() {
cin >> n >> m;
forn(i,n)
forn(j,m)
scanf("%d", &a[i][j]);
}
void solve() {
memset(row, 0, sizeof row);
memset(col, 0, sizeof col);
forn(i,n) {
forn(j,m) {
row[i] = max(row[i], a[i][j]);
col[j] = max(col[j], a[i][j]);
}
}
bool ok = true;
forn(i,n)
forn(j,m)
ok &= a[i][j] == min(row[i], col[j]);
if (ok) {
puts("YES");
return;
}
puts("NO");
}
int main() {
freopen ("input.txt", "rt", stdin);
freopen ("output.txt", "wt", stdout);
int ts;
cin >> ts;
forn(tt,ts) {
read();
if (! cin) throw;
printf ("Case #%d: ", tt+1);
solve();
}
} | [
"eewestman@gmail.com"
] | eewestman@gmail.com |
c5664f7ca8aead5d421be0b8f8d68782b5fa6e54 | dc64cbe907bce51f3b606fd915839c63eda69c8b | /source/cartint/methods.h | 416a146a314eb74eb1e1d434084422bb441a26cc | [] | no_license | Oo1Insane1oO/Cartint | 630ec682eae78d82f921d74027dd06f6ec39149a | ab3e6ef263ab4d736b73df2f30b75672efc15f3c | refs/heads/master | 2020-08-11T20:25:32.277977 | 2019-10-12T16:33:11 | 2019-10-12T16:33:11 | 214,621,923 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,242 | h | #ifndef METHODS_H
#define METHODS_H
#include <Eigen/Dense>
#include <string>
#include <iostream>
#include <iomanip>
class Methods {
private:
Methods ();
virtual ~Methods ();
public:
static void printProgressBar(std::string&, const float&, const int,
const std::string& extra="");
static std::string stringPos(const unsigned int&, const int&);
static int divider(const unsigned int&, const unsigned int&, const
int&);
static void setDisplacement(int[], int[], const int[], int);
template <typename T> static inline T refSum(const Eigen::Matrix<T*,
Eigen::Dynamic, 1>& vec) {
/* sum values of a vector of pointers(de-reference and sum) */
T sum = 0;
for (unsigned int i = 0; i < vec.size(); ++i) {
sum += *(vec(i));
} // end fori
return sum;
} // end function refSum
template<typename T> static void setMax(T& a, T b) {
/* set a to max of a and b */
if (b > a) {
a = b;
} // end if
} // end function setMax
template<typename T> static void setMin(T& a, T b) {
/* set a to min of a and b */
if (b < a) {
a = b;
} // end if
} // end function setMax
struct expand {
/* struct for expanding function pack */
template<typename... T> expand(T&&...) {}
};
template<typename T, typename... Args> static inline T max(T arg0,
Args... args) {
/* return maximum of args */
T prev = arg0;
expand{0, (setMax(prev, args), 0)...};
return prev;
} // end function max
template<typename T, typename... Args> static inline T min(T arg0,
Args... args) {
/* return minimum of args */
T prev = arg0;
expand{0, (setMin(prev, args), 0)...};
return prev;
} // end function max
template<typename T> static inline void print1(T arg) {
std::cout << arg << " ";
} // end function print1
template<typename... Args> static inline void sepPrint(Args... args) {
/* print args with spaces */
expand{0, (print1(args), 0)...};
std::cout << "\n";
} // end function sepPrint
template<typename T> static inline void refSum(Eigen::Array<T,
Eigen::Dynamic, 1>& buffer, const Eigen::Array<T*,
Eigen::Dynamic, 1>& refArray) {
/* override for expansion with more than 1 array */
for (unsigned int i = 0; i < buffer.size(); ++i) {
buffer(i) += *(refArray(i));
} // end fori
} // end function refSum
template<typename T, typename ...Args> static inline void
refSum(Eigen::Array<T, Eigen::Dynamic, 1>& buffer, const Args&...
arrays) {
/* sum arrays Elementwise */
expand{0, (refSum(buffer, arrays), 0)...};
} // end function refSum
};
#endif /* METHODS_H */
| [
"alocia0@gmail.com"
] | alocia0@gmail.com |
8eb71b2b9bbba846d16bf1df022a4861a4435c88 | 7b529d8566deae401c798531413a188c9618f331 | /tests/unit/api/c/test_llrp_manager.cpp | 0f481e43ace28aff32422195b0dfae885ad2c464 | [
"Apache-2.0"
] | permissive | ETCLabs/RDMnet | 2135ff974c264dd9759951ee8bee1ff0b5bf7742 | b254f1a5e4fe8ebc986ae6d5a24a2fe49b2e8e9c | refs/heads/main | 2023-04-15T13:37:16.082314 | 2023-04-10T15:50:19 | 2023-04-10T15:50:19 | 137,389,831 | 35 | 16 | Apache-2.0 | 2022-09-12T17:10:19 | 2018-06-14T17:40:11 | C | UTF-8 | C++ | false | false | 3,574 | cpp | /******************************************************************************
* Copyright 2020 ETC 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.
******************************************************************************
* This file is a part of RDMnet. For more information, go to:
* https://github.com/ETCLabs/RDMnet
*****************************************************************************/
#include "rdmnet/llrp_manager.h"
#include "etcpal/cpp/uuid.h"
#include "rdmnet_mock/core/common.h"
#include "rdmnet_mock/core/llrp_manager.h"
#include "gtest/gtest.h"
#include "fff.h"
FAKE_VOID_FUNC(handle_llrp_manager_target_discovered, llrp_manager_t, const LlrpDiscoveredTarget*, void*);
FAKE_VOID_FUNC(handle_llrp_manager_rdm_response_received, llrp_manager_t, const LlrpRdmResponse*, void*);
FAKE_VOID_FUNC(handle_llrp_manager_discovery_finished, llrp_manager_t, void*);
class TestLlrpManagerApi;
static TestLlrpManagerApi* current_test_fixture{nullptr};
class TestLlrpManagerApi : public testing::Test
{
public:
LlrpManagerConfig config_ = LLRP_MANAGER_CONFIG_DEFAULT_INIT;
protected:
static constexpr uint16_t kTestManufId = 0x1234;
void ResetLocalFakes()
{
RESET_FAKE(handle_llrp_manager_target_discovered);
RESET_FAKE(handle_llrp_manager_rdm_response_received);
RESET_FAKE(handle_llrp_manager_discovery_finished);
}
void SetUp() override
{
current_test_fixture = this;
ResetLocalFakes();
rdmnet_mock_core_reset();
ASSERT_EQ(rdmnet_init(nullptr, nullptr), kEtcPalErrOk);
config_.manu_id = 0x6574;
config_.netint.index = 1;
config_.netint.ip_type = kEtcPalIpTypeV4;
config_.cid = etcpal::Uuid::FromString("69c437e5-936e-4a6d-8d75-0a35512a0277").get();
llrp_manager_config_set_callbacks(&config_, handle_llrp_manager_target_discovered,
handle_llrp_manager_rdm_response_received, handle_llrp_manager_discovery_finished,
nullptr);
}
void TearDown() override
{
rdmnet_deinit();
current_test_fixture = nullptr;
}
};
TEST_F(TestLlrpManagerApi, CreateRegistersManagerCorrectly)
{
rc_llrp_manager_register_fake.custom_fake = [](RCLlrpManager* manager) {
EXPECT_NE(manager, nullptr);
EXPECT_NE(manager->lock, nullptr);
EXPECT_EQ(manager->cid, current_test_fixture->config_.cid);
EXPECT_EQ(manager->netint.index, current_test_fixture->config_.netint.index);
EXPECT_EQ(manager->netint.ip_type, current_test_fixture->config_.netint.ip_type);
EXPECT_EQ(RDM_GET_MANUFACTURER_ID(&manager->uid), current_test_fixture->config_.manu_id);
EXPECT_NE(manager->callbacks.rdm_response_received, nullptr);
EXPECT_NE(manager->callbacks.discovery_finished, nullptr);
EXPECT_NE(manager->callbacks.target_discovered, nullptr);
EXPECT_NE(manager->callbacks.destroyed, nullptr);
return kEtcPalErrOk;
};
llrp_manager_t handle;
EXPECT_EQ(llrp_manager_create(&config_, &handle), kEtcPalErrOk);
EXPECT_EQ(rc_llrp_manager_register_fake.call_count, 1u);
}
| [
"samuelmkearney@gmail.com"
] | samuelmkearney@gmail.com |
bcd7953151a239391f8f1ad1b17c86c83bb06bf3 | fb7f17ed0d5fd1ccfd8dc8206c49d4627228d254 | /Array/Duplicates_in_array.cpp | 0d5acfbd48278101770b448e7283664b544af7a4 | [] | no_license | vikashkumar2020/Ace-DSA | ef2569e03158ef4ed9ed793008073f0d7fe7f9d4 | c63c2b09b010d9bec23bbca0452db42bfb9e7a86 | refs/heads/main | 2023-08-28T09:08:57.619771 | 2021-11-06T04:24:17 | 2021-11-06T04:24:17 | 401,689,633 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,024 | cpp | // https://leetcode.com/problems/find-the-duplicate-number/
#include <bits/stdc++.h>
using namespace std;
int duplicates(vector<int>& nums) {
int curr_1 = nums[0];
int curr_2 = nums[0];
while (1) {
curr_1 = nums[curr_1];
curr_2 = nums[nums[curr_2]];
if (curr_1 == curr_2) break;
}
curr_1 = nums[0];
while (curr_1!=curr_2) {
curr_1 = nums[curr_1];
curr_2 = nums[curr_2];
}
return curr_2;
// method 2
// unordered_map<int, int> m_map;
// for(const auto& n : nums)
// {
// if(m_map.count(n) > 0)
// return n;
// m_map[n]++;
// }
}
int main() {
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
vector<int>a(n);
for (int i = 0; i < n; i++) cin >> a[i];
int ans = duplicates(a);
cout<<ans;
cout << endl;
}
return 0;
} | [
"kvvik2020@gmail.com"
] | kvvik2020@gmail.com |
be2ecfccb5c91c2d81f9b15b7056c5f837cb9583 | fe6d55233610a0c78cfd63cc25564400982b0a4e | /examples/openglviewer/shaders/no_skinning.vert_inc.hh | 12b778bd96af110f04b1fd96ec1ad16862436c19 | [
"Zlib",
"MIT",
"MIT-0",
"BSD-3-Clause",
"ISC",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | syoyo/tinyusdz | 6cc9c18ec4df61a514571cda8a5f8c3ee4ef279a | cf6e7f3c6428135109c1d66a261e9291b06f4970 | refs/heads/dev | 2023-08-19T06:06:10.594203 | 2023-08-18T12:34:09 | 2023-08-18T12:34:09 | 255,649,890 | 345 | 23 | MIT | 2023-07-14T09:20:59 | 2020-04-14T15:36:33 | C++ | UTF-8 | C++ | false | false | 11,668 | hh | // input filename: shaders/no_skinning.vert
unsigned char shaders_no_skinning_vert[] = {
0x0a, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x20, 0x28, 0x6c, 0x6f, 0x63,
0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x30, 0x29, 0x20, 0x69,
0x6e, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74,
0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x3b, 0x0a, 0x6c,
0x61, 0x79, 0x6f, 0x75, 0x74, 0x20, 0x28, 0x6c, 0x6f, 0x63, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x31, 0x29, 0x20, 0x69, 0x6e, 0x20,
0x76, 0x65, 0x63, 0x33, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x6e,
0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x3b, 0x0a, 0x6c, 0x61, 0x79, 0x6f, 0x75,
0x74, 0x20, 0x28, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20,
0x3d, 0x20, 0x32, 0x29, 0x20, 0x69, 0x6e, 0x20, 0x76, 0x65, 0x63, 0x32,
0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x75, 0x76, 0x3b, 0x0a, 0x6c,
0x61, 0x79, 0x6f, 0x75, 0x74, 0x20, 0x28, 0x6c, 0x6f, 0x63, 0x61, 0x74,
0x69, 0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x33, 0x29, 0x20, 0x69, 0x6e, 0x20,
0x76, 0x65, 0x63, 0x34, 0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x63,
0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x3b, 0x0a, 0x6c, 0x61, 0x79, 0x6f, 0x75,
0x74, 0x20, 0x28, 0x6c, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20,
0x3d, 0x20, 0x34, 0x29, 0x20, 0x69, 0x6e, 0x20, 0x76, 0x65, 0x63, 0x34,
0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x6a, 0x6f, 0x69, 0x6e, 0x74,
0x73, 0x3b, 0x0a, 0x6c, 0x61, 0x79, 0x6f, 0x75, 0x74, 0x20, 0x28, 0x6c,
0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x35, 0x29,
0x20, 0x69, 0x6e, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x69, 0x6e, 0x70,
0x75, 0x74, 0x5f, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x73, 0x3b, 0x0a,
0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6d, 0x61, 0x74,
0x34, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x6c, 0x3b, 0x0a, 0x75, 0x6e, 0x69,
0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6d, 0x61, 0x74, 0x34, 0x20, 0x6d, 0x76,
0x70, 0x3b, 0x0a, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x6d,
0x61, 0x74, 0x33, 0x20, 0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x3b, 0x0a,
0x2f, 0x2f, 0x75, 0x6e, 0x69, 0x66, 0x6f, 0x72, 0x6d, 0x20, 0x69, 0x6e,
0x74, 0x20, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x6a, 0x6f, 0x69,
0x6e, 0x74, 0x3b, 0x0a, 0x0a, 0x2f, 0x2f, 0x75, 0x6e, 0x69, 0x66, 0x6f,
0x72, 0x6d, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x61, 0x63, 0x74, 0x69,
0x76, 0x65, 0x5f, 0x76, 0x65, 0x72, 0x74, 0x65, 0x78, 0x3b, 0x0a, 0x0a,
0x6f, 0x75, 0x74, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x69, 0x6e, 0x74,
0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x6e, 0x6f,
0x72, 0x6d, 0x61, 0x6c, 0x3b, 0x0a, 0x6f, 0x75, 0x74, 0x20, 0x76, 0x65,
0x63, 0x33, 0x20, 0x66, 0x72, 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x5f,
0x77, 0x6f, 0x72, 0x6c, 0x64, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x3b, 0x0a, 0x6f, 0x75, 0x74, 0x20, 0x76, 0x65, 0x63, 0x34,
0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65,
0x64, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x3b, 0x0a, 0x0a, 0x6f,
0x75, 0x74, 0x20, 0x76, 0x65, 0x63, 0x32, 0x20, 0x69, 0x6e, 0x74, 0x65,
0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x75, 0x76, 0x3b,
0x0a, 0x6f, 0x75, 0x74, 0x20, 0x76, 0x65, 0x63, 0x34, 0x20, 0x69, 0x6e,
0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x77,
0x65, 0x69, 0x67, 0x68, 0x74, 0x73, 0x3b, 0x0a, 0x0a, 0x2f, 0x2f, 0x6f,
0x75, 0x74, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x20, 0x73, 0x65, 0x6c,
0x65, 0x63, 0x74, 0x65, 0x64, 0x3b, 0x0a, 0x0a, 0x76, 0x65, 0x63, 0x33,
0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x5f, 0x74, 0x6f, 0x5f, 0x72, 0x67,
0x62, 0x28, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x20, 0x76, 0x61, 0x6c, 0x75,
0x65, 0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, 0x33, 0x28,
0x30, 0x2e, 0x30, 0x66, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x66, 0x2c, 0x20,
0x30, 0x2e, 0x30, 0x66, 0x29, 0x3b, 0x0a, 0x0a, 0x69, 0x66, 0x28, 0x76,
0x61, 0x6c, 0x75, 0x65, 0x20, 0x3c, 0x20, 0x30, 0x2e, 0x30, 0x30, 0x30,
0x30, 0x31, 0x66, 0x29, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20,
0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x3b, 0x0a, 0x0a, 0x20, 0x76, 0x61, 0x6c,
0x75, 0x65, 0x20, 0x2a, 0x3d, 0x20, 0x32, 0x2e, 0x30, 0x66, 0x3b, 0x0a,
0x0a, 0x20, 0x69, 0x66, 0x28, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x3c,
0x20, 0x30, 0x2e, 0x35, 0x66, 0x29, 0x0a, 0x20, 0x7b, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x2e, 0x62, 0x20, 0x3d, 0x20,
0x31, 0x2e, 0x30, 0x66, 0x20, 0x2d, 0x20, 0x28, 0x76, 0x61, 0x6c, 0x75,
0x65, 0x20, 0x2b, 0x20, 0x30, 0x2e, 0x35, 0x66, 0x29, 0x3b, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x2e, 0x67, 0x20, 0x3d,
0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x2b, 0x20, 0x30, 0x2e, 0x35,
0x66, 0x3b, 0x0a, 0x20, 0x7d, 0x0a, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x0a,
0x20, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x76, 0x61, 0x6c, 0x75, 0x65,
0x20, 0x3d, 0x20, 0x28, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x2a, 0x20,
0x32, 0x2e, 0x30, 0x66, 0x29, 0x20, 0x2d, 0x20, 0x31, 0x2e, 0x30, 0x66,
0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x2e,
0x67, 0x20, 0x3d, 0x20, 0x31, 0x2e, 0x30, 0x66, 0x20, 0x2d, 0x20, 0x28,
0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x2b, 0x20, 0x30, 0x2e, 0x35, 0x66,
0x29, 0x3b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72,
0x2e, 0x72, 0x20, 0x3d, 0x20, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x20, 0x2b,
0x20, 0x30, 0x2e, 0x35, 0x66, 0x3b, 0x0a, 0x20, 0x7d, 0x0a, 0x0a, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x63, 0x6f, 0x6c, 0x6f,
0x72, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x76, 0x65, 0x63, 0x34, 0x20, 0x77,
0x65, 0x69, 0x67, 0x68, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x28,
0x29, 0x0a, 0x7b, 0x0a, 0x20, 0x20, 0x76, 0x65, 0x63, 0x33, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, 0x33, 0x28,
0x30, 0x2e, 0x30, 0x66, 0x2c, 0x20, 0x30, 0x2e, 0x30, 0x66, 0x2c, 0x20,
0x30, 0x2e, 0x30, 0x66, 0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x66,
0x28, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x6a, 0x6f, 0x69, 0x6e, 0x74,
0x73, 0x2e, 0x78, 0x20, 0x3d, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74,
0x28, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x6a, 0x6f, 0x69, 0x6e,
0x74, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f,
0x72, 0x20, 0x2b, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x5f, 0x74,
0x6f, 0x5f, 0x72, 0x67, 0x62, 0x28, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f,
0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x73, 0x2e, 0x78, 0x29, 0x3b, 0x0a,
0x0a, 0x20, 0x20, 0x69, 0x66, 0x28, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f,
0x6a, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x2e, 0x79, 0x20, 0x3d, 0x3d, 0x20,
0x66, 0x6c, 0x6f, 0x61, 0x74, 0x28, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65,
0x5f, 0x6a, 0x6f, 0x69, 0x6e, 0x74, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x2b, 0x3d, 0x20, 0x66, 0x6c,
0x6f, 0x61, 0x74, 0x5f, 0x74, 0x6f, 0x5f, 0x72, 0x67, 0x62, 0x28, 0x69,
0x6e, 0x70, 0x75, 0x74, 0x5f, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x73,
0x2e, 0x79, 0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x69, 0x66, 0x28, 0x69,
0x6e, 0x70, 0x75, 0x74, 0x5f, 0x6a, 0x6f, 0x69, 0x6e, 0x74, 0x73, 0x2e,
0x7a, 0x20, 0x3d, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x28, 0x61,
0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x6a, 0x6f, 0x69, 0x6e, 0x74, 0x29,
0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x20,
0x2b, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61, 0x74, 0x5f, 0x74, 0x6f, 0x5f,
0x72, 0x67, 0x62, 0x28, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x77, 0x65,
0x69, 0x67, 0x68, 0x74, 0x73, 0x2e, 0x7a, 0x29, 0x3b, 0x0a, 0x0a, 0x20,
0x20, 0x69, 0x66, 0x28, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x6a, 0x6f,
0x69, 0x6e, 0x74, 0x73, 0x2e, 0x77, 0x20, 0x3d, 0x3d, 0x20, 0x66, 0x6c,
0x6f, 0x61, 0x74, 0x28, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x6a,
0x6f, 0x69, 0x6e, 0x74, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x63,
0x6f, 0x6c, 0x6f, 0x72, 0x20, 0x2b, 0x3d, 0x20, 0x66, 0x6c, 0x6f, 0x61,
0x74, 0x5f, 0x74, 0x6f, 0x5f, 0x72, 0x67, 0x62, 0x28, 0x69, 0x6e, 0x70,
0x75, 0x74, 0x5f, 0x77, 0x65, 0x69, 0x67, 0x68, 0x74, 0x73, 0x2e, 0x77,
0x29, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e,
0x20, 0x76, 0x65, 0x63, 0x34, 0x28, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x2c,
0x20, 0x31, 0x2e, 0x30, 0x66, 0x29, 0x3b, 0x0a, 0x7d, 0x0a, 0x0a, 0x76,
0x6f, 0x69, 0x64, 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x28, 0x29, 0x0a, 0x7b,
0x0a, 0x20, 0x20, 0x67, 0x6c, 0x5f, 0x50, 0x6f, 0x73, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x6d, 0x76, 0x70, 0x20, 0x2a, 0x20, 0x76,
0x65, 0x63, 0x34, 0x28, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x70, 0x6f,
0x73, 0x69, 0x74, 0x69, 0x6f, 0x6e, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x66,
0x29, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x6f,
0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c,
0x20, 0x3d, 0x20, 0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x20, 0x2a, 0x20,
0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x28, 0x69, 0x6e,
0x70, 0x75, 0x74, 0x5f, 0x6e, 0x6f, 0x72, 0x6d, 0x61, 0x6c, 0x29, 0x3b,
0x0a, 0x20, 0x20, 0x66, 0x72, 0x61, 0x67, 0x6d, 0x65, 0x6e, 0x74, 0x5f,
0x77, 0x6f, 0x72, 0x6c, 0x64, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69,
0x6f, 0x6e, 0x20, 0x3d, 0x20, 0x76, 0x65, 0x63, 0x33, 0x28, 0x6d, 0x6f,
0x64, 0x65, 0x6c, 0x20, 0x2a, 0x20, 0x76, 0x65, 0x63, 0x34, 0x28, 0x69,
0x6e, 0x70, 0x75, 0x74, 0x5f, 0x70, 0x6f, 0x73, 0x69, 0x74, 0x69, 0x6f,
0x6e, 0x2c, 0x20, 0x31, 0x2e, 0x30, 0x66, 0x29, 0x29, 0x3b, 0x0a, 0x20,
0x20, 0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c,
0x61, 0x74, 0x65, 0x64, 0x5f, 0x75, 0x76, 0x20, 0x3d, 0x20, 0x69, 0x6e,
0x70, 0x75, 0x74, 0x5f, 0x75, 0x76, 0x3b, 0x0a, 0x20, 0x20, 0x69, 0x6e,
0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f, 0x77,
0x65, 0x69, 0x67, 0x68, 0x74, 0x73, 0x20, 0x3d, 0x20, 0x77, 0x65, 0x69,
0x67, 0x68, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x28, 0x29, 0x3b,
0x0a, 0x20, 0x20, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x70, 0x6f, 0x6c, 0x61,
0x74, 0x65, 0x64, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72, 0x73, 0x20, 0x3d,
0x20, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x5f, 0x63, 0x6f, 0x6c, 0x6f, 0x72,
0x73, 0x3b, 0x0a, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x69, 0x66, 0x28, 0x67,
0x6c, 0x5f, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, 0x49, 0x44, 0x20, 0x3d,
0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65,
0x5f, 0x76, 0x65, 0x72, 0x74, 0x65, 0x78, 0x2e, 0x78, 0x29, 0x0a, 0x20,
0x20, 0x2f, 0x2f, 0x7c, 0x7c, 0x20, 0x67, 0x6c, 0x5f, 0x56, 0x65, 0x72,
0x74, 0x65, 0x78, 0x49, 0x44, 0x20, 0x3d, 0x3d, 0x20, 0x69, 0x6e, 0x74,
0x28, 0x61, 0x63, 0x74, 0x69, 0x76, 0x65, 0x5f, 0x76, 0x65, 0x72, 0x74,
0x65, 0x78, 0x2e, 0x79, 0x29, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x7c, 0x7c,
0x20, 0x67, 0x6c, 0x5f, 0x56, 0x65, 0x72, 0x74, 0x65, 0x78, 0x49, 0x44,
0x20, 0x3d, 0x3d, 0x20, 0x69, 0x6e, 0x74, 0x28, 0x61, 0x63, 0x74, 0x69,
0x76, 0x65, 0x5f, 0x76, 0x65, 0x72, 0x74, 0x65, 0x78, 0x2e, 0x7a, 0x29,
0x29, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x7b, 0x0a, 0x20, 0x20, 0x2f, 0x2f,
0x20, 0x20, 0x73, 0x65, 0x6c, 0x65, 0x63, 0x74, 0x65, 0x64, 0x20, 0x3d,
0x20, 0x31, 0x2e, 0x66, 0x3b, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x7d, 0x0a,
0x20, 0x20, 0x2f, 0x2f, 0x65, 0x6c, 0x73, 0x65, 0x0a, 0x20, 0x20, 0x2f,
0x2f, 0x7b, 0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x20, 0x20, 0x73, 0x65, 0x6c,
0x65, 0x63, 0x74, 0x65, 0x64, 0x20, 0x3d, 0x20, 0x30, 0x2e, 0x66, 0x3b,
0x0a, 0x20, 0x20, 0x2f, 0x2f, 0x7d, 0x0a, 0x7d, 0x0a,
};
unsigned int shaders_no_skinning_vert_len = 1869;
| [
"syoyo@lighttransport.com"
] | syoyo@lighttransport.com |
bbd26c4ed142712975acca0ff7d7dc8e46ffe8c2 | 06aa4cef73fee0291c3c3ad95fb92c26d741796e | /Digital Signal Generation and Analysis/build/Release/usr/local/include/FourierGenerator.h | 999d92d25ea09bf26511ec1a101da530aa934f3b | [] | no_license | eriser/Digital_Signal_Generation_and_Analysis | ecff7ff2b8fbb05df33efaf45976e4289f5e5e39 | bf9be1781fb778b840b2ed25300b97399ce3753e | refs/heads/master | 2020-04-05T18:56:23.440882 | 2014-09-23T15:25:03 | 2014-09-23T15:25:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,062 | h | //
// FourierGenerator.h
// Waveform
//
// Created by Alexander Zywicki on 8/20/14.
// Copyright (c) 2014 Alexander Zywicki. All rights reserved.
//
#ifndef __Waveform__FourierGenerator__
#define __Waveform__FourierGenerator__
#include "SignalGenerator.h"
#include "SineLUT.h"
#include "HarmonicTable.h"
namespace DSG {
/*
Fourier Generator is designed with built in phasor code for use in genorating classic analog style waveforms using fourier synthesis i.e. additive combination of sine waves based on a fourier series
*/
/*!\brief A Class Extending The SignalGenerator Class with functionality for generating a wave by summing sinusoids
*/
class FourierGenerator: public SignalGenerator {
public:
FourierGenerator();
FourierGenerator(double const& frequency,double const& phase_offset);
virtual ~FourierGenerator();
virtual inline bool Perform( Sample& signal);
virtual inline bool Perform( RingBuffer& signal);
protected:
inline unsigned long _maxHarms(double _frq);
Sample _sample;
Sample _storage;
static DSG::Backend::HarmonicTable _harmonicTable;
static DSG::Backend::SineLUT<float, 32768> _sineLut;
};
inline bool FourierGenerator::Perform( Sample& signal){
signal = 0;
return false;
}
inline bool FourierGenerator::Perform( RingBuffer& signal){
signal.Flush();
return false;
}
inline unsigned long FourierGenerator::_maxHarms(double _frq){
//double softLim = 0.45;
//double hardLim = 0.5;
double _s = Sample_Rate()* (20000.0/ Sample_Rate());//uses harmonic roll of based on max human hearing and sample rate
_s/=_frq;
return trunc(_s);
}
}
#endif /* defined(__Waveform__FourierGenerator__) */
| [
"alexander.zywicki@loop.colum.edu"
] | alexander.zywicki@loop.colum.edu |
76e3df3cc8b749082ff337ee82ca54ec28de899d | cf6e55d499b5858f7c350227bd23260f16e60e44 | /showresult.h | 00b5ff4f36ab522790dcb421976ee3b845c6a10a | [] | no_license | Kingtous/DeathSquadProblem-DataStructureClassDesign | d1b740a837e77f306fbe5ffb59d9e71ff0a060d1 | 7a4134ca1ccf32aa40156bb9881a828df9614390 | refs/heads/master | 2020-04-16T01:47:16.312927 | 2019-01-11T05:42:03 | 2019-01-11T05:42:03 | 165,185,428 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | #ifndef SHOWRESULT_H
#define SHOWRESULT_H
#include <QDialog>
namespace Ui {
class ShowResult;
}
class ShowResult : public QDialog
{
Q_OBJECT
public:
explicit ShowResult(QWidget *parent = nullptr);
~ShowResult();
Ui::ShowResult *ui;
private slots:
void on_pushButton_clicked();
};
#endif // SHOWRESULT_H
| [
"kingtous@qq.com"
] | kingtous@qq.com |
6e19d072019b06a6b3be98d2eb858ccc20d1de30 | 36dfd840637e3ef261819521da4a2ebed8730650 | /third_party/xsimd/types/xsimd_avx512_bool.hpp | 29bd6a409c34a41413c25026df1bc6415f5cc8df | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | hroncok/pythran | 1229c10734377fdc52b96c1a7482d720981f1d0d | 1887d6b97cdbaed42d4ff94ed191714111a57a44 | refs/heads/master | 2023-07-08T22:59:57.585351 | 2020-09-10T11:40:42 | 2020-09-10T11:40:42 | 166,581,833 | 0 | 0 | BSD-3-Clause | 2020-09-14T13:35:24 | 2019-01-19T18:52:44 | Python | UTF-8 | C++ | false | false | 12,476 | hpp | /***************************************************************************
* Copyright (c) Johan Mabille, Sylvain Corlay, Wolf Vollprecht and *
* Martin Renou *
* Copyright (c) QuantStack *
* *
* Distributed under the terms of the BSD 3-Clause License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#ifndef XSIMD_AVX512_BOOL_HPP
#define XSIMD_AVX512_BOOL_HPP
#include "xsimd_avx512_int_base.hpp"
#include "xsimd_utils.hpp"
namespace xsimd
{
/*******************
* bool_mask_proxy *
*******************/
template <class MASK>
class bool_mask_proxy
{
public:
bool_mask_proxy(MASK& ref, std::size_t idx);
bool_mask_proxy(const bool_mask_proxy&) = default;
bool_mask_proxy& operator=(const bool_mask_proxy&) = default;
bool_mask_proxy(bool_mask_proxy&&) = default;
bool_mask_proxy& operator=(bool_mask_proxy&&) = default;
operator bool() const;
bool_mask_proxy& operator=(bool);
private:
MASK& m_ref;
std::size_t m_idx;
};
/*********************
* batch_bool_avx512 *
*********************/
template <class MASK, class B>
class batch_bool_avx512 : public simd_batch_bool<B>
{
public:
batch_bool_avx512();
explicit batch_bool_avx512(bool b);
template <class... Args, class Enable = detail::is_array_initializer_t<bool, sizeof(MASK) * 8, Args...>>
batch_bool_avx512(Args... args);
batch_bool_avx512(const bool (&init)[sizeof(MASK) * 8]);
batch_bool_avx512(const MASK& rhs);
batch_bool_avx512& operator=(const __m512& rhs);
bool_mask_proxy<MASK> operator[](std::size_t index);
bool operator[](std::size_t index) const;
operator MASK() const;
private:
B& load_array(const std::array<bool, sizeof(MASK) * 8>& src);
template <class... Args>
B& load_values(Args... args);
MASK m_value;
friend class simd_batch_bool<B>;
};
/******************************
* avx512_fallback_batch_bool *
******************************/
template <class T, std::size_t N>
class avx512_fallback_batch_bool : public simd_batch_bool<batch_bool<T, N>>
{
public:
avx512_fallback_batch_bool();
explicit avx512_fallback_batch_bool(bool b);
template <class... Args, class Enable = detail::is_array_initializer_t<bool, N, Args...>>
avx512_fallback_batch_bool(Args... args);
avx512_fallback_batch_bool(const __m512i& rhs);
avx512_fallback_batch_bool& operator=(const __m512i& rhs);
operator __m512i() const;
bool_proxy<T> operator[](std::size_t index);
bool operator[](std::size_t index) const;
private:
template <class... Args>
batch_bool<T, N>& load_values(Args... b);
union
{
__m512i m_value;
T m_array[N];
};
friend class simd_batch_bool<batch_bool<T, N>>;
};
/**********************************
* bool_mask_proxy implementation *
**********************************/
template <class MASK>
inline bool_mask_proxy<MASK>::bool_mask_proxy(MASK& ref, std::size_t idx)
: m_ref(ref), m_idx(idx)
{
}
template <class MASK>
inline bool_mask_proxy<MASK>::operator bool() const
{
return ((m_ref >> m_idx) & MASK(1)) != 0;
}
template <class MASK>
inline bool_mask_proxy<MASK>& bool_mask_proxy<MASK>::operator=(bool rhs)
{
MASK tmp = static_cast<MASK>(rhs);
m_ref ^= (-tmp ^ m_ref) & (MASK(1) << m_idx);
return *this;
}
/************************************
* batch_bool_avx512 implementation *
************************************/
template <class MASK, class T>
inline batch_bool_avx512<MASK, T>::batch_bool_avx512()
{
}
template <class MASK, class T>
template <class... Args, class>
inline batch_bool_avx512<MASK, T>::batch_bool_avx512(Args... args)
: batch_bool_avx512({{static_cast<bool>(args)...}})
{
}
template <class MASK, class T>
inline batch_bool_avx512<MASK, T>::batch_bool_avx512(bool b)
: m_value(b ? -1 : 0)
{
}
namespace detail
{
template <class T>
constexpr T get_init_value_impl(const bool (&/*init*/)[sizeof(T) * 8])
{
return T(0);
}
template <class T, std::size_t IX, std::size_t... I>
constexpr T get_init_value_impl(const bool (&init)[sizeof(T) * 8])
{
return (T(init[IX]) << IX) | get_init_value_impl<T, I...>(init);
}
template <class T, std::size_t... I>
constexpr T get_init_value(const bool (&init)[sizeof(T) * 8], detail::index_sequence<I...>)
{
return get_init_value_impl<T, I...>(init);
}
}
template <class MASK, class T>
inline batch_bool_avx512<MASK, T>::batch_bool_avx512(const bool (&init)[sizeof(MASK) * 8])
: m_value(detail::get_init_value<MASK>(init, detail::make_index_sequence<sizeof(MASK) * 8>{}))
{
}
template <class MASK, class T>
inline batch_bool_avx512<MASK, T>::batch_bool_avx512(const MASK& rhs)
: m_value(rhs)
{
}
template <class MASK, class T>
inline batch_bool_avx512<MASK, T>::operator MASK() const
{
return m_value;
}
template <class MASK, class T>
inline bool_mask_proxy<MASK> batch_bool_avx512<MASK, T>::operator[](std::size_t idx)
{
std::size_t s = simd_batch_traits<T>::size - 1;
return bool_mask_proxy<MASK>(m_value, idx & s);
}
template <class MASK, class T>
inline bool batch_bool_avx512<MASK, T>::operator[](std::size_t idx) const
{
std::size_t s = simd_batch_traits<T>::size - 1;
return (m_value & (MASK(1) << (idx & s))) != 0;
}
template <class MASK, class T>
inline T& batch_bool_avx512<MASK, T>::load_array(const std::array<bool, sizeof(MASK) * 8>& src)
{
MASK tmp(false);
for(std::size_t i = 0; i < sizeof(MASK) * 8; ++i)
{
tmp |= MASK(src[i]) << i;
}
m_value = tmp;
return (*this)();
}
template <class MASK, class T>
template <class... Args>
inline T& batch_bool_avx512<MASK, T>::load_values(Args... b)
{
return load_array({b...});
}
namespace detail
{
template <class T, std::size_t N>
struct batch_bool_kernel_avx512
{
using batch_type = batch_bool<T, N>;
using mt = typename mask_type<N>::type;
static batch_type bitwise_and(const batch_type& lhs, const batch_type& rhs)
{
return mt(lhs) & mt(rhs);
}
static batch_type bitwise_or(const batch_type& lhs, const batch_type& rhs)
{
return mt(lhs) | mt(rhs);
}
static batch_type bitwise_xor(const batch_type& lhs, const batch_type& rhs)
{
return mt(lhs) ^ mt(rhs);
}
static batch_type bitwise_not(const batch_type& rhs)
{
return ~mt(rhs);
}
static batch_type bitwise_andnot(const batch_type& lhs, const batch_type& rhs)
{
return mt(lhs) ^ mt(rhs);
}
static batch_type equal(const batch_type& lhs, const batch_type& rhs)
{
return (~mt(lhs)) ^ mt(rhs);
}
static batch_type not_equal(const batch_type& lhs, const batch_type& rhs)
{
return mt(lhs) ^ mt(rhs);
}
static bool all(const batch_type& rhs)
{
return mt(rhs) == mt(-1);
}
static bool any(const batch_type& rhs)
{
return mt(rhs) != mt(0);
}
};
}
/*********************************************
* avx512_fallback_batch_bool implementation *
*********************************************/
template <class T, std::size_t N>
inline avx512_fallback_batch_bool<T, N>::avx512_fallback_batch_bool()
{
}
template <class T, std::size_t N>
inline avx512_fallback_batch_bool<T, N>::avx512_fallback_batch_bool(bool b)
: m_value(_mm512_set1_epi64(-(int64_t)b))
{
}
template <class T, std::size_t N>
template <class... Args, class>
inline avx512_fallback_batch_bool<T, N>::avx512_fallback_batch_bool(Args... args)
: m_value(avx512_detail::int_init(std::integral_constant<std::size_t, sizeof(int8_t)>{},
static_cast<int8_t>(-static_cast<bool>(args))...))
{
}
template <class T, std::size_t N>
inline avx512_fallback_batch_bool<T, N>::avx512_fallback_batch_bool(const __m512i& rhs)
: m_value(rhs)
{
}
template <class T, std::size_t N>
inline avx512_fallback_batch_bool<T, N>::operator __m512i() const
{
return m_value;
}
template <class T, std::size_t N>
inline avx512_fallback_batch_bool<T, N>& avx512_fallback_batch_bool<T, N>::operator=(const __m512i& rhs)
{
m_value = rhs;
return *this;
}
template <class T, std::size_t N>
inline bool_proxy<T> avx512_fallback_batch_bool<T, N>::operator[](std::size_t idx)
{
return bool_proxy<T>(m_array[idx & (N - 1)]);
}
template <class T, std::size_t N>
inline bool avx512_fallback_batch_bool<T, N>::operator[](std::size_t idx) const
{
return static_cast<bool>(m_array[idx & (N - 1)]);
}
template <class T, std::size_t N>
template <class... Args>
inline batch_bool<T, N>& avx512_fallback_batch_bool<T, N>::load_values(Args... b)
{
m_value = avx512_detail::int_init(std::integral_constant<std::size_t, sizeof(int8_t)>{},
static_cast<int8_t>(-static_cast<bool>(b))...);
return (*this)();
}
namespace detail
{
template <class T, std::size_t N>
struct avx512_fallback_batch_bool_kernel
{
using batch_type = batch_bool<T, N>;
static batch_type bitwise_and(const batch_type& lhs, const batch_type& rhs)
{
return _mm512_and_si512(lhs, rhs);
}
static batch_type bitwise_or(const batch_type& lhs, const batch_type& rhs)
{
return _mm512_or_si512(lhs, rhs);
}
static batch_type bitwise_xor(const batch_type& lhs, const batch_type& rhs)
{
return _mm512_xor_si512(lhs, rhs);
}
static batch_type bitwise_not(const batch_type& rhs)
{
return _mm512_xor_si512(rhs, _mm512_set1_epi64(-1)); // xor with all one
}
static batch_type bitwise_andnot(const batch_type& lhs, const batch_type& rhs)
{
return _mm512_andnot_si512(lhs, rhs);
}
static batch_type equal(const batch_type& lhs, const batch_type& rhs)
{
return ~(lhs ^ rhs);
}
static batch_type not_equal(const batch_type& lhs, const batch_type& rhs)
{
return lhs ^ rhs;
}
static bool all(const batch_type& rhs)
{
XSIMD_SPLIT_AVX512(rhs);
bool res_hi = _mm256_testc_si256(rhs_high, batch_bool<int32_t, 8>(true)) != 0;
bool res_lo = _mm256_testc_si256(rhs_low, batch_bool<int32_t, 8>(true)) != 0;
return res_hi && res_lo;
}
static bool any(const batch_type& rhs)
{
XSIMD_SPLIT_AVX512(rhs);
bool res_hi = !_mm256_testz_si256(rhs_high, rhs_high);
bool res_lo = !_mm256_testz_si256(rhs_low, rhs_low);
return res_hi || res_lo;
}
};
}
}
#endif
| [
"serge.guelton@telecom-bretagne.eu"
] | serge.guelton@telecom-bretagne.eu |
f8e0f7406afe9e43bb2f19fcd761bc304886771c | 865dfc8a09993500f9477d2cb794dfdcad9d1153 | /ReplayParser/model/ReplayCameraGroup.h | ad01db77dffd3d05bc0eb8772d68ec4ccc0a177d | [] | no_license | plucked/vcrparser_rf1 | 1cead35dac96a14b0bb23b76ea4cd0e5df0edacc | c9e15cf7687c8f71c24bd8be9f652a3cd0bf0e02 | refs/heads/master | 2021-01-22T20:29:06.610165 | 2017-03-24T14:18:19 | 2017-03-24T14:18:19 | 7,468,889 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,564 | h | /*
Copyright (c) 2013 Rainer Heynke <rainer.heynke@plucked.de> (@plucked on twitter)
This software is licensed with the cc-by license (http://creativecommons.org/licenses/by/3.0/)
*/
#ifndef ReplayCameraGroup_h__
#define ReplayCameraGroup_h__
#include "ReplayCamera.h"
class ReplayCameraGroup
{
public:
typedef boost::shared_ptr<ReplayCameraGroup> Shared;
int unknown_integer_1; // was "1" in my testing cases
int unknown_integer_2; // was 0 in my testing cases
typedef vector<ReplayCamera::Shared> t_CameraContainer;
t_CameraContainer cameras;
static ReplayCameraGroup::Shared ReadFromStream(istream& stream)
{
ReplayCameraGroup::Shared result(new ReplayCameraGroup);
result->unknown_integer_1 = BinaryStreamUtil::ReadBinary<int>(stream);
result->unknown_integer_2 = BinaryStreamUtil::ReadBinary<int>(stream);
u_int camera_count = BinaryStreamUtil::ReadBinary<int>(stream);
for(u_int i = 0; i < camera_count; ++i)
{
result->cameras.push_back(ReplayCamera::ReadFromStream(stream));
}
return result;
}
void WriteToStream(std::ostream& stream) const
{
BinaryStreamUtil::WriteBinary<int>(unknown_integer_1, stream);
BinaryStreamUtil::WriteBinary<int>(unknown_integer_2, stream);
BinaryStreamUtil::WriteBinary<int>(cameras.size(), stream);
t_CameraContainer::const_iterator it = cameras.begin();
t_CameraContainer::const_iterator itEnd = cameras.end();
for(; it != itEnd; ++it)
{
it->get()->WriteToStream(stream);
}
}
};
#endif // ReplayCameraGroup_h__
| [
"rainer.heynke@plucked.de"
] | rainer.heynke@plucked.de |
836b71f6277c3dd1db3dde233f95270bb5c5d820 | ccb95a1e3d9869d15bd02f4e945bb7bd8415bbff | /abc076/abc076_b.cpp | 01486a4dec2bc80d10834f9c3a2c57c33e70a19d | [] | no_license | sacckey/atcoder | b9470f8a21dc7c176e6a6744214ffc7445272dcb | 9f457faae7a7fcc12700bba1720abbc279a5ae68 | refs/heads/master | 2023-01-01T06:12:11.887881 | 2020-10-18T06:23:52 | 2020-10-18T06:23:52 | 183,706,069 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | #include <bits/stdc++.h>
using namespace std;
int main(){
int n,k;
cin >> n >> k;
int ans=1;
for (int i = 0; i < n; i++)
{
if(ans<k) ans*=2;
else ans+=k;
}
cout << ans << endl;
} | [
"sackeyad24@gmail.com"
] | sackeyad24@gmail.com |
e270b4569833cd3b295dfcf15d2fe30c2b894278 | c828ce3fa9fca523da7b0d4b1a4aea744fa5f35c | /SpaceInvaders/CDP/Headers/Physics.h | c255944c74dc8c5cc1afe333388c87a7bd68d5f3 | [
"MIT"
] | permissive | Otard95/Cpp-Home-Exam | 80e94319b8d1baf1dd4f7d60d7b2bdef20b8bc77 | 9ad6037f12e99f1ee8c054d5bd84e420704e6434 | refs/heads/master | 2020-03-14T22:53:35.106831 | 2018-05-05T09:31:07 | 2018-05-05T09:31:07 | 131,831,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 758 | h | #ifndef __PHYSICS_H__
#define __PHYSICS_H__
#include <vector>
#include "Time.h"
#include "Rigidbody.h"
#include "Collider.h"
namespace CDP {
class Physics {
Physics ();
static Physics m_instance;
Time& m_time;
std::vector<std::shared_ptr<Rigidbody>> m_rigidbodies;
std::vector<std::shared_ptr<Collider>> m_colliders;
//std::shared_ptr<std::vector<Transform>> m_transforms;
public:
static Physics& Instance ();
void Init (std::vector<std::shared_ptr<Rigidbody>>& rigidbodies,
std::vector<std::shared_ptr<Collider>>& colliders
/*std::vector<Transform> * transforms*/);
Physics (Physics const &) = delete;
Physics& operator= (const Physics&) = delete;
~Physics () = default;
void Update ();
};
}
#endif
| [
"stian.myklebostad@getmail.no"
] | stian.myklebostad@getmail.no |
eced11b4b7ea570ed860186fca6f1696ce5f19fd | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /components/drive/chromeos/search_metadata.h | f515c2d8a9957a8ca7237b50ae1f263411230a7a | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 3,079 | h | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_DRIVE_CHROMEOS_SEARCH_METADATA_H_
#define COMPONENTS_DRIVE_CHROMEOS_SEARCH_METADATA_H_
#include <stddef.h>
#include <memory>
#include <string>
#include <vector>
#include "base/sequenced_task_runner.h"
#include "components/drive/chromeos/file_system_interface.h"
namespace base {
namespace i18n {
class FixedPatternStringSearchIgnoringCaseAndAccents;
} // namespace i18n
} // namespace base
namespace drive {
namespace internal {
class ResourceMetadata;
typedef base::RepeatingCallback<bool(const ResourceEntry&)>
SearchMetadataPredicate;
// Searches the local resource metadata, and returns the entries
// |at_most_num_matches| that contain |query| in their base names. Search is
// done in a case-insensitive fashion. |query| is splitted into keywords by
// whitespace. All keywords are considered as AND condition. The eligible
// entries are selected based on the given |options|, which is a bit-wise OR of
// SearchMetadataOptions. |callback| must not be null. Must be called on UI
// thread. Empty |query| matches any base name. i.e. returns everything.
// |blocking_task_runner| must be the same one as |resource_metadata| uses.
void SearchMetadata(
scoped_refptr<base::SequencedTaskRunner> blocking_task_runner,
ResourceMetadata* resource_metadata,
const std::string& query,
const SearchMetadataPredicate& predicate,
size_t at_most_num_matches,
MetadataSearchOrder order,
SearchMetadataCallback callback);
// Returns true if |entry| is eligible for the search |options| and should be
// tested for the match with the query. If
// SEARCH_METADATA_EXCLUDE_HOSTED_DOCUMENTS is requested, the hosted documents
// are skipped. If SEARCH_METADATA_EXCLUDE_DIRECTORIES is requested, the
// directories are skipped. If SEARCH_METADATA_SHARED_WITH_ME is requested, only
// the entries with shared-with-me label will be tested. If
// SEARCH_METADATA_OFFLINE is requested, only hosted documents and cached files
// match with the query. This option can not be used with other options.
bool MatchesType(int options, const ResourceEntry& entry);
// Finds |queries| in |text| while ignoring cases or accents. Cases of non-ASCII
// characters are also ignored; they are compared in the 'Primary Level' of
// http://userguide.icu-project.org/collation/concepts.
// Returns true if |queries| are found. |highlighted_text| will have the
// original
// text with matched portions highlighted with <b> tag (only the first match
// is highlighted). Meta characters are escaped like <. The original
// contents of |highlighted_text| will be lost.
bool FindAndHighlight(
const std::string& text,
const std::vector<std::unique_ptr<
base::i18n::FixedPatternStringSearchIgnoringCaseAndAccents>>& queries,
std::string* highlighted_text);
} // namespace internal
} // namespace drive
#endif // COMPONENTS_DRIVE_CHROMEOS_SEARCH_METADATA_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
9195a0800284c13e640be4eb3159f50093b1f89b | 451dca272630e58539f803d2c3b767a8ae6451a2 | /IMS/MaleVole.cpp | f3fb0a8d28f457d775373a9f5bbbf65ef72d8aba | [] | no_license | MatejPrasek/IMS-CellularAutomata | bcaf260492b00ddbe07ff3a55fe0744efe37a27f | 0ca11dab7c33eec3aa9695e4bffe535a1abf1258 | refs/heads/master | 2022-12-14T14:50:59.679427 | 2020-09-05T09:43:24 | 2020-09-05T09:43:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,713 | cpp | #include "MaleVole.h"
#include <iostream>
#include <algorithm>
#include "FemaleVole.h"
MaleVole::MaleVole(unsigned int adultGen, int height, int width) : Vole(adultGen, height, width)
{
}
void MaleVole::NextGeneration(std::vector<std::vector<std::unique_ptr<Cell>>>* field, unsigned generation, int height, int width)
{
if (WillDie)
{
(*field)[height][width] = nullptr;
return;
}
nextGenerationHeight = height;
nextGenerationWidth = width;
if (adultGeneration == generation)
{
isAdult = true;
return;
}
int maxHeight = field->size() - 1;
int maxWidth = field[0].size() - 1;
if (isAdult)
{
std::unique_ptr<Cell>* target = FindClose(CellTypes::FemaleVole, field);
if (target == nullptr)
target = FindFar(CellTypes::FemaleVole, field);
if (target != nullptr)
{
GoToDirection(target->get()->nextGenerationHeight - nextGenerationHeight, target->get()->nextGenerationWidth - nextGenerationWidth, maxHeight, maxWidth);
return;
}
}
std::unique_ptr<Cell>* food = FindFar(CellTypes::Poison, field);
if (food == nullptr)
food = FindFar(CellTypes::Poison, field);
if (food != nullptr)
{
GoToDirection(food->get()->nextGenerationHeight - nextGenerationHeight, food->get()->nextGenerationWidth - nextGenerationWidth, maxHeight, maxWidth);
return;
}
GoToRandomDirection(maxHeight, maxWidth);
}
CellTypes MaleVole::WhatAmI()
{
return CellTypes::MaleVole;
}
std::unique_ptr<Cell>* MaleVole::FindCloseForReproduction(std::vector<std::vector<std::unique_ptr<Cell>>>* field)
{
return FindForReproduction(field, 1);
}
std::unique_ptr<Cell>* MaleVole::FindFarForReproduction(std::vector<std::vector<std::unique_ptr<Cell>>>* field)
{
return FindForReproduction(field, 2);
}
std::unique_ptr<Cell>* MaleVole::FindForReproduction(std::vector<std::vector<std::unique_ptr<Cell>>>* field, int distance)
{
const int maxHeight = (*field).size() - 1;
const int maxWidth = (*field)[0].size() - 1;
for (auto i = -distance; i <= distance; ++i)
{
const auto height = i < 0 ? std::max(nextGenerationHeight + i, 0) : std::min(nextGenerationHeight + i, maxHeight);
for (auto j = -distance; j <= distance; ++j)
{
if (std::abs(i) < distance && std::abs(j) < distance)
continue;
const auto width = j < 0 ? std::max(nextGenerationWidth + j, 0) : std::min(nextGenerationWidth + j, maxWidth);
const auto type = (*field)[height][width]->WhatAmI();
if (type == CellTypes::FemaleVole)
{
const auto target = dynamic_cast<FemaleVole*>((*field)[height][width].get());
if (target->isAdult && !target->isPregnant)
return &(*field)[height][width];
}
}
}
return nullptr;
} | [
"prasek.matej@seznam.cz"
] | prasek.matej@seznam.cz |
3f9be8754033d1dae94375b19e8222926a35c1b2 | c27664c1fae55de6118854c2856c2f4a6085b7cb | /Classes/Model/GateGroup.hpp | 257d3d20bf6c380d7401429ae67760fac5c66b28 | [] | no_license | xiatian0019/ColorGate | 5c3b6469a0221b96213ca514148c54e4f1cd9e33 | 5edeb7063ea0751d008a97ed7d0f966b836de156 | refs/heads/master | 2021-01-12T12:19:13.267223 | 2016-10-31T11:50:14 | 2016-10-31T11:50:14 | 72,431,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | hpp | //
// GateGroup.hpp
// ColorGate
//
// Created by xiaoming on 16/4/28.
//
//
#ifndef GateGroup_hpp
#define GateGroup_hpp
#include <stdio.h>
#include "Gate.hpp"
#include "GameSetting.h"
class GateGroupDelegate
{
public:
virtual void gateCorrect(GATE_COLOR newColor,int lastPos)=0;
virtual void gateWrong()=0;
virtual void gatePress(GATE_COLOR gateColor,Vec2 point)=0;
};
class GateGroup : public Layer
{
public:
GateGroup(GATE_COLOR correctColor);
void setDelegate(GateGroupDelegate *delegate);
private:
GATE_COLOR correctColor;
void openTouchEvent();
bool onTouchBegan(Touch* touch, Event* event);
void onTouchEnded(Touch* touch, Event* event);
Vec2 startPoint;
std::vector<Gate *>gateList;
void addGate();
GateGroupDelegate *myDelegate;
void gatePressed(bool correct,GATE_COLOR pressedColor,Vec2 gatePos);
void addExplosionEffect(GATE_COLOR color,Vec2 point);
void gateOpenAnime();
};
#endif /* GateGroup_hpp */
| [
"xiaoming@xiaomingdeMacBook-Pro.local"
] | xiaoming@xiaomingdeMacBook-Pro.local |
290c57a110dee04c2987a8a40aae67f118039f70 | 25bf268b8171fcb4a7d3b59088a36ae31fc29fe5 | /openuasl-server/src/session_uav.cpp | 988ba53f874f5756195dfb39b41747621c3e42d1 | [] | no_license | openuasl/openuasl-server | 55749f050c3f6a901ac87083a4c5e70b8be64adc | 68956fb9994026295f9aef6236fedf896239d0a7 | refs/heads/master | 2020-12-24T15:14:44.178963 | 2014-08-29T04:55:35 | 2014-08-29T04:55:35 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,401 | cpp |
#include <openuasl/server_conf.h>
#include <openuasl/session_app.h>
#include <openuasl/session_uav.h>
namespace openuasl{
namespace server{
session_uav::session_uav(std::string& id, SecureSocket& sock, size_t buf_size)
: skeleton::BaseUavSession(id, sock, buf_size){}
session_uav::~session_uav(){}
void session_uav::Start(){
_Socket.async_read_some(
boost::asio::buffer(this->_Buffer, this->_BufferSize),
boost::bind(&session_uav::ReaduavStreamming, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void session_uav::ReaduavStreamming( //오드로이드에서 읽어오는거
const boost::system::error_code& error, size_t bytes_transferred){
if(!error){
_Resq->_Socket.async_write_some(
boost::asio::buffer(this->_Buffer, bytes_transferred),
boost::bind(&session_uav::WriteappStreamming, this,
boost::asio::placeholders::error));
}else{
delete this;
}
}
void session_uav::WriteappStreamming( //앱에 쓰는거
const boost::system::error_code& error){
if(!error){
_Socket.async_read_some(
boost::asio::buffer(this->_Buffer, this->_BufferSize),
boost::bind(&session_uav::ReaduavStreamming, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}else{
delete this;
}
}
}
} | [
"wlgus921211@naver.com"
] | wlgus921211@naver.com |
592dcf9d13eb2f21cd5308452ec09162a88650ab | 13080077fb976e21b37e19a4e62e73379d8964b4 | /Platformer/Platformer/Timer.h | 0f9072cbddb13d6e85a8b11d3fd08d82029c581e | [] | no_license | Suraj-Nishad/Computer-Games-Development | 3d2b8543467b155b70f78b6ec00256342887357e | e7ff7d44bb3b62394d4cd24c516a42f5a96e9aa9 | refs/heads/master | 2020-04-28T18:00:18.337962 | 2018-02-28T16:43:26 | 2018-02-28T16:43:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 590 | h | #pragma once
#include <SDL/SDL.h>
//Based on the SDL tutorial found here: http://lazyfoo.net/tutorials/SDL/23_advanced_timers/index.php
class Timer
{
public:
Timer();
~Timer();
//Clock actions
void start();
void stop();
void restart();
void pause();
void unpause();
//Get the timer's time
Uint32 getTicks();
//Check the status of the timer
bool isStarted();
bool isPaused();
private:
//The clock time when the timer started
Uint32 mStartTicks;
//The ticks stored when the timer was paused
Uint32 mPausedTicks;
//The timer status
bool mPaused;
bool mStarted;
};
| [
"jackhookham@gmail.com"
] | jackhookham@gmail.com |
1ac5d963759ac9f6d8d02fd8747f264ce08b9cdb | 639cdc6ce0e94a27b72ceede7a295ca621fae21a | /build/linux-build/Sources/include/hxinc/scene/Scene.h | 1d0199d15d1baffc86d85a10059e62790d737ab9 | [
"MIT"
] | permissive | HedgehogFog/TimeOfDeath | fb04bd6010115dc37b5d7777821f8fa53e1854a0 | b78abacf940e1a88c8b987d99764ebb6876c5dc6 | refs/heads/master | 2020-04-27T10:48:43.759612 | 2019-03-18T04:30:47 | 2019-03-18T04:30:47 | 174,270,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 1,082 | h | // Generated by Haxe 4.0.0-preview.5
#ifndef INCLUDED_scene_Scene
#define INCLUDED_scene_Scene
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
HX_DECLARE_CLASS2(kha,graphics2,Graphics)
HX_DECLARE_CLASS1(scene,Scene)
namespace scene{
class HXCPP_CLASS_ATTRIBUTES Scene_obj {
public:
typedef hx::Object super;
HX_DO_INTERFACE_RTTI;
void (hx::Object :: *_hx_draw)( ::kha::graphics2::Graphics gr);
static inline void draw( ::Dynamic _hx_, ::kha::graphics2::Graphics gr) {
(_hx_.mPtr->*( static_cast< ::scene::Scene_obj *>(_hx_.mPtr->_hx_getInterface(0x199446a0)))->_hx_draw)(gr);
}
void (hx::Object :: *_hx_update)(Float dt);
static inline void update( ::Dynamic _hx_,Float dt) {
(_hx_.mPtr->*( static_cast< ::scene::Scene_obj *>(_hx_.mPtr->_hx_getInterface(0x199446a0)))->_hx_update)(dt);
}
void (hx::Object :: *_hx_destroy)();
static inline void destroy( ::Dynamic _hx_) {
(_hx_.mPtr->*( static_cast< ::scene::Scene_obj *>(_hx_.mPtr->_hx_getInterface(0x199446a0)))->_hx_destroy)();
}
};
} // end namespace scene
#endif /* INCLUDED_scene_Scene */
| [
"hedgehog_fogs@mail.ru"
] | hedgehog_fogs@mail.ru |
c9910b76b07dfb8c31b9c95077f8cfdf9626f646 | 847056145036966495171a6627ad373468347e03 | /College/Hailstone.cpp | ddefc9c73daee0f4eb276dbca28c2b4588a1701f | [] | no_license | cocokechun/Programming | f5f3e0b0a1fbdc105b718469c1bf893280cddba3 | 9a400ba2d38cdbb4af50d07b09273adb8bcbf427 | refs/heads/master | 2021-01-22T01:14:23.328035 | 2017-09-02T18:02:28 | 2017-09-02T18:02:28 | 102,213,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | #include <iostream>
#include <algorithm>
#include <cmath>
#include <set>
using namespace std;
int main() {
int n;
cin >> n;
int index, num;
for (int i=0; i<n; i++) {
cin >> index >> num;
set<int> seen;
int tmp = num;
int max = num;
while (tmp != 1 && seen.find(tmp) == seen.end() ) {
seen.insert(tmp);
if (tmp % 2 == 0) {
tmp /= 2;
} else {
tmp = tmp * 3 + 1;
}
if (tmp > max) {
max = tmp;
}
}
cout << index << " " << max << endl;
}
}
| [
"kechunmao@KechuntekiMacBook-Pro.local"
] | kechunmao@KechuntekiMacBook-Pro.local |
6506a97889e1ab92887280881b57d6b84e251dae | 7d7cfacec6c0e23fe573d609d977a44c235b1ef3 | /PacketPacker/PacketPacker/VersionHandler.cpp | ac7371e2e22b38f2c1ff67e68bd1ba0101c2c4e8 | [] | no_license | pjc0247/SocialMe_Server | 863713159645343e055a992cc568b66c3917a98e | e00f943d7c047af2e96c6c19cff4e746cc428059 | refs/heads/master | 2020-04-29T02:55:38.766437 | 2013-01-04T03:11:57 | 2013-01-04T03:11:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 592 | cpp | #include "stdafx.h"
#include "ServerHandler.h"
#include "Protocol.h"
bool VersionCheck(PacketHandlerData d){
NetPacket *p;
p = d.pkt;
int major, minor, fix;
major = NetGetNumberData(p, "major");
minor = NetGetNumberData(p, "minor");
fix = NetGetNumberData(p, "fix");
NetPacket *pkt;
pkt = NetCreatePacket();
if(major != SERVER_VERSION_MAJOR ||
minor != SERVER_VERSION_MINOR ||
fix != SERVER_VERSION_FIX){
pkt->header.type = VERSION_FAILED;
}
else{
pkt->header.type = VERSION_OK;
}
NetSendPacket(d.handle, d.io, pkt);
NetDisposePacket(pkt, true);
return true;
} | [
"pjc0247@naver.com"
] | pjc0247@naver.com |
a56a98ff4cf4b6354b40b2de7d748a1556ea0beb | c1bb97ca23a255851efda9d1d828a4051d4bfe45 | /1. SourceCode/Introduction-to-libcxx/libcxx/include/numeric | d44542651069ce109a87fdadd2c95ce2143aa2dd | [] | no_license | zhiyaluo/Introduction-to-libcxx | f4af2ff08fd6f54f14e23cfb48d7b3bd4b88dc2c | 181789af8891d2e344a69fa915987126c6fd15f3 | refs/heads/master | 2023-03-04T18:04:07.201091 | 2021-02-25T10:44:18 | 2021-02-25T10:44:18 | 266,662,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,307 | // -*- C++ -*-
//===---------------------------- numeric ---------------------------------===//
//
// 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.
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_NUMERIC
#define _LIBCPP_NUMERIC
/*
numeric synopsis
namespace std
{
template <class InputIterator, class T>
T
accumulate(InputIterator first, InputIterator last, T init);
template <class InputIterator, class T, class BinaryOperation>
T
accumulate(InputIterator first, InputIterator last, T init, BinaryOperation binary_op);
template <class InputIterator1, class InputIterator2, class T>
T
inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, T init);
template <class InputIterator1, class InputIterator2, class T, class BinaryOperation1, class BinaryOperation2>
T
inner_product(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,
T init, BinaryOperation1 binary_op1, BinaryOperation2 binary_op2);
template <class InputIterator, class OutputIterator>
OutputIterator
partial_sum(InputIterator first, InputIterator last, OutputIterator result);
template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator
partial_sum(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op);
template <class InputIterator, class OutputIterator>
OutputIterator
adjacent_difference(InputIterator first, InputIterator last, OutputIterator result);
template <class InputIterator, class OutputIterator, class BinaryOperation>
OutputIterator
adjacent_difference(InputIterator first, InputIterator last, OutputIterator result, BinaryOperation binary_op);
template <class ForwardIterator, class T>
void iota(ForwardIterator first, ForwardIterator last, T value);
} // std
*/
#include <__config>
#include <iterator>
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
_LIBCPP_BEGIN_NAMESPACE_STD
template <class _InputIterator, class _Tp>
inline _LIBCPP_INLINE_VISIBILITY
_Tp
accumulate(_InputIterator __first, _InputIterator __last, _Tp __init)
{
for (; __first != __last; ++__first)
__init = __init + *__first;
return __init;
}
template <class _InputIterator, class _Tp, class _BinaryOperation>
inline _LIBCPP_INLINE_VISIBILITY
_Tp
accumulate(_InputIterator __first, _InputIterator __last, _Tp __init, _BinaryOperation __binary_op)
{
for (; __first != __last; ++__first)
__init = __binary_op(__init, *__first);
return __init;
}
template <class _InputIterator1, class _InputIterator2, class _Tp>
inline _LIBCPP_INLINE_VISIBILITY
_Tp
inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2, _Tp __init)
{
for (; __first1 != __last1; ++__first1, ++__first2)
__init = __init + *__first1 * *__first2;
return __init;
}
template <class _InputIterator1, class _InputIterator2, class _Tp, class _BinaryOperation1, class _BinaryOperation2>
inline _LIBCPP_INLINE_VISIBILITY
_Tp
inner_product(_InputIterator1 __first1, _InputIterator1 __last1, _InputIterator2 __first2,
_Tp __init, _BinaryOperation1 __binary_op1, _BinaryOperation2 __binary_op2)
{
for (; __first1 != __last1; ++__first1, ++__first2)
__init = __binary_op1(__init, __binary_op2(*__first1, *__first2));
return __init;
}
template <class _InputIterator, class _OutputIterator>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
{
if (__first != __last)
{
typename iterator_traits<_InputIterator>::value_type __t(*__first);
*__result = __t;
for (++__first, ++__result; __first != __last; ++__first, ++__result)
{
__t = __t + *__first;
*__result = __t;
}
}
return __result;
}
template <class _InputIterator, class _OutputIterator, class _BinaryOperation>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
partial_sum(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
_BinaryOperation __binary_op)
{
if (__first != __last)
{
typename iterator_traits<_InputIterator>::value_type __t(*__first);
*__result = __t;
for (++__first, ++__result; __first != __last; ++__first, ++__result)
{
__t = __binary_op(__t, *__first);
*__result = __t;
}
}
return __result;
}
template <class _InputIterator, class _OutputIterator>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result)
{
if (__first != __last)
{
typename iterator_traits<_InputIterator>::value_type __t1(*__first);
*__result = __t1;
for (++__first, ++__result; __first != __last; ++__first, ++__result)
{
typename iterator_traits<_InputIterator>::value_type __t2(*__first);
*__result = __t2 - __t1;
__t1 = __t2;
}
}
return __result;
}
template <class _InputIterator, class _OutputIterator, class _BinaryOperation>
inline _LIBCPP_INLINE_VISIBILITY
_OutputIterator
adjacent_difference(_InputIterator __first, _InputIterator __last, _OutputIterator __result,
_BinaryOperation __binary_op)
{
if (__first != __last)
{
typename iterator_traits<_InputIterator>::value_type __t1(*__first);
*__result = __t1;
for (++__first, ++__result; __first != __last; ++__first, ++__result)
{
typename iterator_traits<_InputIterator>::value_type __t2(*__first);
*__result = __binary_op(__t2, __t1);
__t1 = __t2;
}
}
return __result;
}
template <class _ForwardIterator, class _Tp>
inline _LIBCPP_INLINE_VISIBILITY
void
iota(_ForwardIterator __first, _ForwardIterator __last, _Tp __value_)
{
for (; __first != __last; ++__first, ++__value_)
*__first = __value_;
}
_LIBCPP_END_NAMESPACE_STD
#endif // _LIBCPP_NUMERIC
| [
"zhiya.luo@qq.com"
] | zhiya.luo@qq.com | |
976ad2ce66e46367e6c20e379d89211b3f2b5797 | a5326af130d8c0f3138282e0e8f84704d662e341 | /library/tracking_data/io/track_writer.h | c3a7c9af68d35a80172d87722dabb693e290baca | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | daniel-riehm/burn-out | 98b75739400f981f7509a966da4bf449e3397a38 | 1d2afcd36d37127b5a3b6fa3f60bc195408ab3ea | refs/heads/master | 2022-03-05T12:25:59.466369 | 2019-11-15T01:37:47 | 2019-11-15T01:37:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,439 | h | /*ckwg +5
* Copyright 2013-2015 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#ifndef track_writer_h_
#define track_writer_h_
#include <tracking_data/track.h>
#include <tracking_data/io/track_writer_interface.h>
#include <utilities/config_block.h>
#include <string>
#include <map>
#include <boost/noncopyable.hpp>
namespace vidtk
{
// ----------------------------------------------------------------
/*! \brief Track writer.
*
* This class represents a track writer that can write tracks and
* associated data in various formats. Individual track output formats
* are implemented by deriving a class from track_writer_interface.
* Common utput formats are registered by default in the
* constructor. Custom formats can be registered at run time.
*
* \sa track_writer_interface
*
* Dynamics
\msc
process, writer, format;
process=>writer [ label = "<<create>>" ];
writer=>writer [ label = "add_writer()" ];
--- [ label = "for all file formats" ];
process=>writer [ label = "add_writer() - add custom writer" ];
process=>writer [ label = "get_writer_names() - for help message" ];
--- [ label = "process::set_params()" ];
process=>writer [ label = "set_format()" ];
writer=>writer [ label = "get_writer()" ];
--- [ label = "process::initialize()" ];
process=>writer [ label = "open()" ];
--- [ label = "process::step2()" ];
process=>writer [ label = "write()" ];
\endmsc
*
*/
class track_writer
: private boost::noncopyable
{
public:
track_writer( );
~track_writer();
bool write( track_vector_t const& tracks );
bool write( track_vector_t const& tracks,
std::vector< vidtk::image_object_sptr > const* ios,
timestamp const& ts );
/**
* \brief Select output format.
*
* This method selects the output format that is to be written. The
* format name must be one that is currently supported. (\sa
* get_writer_names()) The format must be sepected before the file
* is opened.
*
* @param format Name of format to write
*
* @return \b true if format is registered; \b false otherwise.
*/
bool set_format( std::string const& format );
/**
* \brief Open names file for writing.
*
* The named file is opened, and created if necessary.
*
* @param fname Name of file to open.
*
* @return \b true if file is opened; \b false otherwise.
*/
bool open( std::string const& fname );
bool is_open() const;
void close();
bool is_good() const;
void set_options(track_writer_options const& options);
void add_writer(std::string const& tag, track_writer_interface_sptr w);
/**
* \brief Get list of file format names.
*
* This method returns a list of all currently registered file
* format writer names (or format types). This string can be used as
* the config parameter description for the format to write.
*
* @return List of file format names.
*/
std::string const& get_writer_formats() const;
config_block const& get_writer_config() const;
private:
track_writer_interface_sptr get_writer(std::string const& tag);
track_writer_interface_sptr writer_;
std::map< std::string, track_writer_interface_sptr > writer_options_;
std::string writer_formats_;
config_block m_plugin_config;
};
} //namespace vidtk
#endif
| [
"matt.dawkins@kitware.com"
] | matt.dawkins@kitware.com |
c4abda43e43bc7ccc3a03f0ad2ab3b94142aef9c | 51a63ed3e5ca80b92d11dc5f891813fb09f8018a | /openingTheGL/src/VertexArray.cpp | 4883361ebddf9ae4ccdb65bbcb3172a3b49f1ea7 | [] | no_license | prajwalshettydev/OpeningTheGL | 0be419d526de580aa5632a922c5164e663d0a5c0 | 4f5b35bbd5467c310c779cdca2ce196505e969f3 | refs/heads/master | 2020-12-14T03:05:26.446064 | 2020-04-25T12:02:07 | 2020-04-25T12:02:07 | 234,614,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,832 | cpp | #include"VertexArray.h"
#include "Renderer.h"
#include "VertexBufferLayout.h"
VertexArray::VertexArray()
{
//create a new VertexArray,
GLCall(glGenVertexArrays(1, &m_RendererID));
}
VertexArray::~VertexArray()
{
GLCall(glDeleteVertexArrays(1, &m_RendererID));
}
void VertexArray::AddBuffer(const VertexBuffer& vb, const VertexBufferLayout& layout)
{
Bind();
vb.Bind();
const auto& elements = layout.GetElements();
unsigned int offset = 0;
for (unsigned int i = 0; i < elements.size(); i++)
{
const auto& element = elements[i];
//the vertex attribute array need to be enabled to be used
//http://docs.gl/gl4/glEnableVertexAttribArray
GLCall(glEnableVertexAttribArray(i));
//Define each attribute in the data which in turn is in the buffer
//ip1: start
//ip2: for example, how many data blocks at once(currently float), so for a 2D position its 2 float blocks
//ip5: data total size
//offset from start of attribute array
//for example: GLCall(glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 2, 0));
//http://docs.gl/gl4/glVertexAttribPointer
GLCall(glVertexAttribPointer(i, element.count, element.type, element.normalized, layout.GetStride(), (const void*)offset));
offset += element.count * VertexBufferElement::GetSizeOfType(element.type);
}
}
void VertexArray::Bind() const
{
//After creating the array, u need to select the array which is called "Binding" in opengl
GLCall(glBindVertexArray(m_RendererID));
//after binding the vertex array, in the next set of code you are binding a vertex buffer and defining attributes' structure in the vertex buffer,
//Which will in turn be linked to the just created vertex array so that we can eliminate calling vertex attribute setup function every frame
}
void VertexArray::UnBind() const
{
GLCall(glBindVertexArray(0));
}
| [
"prajwalshetty2018@gmail.com"
] | prajwalshetty2018@gmail.com |
d4bee95f847bfa90edebc5fabc13561f5e9ed641 | 1f6824a64c3cc6b0827b55f24079edc23ed6bc2b | /Plugins/VoxelFree/Source/VoxelGraph/Private/VoxelNodes/VoxelRandomNodes.cpp | 92560c144a25fe04c2c9cfed7baba553998ddf58 | [
"MIT"
] | permissive | lineCode/Woodlands | bb330644567c92e041e4da3d5d80326755c370c5 | 9e99f948543ad3f8f0eead691eddb4125da272f5 | refs/heads/master | 2023-04-15T13:56:45.978505 | 2021-04-19T04:30:44 | 2021-04-19T04:30:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | // Copyright 2021 Phyronnaz
#include "VoxelNodes/VoxelRandomNodes.h"
#include "Runtime/VoxelNodeType.h"
#include "CppTranslation/VoxelVariables.h"
#include "VoxelContext.h"
#include "NodeFunctions/VoxelNodeFunctions.h"
UVoxelNode_RandomFloat::UVoxelNode_RandomFloat()
{
SetInputs({"Seed", EC::Seed, "Seed"});
SetOutputs(EC::Float);
}
FText UVoxelNode_RandomFloat::GetTitle() const
{
return FText::FromString("Rand Float " + FString::SanitizeFloat(Min) + " " + FString::SanitizeFloat(Max));
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
UVoxelNode_RandomInt::UVoxelNode_RandomInt()
{
SetInputs({"Seed", EC::Seed, "Seed"});
SetOutputs(EC::Int);
}
FText UVoxelNode_RandomInt::GetTitle() const
{
return FText::FromString("Rand Int " + FString::FromInt(Min) + " " + FString::FromInt(Max));
}
| [
"Mattrb_99@ymail.com"
] | Mattrb_99@ymail.com |
c6f6d1c7c2348cca9ee888349d5c9bc2a6e2b30c | d4e1dba9e6e58e9654fd5affad7b836f6a71f02e | /object_tracker/src/image_tracking_ex.cpp | 63f532477c3450f9b236e34ce8e77a8cc8c34230 | [] | no_license | DavidHan008/visual_tracker_ros | 2ac1bd1b266dc3579c8f3e70343d213b8aea35bf | 146f34a2bc99e1f70ad599174b643ebe626b311e | refs/heads/master | 2020-03-17T17:02:21.487899 | 2017-07-19T09:52:16 | 2017-07-19T09:52:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,747 | cpp | // The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
/*
This example shows how to use the correlation_tracker from the dlib C++ library. This
object lets you track the position of an object as it moves from frame to frame in a
video sequence. To use it, you give the correlation_tracker the bounding box of the
object you want to track in the current video frame. Then it will identify the
location of the object in subsequent frames.
In this particular example, we are going to run on the video sequence that comes with
dlib, which can be found in the examples/video_frames folder. This video shows a juice
box sitting on a table and someone is waving the camera around. The task is to track the
position of the juice box as the camera moves around.
*/
#include<time.h>
#include <dlib/image_processing.h>
#include <dlib/gui_widgets.h>
#include <dlib/image_io.h>
#include <dlib/dir_nav.h>
#include <dlib/opencv.h>
#include<opencv2/core/utility.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgproc.hpp>
#include <iostream>
#include <signal.h>
#include <termios.h>
using namespace cv;
//using namespace dlib;
using namespace std;
static Mat image;
static Rect boundingBox;
static bool paused;
static bool selectObject=false;
static bool startSelection=false;
static void onMouse(int event,int x,int y,int,void*)
{
if(!selectObject)
{
switch(event)
{
case EVENT_LBUTTONDOWN:
startSelection=true;
boundingBox.x=x;
boundingBox.y=y;
break;
case EVENT_LBUTTONUP:
boundingBox.width=std::abs(x-boundingBox.x);
boundingBox.height=std::abs(y-boundingBox.y);
paused=false;
selectObject=true;
break;
case EVENT_MOUSEMOVE:
if(startSelection && !selectObject)
{
Mat currentFrame;
image.copyTo(currentFrame);
rectangle(currentFrame,Point(boundingBox.x,boundingBox.y),Point(x,y),Scalar(255,0,0),2,1);
imshow("Tracking API",currentFrame);
}
break;
}
}
}
long getcurrentMill()
{
struct timeval tv;
gettimeofday(&tv,NULL);
return tv.tv_sec*1000+tv.tv_usec/1000;
}
bool compare1(dlib::file& f1,dlib::file& f2)
{
int index1= f1.full_name().find_last_of('/');
std::string name1= f1.full_name().substr(index1+1);
int temp1= name1.find_first_of('.');
std::string nameonly1=name1.substr(0,temp1);
int namenum1=std::atoi(nameonly1.c_str());
int index2= f2.full_name().find_last_of('/');
std::string name2= f2.full_name().substr(index2+1);
int temp2= name2.find_first_of('.');
std::string nameonly2=name2.substr(0,temp2);
int namenum2=std::atoi(nameonly2.c_str());
return namenum1<namenum2;
}
int main(int argc, char** argv) try
{
//CommandLineParser parser(argc,argv,"param error!");
//String video_name=parser.get<String>(1);
// if (video_name.empty())
// {
// cout << "Call this program like this: " << endl;
// cout << "./video_tracking_ex /dev/video0" << endl;
// return 1;
// }
cout<<"fuck!";
if(argc!=3)
{
cout<<"param wrong!";
return 0;
}
//Mat frame;
paused=true;
namedWindow("Tracking API",1);
setMouseCallback("Tracking API",onMouse,0);
dlib::correlation_tracker tracker;
//Get the list of video frames.
std::vector<dlib::file> files = dlib::get_files_in_directory_tree(argv[1], dlib::match_ending(argv[2]));
std::sort(files.begin(), files.end(),compare1);
if (files.size() == 0)
{
cout << "No images found in " << argv[1] << endl;
return 1;
}
// Load the first frame.
dlib::array2d<dlib::bgr_pixel> img;
//dlib::cv_image<dlib::bgr_pixel> img;
dlib::load_image(img, files[0]);
Mat frame=dlib::toMat(img);
frame.copyTo(image);
imshow("Tracking API",image);
long oldtime=getcurrentMill();
int fps=0;
bool initialized=false;
int fileIndex=1;
for(;;)
{
if(!paused)
{
fps++;
if(getcurrentMill()>oldtime+1000)
{
cout<<fps<<" ";
fps=0;
oldtime=getcurrentMill();
cout.flush();
}
//cout<<getcurrentMill()<<endl;
//cap>>frame;
//dlib::cv_image<dlib::bgr_pixel> cimg(frame);
if(!initialized && selectObject)
{
tracker.start_track(img, dlib::drectangle(boundingBox.x,boundingBox.y,boundingBox.x+boundingBox.width,boundingBox.y+boundingBox.height));
initialized=true;
}
else if(initialized)
{
if(fileIndex>=files.size())
break;
dlib::load_image(img,files[fileIndex++]);
frame=dlib::toMat(img);
frame.copyTo(image);
double rtn=tracker.update(img);
if(rtn)
{
Rect targRect;
targRect.x=tracker.get_position().left();
targRect.y=tracker.get_position().top();
targRect.width=tracker.get_position().width();
targRect.height=tracker.get_position().height();
cv::rectangle(image,targRect,Scalar(255,0,0),2,1);
std::stringstream ss;
ss<<rtn;
string rtnStr;
ss>>rtnStr;
std::cout<<rtn<<std::endl;
//cv::putText(image,rtnStr,targRect.br(),2,0.5,Scalar(255,0,0));
// time_t new_time= time(NULL);
// count++;
// time_t new_time= time(NULL);
// if(new_time>=timer+1)
// {
// cout<<count<<" ";
// timer=new_time;
// count=0;
// }
}
//usleep(500);
//sleep(1);
}
imshow("Tracking API",image);
}
char c=(char)waitKey(2);
if(c=='q')
break;
if(c=='p')
paused=!paused;
}
return 0;
// Get the list of video frames.
//std::vector<file> files = dlib::get_files_in_directory_tree(argv[1], match_ending(".jpg"));
//std::sort(files.begin(), files.end());
// if (files.size() == 0)
// {
// cout << "No images found in " << argv[1] << endl;
// return 1;
// }
// Load the first frame.
//dlib::array2d<unsigned char> img;
//dlib::load_image(img, files[0]);
// Now create a tracker and start a track on the juice box. If you look at the first
// frame you will see that the juice box is centered at pixel point(92,110) and 38
// pixels wide and 86 pixels tall.
//correlation_tracker tracker;
//tracker.start_track(img, centered_rect(point(93,110), 38, 86));
// Now run the tracker. All we have to do is call tracker.update() and it will keep
// track of the juice box!
// image_window win;
// for (unsigned long i = 1; i < files.size(); ++i)
// {
// load_image(img, files[i]);
// tracker.update(img);
// win.set_image(img);
// win.clear_overlay();
// win.add_overlay(tracker.get_position());
// cout << "hit enter to process next frame" << endl;
// cin.get();
// }
}
catch (std::exception& e)
{
cout << e.what() << endl;
}
| [
"1053988516@qq.com"
] | 1053988516@qq.com |
0e870ea6e0668c8fc374fe1b834a071e4a839a6f | 248bdd698605a8b2b623fe82899eec15bc80b889 | /gfx/harfbuzz/src/hb-subset-cff1.cc | 49ac0bf429914fe4ac45b60518e838feb1665ab0 | [
"LicenseRef-scancode-other-permissive",
"MIT-Modern-Variant",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Feodor2/Mypal68 | 64a6f8055cb22ae6183a3a018e1487a44e20886e | dc92ce6bcc8032b5311ffc4f9f0cca38411637b1 | refs/heads/main | 2023-08-31T00:31:47.840415 | 2023-08-26T10:26:15 | 2023-08-26T10:26:15 | 478,824,817 | 393 | 39 | NOASSERTION | 2023-06-23T04:53:57 | 2022-04-07T04:21:39 | null | UTF-8 | C++ | false | false | 35,156 | cc | /*
* Copyright © 2018 Adobe Inc.
*
* This is part of HarfBuzz, a text shaping library.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in
* all copies of this software.
*
* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Adobe Author(s): Michiharu Ariza
*/
#include "hb-open-type.hh"
#include "hb-ot-cff1-table.hh"
#include "hb-set.h"
#include "hb-subset-cff1.hh"
#include "hb-subset-plan.hh"
#include "hb-subset-cff-common.hh"
#include "hb-cff1-interp-cs.hh"
using namespace CFF;
struct remap_sid_t : remap_t
{
unsigned int add (unsigned int sid)
{
if ((sid != CFF_UNDEF_SID) && !is_std_std (sid))
return offset_sid (remap_t::add (unoffset_sid (sid)));
else
return sid;
}
unsigned int operator[] (unsigned int sid) const
{
if (is_std_std (sid) || (sid == CFF_UNDEF_SID))
return sid;
else
return offset_sid (remap_t::operator [] (unoffset_sid (sid)));
}
static const unsigned int num_std_strings = 391;
static bool is_std_std (unsigned int sid) { return sid < num_std_strings; }
static unsigned int offset_sid (unsigned int sid) { return sid + num_std_strings; }
static unsigned int unoffset_sid (unsigned int sid) { return sid - num_std_strings; }
};
struct cff1_sub_table_offsets_t : cff_sub_table_offsets_t
{
cff1_sub_table_offsets_t ()
: cff_sub_table_offsets_t (),
nameIndexOffset (0),
encodingOffset (0)
{
stringIndexInfo.init ();
charsetInfo.init ();
privateDictInfo.init ();
}
unsigned int nameIndexOffset;
table_info_t stringIndexInfo;
unsigned int encodingOffset;
table_info_t charsetInfo;
table_info_t privateDictInfo;
};
/* a copy of a parsed out cff1_top_dict_values_t augmented with additional operators */
struct cff1_top_dict_values_mod_t : cff1_top_dict_values_t
{
void init (const cff1_top_dict_values_t *base_= &Null(cff1_top_dict_values_t))
{
SUPER::init ();
base = base_;
}
void fini () { SUPER::fini (); }
unsigned get_count () const { return base->get_count () + SUPER::get_count (); }
const cff1_top_dict_val_t &get_value (unsigned int i) const
{
if (i < base->get_count ())
return (*base)[i];
else
return SUPER::values[i - base->get_count ()];
}
const cff1_top_dict_val_t &operator [] (unsigned int i) const { return get_value (i); }
void reassignSIDs (const remap_sid_t& sidmap)
{
for (unsigned int i = 0; i < name_dict_values_t::ValCount; i++)
nameSIDs[i] = sidmap[base->nameSIDs[i]];
}
protected:
typedef cff1_top_dict_values_t SUPER;
const cff1_top_dict_values_t *base;
};
struct top_dict_modifiers_t
{
top_dict_modifiers_t (const cff1_sub_table_offsets_t &offsets_,
const unsigned int (&nameSIDs_)[name_dict_values_t::ValCount])
: offsets (offsets_),
nameSIDs (nameSIDs_)
{}
const cff1_sub_table_offsets_t &offsets;
const unsigned int (&nameSIDs)[name_dict_values_t::ValCount];
};
struct cff1_top_dict_op_serializer_t : cff_top_dict_op_serializer_t<cff1_top_dict_val_t>
{
bool serialize (hb_serialize_context_t *c,
const cff1_top_dict_val_t &opstr,
const top_dict_modifiers_t &mod) const
{
TRACE_SERIALIZE (this);
op_code_t op = opstr.op;
switch (op)
{
case OpCode_charset:
return_trace (FontDict::serialize_offset4_op(c, op, mod.offsets.charsetInfo.offset));
case OpCode_Encoding:
return_trace (FontDict::serialize_offset4_op(c, op, mod.offsets.encodingOffset));
case OpCode_Private:
{
if (unlikely (!UnsizedByteStr::serialize_int2 (c, mod.offsets.privateDictInfo.size)))
return_trace (false);
if (unlikely (!UnsizedByteStr::serialize_int4 (c, mod.offsets.privateDictInfo.offset)))
return_trace (false);
HBUINT8 *p = c->allocate_size<HBUINT8> (1);
if (unlikely (p == nullptr)) return_trace (false);
p->set (OpCode_Private);
}
break;
case OpCode_version:
case OpCode_Notice:
case OpCode_Copyright:
case OpCode_FullName:
case OpCode_FamilyName:
case OpCode_Weight:
case OpCode_PostScript:
case OpCode_BaseFontName:
case OpCode_FontName:
return_trace (FontDict::serialize_offset2_op(c, op, mod.nameSIDs[name_dict_values_t::name_op_to_index (op)]));
case OpCode_ROS:
{
/* for registry & ordering, reassigned SIDs are serialized
* for supplement, the original byte string is copied along with the op code */
op_str_t supp_op;
supp_op.op = op;
if ( unlikely (!(opstr.str.length >= opstr.last_arg_offset + 3)))
return_trace (false);
supp_op.str = byte_str_t (&opstr.str + opstr.last_arg_offset, opstr.str.length - opstr.last_arg_offset);
return_trace (UnsizedByteStr::serialize_int2 (c, mod.nameSIDs[name_dict_values_t::registry]) &&
UnsizedByteStr::serialize_int2 (c, mod.nameSIDs[name_dict_values_t::ordering]) &&
copy_opstr (c, supp_op));
}
default:
return_trace (cff_top_dict_op_serializer_t<cff1_top_dict_val_t>::serialize (c, opstr, mod.offsets));
}
return_trace (true);
}
unsigned int calculate_serialized_size (const cff1_top_dict_val_t &opstr) const
{
op_code_t op = opstr.op;
switch (op)
{
case OpCode_charset:
case OpCode_Encoding:
return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (op);
case OpCode_Private:
return OpCode_Size (OpCode_longintdict) + 4 + OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_Private);
case OpCode_version:
case OpCode_Notice:
case OpCode_Copyright:
case OpCode_FullName:
case OpCode_FamilyName:
case OpCode_Weight:
case OpCode_PostScript:
case OpCode_BaseFontName:
case OpCode_FontName:
return OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (op);
case OpCode_ROS:
return ((OpCode_Size (OpCode_shortint) + 2) * 2) + (opstr.str.length - opstr.last_arg_offset)/* supplement + op */;
default:
return cff_top_dict_op_serializer_t<cff1_top_dict_val_t>::calculate_serialized_size (opstr);
}
}
};
struct font_dict_values_mod_t
{
void init (const cff1_font_dict_values_t *base_,
unsigned int fontName_,
const table_info_t &privateDictInfo_)
{
base = base_;
fontName = fontName_;
privateDictInfo = privateDictInfo_;
}
unsigned get_count () const { return base->get_count (); }
const op_str_t &operator [] (unsigned int i) const { return (*base)[i]; }
const cff1_font_dict_values_t *base;
table_info_t privateDictInfo;
unsigned int fontName;
};
struct cff1_font_dict_op_serializer_t : cff_font_dict_op_serializer_t
{
bool serialize (hb_serialize_context_t *c,
const op_str_t &opstr,
const font_dict_values_mod_t &mod) const
{
TRACE_SERIALIZE (this);
if (opstr.op == OpCode_FontName)
return_trace (FontDict::serialize_uint2_op (c, opstr.op, mod.fontName));
else
return_trace (SUPER::serialize (c, opstr, mod.privateDictInfo));
}
unsigned int calculate_serialized_size (const op_str_t &opstr) const
{
if (opstr.op == OpCode_FontName)
return OpCode_Size (OpCode_shortint) + 2 + OpCode_Size (OpCode_FontName);
else
return SUPER::calculate_serialized_size (opstr);
}
private:
typedef cff_font_dict_op_serializer_t SUPER;
};
struct cff1_cs_opset_flatten_t : cff1_cs_opset_t<cff1_cs_opset_flatten_t, flatten_param_t>
{
static void flush_args_and_op (op_code_t op, cff1_cs_interp_env_t &env, flatten_param_t& param)
{
if (env.arg_start > 0)
flush_width (env, param);
switch (op)
{
case OpCode_hstem:
case OpCode_hstemhm:
case OpCode_vstem:
case OpCode_vstemhm:
case OpCode_hintmask:
case OpCode_cntrmask:
case OpCode_dotsection:
if (param.drop_hints)
{
env.clear_args ();
return;
}
HB_FALLTHROUGH;
default:
SUPER::flush_args_and_op (op, env, param);
break;
}
}
static void flush_args (cff1_cs_interp_env_t &env, flatten_param_t& param)
{
str_encoder_t encoder (param.flatStr);
for (unsigned int i = env.arg_start; i < env.argStack.get_count (); i++)
encoder.encode_num (env.eval_arg (i));
SUPER::flush_args (env, param);
}
static void flush_op (op_code_t op, cff1_cs_interp_env_t &env, flatten_param_t& param)
{
str_encoder_t encoder (param.flatStr);
encoder.encode_op (op);
}
static void flush_width (cff1_cs_interp_env_t &env, flatten_param_t& param)
{
assert (env.has_width);
str_encoder_t encoder (param.flatStr);
encoder.encode_num (env.width);
}
static void flush_hintmask (op_code_t op, cff1_cs_interp_env_t &env, flatten_param_t& param)
{
SUPER::flush_hintmask (op, env, param);
if (!param.drop_hints)
{
str_encoder_t encoder (param.flatStr);
for (unsigned int i = 0; i < env.hintmask_size; i++)
encoder.encode_byte (env.str_ref[i]);
}
}
private:
typedef cff1_cs_opset_t<cff1_cs_opset_flatten_t, flatten_param_t> SUPER;
};
struct range_list_t : hb_vector_t<code_pair_t>
{
/* replace the first glyph ID in the "glyph" field each range with a nLeft value */
bool finalize (unsigned int last_glyph)
{
bool two_byte = false;
for (unsigned int i = (*this).length; i > 0; i--)
{
code_pair_t &pair = (*this)[i - 1];
unsigned int nLeft = last_glyph - pair.glyph - 1;
if (nLeft >= 0x100)
two_byte = true;
last_glyph = pair.glyph;
pair.glyph = nLeft;
}
return two_byte;
}
};
struct cff1_cs_opset_subr_subset_t : cff1_cs_opset_t<cff1_cs_opset_subr_subset_t, subr_subset_param_t>
{
static void process_op (op_code_t op, cff1_cs_interp_env_t &env, subr_subset_param_t& param)
{
switch (op) {
case OpCode_return:
param.current_parsed_str->add_op (op, env.str_ref);
param.current_parsed_str->set_parsed ();
env.returnFromSubr ();
param.set_current_str (env, false);
break;
case OpCode_endchar:
param.current_parsed_str->add_op (op, env.str_ref);
param.current_parsed_str->set_parsed ();
SUPER::process_op (op, env, param);
break;
case OpCode_callsubr:
process_call_subr (op, CSType_LocalSubr, env, param, env.localSubrs, param.local_closure);
break;
case OpCode_callgsubr:
process_call_subr (op, CSType_GlobalSubr, env, param, env.globalSubrs, param.global_closure);
break;
default:
SUPER::process_op (op, env, param);
param.current_parsed_str->add_op (op, env.str_ref);
break;
}
}
protected:
static void process_call_subr (op_code_t op, cs_type_t type,
cff1_cs_interp_env_t &env, subr_subset_param_t& param,
cff1_biased_subrs_t& subrs, hb_set_t *closure)
{
byte_str_ref_t str_ref = env.str_ref;
env.callSubr (subrs, type);
param.current_parsed_str->add_call_op (op, str_ref, env.context.subr_num);
hb_set_add (closure, env.context.subr_num);
param.set_current_str (env, true);
}
private:
typedef cff1_cs_opset_t<cff1_cs_opset_subr_subset_t, subr_subset_param_t> SUPER;
};
struct cff1_subr_subsetter_t : subr_subsetter_t<cff1_subr_subsetter_t, CFF1Subrs, const OT::cff1::accelerator_subset_t, cff1_cs_interp_env_t, cff1_cs_opset_subr_subset_t, OpCode_endchar>
{
cff1_subr_subsetter_t (const OT::cff1::accelerator_subset_t &acc, const hb_subset_plan_t *plan)
: subr_subsetter_t (acc, plan) {}
static void finalize_parsed_str (cff1_cs_interp_env_t &env, subr_subset_param_t& param, parsed_cs_str_t &charstring)
{
/* insert width at the beginning of the charstring as necessary */
if (env.has_width)
charstring.set_prefix (env.width);
/* subroutines/charstring left on the call stack are legally left unmarked
* unmarked when a subroutine terminates with endchar. mark them.
*/
param.current_parsed_str->set_parsed ();
for (unsigned int i = 0; i < env.callStack.get_count (); i++)
{
parsed_cs_str_t *parsed_str = param.get_parsed_str_for_context (env.callStack[i]);
if (likely (parsed_str != nullptr))
parsed_str->set_parsed ();
else
env.set_error ();
}
}
};
struct cff_subset_plan {
cff_subset_plan ()
: final_size (0),
offsets (),
orig_fdcount (0),
subset_fdcount (1),
subset_fdselect_format (0),
drop_hints (false),
desubroutinize(false)
{
topdict_sizes.init ();
topdict_sizes.resize (1);
topdict_mod.init ();
subset_fdselect_ranges.init ();
fdmap.init ();
subset_charstrings.init ();
subset_globalsubrs.init ();
subset_localsubrs.init ();
fontdicts_mod.init ();
subset_enc_code_ranges.init ();
subset_enc_supp_codes.init ();
subset_charset_ranges.init ();
sidmap.init ();
for (unsigned int i = 0; i < name_dict_values_t::ValCount; i++)
topDictModSIDs[i] = CFF_UNDEF_SID;
}
~cff_subset_plan ()
{
topdict_sizes.fini ();
topdict_mod.fini ();
subset_fdselect_ranges.fini ();
fdmap.fini ();
subset_charstrings.fini_deep ();
subset_globalsubrs.fini_deep ();
subset_localsubrs.fini_deep ();
fontdicts_mod.fini ();
subset_enc_code_ranges.fini ();
subset_enc_supp_codes.fini ();
subset_charset_ranges.fini ();
sidmap.fini ();
}
unsigned int plan_subset_encoding (const OT::cff1::accelerator_subset_t &acc, hb_subset_plan_t *plan)
{
const Encoding *encoding = acc.encoding;
unsigned int size0, size1, supp_size;
hb_codepoint_t code, last_code = CFF_UNDEF_CODE;
hb_vector_t<hb_codepoint_t> supp_codes;
subset_enc_code_ranges.resize (0);
supp_size = 0;
supp_codes.init ();
subset_enc_num_codes = plan->num_output_glyphs () - 1;
unsigned int glyph;
for (glyph = 1; glyph < plan->num_output_glyphs (); glyph++)
{
hb_codepoint_t old_glyph;
if (!plan->old_gid_for_new_gid (glyph, &old_glyph))
{
/* Retain the code for the old missing glyph ID */
old_glyph = glyph;
}
code = acc.glyph_to_code (old_glyph);
if (code == CFF_UNDEF_CODE)
{
subset_enc_num_codes = glyph - 1;
break;
}
if ((last_code == CFF_UNDEF_CODE) || (code != last_code + 1))
{
code_pair_t pair = { code, glyph };
subset_enc_code_ranges.push (pair);
}
last_code = code;
if (encoding != &Null(Encoding))
{
hb_codepoint_t sid = acc.glyph_to_sid (old_glyph);
encoding->get_supplement_codes (sid, supp_codes);
for (unsigned int i = 0; i < supp_codes.length; i++)
{
code_pair_t pair = { supp_codes[i], sid };
subset_enc_supp_codes.push (pair);
}
supp_size += SuppEncoding::static_size * supp_codes.length;
}
}
supp_codes.fini ();
subset_enc_code_ranges.finalize (glyph);
assert (subset_enc_num_codes <= 0xFF);
size0 = Encoding0::min_size + HBUINT8::static_size * subset_enc_num_codes;
size1 = Encoding1::min_size + Encoding1_Range::static_size * subset_enc_code_ranges.length;
if (size0 < size1)
subset_enc_format = 0;
else
subset_enc_format = 1;
return Encoding::calculate_serialized_size (
subset_enc_format,
subset_enc_format? subset_enc_code_ranges.length: subset_enc_num_codes,
subset_enc_supp_codes.length);
}
unsigned int plan_subset_charset (const OT::cff1::accelerator_subset_t &acc, hb_subset_plan_t *plan)
{
unsigned int size0, size_ranges;
hb_codepoint_t sid, last_sid = CFF_UNDEF_CODE;
subset_charset_ranges.resize (0);
unsigned int glyph;
for (glyph = 1; glyph < plan->num_output_glyphs (); glyph++)
{
hb_codepoint_t old_glyph;
if (!plan->old_gid_for_new_gid (glyph, &old_glyph))
{
/* Retain the SID for the old missing glyph ID */
old_glyph = glyph;
}
sid = acc.glyph_to_sid (old_glyph);
if (!acc.is_CID ())
sid = sidmap.add (sid);
if ((last_sid == CFF_UNDEF_CODE) || (sid != last_sid + 1))
{
code_pair_t pair = { sid, glyph };
subset_charset_ranges.push (pair);
}
last_sid = sid;
}
bool two_byte = subset_charset_ranges.finalize (glyph);
size0 = Charset0::min_size + HBUINT16::static_size * (plan->num_output_glyphs () - 1);
if (!two_byte)
size_ranges = Charset1::min_size + Charset1_Range::static_size * subset_charset_ranges.length;
else
size_ranges = Charset2::min_size + Charset2_Range::static_size * subset_charset_ranges.length;
if (size0 < size_ranges)
subset_charset_format = 0;
else if (!two_byte)
subset_charset_format = 1;
else
subset_charset_format = 2;
return Charset::calculate_serialized_size (
subset_charset_format,
subset_charset_format? subset_charset_ranges.length: plan->num_output_glyphs ());
}
bool collect_sids_in_dicts (const OT::cff1::accelerator_subset_t &acc)
{
if (unlikely (!sidmap.reset (acc.stringIndex->count)))
return false;
for (unsigned int i = 0; i < name_dict_values_t::ValCount; i++)
{
unsigned int sid = acc.topDict.nameSIDs[i];
if (sid != CFF_UNDEF_SID)
{
(void)sidmap.add (sid);
topDictModSIDs[i] = sidmap[sid];
}
}
if (acc.fdArray != &Null(CFF1FDArray))
for (unsigned int i = 0; i < orig_fdcount; i++)
if (fdmap.includes (i))
(void)sidmap.add (acc.fontDicts[i].fontName);
return true;
}
bool create (const OT::cff1::accelerator_subset_t &acc,
hb_subset_plan_t *plan)
{
/* make sure notdef is first */
hb_codepoint_t old_glyph;
if (!plan->old_gid_for_new_gid (0, &old_glyph) || (old_glyph != 0)) return false;
final_size = 0;
num_glyphs = plan->num_output_glyphs ();
orig_fdcount = acc.fdCount;
drop_hints = plan->drop_hints;
desubroutinize = plan->desubroutinize;
/* check whether the subset renumbers any glyph IDs */
gid_renum = false;
for (hb_codepoint_t new_glyph = 0; new_glyph < plan->num_output_glyphs (); new_glyph++)
{
if (!plan->old_gid_for_new_gid(new_glyph, &old_glyph))
continue;
if (new_glyph != old_glyph) {
gid_renum = true;
break;
}
}
subset_charset = gid_renum || !acc.is_predef_charset ();
subset_encoding = !acc.is_CID() && !acc.is_predef_encoding ();
/* CFF header */
final_size += OT::cff1::static_size;
/* Name INDEX */
offsets.nameIndexOffset = final_size;
final_size += acc.nameIndex->get_size ();
/* top dict INDEX */
{
/* Add encoding/charset to a (copy of) top dict as necessary */
topdict_mod.init (&acc.topDict);
bool need_to_add_enc = (subset_encoding && !acc.topDict.has_op (OpCode_Encoding));
bool need_to_add_set = (subset_charset && !acc.topDict.has_op (OpCode_charset));
if (need_to_add_enc || need_to_add_set)
{
if (need_to_add_enc)
topdict_mod.add_op (OpCode_Encoding);
if (need_to_add_set)
topdict_mod.add_op (OpCode_charset);
}
offsets.topDictInfo.offset = final_size;
cff1_top_dict_op_serializer_t topSzr;
unsigned int topDictSize = TopDict::calculate_serialized_size (topdict_mod, topSzr);
offsets.topDictInfo.offSize = calcOffSize(topDictSize);
if (unlikely (offsets.topDictInfo.offSize > 4))
return false;
final_size += CFF1IndexOf<TopDict>::calculate_serialized_size<cff1_top_dict_values_mod_t>
(offsets.topDictInfo.offSize,
&topdict_mod, 1, topdict_sizes, topSzr);
}
/* Determine re-mapping of font index as fdmap among other info */
if (acc.fdSelect != &Null(CFF1FDSelect))
{
if (unlikely (!hb_plan_subset_cff_fdselect (plan,
orig_fdcount,
*acc.fdSelect,
subset_fdcount,
offsets.FDSelectInfo.size,
subset_fdselect_format,
subset_fdselect_ranges,
fdmap)))
return false;
}
else
fdmap.identity (1);
/* remove unused SIDs & reassign SIDs */
{
/* SIDs for name strings in dicts are added before glyph names so they fit in 16-bit int range */
if (unlikely (!collect_sids_in_dicts (acc)))
return false;
if (unlikely (sidmap.get_count () > 0x8000)) /* assumption: a dict won't reference that many strings */
return false;
if (subset_charset)
offsets.charsetInfo.size = plan_subset_charset (acc, plan);
topdict_mod.reassignSIDs (sidmap);
}
/* String INDEX */
{
offsets.stringIndexInfo.offset = final_size;
offsets.stringIndexInfo.size = acc.stringIndex->calculate_serialized_size (offsets.stringIndexInfo.offSize, sidmap);
final_size += offsets.stringIndexInfo.size;
}
if (desubroutinize)
{
/* Flatten global & local subrs */
subr_flattener_t<const OT::cff1::accelerator_subset_t, cff1_cs_interp_env_t, cff1_cs_opset_flatten_t, OpCode_endchar>
flattener(acc, plan);
if (!flattener.flatten (subset_charstrings))
return false;
/* no global/local subroutines */
offsets.globalSubrsInfo.size = CFF1Subrs::calculate_serialized_size (1, 0, 0);
}
else
{
cff1_subr_subsetter_t subr_subsetter (acc, plan);
/* Subset subrs: collect used subroutines, leaving all unused ones behind */
if (!subr_subsetter.subset ())
return false;
/* encode charstrings, global subrs, local subrs with new subroutine numbers */
if (!subr_subsetter.encode_charstrings (subset_charstrings))
return false;
if (!subr_subsetter.encode_globalsubrs (subset_globalsubrs))
return false;
/* global subrs */
unsigned int dataSize = subset_globalsubrs.total_size ();
offsets.globalSubrsInfo.offSize = calcOffSize (dataSize);
if (unlikely (offsets.globalSubrsInfo.offSize > 4))
return false;
offsets.globalSubrsInfo.size = CFF1Subrs::calculate_serialized_size (offsets.globalSubrsInfo.offSize, subset_globalsubrs.length, dataSize);
/* local subrs */
if (!offsets.localSubrsInfos.resize (orig_fdcount))
return false;
if (!subset_localsubrs.resize (orig_fdcount))
return false;
for (unsigned int fd = 0; fd < orig_fdcount; fd++)
{
subset_localsubrs[fd].init ();
offsets.localSubrsInfos[fd].init ();
if (fdmap.includes (fd))
{
if (!subr_subsetter.encode_localsubrs (fd, subset_localsubrs[fd]))
return false;
unsigned int dataSize = subset_localsubrs[fd].total_size ();
if (dataSize > 0)
{
offsets.localSubrsInfos[fd].offset = final_size;
offsets.localSubrsInfos[fd].offSize = calcOffSize (dataSize);
if (unlikely (offsets.localSubrsInfos[fd].offSize > 4))
return false;
offsets.localSubrsInfos[fd].size = CFF1Subrs::calculate_serialized_size (offsets.localSubrsInfos[fd].offSize, subset_localsubrs[fd].length, dataSize);
}
}
}
}
/* global subrs */
offsets.globalSubrsInfo.offset = final_size;
final_size += offsets.globalSubrsInfo.size;
/* Encoding */
if (!subset_encoding)
offsets.encodingOffset = acc.topDict.EncodingOffset;
else
{
offsets.encodingOffset = final_size;
final_size += plan_subset_encoding (acc, plan);
}
/* Charset */
if (!subset_charset && acc.is_predef_charset ())
offsets.charsetInfo.offset = acc.topDict.CharsetOffset;
else
offsets.charsetInfo.offset = final_size;
final_size += offsets.charsetInfo.size;
/* FDSelect */
if (acc.fdSelect != &Null(CFF1FDSelect))
{
offsets.FDSelectInfo.offset = final_size;
final_size += offsets.FDSelectInfo.size;
}
/* FDArray (FDIndex) */
if (acc.fdArray != &Null(CFF1FDArray)) {
offsets.FDArrayInfo.offset = final_size;
cff1_font_dict_op_serializer_t fontSzr;
unsigned int dictsSize = 0;
for (unsigned int i = 0; i < acc.fontDicts.length; i++)
if (fdmap.includes (i))
dictsSize += FontDict::calculate_serialized_size (acc.fontDicts[i], fontSzr);
offsets.FDArrayInfo.offSize = calcOffSize (dictsSize);
if (unlikely (offsets.FDArrayInfo.offSize > 4))
return false;
final_size += CFF1Index::calculate_serialized_size (offsets.FDArrayInfo.offSize, subset_fdcount, dictsSize);
}
/* CharStrings */
{
offsets.charStringsInfo.offset = final_size;
unsigned int dataSize = subset_charstrings.total_size ();
offsets.charStringsInfo.offSize = calcOffSize (dataSize);
if (unlikely (offsets.charStringsInfo.offSize > 4))
return false;
final_size += CFF1CharStrings::calculate_serialized_size (offsets.charStringsInfo.offSize, plan->num_output_glyphs (), dataSize);
}
/* private dicts & local subrs */
offsets.privateDictInfo.offset = final_size;
for (unsigned int i = 0; i < orig_fdcount; i++)
{
if (fdmap.includes (i))
{
bool has_localsubrs = offsets.localSubrsInfos[i].size > 0;
cff_private_dict_op_serializer_t privSzr (desubroutinize, plan->drop_hints);
unsigned int priv_size = PrivateDict::calculate_serialized_size (acc.privateDicts[i], privSzr, has_localsubrs);
table_info_t privInfo = { final_size, priv_size, 0 };
font_dict_values_mod_t fontdict_mod;
if (!acc.is_CID ())
fontdict_mod.init ( &Null(cff1_font_dict_values_t), CFF_UNDEF_SID, privInfo );
else
fontdict_mod.init ( &acc.fontDicts[i], sidmap[acc.fontDicts[i].fontName], privInfo );
fontdicts_mod.push (fontdict_mod);
final_size += privInfo.size;
if (!plan->desubroutinize && has_localsubrs)
{
offsets.localSubrsInfos[i].offset = final_size;
final_size += offsets.localSubrsInfos[i].size;
}
}
}
if (!acc.is_CID ())
offsets.privateDictInfo = fontdicts_mod[0].privateDictInfo;
return ((subset_charstrings.length == plan->num_output_glyphs ())
&& (fontdicts_mod.length == subset_fdcount));
}
unsigned int get_final_size () const { return final_size; }
unsigned int final_size;
hb_vector_t<unsigned int> topdict_sizes;
cff1_top_dict_values_mod_t topdict_mod;
cff1_sub_table_offsets_t offsets;
unsigned int num_glyphs;
unsigned int orig_fdcount;
unsigned int subset_fdcount;
unsigned int subset_fdselect_format;
hb_vector_t<code_pair_t> subset_fdselect_ranges;
/* font dict index remap table from fullset FDArray to subset FDArray.
* set to CFF_UNDEF_CODE if excluded from subset */
remap_t fdmap;
str_buff_vec_t subset_charstrings;
str_buff_vec_t subset_globalsubrs;
hb_vector_t<str_buff_vec_t> subset_localsubrs;
hb_vector_t<font_dict_values_mod_t> fontdicts_mod;
bool drop_hints;
bool gid_renum;
bool subset_encoding;
uint8_t subset_enc_format;
unsigned int subset_enc_num_codes;
range_list_t subset_enc_code_ranges;
hb_vector_t<code_pair_t> subset_enc_supp_codes;
uint8_t subset_charset_format;
range_list_t subset_charset_ranges;
bool subset_charset;
remap_sid_t sidmap;
unsigned int topDictModSIDs[name_dict_values_t::ValCount];
bool desubroutinize;
};
static inline bool _write_cff1 (const cff_subset_plan &plan,
const OT::cff1::accelerator_subset_t &acc,
unsigned int num_glyphs,
unsigned int dest_sz,
void *dest)
{
hb_serialize_context_t c (dest, dest_sz);
OT::cff1 *cff = c.start_serialize<OT::cff1> ();
if (unlikely (!c.extend_min (*cff)))
return false;
/* header */
cff->version.major.set (0x01);
cff->version.minor.set (0x00);
cff->nameIndex.set (cff->min_size);
cff->offSize.set (4); /* unused? */
/* name INDEX */
{
assert (cff->nameIndex == (unsigned) (c.head - c.start));
CFF1NameIndex *dest = c.start_embed<CFF1NameIndex> ();
if (unlikely (dest == nullptr)) return false;
if (unlikely (!dest->serialize (&c, *acc.nameIndex)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF name INDEX");
return false;
}
}
/* top dict INDEX */
{
assert (plan.offsets.topDictInfo.offset == (unsigned) (c.head - c.start));
CFF1IndexOf<TopDict> *dest = c.start_embed< CFF1IndexOf<TopDict> > ();
if (dest == nullptr) return false;
cff1_top_dict_op_serializer_t topSzr;
top_dict_modifiers_t modifier (plan.offsets, plan.topDictModSIDs);
if (unlikely (!dest->serialize (&c, plan.offsets.topDictInfo.offSize,
&plan.topdict_mod, 1,
plan.topdict_sizes, topSzr, modifier)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF top dict");
return false;
}
}
/* String INDEX */
{
assert (plan.offsets.stringIndexInfo.offset == (unsigned) (c.head - c.start));
CFF1StringIndex *dest = c.start_embed<CFF1StringIndex> ();
if (unlikely (dest == nullptr)) return false;
if (unlikely (!dest->serialize (&c, *acc.stringIndex, plan.offsets.stringIndexInfo.offSize, plan.sidmap)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF string INDEX");
return false;
}
}
/* global subrs */
{
assert (plan.offsets.globalSubrsInfo.offset != 0);
assert (plan.offsets.globalSubrsInfo.offset == (unsigned) (c.head - c.start));
CFF1Subrs *dest = c.start_embed <CFF1Subrs> ();
if (unlikely (dest == nullptr)) return false;
if (unlikely (!dest->serialize (&c, plan.offsets.globalSubrsInfo.offSize, plan.subset_globalsubrs)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize global subroutines");
return false;
}
}
/* Encoding */
if (plan.subset_encoding)
{
assert (plan.offsets.encodingOffset == (unsigned) (c.head - c.start));
Encoding *dest = c.start_embed<Encoding> ();
if (unlikely (dest == nullptr)) return false;
if (unlikely (!dest->serialize (&c,
plan.subset_enc_format,
plan.subset_enc_num_codes,
plan.subset_enc_code_ranges,
plan.subset_enc_supp_codes)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize Encoding");
return false;
}
}
/* Charset */
if (plan.subset_charset)
{
assert (plan.offsets.charsetInfo.offset == (unsigned) (c.head - c.start));
Charset *dest = c.start_embed<Charset> ();
if (unlikely (dest == nullptr)) return false;
if (unlikely (!dest->serialize (&c,
plan.subset_charset_format,
plan.num_glyphs,
plan.subset_charset_ranges)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize Charset");
return false;
}
}
/* FDSelect */
if (acc.fdSelect != &Null(CFF1FDSelect))
{
assert (plan.offsets.FDSelectInfo.offset == (unsigned) (c.head - c.start));
if (unlikely (!hb_serialize_cff_fdselect (&c, num_glyphs, *acc.fdSelect, acc.fdCount,
plan.subset_fdselect_format, plan.offsets.FDSelectInfo.size,
plan.subset_fdselect_ranges)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF subset FDSelect");
return false;
}
}
/* FDArray (FD Index) */
if (acc.fdArray != &Null(CFF1FDArray))
{
assert (plan.offsets.FDArrayInfo.offset == (unsigned) (c.head - c.start));
CFF1FDArray *fda = c.start_embed<CFF1FDArray> ();
if (unlikely (fda == nullptr)) return false;
cff1_font_dict_op_serializer_t fontSzr;
if (unlikely (!fda->serialize (&c, plan.offsets.FDArrayInfo.offSize,
plan.fontdicts_mod,
fontSzr)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF FDArray");
return false;
}
}
/* CharStrings */
{
assert (plan.offsets.charStringsInfo.offset == (unsigned) (c.head - c.start));
CFF1CharStrings *cs = c.start_embed<CFF1CharStrings> ();
if (unlikely (cs == nullptr)) return false;
if (unlikely (!cs->serialize (&c, plan.offsets.charStringsInfo.offSize, plan.subset_charstrings)))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF CharStrings");
return false;
}
}
/* private dicts & local subrs */
assert (plan.offsets.privateDictInfo.offset == (unsigned) (c.head - c.start));
for (unsigned int i = 0; i < acc.privateDicts.length; i++)
{
if (plan.fdmap.includes (i))
{
PrivateDict *pd = c.start_embed<PrivateDict> ();
if (unlikely (pd == nullptr)) return false;
unsigned int priv_size = plan.fontdicts_mod[plan.fdmap[i]].privateDictInfo.size;
bool result;
cff_private_dict_op_serializer_t privSzr (plan.desubroutinize, plan.drop_hints);
/* N.B. local subrs immediately follows its corresponding private dict. i.e., subr offset == private dict size */
unsigned int subroffset = (plan.offsets.localSubrsInfos[i].size > 0)? priv_size: 0;
result = pd->serialize (&c, acc.privateDicts[i], privSzr, subroffset);
if (unlikely (!result))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize CFF Private Dict[%d]", i);
return false;
}
if (plan.offsets.localSubrsInfos[i].size > 0)
{
CFF1Subrs *dest = c.start_embed <CFF1Subrs> ();
if (unlikely (dest == nullptr)) return false;
if (unlikely (!dest->serialize (&c, plan.offsets.localSubrsInfos[i].offSize, plan.subset_localsubrs[i])))
{
DEBUG_MSG (SUBSET, nullptr, "failed to serialize local subroutines");
return false;
}
}
}
}
assert (c.head == c.end);
c.end_serialize ();
return true;
}
static bool
_hb_subset_cff1 (const OT::cff1::accelerator_subset_t &acc,
const char *data,
hb_subset_plan_t *plan,
hb_blob_t **prime /* OUT */)
{
cff_subset_plan cff_plan;
if (unlikely (!cff_plan.create (acc, plan)))
{
DEBUG_MSG(SUBSET, nullptr, "Failed to generate a cff subsetting plan.");
return false;
}
unsigned int cff_prime_size = cff_plan.get_final_size ();
char *cff_prime_data = (char *) calloc (1, cff_prime_size);
if (unlikely (!_write_cff1 (cff_plan, acc, plan->num_output_glyphs (),
cff_prime_size, cff_prime_data))) {
DEBUG_MSG(SUBSET, nullptr, "Failed to write a subset cff.");
free (cff_prime_data);
return false;
}
*prime = hb_blob_create (cff_prime_data,
cff_prime_size,
HB_MEMORY_MODE_READONLY,
cff_prime_data,
free);
return true;
}
/**
* hb_subset_cff1:
* Subsets the CFF table according to a provided plan.
*
* Return value: subsetted cff table.
**/
bool
hb_subset_cff1 (hb_subset_plan_t *plan,
hb_blob_t **prime /* OUT */)
{
hb_blob_t *cff_blob = hb_sanitize_context_t().reference_table<CFF::cff1> (plan->source);
const char *data = hb_blob_get_data(cff_blob, nullptr);
OT::cff1::accelerator_subset_t acc;
acc.init(plan->source);
bool result = likely (acc.is_valid ()) &&
_hb_subset_cff1 (acc, data, plan, prime);
hb_blob_destroy (cff_blob);
acc.fini ();
return result;
}
| [
"Feodor2@mail.ru@"
] | Feodor2@mail.ru@ |
4f146cd480d6f59f9c832afb490e46568cdb100a | 76943449993b9a7aef4a1773f866b35c3a9dffe2 | /source/generator_kotlin.cpp | 73ba9e89fe72ac91ce2cc0a778095a041ac7cad8 | [
"MIT"
] | permissive | ismiyati/FastBinaryEncoding | 0a17ee4bf6e44c76b05835c54d44343fc9c5add2 | e961feeb1ed897a8237f13f7fe3ef33828e5e56e | refs/heads/master | 2020-05-31T14:40:55.525775 | 2019-05-31T11:06:24 | 2019-05-31T11:06:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256,204 | cpp | /*!
\file generator_kotlin.cpp
\brief Fast binary encoding Kotlin generator implementation
\author Ivan Shynkarenka
\date 03.10.2018
\copyright MIT License
*/
#include "generator_kotlin.h"
namespace FBE {
void GeneratorKotlin::Generate(const std::shared_ptr<Package>& package)
{
GenerateFBEPackage("fbe");
GenerateFBEUUIDGenerator("fbe");
GenerateFBEBuffer("fbe");
GenerateFBEModel("fbe");
GenerateFBEFieldModel("fbe");
GenerateFBEFieldModel("fbe", "Boolean", "Boolean", "", "1", "false");
GenerateFBEFieldModel("fbe", "Byte", "Byte", "", "1", "0.toByte()");
GenerateFBEFieldModel("fbe", "Char", "Char", ".toByte()", "1", "'\\u0000'");
GenerateFBEFieldModel("fbe", "WChar", "Char", ".toInt()", "4", "'\\u0000'");
GenerateFBEFieldModel("fbe", "Int8", "Byte", "", "1", "0.toByte()");
GenerateFBEFieldModel("fbe", "UInt8", "UByte", "", "1", "0.toUByte()");
GenerateFBEFieldModel("fbe", "Int16", "Short", "", "2", "0.toShort()");
GenerateFBEFieldModel("fbe", "UInt16", "UShort", "", "2", "0.toUShort()");
GenerateFBEFieldModel("fbe", "Int32", "Int", "", "4", "0");
GenerateFBEFieldModel("fbe", "UInt32", "UInt", "", "4", "0u");
GenerateFBEFieldModel("fbe", "Int64", "Long", "", "8", "0L");
GenerateFBEFieldModel("fbe", "UInt64", "ULong", "", "8", "0uL");
GenerateFBEFieldModel("fbe", "Float", "Float", "", "4", "0.0f");
GenerateFBEFieldModel("fbe", "Double", "Double", "", "8", "0.0");
GenerateFBEFieldModel("fbe", "UUID", "UUID", "", "16", "UUIDGenerator.nil()");
GenerateFBEFieldModelDecimal("fbe");
GenerateFBEFieldModelTimestamp("fbe");
GenerateFBEFieldModelBytes("fbe");
GenerateFBEFieldModelString("fbe");
if (Final())
{
GenerateFBESize("fbe");
GenerateFBEFinalModel("fbe");
GenerateFBEFinalModel("fbe", "Boolean", "Boolean", "", "1", "false");
GenerateFBEFinalModel("fbe", "Byte", "Byte", "", "1", "0.toByte()");
GenerateFBEFinalModel("fbe", "Char", "Char", ".toByte()", "1", "'\\u0000'");
GenerateFBEFinalModel("fbe", "WChar", "Char", ".toInt()", "4", "'\\u0000'");
GenerateFBEFinalModel("fbe", "Int8", "Byte", "", "1", "0.toByte()");
GenerateFBEFinalModel("fbe", "UInt8", "UByte", "", "1", "0.toUByte()");
GenerateFBEFinalModel("fbe", "Int16", "Short", "", "2", "0.toShort()");
GenerateFBEFinalModel("fbe", "UInt16", "UShort", "", "2", "0.toUShort()");
GenerateFBEFinalModel("fbe", "Int32", "Int", "", "4", "0");
GenerateFBEFinalModel("fbe", "UInt32", "UInt", "", "4", "0u");
GenerateFBEFinalModel("fbe", "Int64", "Long", "", "8", "0L");
GenerateFBEFinalModel("fbe", "UInt64", "ULong", "", "8", "0uL");
GenerateFBEFinalModel("fbe", "Float", "Float", "", "4", "0.0f");
GenerateFBEFinalModel("fbe", "Double", "Double", "", "8", "0.0");
GenerateFBEFinalModel("fbe", "UUID", "UUID", "", "16", "UUIDGenerator.nil()");
GenerateFBEFinalModelDecimal("fbe");
GenerateFBEFinalModelTimestamp("fbe");
GenerateFBEFinalModelBytes("fbe");
GenerateFBEFinalModelString("fbe");
}
if (Sender())
{
GenerateFBESender("fbe");
GenerateFBEReceiver("fbe");
}
if (JSON())
GenerateFBEJson("fbe");
GeneratePackage(package);
}
void GeneratorKotlin::GenerateHeader(const std::string& source)
{
std::string code = R"CODE(// Automatically generated by the Fast Binary Encoding compiler, do not modify!
// https://github.com/chronoxor/FastBinaryEncoding
// Source: _INPUT_
// Version: _VERSION_
@file:Suppress("UnusedImport", "unused")
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_INPUT_"), source);
code = std::regex_replace(code, std::regex("_VERSION_"), version);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
}
void GeneratorKotlin::GenerateFooter()
{
}
void GeneratorKotlin::GenerateImports(const std::string& package)
{
// Generate package name
WriteLine();
WriteLineIndent("package " + package);
// Generate common import
WriteLine();
WriteLineIndent("import java.io.*");
WriteLineIndent("import java.lang.*");
WriteLineIndent("import java.lang.reflect.*");
WriteLineIndent("import java.math.*");
WriteLineIndent("import java.nio.charset.*");
WriteLineIndent("import java.time.*");
WriteLineIndent("import java.util.*");
}
void GeneratorKotlin::GenerateImports(const std::shared_ptr<Package>& p)
{
// Generate common import
GenerateImports(*p->name);
// Generate FBE import
WriteLine();
WriteLineIndent("import fbe.*");
// Generate packages import
if (p->import)
for (const auto& import : p->import->imports)
WriteLineIndent("import " + *import + ".*");
}
void GeneratorKotlin::GenerateFBEPackage(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Create FBE package path
CppCommon::Directory::CreateTree(path);
}
void GeneratorKotlin::GenerateFBEUUIDGenerator(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "UUIDGenerator.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding UUID generator
object UUIDGenerator
{
// Gregorian epoch
private const val GregorianEpoch = 0xFFFFF4E2F964AC00uL
// Kotlin constants workaround
private val Sign = java.lang.Long.parseUnsignedLong("8000000000000000", 16)
private val Low = java.lang.Long.parseUnsignedLong("00000000FFFFFFFF", 16)
private val Mid = java.lang.Long.parseUnsignedLong("0000FFFF00000000", 16)
private val High = java.lang.Long.parseUnsignedLong("FFFF000000000000", 16)
// Lock and random generator
private val lock = Object()
private val generator = Random()
// Node & clock sequence bytes
private val node = makeNode()
private var nodeAndClockSequence = makeNodeAndClockSequence()
// Last UUID generated timestamp
private var last = GregorianEpoch
private fun makeNode(): ULong = generator.nextLong().toULong() or 0x0000010000000000uL
private fun makeNodeAndClockSequence(): ULong
{
val clock = generator.nextLong().toULong()
var lsb: ULong = 0u
// Variant (2 bits)
lsb = lsb or 0x8000000000000000uL
// Clock sequence (14 bits)
lsb = lsb or ((clock and 0x0000000000003FFFuL) shl 48)
// 6 bytes
lsb = lsb or node
return lsb
}
// Generate nil UUID0 (all bits set to zero)
fun nil(): UUID = UUID(0, 0)
// Generate sequential UUID1 (time based version)
fun sequential(): UUID
{
val now = System.currentTimeMillis().toULong()
// Generate new clock sequence bytes to get rid of UUID duplicates
synchronized(lock)
{
if (now <= last)
nodeAndClockSequence = makeNodeAndClockSequence()
last = now
}
val nanosSince = (now - GregorianEpoch) * 10000u
var msb = 0uL
msb = msb or (0x00000000FFFFFFFFuL and nanosSince).shl(32)
msb = msb or (0x0000FFFF00000000uL and nanosSince).shr(16)
msb = msb or (0xFFFF000000000000uL and nanosSince).shr(48)
// Sets the version to 1
msb = msb or 0x0000000000001000uL
return UUID(msb.toLong(), nodeAndClockSequence.toLong())
}
// Generate random UUID4 (randomly or pseudo-randomly generated version)
fun random(): UUID = UUID.randomUUID()
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEBuffer(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "Buffer.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding buffer based on dynamic byte array
class Buffer
{
// Is the buffer empty?
val empty: Boolean
get() = size == 0L
// Get bytes memory buffer
var data = ByteArray(0)
private set
// Get bytes memory buffer capacity
val capacity: Long
get() = data.size.toLong()
// Get bytes memory buffer size
var size: Long = 0
private set
// Get bytes memory buffer offset
var offset: Long = 0
private set
// Initialize a new expandable buffer with zero capacity
constructor()
// Initialize a new expandable buffer with the given capacity
constructor(capacity: Long) { attach(capacity) }
// Initialize a new buffer based on the specified byte array
constructor(buffer: ByteArray) { attach(buffer) }
// Initialize a new buffer based on the specified region (offset) of a byte array
constructor(buffer: ByteArray, offset: Long) { attach(buffer, offset) }
// Initialize a new buffer based on the specified region (size and offset) of a byte array
constructor(buffer: ByteArray, size: Long, offset: Long) { attach(buffer, size, offset) }
// Attach memory buffer methods
fun attach() { data = ByteArray(0); size = 0; offset = 0 }
fun attach(capacity: Long) { data = ByteArray(capacity.toInt()); size = 0; offset = 0 }
fun attach(buffer: ByteArray) { data = buffer; size = buffer.size.toLong(); offset = 0 }
fun attach(buffer: ByteArray, offset: Long) { data = buffer; size = buffer.size.toLong(); this.offset = offset }
fun attach(buffer: ByteArray, size: Long, offset: Long) { data = buffer; this.size = size; this.offset = offset }
// Allocate memory in the current buffer and return offset to the allocated memory block
fun allocate(size: Long): Long
{
assert(size >= 0) { "Invalid allocation size!" }
if (size < 0)
throw IllegalArgumentException("Invalid allocation size!")
val offset = this.size
// Calculate a new buffer size
val total = this.size + size
if (total <= data.size)
{
this.size = total
return offset
}
val data = ByteArray(Math.max(total, 2L * this.data.size).toInt())
System.arraycopy(this.data, 0, data, 0, this.size.toInt())
this.data = data
this.size = total
return offset
}
// Remove some memory of the given size from the current buffer
fun remove(offset: Long, size: Long)
{
assert((offset + size) <= this.size) { "Invalid offset & size!" }
if ((offset + size) > this.size)
throw IllegalArgumentException("Invalid offset & size!")
System.arraycopy(data, (offset + size).toInt(), data, offset.toInt(), (this.size - size - offset).toInt())
this.size -= size
if (this.offset >= offset + size)
this.offset -= size
else if (this.offset >= offset)
{
this.offset -= this.offset - offset
if (this.offset > this.size)
this.offset = this.size
}
}
// Reserve memory of the given capacity in the current buffer
fun reserve(capacity: Long)
{
assert(capacity >= 0) { "Invalid reserve capacity!" }
if (capacity < 0)
throw IllegalArgumentException("Invalid reserve capacity!")
if (capacity > data.size)
{
val data = ByteArray(Math.max(capacity, 2L * this.data.size).toInt())
System.arraycopy(this.data, 0, data, 0, size.toInt())
this.data = data
}
}
// Resize the current buffer
fun resize(size: Long)
{
reserve(size)
this.size = size
if (offset > this.size)
offset = this.size
}
// Reset the current buffer and its offset
fun reset()
{
size = 0
offset = 0
}
// Shift the current buffer offset
fun shift(offset: Long) { this.offset += offset }
// Unshift the current buffer offset
fun unshift(offset: Long) { this.offset -= offset }
companion object
{
// Buffer I/O methods
fun readBoolean(buffer: ByteArray, offset: Long): Boolean
{
val index = offset.toInt()
return buffer[index].toInt() != 0
}
fun readByte(buffer: ByteArray, offset: Long): Byte
{
val index = offset.toInt()
return buffer[index]
}
fun readChar(buffer: ByteArray, offset: Long): Char
{
return readInt8(buffer, offset).toChar()
}
fun readWChar(buffer: ByteArray, offset: Long): Char
{
return readInt32(buffer, offset).toChar()
}
fun readInt8(buffer: ByteArray, offset: Long): Byte
{
val index = offset.toInt()
return buffer[index]
}
fun readUInt8(buffer: ByteArray, offset: Long): UByte
{
val index = offset.toInt()
return buffer[index].toUByte()
}
fun readInt16(buffer: ByteArray, offset: Long): Short
{
val index = offset.toInt()
return (((buffer[index + 0].toInt() and 0xFF) shl 0) or
((buffer[index + 1].toInt() and 0xFF) shl 8)).toShort()
}
fun readUInt16(buffer: ByteArray, offset: Long): UShort
{
val index = offset.toInt()
return (((buffer[index + 0].toUInt() and 0xFFu) shl 0) or
((buffer[index + 1].toUInt() and 0xFFu) shl 8)).toUShort()
}
fun readInt32(buffer: ByteArray, offset: Long): Int
{
val index = offset.toInt()
return ((buffer[index + 0].toInt() and 0xFF) shl 0) or
((buffer[index + 1].toInt() and 0xFF) shl 8) or
((buffer[index + 2].toInt() and 0xFF) shl 16) or
((buffer[index + 3].toInt() and 0xFF) shl 24)
}
fun readUInt32(buffer: ByteArray, offset: Long): UInt
{
val index = offset.toInt()
return ((buffer[index + 0].toUInt() and 0xFFu) shl 0) or
((buffer[index + 1].toUInt() and 0xFFu) shl 8) or
((buffer[index + 2].toUInt() and 0xFFu) shl 16) or
((buffer[index + 3].toUInt() and 0xFFu) shl 24)
}
fun readInt64(buffer: ByteArray, offset: Long): Long
{
val index = offset.toInt()
return ((buffer[index + 0].toLong() and 0xFF) shl 0) or
((buffer[index + 1].toLong() and 0xFF) shl 8) or
((buffer[index + 3].toLong() and 0xFF) shl 24) or
((buffer[index + 2].toLong() and 0xFF) shl 16) or
((buffer[index + 4].toLong() and 0xFF) shl 32) or
((buffer[index + 5].toLong() and 0xFF) shl 40) or
((buffer[index + 6].toLong() and 0xFF) shl 48) or
((buffer[index + 7].toLong() and 0xFF) shl 56)
}
fun readUInt64(buffer: ByteArray, offset: Long): ULong
{
val index = offset.toInt()
return ((buffer[index + 0].toULong() and 0xFFu) shl 0) or
((buffer[index + 1].toULong() and 0xFFu) shl 8) or
((buffer[index + 3].toULong() and 0xFFu) shl 24) or
((buffer[index + 2].toULong() and 0xFFu) shl 16) or
((buffer[index + 4].toULong() and 0xFFu) shl 32) or
((buffer[index + 5].toULong() and 0xFFu) shl 40) or
((buffer[index + 6].toULong() and 0xFFu) shl 48) or
((buffer[index + 7].toULong() and 0xFFu) shl 56)
}
private fun readInt64BE(buffer: ByteArray, offset: Long): Long
{
val index = offset.toInt()
return ((buffer[index + 0].toLong() and 0xFF) shl 56) or
((buffer[index + 1].toLong() and 0xFF) shl 48) or
((buffer[index + 2].toLong() and 0xFF) shl 40) or
((buffer[index + 3].toLong() and 0xFF) shl 32) or
((buffer[index + 4].toLong() and 0xFF) shl 24) or
((buffer[index + 5].toLong() and 0xFF) shl 16) or
((buffer[index + 6].toLong() and 0xFF) shl 8) or
((buffer[index + 7].toLong() and 0xFF) shl 0)
}
fun readFloat(buffer: ByteArray, offset: Long): Float
{
val bits = readInt32(buffer, offset)
return java.lang.Float.intBitsToFloat(bits)
}
fun readDouble(buffer: ByteArray, offset: Long): Double
{
val bits = readInt64(buffer, offset)
return java.lang.Double.longBitsToDouble(bits)
}
fun readBytes(buffer: ByteArray, offset: Long, size: Long): ByteArray
{
val result = ByteArray(size.toInt())
System.arraycopy(buffer, offset.toInt(), result, 0, size.toInt())
return result
}
fun readString(buffer: ByteArray, offset: Long, size: Long): String
{
return kotlin.text.String(buffer, offset.toInt(), size.toInt(), StandardCharsets.UTF_8)
}
fun readUUID(buffer: ByteArray, offset: Long): UUID
{
return UUID(readInt64BE(buffer, offset), readInt64BE(buffer, offset + 8))
}
fun write(buffer: ByteArray, offset: Long, value: Boolean)
{
buffer[offset.toInt()] = (if (value) 1 else 0).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: Byte)
{
buffer[offset.toInt()] = value
}
fun write(buffer: ByteArray, offset: Long, value: UByte)
{
buffer[offset.toInt()] = value.toByte()
}
fun write(buffer: ByteArray, offset: Long, value: Short)
{
buffer[offset.toInt() + 0] = (value.toInt() shr 0).toByte()
buffer[offset.toInt() + 1] = (value.toInt() shr 8).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: UShort)
{
buffer[offset.toInt() + 0] = (value.toUInt() shr 0).toByte()
buffer[offset.toInt() + 1] = (value.toUInt() shr 8).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: Int)
{
buffer[offset.toInt() + 0] = (value shr 0).toByte()
buffer[offset.toInt() + 1] = (value shr 8).toByte()
buffer[offset.toInt() + 2] = (value shr 16).toByte()
buffer[offset.toInt() + 3] = (value shr 24).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: UInt)
{
buffer[offset.toInt() + 0] = (value shr 0).toByte()
buffer[offset.toInt() + 1] = (value shr 8).toByte()
buffer[offset.toInt() + 2] = (value shr 16).toByte()
buffer[offset.toInt() + 3] = (value shr 24).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: Long)
{
buffer[offset.toInt() + 0] = (value shr 0).toByte()
buffer[offset.toInt() + 1] = (value shr 8).toByte()
buffer[offset.toInt() + 2] = (value shr 16).toByte()
buffer[offset.toInt() + 3] = (value shr 24).toByte()
buffer[offset.toInt() + 4] = (value shr 32).toByte()
buffer[offset.toInt() + 5] = (value shr 40).toByte()
buffer[offset.toInt() + 6] = (value shr 48).toByte()
buffer[offset.toInt() + 7] = (value shr 56).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: ULong)
{
buffer[offset.toInt() + 0] = (value shr 0).toByte()
buffer[offset.toInt() + 1] = (value shr 8).toByte()
buffer[offset.toInt() + 2] = (value shr 16).toByte()
buffer[offset.toInt() + 3] = (value shr 24).toByte()
buffer[offset.toInt() + 4] = (value shr 32).toByte()
buffer[offset.toInt() + 5] = (value shr 40).toByte()
buffer[offset.toInt() + 6] = (value shr 48).toByte()
buffer[offset.toInt() + 7] = (value shr 56).toByte()
}
private fun writeBE(buffer: ByteArray, offset: Long, value: Long)
{
buffer[offset.toInt() + 0] = (value shr 56).toByte()
buffer[offset.toInt() + 1] = (value shr 48).toByte()
buffer[offset.toInt() + 2] = (value shr 40).toByte()
buffer[offset.toInt() + 3] = (value shr 32).toByte()
buffer[offset.toInt() + 4] = (value shr 24).toByte()
buffer[offset.toInt() + 5] = (value shr 16).toByte()
buffer[offset.toInt() + 6] = (value shr 8).toByte()
buffer[offset.toInt() + 7] = (value shr 0).toByte()
}
fun write(buffer: ByteArray, offset: Long, value: Float)
{
val bits = java.lang.Float.floatToIntBits(value)
write(buffer, offset, bits)
}
fun write(buffer: ByteArray, offset: Long, value: Double)
{
val bits = java.lang.Double.doubleToLongBits(value)
write(buffer, offset, bits)
}
fun write(buffer: ByteArray, offset: Long, value: ByteArray)
{
System.arraycopy(value, 0, buffer, offset.toInt(), value.size)
}
fun write(buffer: ByteArray, offset: Long, value: ByteArray, valueOffset: Long, valueSize: Long)
{
System.arraycopy(value, valueOffset.toInt(), buffer, offset.toInt(), valueSize.toInt())
}
fun write(buffer: ByteArray, offset: Long, value: Byte, valueCount: Long)
{
for (i in 0 until valueCount)
buffer[(offset + i).toInt()] = value
}
fun write(buffer: ByteArray, offset: Long, value: UUID)
{
writeBE(buffer, offset, value.mostSignificantBits)
writeBE(buffer, offset + 8, value.leastSignificantBits)
}
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEModel(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "Model.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding base model
open class Model
{
// Get bytes buffer
var buffer = Buffer()
private set
// Initialize a new model
protected constructor()
protected constructor(buffer: Buffer) { this.buffer = buffer }
// Attach memory buffer methods
fun attach() { buffer.attach() }
fun attach(capacity: Long) { buffer.attach(capacity) }
fun attach(buffer: ByteArray) { this.buffer.attach(buffer) }
fun attach(buffer: ByteArray, offset: Long) { this.buffer.attach(buffer, offset) }
fun attach(buffer: ByteArray, size: Long, offset: Long) { this.buffer.attach(buffer, size, offset) }
fun attach(buffer: Buffer) { this.buffer.attach(buffer.data, buffer.size, buffer.offset) }
fun attach(buffer: Buffer, offset: Long) { this.buffer.attach(buffer.data, buffer.size, offset) }
// Model buffer operations
fun allocate(size: Long): Long { return buffer.allocate(size) }
fun remove(offset: Long, size: Long) { buffer.remove(offset, size) }
fun reserve(capacity: Long) { buffer.reserve(capacity) }
fun resize(size: Long) { buffer.resize(size) }
fun reset() { buffer.reset() }
fun shift(offset: Long) { buffer.shift(offset) }
fun unshift(offset: Long) { buffer.unshift(offset) }
// Buffer I/O methods
protected fun readUInt32(offset: Long): UInt { return Buffer.readUInt32(buffer.data, buffer.offset + offset) }
protected fun write(offset: Long, value: UInt) { Buffer.write(buffer.data, buffer.offset + offset, value) }
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModel(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FieldModel.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding base field model
@Suppress("MemberVisibilityCanBePrivate")
abstract class FieldModel protected constructor(protected var _buffer: Buffer, protected var _offset: Long)
{
// Field offset
var fbeOffset: Long
get() = _offset
set(value) { _offset = value }
// Field size
open val fbeSize: Long = 0
// Field extra size
open val fbeExtra: Long = 0
// Shift the current field offset
fun fbeShift(size: Long) { _offset += size }
// Unshift the current field offset
fun fbeUnshift(size: Long) { _offset -= size }
// Check if the value is valid
open fun verify(): Boolean = true
// Buffer I/O methods
protected fun readBoolean(offset: Long): Boolean { return Buffer.readBoolean(_buffer.data, _buffer.offset + offset) }
protected fun readByte(offset: Long): Byte { return Buffer.readByte(_buffer.data, _buffer.offset + offset) }
protected fun readChar(offset: Long): Char { return Buffer.readChar(_buffer.data, _buffer.offset + offset) }
protected fun readWChar(offset: Long): Char { return Buffer.readWChar(_buffer.data, _buffer.offset + offset) }
protected fun readInt8(offset: Long): Byte { return Buffer.readInt8(_buffer.data, _buffer.offset + offset) }
protected fun readUInt8(offset: Long): UByte { return Buffer.readUInt8(_buffer.data, _buffer.offset + offset) }
protected fun readInt16(offset: Long): Short { return Buffer.readInt16(_buffer.data, _buffer.offset + offset) }
protected fun readUInt16(offset: Long): UShort { return Buffer.readUInt16(_buffer.data, _buffer.offset + offset) }
protected fun readInt32(offset: Long): Int { return Buffer.readInt32(_buffer.data, _buffer.offset + offset) }
protected fun readUInt32(offset: Long): UInt { return Buffer.readUInt32(_buffer.data, _buffer.offset + offset) }
protected fun readInt64(offset: Long): Long { return Buffer.readInt64(_buffer.data, _buffer.offset + offset) }
protected fun readUInt64(offset: Long): ULong { return Buffer.readUInt64(_buffer.data, _buffer.offset + offset) }
protected fun readFloat(offset: Long): Float { return Buffer.readFloat(_buffer.data, _buffer.offset + offset) }
protected fun readDouble(offset: Long): Double { return Buffer.readDouble(_buffer.data, _buffer.offset + offset) }
protected fun readBytes(offset: Long, size: Long): ByteArray { return Buffer.readBytes(_buffer.data, _buffer.offset + offset, size) }
protected fun readString(offset: Long, size: Long): String { return Buffer.readString(_buffer.data, _buffer.offset + offset, size) }
protected fun readUUID(offset: Long): UUID { return Buffer.readUUID(_buffer.data, _buffer.offset + offset) }
protected fun write(offset: Long, value: Boolean) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Byte) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: UByte) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Short) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: UShort) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Int) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: UInt) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Long) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: ULong) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Float) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Double) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: ByteArray) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: ByteArray, valueOffset: Long, valueSize: Long) { Buffer.write(_buffer.data, _buffer.offset + offset, value, valueOffset, valueSize) }
protected fun write(offset: Long, value: Byte, valueCount: Long) { Buffer.write(_buffer.data, _buffer.offset + offset, value, valueCount) }
protected fun write(offset: Long, value: UUID) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModel(const std::string& package, const std::string& name, const std::string& type, const std::string& base, const std::string& size, const std::string& defaults)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / ("FieldModel" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding _TYPE_ field model
class FieldModel_NAME_(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = _SIZE_
// Get the value
fun get(defaults: _TYPE_ = _DEFAULTS_): _TYPE_
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return defaults
return read_NAME_(fbeOffset)
}
// Set the value
fun set(value: _TYPE_)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
write(fbeOffset, value_BASE_)
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_BASE_"), base);
code = std::regex_replace(code, std::regex("_SIZE_"), size);
code = std::regex_replace(code, std::regex("_DEFAULTS_"), defaults);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelDecimal(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FieldModelDecimal.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding decimal field model
class FieldModelDecimal(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = 16
// Get the decimal value
fun get(defaults: BigDecimal = BigDecimal.valueOf(0L)): BigDecimal
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return defaults
val magnitude = readBytes(fbeOffset, 12)
val scale = readByte(fbeOffset + 14).toInt()
val signum = if (readByte(fbeOffset + 15) < 0) -1 else 1
// Reverse magnitude
for (i in 0 until (magnitude.size / 2))
{
val temp = magnitude[i]
magnitude[i] = magnitude[magnitude.size - i - 1]
magnitude[magnitude.size - i - 1] = temp
}
val unscaled = BigInteger(signum, magnitude)
return BigDecimal(unscaled, scale)
}
// Set the decimal value
fun set(value: BigDecimal)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
// Get unscaled absolute value
val unscaled = value.abs().unscaledValue()
val bitLength = unscaled.bitLength()
if ((bitLength < 0) || (bitLength > 96))
{
// Value too big for .NET Decimal (bit length is limited to [0, 96])
write(fbeOffset, 0.toByte(), fbeSize)
return
}
// Get byte array
val unscaledBytes = unscaled.toByteArray()
// Get scale
val scale = value.scale()
if ((scale < 0) || (scale > 28))
{
// Value scale exceeds .NET Decimal limit of [0, 28]
write(fbeOffset, 0.toByte(), fbeSize)
return
}
// Write unscaled value to bytes 0-11
var index = 0
var i = unscaledBytes.size - 1
while ((i >= 0) && (index < 12))
{
write(fbeOffset + index, unscaledBytes[i])
i--
index++
}
// Fill remaining bytes with zeros
while (index < 14)
{
write(fbeOffset + index, 0.toByte())
index++
}
// Write scale at byte 14
write(fbeOffset + 14, scale.toByte())
// Write signum at byte 15
write(fbeOffset + 15, (if (value.signum() < 0) -128 else 0).toByte())
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelTimestamp(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FieldModelTimestamp.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding timestamp field model
class FieldModelTimestamp(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = 8
// Get the timestamp value
fun get(defaults: Instant = Instant.EPOCH): Instant
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return defaults
val nanoseconds = readInt64(fbeOffset)
return Instant.ofEpochSecond(nanoseconds / 1000000000, nanoseconds % 1000000000)
}
// Set the timestamp value
fun set(value: Instant)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val nanoseconds = value.epochSecond * 1000000000 + value.nano
write(fbeOffset, nanoseconds.toULong())
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelBytes(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FieldModelBytes.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding bytes field model
class FieldModelBytes(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = 4
// Field extra size
override val fbeExtra: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeBytesOffset = readUInt32(fbeOffset).toLong()
if ((fbeBytesOffset == 0L) || ((_buffer.offset + fbeBytesOffset + 4) > _buffer.size))
return 0
val fbeBytesSize = readUInt32(fbeBytesOffset).toLong()
return 4 + fbeBytesSize
}
// Check if the bytes value is valid
override fun verify(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return true
val fbeBytesOffset = readUInt32(fbeOffset).toLong()
if (fbeBytesOffset == 0L)
return true
if ((_buffer.offset + fbeBytesOffset + 4) > _buffer.size)
return false
val fbeBytesSize = readUInt32(fbeBytesOffset).toLong()
if ((_buffer.offset + fbeBytesOffset + 4 + fbeBytesSize) > _buffer.size)
return false
return true
}
// Get the bytes value
fun get(defaults: ByteArray = ByteArray(0)): ByteArray
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return defaults
val fbeBytesOffset = readUInt32(fbeOffset).toLong()
if (fbeBytesOffset == 0L)
return defaults
assert((_buffer.offset + fbeBytesOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeBytesOffset + 4) > _buffer.size)
return defaults
val fbeBytesSize = readUInt32(fbeBytesOffset).toLong()
assert((_buffer.offset + fbeBytesOffset + 4 + fbeBytesSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeBytesOffset + 4 + fbeBytesSize) > _buffer.size)
return defaults
return readBytes(fbeBytesOffset + 4, fbeBytesSize)
}
// Set the bytes value
fun set(value: ByteArray)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeBytesSize = value.size.toLong()
val fbeBytesOffset = _buffer.allocate(4 + fbeBytesSize) - _buffer.offset
assert((fbeBytesOffset > 0) && ((_buffer.offset + fbeBytesOffset + 4 + fbeBytesSize) <= _buffer.size)) { "Model is broken!" }
if ((fbeBytesOffset <= 0) || ((_buffer.offset + fbeBytesOffset + 4 + fbeBytesSize) > _buffer.size))
return
write(fbeOffset, fbeBytesOffset.toUInt())
write(fbeBytesOffset, fbeBytesSize.toUInt())
write(fbeBytesOffset + 4, value)
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelString(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FieldModelString.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding string field model
class FieldModelString(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = 4
// Field extra size
override val fbeExtra: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeStringOffset = readUInt32(fbeOffset).toLong()
if ((fbeStringOffset == 0L) || ((_buffer.offset + fbeStringOffset + 4) > _buffer.size))
return 0
val fbeStringSize = readUInt32(fbeStringOffset).toLong()
return 4 + fbeStringSize
}
// Check if the string value is valid
override fun verify(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return true
val fbeStringOffset = readUInt32(fbeOffset).toLong()
if (fbeStringOffset == 0L)
return true
if ((_buffer.offset + fbeStringOffset + 4) > _buffer.size)
return false
val fbeStringSize = readUInt32(fbeStringOffset).toLong()
if ((_buffer.offset + fbeStringOffset + 4 + fbeStringSize) > _buffer.size)
return false
return true
}
// Get the string value
fun get(defaults: String = ""): String
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return defaults
val fbeStringOffset = readUInt32(fbeOffset).toLong()
if (fbeStringOffset == 0L)
return defaults
assert((_buffer.offset + fbeStringOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeStringOffset + 4) > _buffer.size)
return defaults
val fbeStringSize = readUInt32(fbeStringOffset).toLong()
assert((_buffer.offset + fbeStringOffset + 4 + fbeStringSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeStringOffset + 4 + fbeStringSize) > _buffer.size)
return defaults
return readString(fbeStringOffset + 4, fbeStringSize)
}
// Set the string value
fun set(value: String)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val bytes = value.toByteArray(StandardCharsets.UTF_8)
val fbeStringSize = bytes.size.toLong()
val fbeStringOffset = _buffer.allocate(4 + fbeStringSize) - _buffer.offset
assert((fbeStringOffset > 0) && ((_buffer.offset + fbeStringOffset + 4 + fbeStringSize) <= _buffer.size)) { "Model is broken!" }
if ((fbeStringOffset <= 0) || ((_buffer.offset + fbeStringOffset + 4 + fbeStringSize) > _buffer.size))
return
write(fbeOffset, fbeStringOffset.toUInt())
write(fbeStringOffset, fbeStringSize.toUInt())
write(fbeStringOffset + 4, bytes)
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelOptional(const std::string& package, const std::string& name, const std::string& type, const std::string& model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FieldModelOptional" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding optional _NAME_ field model
class FieldModelOptional_NAME_(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = 1 + 4
// Field extra size
override val fbeExtra: Long get()
{
if (!hasValue())
return 0
val fbeOptionalOffset = readUInt32(fbeOffset + 1).toLong()
if ((fbeOptionalOffset == 0L) || ((_buffer.offset + fbeOptionalOffset + 4) > _buffer.size))
return 0
_buffer.shift(fbeOptionalOffset)
val fbeResult = value.fbeSize + value.fbeExtra
_buffer.unshift(fbeOptionalOffset)
return fbeResult
}
// Checks if the object contains a value
fun hasValue(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return false
val fbeHasValue = readInt8(fbeOffset).toInt()
return fbeHasValue != 0
}
// Base field model value
val value = _MODEL_(buffer, 0)
// Check if the optional value is valid
override fun verify(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return true
val fbeHasValue = readInt8(fbeOffset).toInt()
if (fbeHasValue == 0)
return true
val fbeOptionalOffset = readUInt32(fbeOffset + 1).toLong()
if (fbeOptionalOffset == 0L)
return false
_buffer.shift(fbeOptionalOffset)
val fbeResult = value.verify()
_buffer.unshift(fbeOptionalOffset)
return fbeResult
}
// Get the optional value (being phase)
fun getBegin(): Long
{
if (!hasValue())
return 0
val fbeOptionalOffset = readUInt32(fbeOffset + 1).toLong()
assert(fbeOptionalOffset > 0) { "Model is broken!" }
if (fbeOptionalOffset <= 0)
return 0
_buffer.shift(fbeOptionalOffset)
return fbeOptionalOffset
}
// Get the optional value (end phase)
fun getEnd(fbeBegin: Long)
{
_buffer.unshift(fbeBegin)
}
// Get the optional value
fun get(defaults: _TYPE_ = null): _TYPE_
{
val fbeBegin = getBegin()
if (fbeBegin == 0L)
return defaults
val optional = value.get()
getEnd(fbeBegin)
return optional
}
// Set the optional value (begin phase)
fun setBegin(hasValue: Boolean): Long
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeHasValue = if (hasValue) 1 else 0
write(fbeOffset, fbeHasValue.toByte())
if (fbeHasValue == 0)
return 0
val fbeOptionalSize = value.fbeSize
val fbeOptionalOffset = _buffer.allocate(fbeOptionalSize) - _buffer.offset
assert((fbeOptionalOffset > 0) && ((_buffer.offset + fbeOptionalOffset + fbeOptionalSize) <= _buffer.size)) { "Model is broken!" }
if ((fbeOptionalOffset <= 0) || ((_buffer.offset + fbeOptionalOffset + fbeOptionalSize) > _buffer.size))
return 0
write(fbeOffset + 1, fbeOptionalOffset.toUInt())
_buffer.shift(fbeOptionalOffset)
return fbeOptionalOffset
}
// Set the optional value (end phase)
fun setEnd(fbeBegin: Long)
{
_buffer.unshift(fbeBegin)
}
// Set the optional value
fun set(optional: _TYPE_)
{
val fbeBegin = setBegin(optional != null)
if (fbeBegin == 0L)
return
value.set(optional!!)
setEnd(fbeBegin)
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_MODEL_"), model);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelArray(const std::string& package, const std::string& name, const std::string& type, const std::string& base, bool optional, const std::string& model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FieldModelArray" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _NAME_ array field model
class FieldModelArray_NAME_(buffer: Buffer, offset: Long, val size: Long) : FieldModel(buffer, offset)
{
private val _model = _MODEL_(buffer, offset)
// Field size
override val fbeSize: Long = size * _model.fbeSize
// Field extra size
override val fbeExtra: Long = 0
// Get the array offset
val offset: Long get() = 0
// Array index operator
fun getItem(index: Long): _MODEL_
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
assert(index < size) { "Index is out of bounds!" }
_model.fbeOffset = fbeOffset
_model.fbeShift(index * _model.fbeSize)
return _model
}
// Check if the array is valid
override fun verify(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return false
_model.fbeOffset = fbeOffset
var i = size
while (i-- > 0)
{
if (!_model.verify())
return false
_model.fbeShift(_model.fbeSize)
}
return true
}
// Get the array
fun get(): _ARRAY_
{
val values = _INIT_
val fbeModel = getItem(0)
for (i in 0 until size)
{
values[i.toInt()] = fbeModel.get()
fbeModel.fbeShift(fbeModel.fbeSize)
}
return values
}
// Get the array
fun get(values: _ARRAY_)
{
val fbeModel = getItem(0)
var i: Long = 0
while ((i < values.size) && (i < size))
{
values[i.toInt()] = fbeModel.get()
fbeModel.fbeShift(fbeModel.fbeSize)
i++
}
}
// Get the array as ArrayList
fun get(values: ArrayList<_TYPE_>)
{
values.clear()
values.ensureCapacity(size.toInt())
val fbeModel = getItem(0)
var i = size
while (i-- > 0)
{
val value = fbeModel.get()
values.add(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
// Set the array
fun set(values: _ARRAY_)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = getItem(0)
var i: Long = 0
while ((i < values.size) && (i < size))
{
fbeModel.set(values[i.toInt()])
fbeModel.fbeShift(fbeModel.fbeSize)
i++
}
}
// Set the array as List
fun set(values: ArrayList<_TYPE_>)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = getItem(0)
var i: Long = 0
while ((i < values.size) && (i < size))
{
fbeModel.set(values[i.toInt()])
fbeModel.fbeShift(fbeModel.fbeSize)
i++
}
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_MODEL_"), model);
code = std::regex_replace(code, std::regex("_ARRAY_"), "Array<" + type + ">");
if (optional)
code = std::regex_replace(code, std::regex("_INIT_"), "arrayOfNulls<" + type + ">(size.toInt())");
else
code = std::regex_replace(code, std::regex("_INIT_"), "Array(size.toInt()) { " + ConvertDefault(base) + " }");
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelVector(const std::string& package, const std::string& name, const std::string& type, const std::string& model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FieldModelVector" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _NAME_ vector field model
class FieldModelVector_NAME_(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
private val _model = _MODEL_(buffer, offset)
// Field size
override val fbeSize: Long = 4
// Field extra size
override val fbeExtra: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeVectorOffset = readUInt32(fbeOffset).toLong()
if ((fbeVectorOffset == 0L) || ((_buffer.offset + fbeVectorOffset + 4) > _buffer.size))
return 0
val fbeVectorSize = readUInt32(fbeVectorOffset).toLong()
var fbeResult: Long = 4
_model.fbeOffset = fbeVectorOffset + 4
var i = fbeVectorSize
while (i-- > 0)
{
fbeResult += _model.fbeSize + _model.fbeExtra
_model.fbeShift(_model.fbeSize)
}
return fbeResult
}
// Get the vector offset
val offset: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
return readUInt32(fbeOffset).toLong()
}
// Get the vector size
val size: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeVectorOffset = readUInt32(fbeOffset).toLong()
if ((fbeVectorOffset == 0L) || ((_buffer.offset + fbeVectorOffset + 4) > _buffer.size))
return 0
return readUInt32(fbeVectorOffset).toLong()
}
// Vector index operator
fun getItem(index: Long): _MODEL_
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
val fbeVectorOffset = readUInt32(fbeOffset).toLong()
assert((fbeVectorOffset > 0) && ((_buffer.offset + fbeVectorOffset + 4) <= _buffer.size)) { "Model is broken!" }
val fbeVectorSize = readUInt32(fbeVectorOffset).toLong()
assert(index < fbeVectorSize) { "Index is out of bounds!" }
_model.fbeOffset = fbeVectorOffset + 4
_model.fbeShift(index * _model.fbeSize)
return _model
}
// Resize the vector and get its first model
fun resize(size: Long): _MODEL_
{
val fbeVectorSize = size * _model.fbeSize
val fbeVectorOffset = _buffer.allocate(4 + fbeVectorSize) - _buffer.offset
assert((fbeVectorOffset > 0) && ((_buffer.offset + fbeVectorOffset + 4) <= _buffer.size)) { "Model is broken!" }
write(fbeOffset, fbeVectorOffset.toUInt())
write(fbeVectorOffset, size.toUInt())
write(fbeVectorOffset + 4, 0.toByte(), fbeVectorSize)
_model.fbeOffset = fbeVectorOffset + 4
return _model
}
// Check if the vector is valid
override fun verify(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return true
val fbeVectorOffset = readUInt32(fbeOffset).toLong()
if (fbeVectorOffset == 0L)
return true
if ((_buffer.offset + fbeVectorOffset + 4) > _buffer.size)
return false
val fbeVectorSize = readUInt32(fbeVectorOffset).toLong()
_model.fbeOffset = fbeVectorOffset + 4
var i = fbeVectorSize
while (i-- > 0)
{
if (!_model.verify())
return false
_model.fbeShift(_model.fbeSize)
}
return true
}
// Get the vector as ArrayList
operator fun get(values: ArrayList<_TYPE_>)
{
values.clear()
val fbeVectorSize = size
if (fbeVectorSize == 0L)
return
values.ensureCapacity(fbeVectorSize.toInt())
val fbeModel = getItem(0)
var i = fbeVectorSize
while (i-- > 0)
{
val value = fbeModel.get()
values.add(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
// Get the vector as LinkedList
operator fun get(values: LinkedList<_TYPE_>)
{
values.clear()
val fbeVectorSize = size
if (fbeVectorSize == 0L)
return
val fbeModel = getItem(0)
var i = fbeVectorSize
while (i-- > 0)
{
val value = fbeModel.get()
values.add(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
// Get the vector as HashSet
operator fun get(values: HashSet<_TYPE_>)
{
values.clear()
val fbeVectorSize = size
if (fbeVectorSize == 0L)
return
val fbeModel = getItem(0)
var i = fbeVectorSize
while (i-- > 0)
{
val value = fbeModel.get()
values.add(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
// Set the vector as ArrayList
fun set(values: ArrayList<_TYPE_>)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = resize(values.size.toLong())
for (value in values)
{
fbeModel.set(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
// Set the vector as LinkedList
fun set(values: LinkedList<_TYPE_>)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = resize(values.size.toLong())
for (value in values)
{
fbeModel.set(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
// Set the vector as HashSet
fun set(values: HashSet<_TYPE_>)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = resize(values.size.toLong())
for (value in values)
{
fbeModel.set(value)
fbeModel.fbeShift(fbeModel.fbeSize)
}
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_MODEL_"), model);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelMap(const std::string& package, const std::string& key_name, const std::string& key_type, const std::string& key_model, const std::string& value_name, const std::string& value_type, const std::string& value_model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FieldModelMap" + key_name + value_name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _KEY_NAME_->_VALUE_NAME_ map field model
class FieldModelMap_KEY_NAME__VALUE_NAME_(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
private val _modelKey = _KEY_MODEL_(buffer, offset)
private val _modelValue = _VALUE_MODEL_(buffer, offset)
// Field size
override val fbeSize: Long = 4
// Field extra size
override val fbeExtra: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeMapOffset = readUInt32(fbeOffset).toLong()
if ((fbeMapOffset == 0L) || ((_buffer.offset + fbeMapOffset + 4) > _buffer.size))
return 0
val fbeMapSize = readUInt32(fbeMapOffset).toLong()
var fbeResult: Long = 4
_modelKey.fbeOffset = fbeMapOffset + 4
_modelValue.fbeOffset = fbeMapOffset + 4 + _modelKey.fbeSize
var i = fbeMapSize
while (i-- > 0)
{
fbeResult += _modelKey.fbeSize + _modelKey.fbeExtra
_modelKey.fbeShift(_modelKey.fbeSize + _modelValue.fbeSize)
fbeResult += _modelValue.fbeSize + _modelValue.fbeExtra
_modelValue.fbeShift(_modelKey.fbeSize + _modelValue.fbeSize)
}
return fbeResult
}
// Get the map offset
val offset: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
return readUInt32(fbeOffset).toLong()
}
// Get the map size
val size: Long get()
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val fbeMapOffset = readUInt32(fbeOffset).toLong()
if ((fbeMapOffset == 0L) || ((_buffer.offset + fbeMapOffset + 4) > _buffer.size))
return 0
return readUInt32(fbeMapOffset).toLong()
}
// Map index operator
fun getItem(index: Long): Pair<_KEY_MODEL_, _VALUE_MODEL_>
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
val fbeMapOffset = readUInt32(fbeOffset).toLong()
assert((fbeMapOffset > 0) && ((_buffer.offset + fbeMapOffset + 4) <= _buffer.size)) { "Model is broken!" }
val fbeMapSize = readUInt32(fbeMapOffset).toLong()
assert(index < fbeMapSize) { "Index is out of bounds!" }
_modelKey.fbeOffset = fbeMapOffset + 4
_modelValue.fbeOffset = fbeMapOffset + 4 + _modelKey.fbeSize
_modelKey.fbeShift(index * (_modelKey.fbeSize + _modelValue.fbeSize))
_modelValue.fbeShift(index * (_modelKey.fbeSize + _modelValue.fbeSize))
return Pair(_modelKey, _modelValue)
}
// Resize the map and get its first model
fun resize(size: Long): Pair<_KEY_MODEL_, _VALUE_MODEL_>
{
val fbeMapSize = size * (_modelKey.fbeSize + _modelValue.fbeSize)
val fbeMapOffset = _buffer.allocate(4 + fbeMapSize) - _buffer.offset
assert((fbeMapOffset > 0) && ((_buffer.offset + fbeMapOffset + 4) <= _buffer.size)) { "Model is broken!" }
write(fbeOffset, fbeMapOffset.toUInt())
write(fbeMapOffset, size.toUInt())
write(fbeMapOffset + 4, 0.toByte(), fbeMapSize)
_modelKey.fbeOffset = fbeMapOffset + 4
_modelValue.fbeOffset = fbeMapOffset + 4 + _modelKey.fbeSize
return Pair(_modelKey, _modelValue)
}
// Check if the map is valid
override fun verify(): Boolean
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return true
val fbeMapOffset = readUInt32(fbeOffset).toLong()
if (fbeMapOffset == 0L)
return true
if ((_buffer.offset + fbeMapOffset + 4) > _buffer.size)
return false
val fbeMapSize = readUInt32(fbeMapOffset).toLong()
_modelKey.fbeOffset = fbeMapOffset + 4
_modelValue.fbeOffset = fbeMapOffset + 4 + _modelKey.fbeSize
var i = fbeMapSize
while (i-- > 0)
{
if (!_modelKey.verify())
return false
_modelKey.fbeShift(_modelKey.fbeSize + _modelValue.fbeSize)
if (!_modelValue.verify())
return false
_modelValue.fbeShift(_modelKey.fbeSize + _modelValue.fbeSize)
}
return true
}
// Get the map as TreeMap
fun get(values: TreeMap<_KEY_TYPE_, _VALUE_TYPE_>)
{
values.clear()
val fbeMapSize = size
if (fbeMapSize == 0L)
return
val fbeModel = getItem(0)
var i = fbeMapSize
while (i-- > 0)
{
val key = fbeModel.first.get()
val value = fbeModel.second.get()
values[key] = value
fbeModel.first.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
fbeModel.second.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
}
}
// Get the map as HashMap
fun get(values: HashMap<_KEY_TYPE_, _VALUE_TYPE_>)
{
values.clear()
val fbeMapSize = size
if (fbeMapSize == 0L)
return
val fbeModel = getItem(0)
var i = fbeMapSize
while (i-- > 0)
{
val key = fbeModel.first.get()
val value = fbeModel.second.get()
values[key] = value
fbeModel.first.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
fbeModel.second.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
}
}
// Set the map as TreeMap
fun set(values: TreeMap<_KEY_TYPE_, _VALUE_TYPE_>)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = resize(values.size.toLong())
for ((key, value1) in values)
{
fbeModel.first.set(key)
fbeModel.first.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
fbeModel.second.set(value1)
fbeModel.second.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
}
}
// Set the map as HashMap
fun set(values: HashMap<_KEY_TYPE_, _VALUE_TYPE_>)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
val fbeModel = resize(values.size.toLong())
for ((key, value1) in values)
{
fbeModel.first.set(key)
fbeModel.first.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
fbeModel.second.set(value1)
fbeModel.second.fbeShift(fbeModel.first.fbeSize + fbeModel.second.fbeSize)
}
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_KEY_NAME_"), key_name);
code = std::regex_replace(code, std::regex("_KEY_TYPE_"), key_type);
code = std::regex_replace(code, std::regex("_KEY_MODEL_"), key_model);
code = std::regex_replace(code, std::regex("_VALUE_NAME_"), value_name);
code = std::regex_replace(code, std::regex("_VALUE_TYPE_"), value_type);
code = std::regex_replace(code, std::regex("_VALUE_MODEL_"), value_model);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFieldModelEnumFlags(const std::string& package, const std::string& name, const std::string& type)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FieldModel" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _NAME_ field model
class FieldModel_NAME_(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)
{
// Field size
override val fbeSize: Long = _SIZE_
// Get the value
fun get(defaults: _NAME_ = _NAME_()): _NAME_
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return defaults
return _NAME_(_READ_(fbeOffset))
}
// Set the value
fun set(value: _NAME_)
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return
write(fbeOffset, value.raw)
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_SIZE_"), ConvertEnumSize(type));
code = std::regex_replace(code, std::regex("_READ_"), ConvertEnumRead(type));
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBESize(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "Size.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding size
class Size
{
var value: Long = 0
// Initialize a new size
constructor()
constructor(size: Long) { value = size }
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModel(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FinalModel.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding base final model
@Suppress("MemberVisibilityCanBePrivate")
abstract class FinalModel protected constructor(protected var _buffer: Buffer, protected var _offset: Long)
{
// Final offset
var fbeOffset: Long
get() = _offset
set(value) { _offset = value }
// Final size
open val fbeSize: Long = 0
// Final extra size
open val fbeExtra: Long = 0
// Shift the current final offset
fun fbeShift(size: Long) { _offset += size }
// Unshift the current final offset
fun fbeUnshift(size: Long) { _offset -= size }
// Check if the value is valid
abstract fun verify(): Long
// Buffer I/O methods
protected fun readBoolean(offset: Long): Boolean { return Buffer.readBoolean(_buffer.data, _buffer.offset + offset) }
protected fun readByte(offset: Long): Byte { return Buffer.readByte(_buffer.data, _buffer.offset + offset) }
protected fun readChar(offset: Long): Char { return Buffer.readChar(_buffer.data, _buffer.offset + offset) }
protected fun readWChar(offset: Long): Char { return Buffer.readWChar(_buffer.data, _buffer.offset + offset) }
protected fun readInt8(offset: Long): Byte { return Buffer.readInt8(_buffer.data, _buffer.offset + offset) }
protected fun readUInt8(offset: Long): UByte { return Buffer.readUInt8(_buffer.data, _buffer.offset + offset) }
protected fun readInt16(offset: Long): Short { return Buffer.readInt16(_buffer.data, _buffer.offset + offset) }
protected fun readUInt16(offset: Long): UShort { return Buffer.readUInt16(_buffer.data, _buffer.offset + offset) }
protected fun readInt32(offset: Long): Int { return Buffer.readInt32(_buffer.data, _buffer.offset + offset) }
protected fun readUInt32(offset: Long): UInt { return Buffer.readUInt32(_buffer.data, _buffer.offset + offset) }
protected fun readInt64(offset: Long): Long { return Buffer.readInt64(_buffer.data, _buffer.offset + offset) }
protected fun readUInt64(offset: Long): ULong { return Buffer.readUInt64(_buffer.data, _buffer.offset + offset) }
protected fun readFloat(offset: Long): Float { return Buffer.readFloat(_buffer.data, _buffer.offset + offset) }
protected fun readDouble(offset: Long): Double { return Buffer.readDouble(_buffer.data, _buffer.offset + offset) }
protected fun readBytes(offset: Long, size: Long): ByteArray { return Buffer.readBytes(_buffer.data, _buffer.offset + offset, size) }
protected fun readString(offset: Long, size: Long): String { return Buffer.readString(_buffer.data, _buffer.offset + offset, size) }
protected fun readUUID(offset: Long): UUID { return Buffer.readUUID(_buffer.data, _buffer.offset + offset) }
protected fun write(offset: Long, value: Boolean) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Byte) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: UByte) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Short) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: UShort) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Int) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: UInt) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Long) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: ULong) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Float) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: Double) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: ByteArray) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
protected fun write(offset: Long, value: ByteArray, valueOffset: Long, valueSize: Long) { Buffer.write(_buffer.data, _buffer.offset + offset, value, valueOffset, valueSize) }
protected fun write(offset: Long, value: Byte, valueCount: Long) { Buffer.write(_buffer.data, _buffer.offset + offset, value, valueCount) }
protected fun write(offset: Long, value: UUID) { Buffer.write(_buffer.data, _buffer.offset + offset, value) }
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModel(const std::string& package, const std::string& name, const std::string& type, const std::string& base, const std::string& size, const std::string& defaults)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / ("FinalModel" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding _TYPE_ final model
class FinalModel_NAME_(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
@Suppress("UNUSED_PARAMETER")
fun fbeAllocationSize(value: _TYPE_): Long = fbeSize
// Final size
override val fbeSize: Long = _SIZE_
// Check if the value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return Long.MAX_VALUE
return fbeSize
}
// Get the value
fun get(size: Size): _TYPE_
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return _DEFAULTS_
size.value = fbeSize
return read_NAME_(fbeOffset)
}
// Set the value
fun set(value: _TYPE_): Long
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
write(fbeOffset, value_BASE_)
return fbeSize
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_BASE_"), base);
code = std::regex_replace(code, std::regex("_SIZE_"), size);
code = std::regex_replace(code, std::regex("_DEFAULTS_"), defaults);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelDecimal(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FinalModelDecimal.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding decimal final model
class FinalModelDecimal(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
@Suppress("UNUSED_PARAMETER")
fun fbeAllocationSize(value: BigDecimal): Long = fbeSize
// Final size
override val fbeSize: Long = 16
// Check if the decimal value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return Long.MAX_VALUE
return fbeSize
}
// Get the decimal value
fun get(size: Size): BigDecimal
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return BigDecimal.valueOf(0L)
val magnitude = readBytes(fbeOffset, 12)
val scale = readByte(fbeOffset + 14).toInt()
val signum = if (readByte(fbeOffset + 15) < 0) -1 else 1
// Reverse magnitude
for (i in 0 until (magnitude.size / 2))
{
val temp = magnitude[i]
magnitude[i] = magnitude[magnitude.size - i - 1]
magnitude[magnitude.size - i - 1] = temp
}
val unscaled = BigInteger(signum, magnitude)
size.value = fbeSize
return BigDecimal(unscaled, scale)
}
// Set the decimal value
fun set(value: BigDecimal): Long
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
// Get unscaled absolute value
val unscaled = value.abs().unscaledValue()
val bitLength = unscaled.bitLength()
if ((bitLength < 0) || (bitLength > 96))
{
// Value too big for .NET Decimal (bit length is limited to [0, 96])
write(fbeOffset, 0.toByte(), fbeSize)
return fbeSize
}
// Get byte array
val unscaledBytes = unscaled.toByteArray()
// Get scale
val scale = value.scale()
if ((scale < 0) || (scale > 28))
{
// Value scale exceeds .NET Decimal limit of [0, 28]
write(fbeOffset, 0.toByte(), fbeSize)
return fbeSize
}
// Write unscaled value to bytes 0-11
var index = 0
var i = unscaledBytes.size - 1
while ((i >= 0) && (index < 12))
{
write(fbeOffset + index, unscaledBytes[i])
i--
index++
}
// Fill remaining bytes with zeros
while (index < 14)
{
write(fbeOffset + index, 0.toByte())
index++
}
// Write scale at byte 14
write(fbeOffset + 14, scale.toByte())
// Write signum at byte 15
write(fbeOffset + 15, (if (value.signum() < 0) -128 else 0).toByte())
return fbeSize
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelTimestamp(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FinalModelTimestamp.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding timestamp final model
class FinalModelTimestamp(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
@Suppress("UNUSED_PARAMETER")
fun fbeAllocationSize(value: Instant): Long = fbeSize
// Final size
override val fbeSize: Long = 8
// Check if the timestamp value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return Long.MAX_VALUE
return fbeSize
}
// Get the timestamp value
fun get(size: Size): Instant
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return Instant.EPOCH
size.value = fbeSize
val nanoseconds = readInt64(fbeOffset)
return Instant.ofEpochSecond(nanoseconds / 1000000000, nanoseconds % 1000000000)
}
// Set the timestamp value
fun set(value: Instant): Long
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
val nanoseconds = value.epochSecond * 1000000000 + value.nano
write(fbeOffset, nanoseconds.toULong())
return fbeSize
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelBytes(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FinalModelBytes.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding bytes final model
class FinalModelBytes(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
fun fbeAllocationSize(value: ByteArray): Long = 4 + value.size.toLong()
// Check if the bytes value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset) + 4 > _buffer.size)
return Long.MAX_VALUE
val fbeBytesSize = readUInt32(fbeOffset).toLong()
if ((_buffer.offset + fbeOffset + 4 + fbeBytesSize) > _buffer.size)
return Long.MAX_VALUE
return 4 + fbeBytesSize
}
// Get the bytes value
fun get(size: Size): ByteArray
{
if ((_buffer.offset + fbeOffset) + 4 > _buffer.size)
{
size.value = 0
return ByteArray(0)
}
val fbeBytesSize = readUInt32(fbeOffset).toLong()
assert((_buffer.offset + fbeOffset + 4 + fbeBytesSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4 + fbeBytesSize) > _buffer.size)
{
size.value = 4
return ByteArray(0)
}
size.value = 4 + fbeBytesSize
return readBytes(fbeOffset + 4, fbeBytesSize)
}
// Set the bytes value
fun set(value: ByteArray): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val fbeBytesSize = value.size.toLong()
assert((_buffer.offset + fbeOffset + 4 + fbeBytesSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4 + fbeBytesSize) > _buffer.size)
return 4
write(fbeOffset, fbeBytesSize.toUInt())
write(fbeOffset + 4, value)
return 4 + fbeBytesSize
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelString(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "FinalModelString.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding string final model
class FinalModelString(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
fun fbeAllocationSize(value: String): Long = 4 + 3 * (value.length.toLong() + 1)
// Check if the string value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return Long.MAX_VALUE
val fbeStringSize = readUInt32(fbeOffset).toLong()
if ((_buffer.offset + fbeOffset + 4 + fbeStringSize) > _buffer.size)
return Long.MAX_VALUE
return 4 + fbeStringSize
}
// Get the string value
fun get(size: Size): String
{
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
{
size.value = 0
return ""
}
val fbeStringSize = readUInt32(fbeOffset).toLong()
assert((_buffer.offset + fbeOffset + 4 + fbeStringSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4 + fbeStringSize) > _buffer.size)
{
size.value = 4
return ""
}
size.value = 4 + fbeStringSize
return readString(fbeOffset + 4, fbeStringSize)
}
// Set the string value
fun set(value: String): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val bytes = value.toByteArray(StandardCharsets.UTF_8)
val fbeStringSize = bytes.size.toLong()
assert((_buffer.offset + fbeOffset + 4 + fbeStringSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4 + fbeStringSize) > _buffer.size)
return 4
write(fbeOffset, fbeStringSize.toUInt())
write(fbeOffset + 4, bytes)
return 4 + fbeStringSize
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelOptional(const std::string& package, const std::string& name, const std::string& type, const std::string& model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FinalModelOptional" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding optional _NAME_ final model
class FinalModelOptional_NAME_(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
fun fbeAllocationSize(optional: _TYPE_): Long = 1 + (if (optional != null) value.fbeAllocationSize(optional) else 0)
// Checks if the object contains a value
fun hasValue(): Boolean
{
if ((_buffer.offset + fbeOffset + 1) > _buffer.size)
return false
val fbeHasValue = readInt8(fbeOffset).toInt()
return fbeHasValue != 0
}
// Base final model value
val value = _MODEL_(buffer, 0)
// Check if the optional value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + 1) > _buffer.size)
return Long.MAX_VALUE
val fbeHasValue = readInt8(fbeOffset).toInt()
if (fbeHasValue == 0)
return 1
_buffer.shift(fbeOffset + 1)
val fbeResult = value.verify()
_buffer.unshift(fbeOffset + 1)
return 1 + fbeResult
}
// Get the optional value
fun get(size: Size): _TYPE_
{
assert((_buffer.offset + fbeOffset + 1) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 1) > _buffer.size)
{
size.value = 0
return null
}
if (!hasValue())
{
size.value = 1
return null
}
_buffer.shift(fbeOffset + 1)
val optional = value.get(size)
_buffer.unshift(fbeOffset + 1)
size.value += 1
return optional
}
// Set the optional value
fun set(optional: _TYPE_): Long
{
assert((_buffer.offset + fbeOffset + 1) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 1) > _buffer.size)
return 0
val fbeHasValue = if (optional != null) 1 else 0
write(fbeOffset, fbeHasValue.toByte())
if (fbeHasValue == 0)
return 1
_buffer.shift(fbeOffset + 1)
val size = value.set(optional!!)
_buffer.unshift(fbeOffset + 1)
return 1 + size
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_MODEL_"), model);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelArray(const std::string& package, const std::string& name, const std::string& type, const std::string& base, bool optional, const std::string& model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FinalModelArray" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _NAME_ array final model
class FinalModelArray_NAME_(buffer: Buffer, offset: Long, private val _size: Long) : FinalModel(buffer, offset)
{
private val _model = _MODEL_(buffer, offset)
// Get the allocation size
fun fbeAllocationSize(values: _ARRAY_): Long
{
var size: Long = 0
var i: Long = 0
while ((i < values.size) && (i < _size))
{
size += _model.fbeAllocationSize(values[i.toInt()])
i++
}
return size
}
fun fbeAllocationSize(values: ArrayList<_TYPE_>): Long
{
var size: Long = 0
var i: Long = 0
while ((i < values.size) && (i < _size))
{
size += _model.fbeAllocationSize(values[i.toInt()])
i++
}
return size
}
// Check if the array is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset) > _buffer.size)
return Long.MAX_VALUE
var size: Long = 0
_model.fbeOffset = fbeOffset
var i = _size
while (i-- > 0)
{
val offset = _model.verify()
if (offset == Long.MAX_VALUE)
return Long.MAX_VALUE
_model.fbeShift(offset)
size += offset
}
return size
}
// Get the array
fun get(size: Size): _ARRAY_
{
val values = _INIT_
assert((_buffer.offset + fbeOffset) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset) > _buffer.size)
{
size.value = 0
return values
}
size.value = 0
val offset = Size()
_model.fbeOffset = fbeOffset
for (i in 0 until _size)
{
offset.value = 0
values[i.toInt()] = _model.get(offset)
_model.fbeShift(offset.value)
size.value += offset.value
}
return values
}
// Get the array
fun get(values: _ARRAY_): Long
{
assert((_buffer.offset + fbeOffset) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset) > _buffer.size)
return 0
var size: Long = 0
val offset = Size()
_model.fbeOffset = fbeOffset
var i: Long = 0
while ((i < values.size) && (i < _size))
{
offset.value = 0
values[i.toInt()] = _model.get(offset)
_model.fbeShift(offset.value)
size += offset.value
i++
}
return size
}
// Get the array as ArrayList
fun get(values: ArrayList<_TYPE_>): Long
{
values.clear()
assert((_buffer.offset + fbeOffset) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset) > _buffer.size)
return 0
values.ensureCapacity(_size.toInt())
var size: Long = 0
val offset = Size()
_model.fbeOffset = fbeOffset
var i = _size
while (i-- > 0)
{
offset.value = 0
val value = _model.get(offset)
values.add(value)
_model.fbeShift(offset.value)
size += offset.value
}
return size
}
// Set the array
fun set(values: _ARRAY_): Long
{
assert((_buffer.offset + fbeOffset) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset) > _buffer.size)
return 0
var size: Long = 0
_model.fbeOffset = fbeOffset
var i: Long = 0
while ((i < values.size) && (i < _size))
{
val offset = _model.set(values[i.toInt()])
_model.fbeShift(offset)
size += offset
i++
}
return size
}
// Set the array as List
fun set(values: ArrayList<_TYPE_>): Long
{
assert((_buffer.offset + fbeOffset) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset) > _buffer.size)
return 0
var size: Long = 0
_model.fbeOffset = fbeOffset
var i: Long = 0
while ((i < values.size) && (i < _size))
{
val offset = _model.set(values[i.toInt()])
_model.fbeShift(offset)
size += offset
i++
}
return size
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_MODEL_"), model);
code = std::regex_replace(code, std::regex("_ARRAY_"), "Array<" + type + ">");
if (optional)
code = std::regex_replace(code, std::regex("_INIT_"), "arrayOfNulls<" + type + ">(_size.toInt())");
else
code = std::regex_replace(code, std::regex("_INIT_"), "Array(_size.toInt()) { " + ConvertDefault(base) + " }");
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelVector(const std::string& package, const std::string& name, const std::string& type, const std::string& model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FinalModelVector" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _NAME_ vector final model
class FinalModelVector_NAME_(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
private val _model = _MODEL_(buffer, offset)
// Get the allocation size
fun fbeAllocationSize(values: ArrayList<_TYPE_>): Long
{
var size: Long = 4
for (value in values)
size += _model.fbeAllocationSize(value)
return size
}
fun fbeAllocationSize(values: LinkedList<_TYPE_>): Long
{
var size: Long = 4
for (value in values)
size += _model.fbeAllocationSize(value)
return size
}
fun fbeAllocationSize(values: HashSet<_TYPE_>): Long
{
var size: Long = 4
for (value in values)
size += _model.fbeAllocationSize(value)
return size
}
// Check if the vector is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return Long.MAX_VALUE
val fbeVectorSize = readUInt32(fbeOffset).toLong()
var size: Long = 4
_model.fbeOffset = fbeOffset + 4
var i = fbeVectorSize
while (i-- > 0)
{
val offset = _model.verify()
if (offset == Long.MAX_VALUE)
return Long.MAX_VALUE
_model.fbeShift(offset)
size += offset
}
return size
}
// Get the vector as ArrayList
fun get(values: ArrayList<_TYPE_>): Long
{
values.clear()
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val fbeVectorSize = readUInt32(fbeOffset).toLong()
if (fbeVectorSize == 0L)
return 4
values.ensureCapacity(fbeVectorSize.toInt())
var size: Long = 4
val offset = Size()
_model.fbeOffset = fbeOffset + 4
for (i in 0 until fbeVectorSize)
{
offset.value = 0
val value = _model.get(offset)
values.add(value)
_model.fbeShift(offset.value)
size += offset.value
}
return size
}
// Get the vector as LinkedList
fun get(values: LinkedList<_TYPE_>): Long
{
values.clear()
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val fbeVectorSize = readUInt32(fbeOffset).toLong()
if (fbeVectorSize == 0L)
return 4
var size: Long = 4
val offset = Size()
_model.fbeOffset = fbeOffset + 4
for (i in 0 until fbeVectorSize)
{
offset.value = 0
val value = _model.get(offset)
values.add(value)
_model.fbeShift(offset.value)
size += offset.value
}
return size
}
// Get the vector as HashSet
fun get(values: HashSet<_TYPE_>): Long
{
values.clear()
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val fbeVectorSize = readUInt32(fbeOffset).toLong()
if (fbeVectorSize == 0L)
return 4
var size: Long = 4
val offset = Size()
_model.fbeOffset = fbeOffset + 4
for (i in 0 until fbeVectorSize)
{
offset.value = 0
val value = _model.get(offset)
values.add(value)
_model.fbeShift(offset.value)
size += offset.value
}
return size
}
// Set the vector as ArrayList
fun set(values: ArrayList<_TYPE_>): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
write(fbeOffset, values.size.toUInt())
var size: Long = 4
_model.fbeOffset = fbeOffset + 4
for (value in values)
{
val offset = _model.set(value)
_model.fbeShift(offset)
size += offset
}
return size
}
// Set the vector as LinkedList
fun set(values: LinkedList<_TYPE_>): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
write(fbeOffset, values.size.toUInt())
var size: Long = 4
_model.fbeOffset = fbeOffset + 4
for (value in values)
{
val offset = _model.set(value)
_model.fbeShift(offset)
size += offset
}
return size
}
// Set the vector as HashSet
fun set(values: HashSet<_TYPE_>): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
write(fbeOffset, values.size.toUInt())
var size: Long = 4
_model.fbeOffset = fbeOffset + 4
for (value in values)
{
val offset = _model.set(value)
_model.fbeShift(offset)
size += offset
}
return size
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_TYPE_"), type);
code = std::regex_replace(code, std::regex("_MODEL_"), model);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelMap(const std::string& package, const std::string& key_name, const std::string& key_type, const std::string& key_model, const std::string& value_name, const std::string& value_type, const std::string& value_model)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FinalModelMap" + key_name + value_name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _KEY_NAME_->_VALUE_NAME_ map final model
class FinalModelMap_KEY_NAME__VALUE_NAME_(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
private val _modelKey = _KEY_MODEL_(buffer, offset)
private val _modelValue = _VALUE_MODEL_(buffer, offset)
// Get the allocation size
fun fbeAllocationSize(values: TreeMap<_KEY_TYPE_, _VALUE_TYPE_>): Long
{
var size: Long = 4
for ((key, value1) in values)
{
size += _modelKey.fbeAllocationSize(key)
size += _modelValue.fbeAllocationSize(value1)
}
return size
}
fun fbeAllocationSize(values: HashMap<_KEY_TYPE_, _VALUE_TYPE_>): Long
{
var size: Long = 4
for ((key, value1) in values)
{
size += _modelKey.fbeAllocationSize(key)
size += _modelValue.fbeAllocationSize(value1)
}
return size
}
// Check if the map is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return Long.MAX_VALUE
val fbeMapSize = readUInt32(fbeOffset).toLong()
var size: Long = 4
_modelKey.fbeOffset = fbeOffset + 4
_modelValue.fbeOffset = fbeOffset + 4
var i = fbeMapSize
while (i-- > 0)
{
val offsetKey = _modelKey.verify()
if (offsetKey == Long.MAX_VALUE)
return Long.MAX_VALUE
_modelKey.fbeShift(offsetKey)
_modelValue.fbeShift(offsetKey)
size += offsetKey
val offsetValue = _modelValue.verify()
if (offsetValue == Long.MAX_VALUE)
return Long.MAX_VALUE
_modelKey.fbeShift(offsetValue)
_modelValue.fbeShift(offsetValue)
size += offsetValue
}
return size
}
// Get the map as TreeMap
fun get(values: TreeMap<_KEY_TYPE_, _VALUE_TYPE_>): Long
{
values.clear()
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val fbeMapSize = readUInt32(fbeOffset).toLong()
if (fbeMapSize == 0L)
return 4
var size: Long = 4
val offset = Size()
_modelKey.fbeOffset = fbeOffset + 4
_modelValue.fbeOffset = fbeOffset + 4
var i = fbeMapSize
while (i-- > 0)
{
offset.value = 0
val key = _modelKey.get(offset)
_modelKey.fbeShift(offset.value)
_modelValue.fbeShift(offset.value)
size += offset.value
offset.value = 0
val value = _modelValue.get(offset)
_modelKey.fbeShift(offset.value)
_modelValue.fbeShift(offset.value)
size += offset.value
values[key] = value
}
return size
}
// Get the map as HashMap
fun get(values: HashMap<_KEY_TYPE_, _VALUE_TYPE_>): Long
{
values.clear()
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
val fbeMapSize = readUInt32(fbeOffset).toLong()
if (fbeMapSize == 0L)
return 4
var size: Long = 4
val offset = Size()
_modelKey.fbeOffset = fbeOffset + 4
_modelValue.fbeOffset = fbeOffset + 4
var i = fbeMapSize
while (i-- > 0)
{
offset.value = 0
val key = _modelKey.get(offset)
_modelKey.fbeShift(offset.value)
_modelValue.fbeShift(offset.value)
size += offset.value
offset.value = 0
val value = _modelValue.get(offset)
_modelKey.fbeShift(offset.value)
_modelValue.fbeShift(offset.value)
size += offset.value
values[key] = value
}
return size
}
// Set the map as TreeMap
fun set(values: TreeMap<_KEY_TYPE_, _VALUE_TYPE_>): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
write(fbeOffset, values.size.toUInt())
var size: Long = 4
_modelKey.fbeOffset = fbeOffset + 4
_modelValue.fbeOffset = fbeOffset + 4
for ((key, value1) in values)
{
val offsetKey = _modelKey.set(key)
_modelKey.fbeShift(offsetKey)
_modelValue.fbeShift(offsetKey)
val offsetValue = _modelValue.set(value1)
_modelKey.fbeShift(offsetValue)
_modelValue.fbeShift(offsetValue)
size += offsetKey + offsetValue
}
return size
}
// Set the map as HashMap
fun set(values: HashMap<_KEY_TYPE_, _VALUE_TYPE_>): Long
{
assert((_buffer.offset + fbeOffset + 4) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + 4) > _buffer.size)
return 0
write(fbeOffset, values.size.toUInt())
var size: Long = 4
_modelKey.fbeOffset = fbeOffset + 4
_modelValue.fbeOffset = fbeOffset + 4
for ((key, value1) in values)
{
val offsetKey = _modelKey.set(key)
_modelKey.fbeShift(offsetKey)
_modelValue.fbeShift(offsetKey)
val offsetValue = _modelValue.set(value1)
_modelKey.fbeShift(offsetValue)
_modelValue.fbeShift(offsetValue)
size += offsetKey + offsetValue
}
return size
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_KEY_NAME_"), key_name);
code = std::regex_replace(code, std::regex("_KEY_TYPE_"), key_type);
code = std::regex_replace(code, std::regex("_KEY_MODEL_"), key_model);
code = std::regex_replace(code, std::regex("_VALUE_NAME_"), value_name);
code = std::regex_replace(code, std::regex("_VALUE_TYPE_"), value_type);
code = std::regex_replace(code, std::regex("_VALUE_MODEL_"), value_model);
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEFinalModelEnumFlags(const std::string& package, const std::string& name, const std::string& type)
{
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FinalModel" + name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
std::string code = R"CODE(
// Fast Binary Encoding _NAME_ final model
class FinalModel_NAME_(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)
{
// Get the allocation size
@Suppress("UNUSED_PARAMETER")
fun fbeAllocationSize(value: _NAME_): Long = fbeSize
// Final size
override val fbeSize: Long = _SIZE_
// Check if the value is valid
override fun verify(): Long
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return Long.MAX_VALUE
return fbeSize
}
// Get the value
fun get(size: Size): _NAME_
{
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return _NAME_()
size.value = fbeSize
return _NAME_(_READ_(fbeOffset))
}
// Set the value
fun set(value: _NAME_): Long
{
assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { "Model is broken!" }
if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)
return 0
write(fbeOffset, value.raw)
return fbeSize
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("_NAME_"), name);
code = std::regex_replace(code, std::regex("_SIZE_"), ConvertEnumSize(type));
code = std::regex_replace(code, std::regex("_READ_"), ConvertEnumRead(type));
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBESender(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "Sender.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding base sender
@Suppress("MemberVisibilityCanBePrivate")
abstract class Sender
{
// Get the bytes buffer
var buffer: Buffer = Buffer()
private set
// Enable/Disable logging
var logging: Boolean = false
// Get the final protocol flag
var final: Boolean = false
private set
protected constructor(final: Boolean) { this.final = final }
protected constructor(buffer: Buffer, final: Boolean) { this.buffer = buffer; this.final = final }
// Reset the sender buffer
fun reset() { buffer.reset() }
// Send serialized buffer.
// Direct call of the method requires knowledge about internals of FBE models serialization.
// Use it with care!
fun sendSerialized(serialized: Long): Long
{
assert(serialized > 0) { "Invalid size of the serialized buffer!" }
if (serialized <= 0)
return 0
// Shift the send buffer
buffer.shift(serialized)
// Send the value
val sent = onSend(buffer.data, 0, buffer.size)
buffer.remove(0, sent)
return sent
}
// Send message handler
protected abstract fun onSend(buffer: ByteArray, offset: Long, size: Long): Long
// Send log message handler
@Suppress("UNUSED_PARAMETER")
protected open fun onSendLog(message: String) {}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEReceiver(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "Receiver.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
std::string code = R"CODE(
// Fast Binary Encoding base receiver
@Suppress("MemberVisibilityCanBePrivate")
abstract class Receiver
{
// Get the bytes buffer
var buffer: Buffer = Buffer()
private set
// Enable/Disable logging
var logging: Boolean = false
// Get the final protocol flag
var final: Boolean = false
private set
protected constructor(final: Boolean) { this.final = final }
protected constructor(buffer: Buffer, final: Boolean) { this.buffer = buffer; this.final = final }
// Reset the receiver buffer
fun reset() { buffer.reset() }
// Receive data
fun receive(buffer: Buffer) { receive(buffer.data, 0, buffer.size) }
fun receive(buffer: ByteArray, offset: Long = 0, size: Long = buffer.size.toLong())
{
assert((offset + size) <= buffer.size) { "Invalid offset & size!" }
if ((offset + size) > buffer.size)
throw IllegalArgumentException("Invalid offset & size!")
if (size == 0L)
return
// Storage buffer
var offset0 = this.buffer.offset
var offset1 = this.buffer.size
var size1 = this.buffer.size
// Receive buffer
var offset2: Long = 0
// While receive buffer is available to handle...
while (offset2 < size)
{
var messageBuffer: ByteArray? = null
var messageOffset: Long = 0
var messageSize: Long = 0
// Try to receive message size
var messageSizeCopied = false
var messageSizeFound = false
while (!messageSizeFound)
{
// Look into the storage buffer
if (offset0 < size1)
{
var count = Math.min(size1 - offset0, 4)
if (count == 4L)
{
messageSizeCopied = true
messageSizeFound = true
messageSize = Buffer.readUInt32(this.buffer.data, offset0).toLong()
offset0 += 4
break
}
else
{
// Fill remaining data from the receive buffer
if (offset2 < size)
{
count = Math.min(size - offset2, 4 - count)
// Allocate and refresh the storage buffer
this.buffer.allocate(count)
size1 += count
System.arraycopy(buffer, (offset + offset2).toInt(), this.buffer.data, offset1.toInt(), count.toInt())
offset1 += count
offset2 += count
continue
}
else
break
}
}
// Look into the receive buffer
if (offset2 < size)
{
val count = Math.min(size - offset2, 4)
if (count == 4L)
{
messageSizeFound = true
messageSize = Buffer.readUInt32(buffer, offset + offset2).toLong()
offset2 += 4
break
}
else
{
// Allocate and refresh the storage buffer
this.buffer.allocate(count)
size1 += count
System.arraycopy(buffer, (offset + offset2).toInt(), this.buffer.data, offset1.toInt(), count.toInt())
offset1 += count
offset2 += count
continue
}
}
else
break
}
if (!messageSizeFound)
return
// Check the message full size
assert(messageSize >= (4 + 4 + 4 + 4)) { "Invalid receive data!" }
if (messageSize < (4 + 4 + 4 + 4))
return
// Try to receive message body
var messageFound = false
while (!messageFound)
{
// Look into the storage buffer
if (offset0 < size1)
{
var count = Math.min(size1 - offset0, messageSize - 4)
if (count == (messageSize - 4))
{
messageFound = true
messageBuffer = this.buffer.data
messageOffset = offset0 - 4
offset0 += messageSize - 4
break
}
else
{
// Fill remaining data from the receive buffer
if (offset2 < size)
{
// Copy message size into the storage buffer
if (!messageSizeCopied)
{
// Allocate and refresh the storage buffer
this.buffer.allocate(4)
size1 += 4
Buffer.write(this.buffer.data, offset0, messageSize.toUInt())
offset0 += 4
offset1 += 4
messageSizeCopied = true
}
count = Math.min(size - offset2, messageSize - 4 - count)
// Allocate and refresh the storage buffer
this.buffer.allocate(count)
size1 += count
System.arraycopy(buffer, (offset + offset2).toInt(), this.buffer.data, offset1.toInt(), count.toInt())
offset1 += count
offset2 += count
continue
}
else
break
}
}
// Look into the receive buffer
if (offset2 < size)
{
val count = Math.min(size - offset2, messageSize - 4)
if (!messageSizeCopied && (count == (messageSize - 4)))
{
messageFound = true
messageBuffer = buffer
messageOffset = offset + offset2 - 4
offset2 += messageSize - 4
break
}
else
{
// Copy message size into the storage buffer
if (!messageSizeCopied)
{
// Allocate and refresh the storage buffer
this.buffer.allocate(4)
size1 += 4
Buffer.write(this.buffer.data, offset0, messageSize.toUInt())
offset0 += 4
offset1 += 4
messageSizeCopied = true
}
// Allocate and refresh the storage buffer
this.buffer.allocate(count)
size1 += count
System.arraycopy(buffer, (offset + offset2).toInt(), this.buffer.data, offset1.toInt(), count.toInt())
offset1 += count
offset2 += count
continue
}
}
else
break
}
if (!messageFound)
{
// Copy message size into the storage buffer
if (!messageSizeCopied)
{
// Allocate and refresh the storage buffer
this.buffer.allocate(4)
size1 += 4
Buffer.write(this.buffer.data, offset0, messageSize.toUInt())
offset0 += 4
offset1 += 4
@Suppress("UNUSED_VALUE")
messageSizeCopied = true
}
return
}
if (messageBuffer != null)
{
@Suppress("ASSIGNED_BUT_NEVER_ACCESSED_VARIABLE")
val fbeStructSize: Long
val fbeStructType: Long
// Read the message parameters
if (final)
{
@Suppress("UNUSED_VALUE")
fbeStructSize = Buffer.readUInt32(messageBuffer, messageOffset).toLong()
fbeStructType = Buffer.readUInt32(messageBuffer, messageOffset + 4).toLong()
}
else
{
val fbeStructOffset = Buffer.readUInt32(messageBuffer, messageOffset + 4).toLong()
@Suppress("UNUSED_VALUE")
fbeStructSize = Buffer.readUInt32(messageBuffer, messageOffset + fbeStructOffset).toLong()
fbeStructType = Buffer.readUInt32(messageBuffer, messageOffset + fbeStructOffset + 4).toLong()
}
// Handle the message
onReceive(fbeStructType, messageBuffer, messageOffset, messageSize)
}
// Reset the storage buffer
this.buffer.reset()
// Refresh the storage buffer
offset0 = this.buffer.offset
offset1 = this.buffer.size
size1 = this.buffer.size
}
}
// Receive message handler
abstract fun onReceive(type: Long, buffer: ByteArray, offset: Long, size: Long): Boolean
// Receive log message handler
@Suppress("UNUSED_PARAMETER")
protected open fun onReceiveLog(message: String) {}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateFBEJson(const std::string& package)
{
CppCommon::Path path = CppCommon::Path(_output) / package;
// Open the file
CppCommon::Path file = path / "Json.kt";
Open(file);
// Generate headers
GenerateHeader("fbe");
GenerateImports(package);
// Generate custom import
WriteLine();
WriteLineIndent("import com.google.gson.*");
std::string code = R"CODE(
internal class BytesJson : JsonSerializer<ByteArray>, JsonDeserializer<ByteArray>
{
override fun serialize(src: ByteArray, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
return JsonPrimitive(Base64.getEncoder().encodeToString(src))
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): ByteArray
{
return Base64.getDecoder().decode(json.asString)
}
}
internal class CharacterJson : JsonSerializer<Char>, JsonDeserializer<Char>
{
override fun serialize(src: Char, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
return JsonPrimitive(src.toLong())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): Char
{
return json.asLong.toChar()
}
}
internal class InstantJson : JsonSerializer<Instant>, JsonDeserializer<Instant>
{
override fun serialize(src: Instant, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
val nanoseconds = src.epochSecond * 1000000000 + src.nano
return JsonPrimitive(nanoseconds)
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): Instant
{
val nanoseconds = json.asJsonPrimitive.asLong
return Instant.ofEpochSecond(nanoseconds / 1000000000, nanoseconds % 1000000000)
}
}
internal class BigDecimalJson : JsonSerializer<BigDecimal>, JsonDeserializer<BigDecimal>
{
override fun serialize(src: BigDecimal, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
return JsonPrimitive(src.toPlainString())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): BigDecimal
{
return BigDecimal(json.asJsonPrimitive.asString)
}
}
internal class UUIDJson : JsonSerializer<UUID>, JsonDeserializer<UUID>
{
override fun serialize(src: UUID, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
return JsonPrimitive(src.toString())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): UUID {
return UUID.fromString(json.asJsonPrimitive.asString)
}
}
internal class UByteNullableJson : JsonSerializer<UByte?>, JsonDeserializer<UByte?>
{
override fun serialize(src: UByte?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
if (src == null)
return JsonNull.INSTANCE
return JsonPrimitive(src.toLong())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): UByte?
{
if (json.isJsonNull)
return null
return json.asLong.toUByte()
}
}
internal class UShortNullableJson : JsonSerializer<UShort?>, JsonDeserializer<UShort?>
{
override fun serialize(src: UShort?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
if (src == null)
return JsonNull.INSTANCE
return JsonPrimitive(src.toLong())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): UShort?
{
if (json.isJsonNull)
return null
return json.asLong.toUShort()
}
}
internal class UIntNullableJson : JsonSerializer<UInt?>, JsonDeserializer<UInt?>
{
override fun serialize(src: UInt?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
if (src == null)
return JsonNull.INSTANCE
return JsonPrimitive(src.toLong())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): UInt?
{
if (json.isJsonNull)
return null
return json.asLong.toUInt()
}
}
internal class ULongNullableJson : JsonSerializer<ULong?>, JsonDeserializer<ULong?>
{
override fun serialize(src: ULong?, typeOfSrc: Type, context: JsonSerializationContext): JsonElement
{
if (src == null)
return JsonNull.INSTANCE
return JsonPrimitive(src.toLong())
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): ULong?
{
if (json.isJsonNull)
return null
return json.asLong.toULong()
}
}
// Fast Binary Encoding base JSON engine
@Suppress("MemberVisibilityCanBePrivate")
object Json
{
// Get the JSON engine
val engine: Gson = register(GsonBuilder()).create()
fun register(builder: GsonBuilder): GsonBuilder
{
builder.serializeNulls()
builder.registerTypeAdapter(ByteArray::class.java, BytesJson())
builder.registerTypeAdapter(Char::class.java, CharacterJson())
builder.registerTypeAdapter(Character::class.java, CharacterJson())
builder.registerTypeAdapter(Instant::class.java, InstantJson())
builder.registerTypeAdapter(BigDecimal::class.java, BigDecimalJson())
builder.registerTypeAdapter(UUID::class.java, UUIDJson())
builder.registerTypeAdapter(kotlin.UByte::class.java, UByteNullableJson())
builder.registerTypeAdapter(kotlin.UShort::class.java, UShortNullableJson())
builder.registerTypeAdapter(kotlin.UInt::class.java, UIntNullableJson())
builder.registerTypeAdapter(kotlin.ULong::class.java, ULongNullableJson())
return builder
}
}
)CODE";
// Prepare code template
code = std::regex_replace(code, std::regex("\n"), EndLine());
Write(code);
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateContainers(const std::shared_ptr<Package>& p, bool final)
{
CppCommon::Path path = CppCommon::Path(_output) / *p->name;
// Create package path
CppCommon::Directory::CreateTree(path);
if (p->body)
{
// Check all structs in the package
for (const auto& s : p->body->structs)
{
if (s->body)
{
// Check all fields in the struct
for (const auto& field : s->body->fields)
{
if (field->array)
{
if (final)
GenerateFBEFinalModelArray(*p->name, (field->optional ? "Optional" : "") + ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), *field->type, field->optional, ConvertTypeFieldDeclaration(*field->type, field->optional, final));
else
GenerateFBEFieldModelArray(*p->name, (field->optional ? "Optional" : "") + ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), *field->type, field->optional, ConvertTypeFieldDeclaration(*field->type, field->optional, final));
}
if (field->vector || field->list || field->set)
{
if (final)
GenerateFBEFinalModelVector(*p->name, (field->optional ? "Optional" : "") + ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), ConvertTypeFieldDeclaration(*field->type, field->optional, final));
else
GenerateFBEFieldModelVector(*p->name, (field->optional ? "Optional" : "") + ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), ConvertTypeFieldDeclaration(*field->type, field->optional, final));
}
if (field->map || field->hash)
{
if (final)
GenerateFBEFinalModelMap(*p->name, ConvertTypeFieldName(*field->key), ConvertTypeFieldType(*field->key, false), ConvertTypeFieldDeclaration(*field->key, false, final), (field->optional ? "Optional" : "") + ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), ConvertTypeFieldDeclaration(*field->type, field->optional, final));
else
GenerateFBEFieldModelMap(*p->name, ConvertTypeFieldName(*field->key), ConvertTypeFieldType(*field->key, false), ConvertTypeFieldDeclaration(*field->key, false, final), (field->optional ? "Optional" : "") + ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), ConvertTypeFieldDeclaration(*field->type, field->optional, final));
}
if (field->optional)
{
if (final)
GenerateFBEFinalModelOptional(*p->name, ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), ConvertTypeFieldDeclaration(*field->type, false, final));
else
GenerateFBEFieldModelOptional(*p->name, ConvertTypeFieldName(*field->type), ConvertTypeFieldType(*field->type, field->optional), ConvertTypeFieldDeclaration(*field->type, false, final));
}
}
}
}
}
}
void GeneratorKotlin::GeneratePackage(const std::shared_ptr<Package>& p)
{
CppCommon::Path path = CppCommon::Path(_output) / *p->name;
// Create package path
CppCommon::Directory::CreateTree(path);
// Generate namespace
if (p->body)
{
// Generate child enums
for (const auto& child_e : p->body->enums)
GenerateEnum(p, child_e, path);
// Generate child flags
for (const auto& child_f : p->body->flags)
GenerateFlags(p, child_f, path);
// Generate child structs
for (const auto& child_s : p->body->structs)
GenerateStruct(p, child_s, path);
}
// Generate containers
GenerateContainers(p, false);
if (Final())
GenerateContainers(p, true);
// Generate sender & receiver
if (Sender())
{
GenerateSender(p, false);
GenerateReceiver(p, false);
GenerateProxy(p, false);
if (Final())
{
GenerateSender(p, true);
GenerateReceiver(p, true);
}
}
// Generate JSON engine
if (JSON())
GenerateJson(p);
}
void GeneratorKotlin::GenerateEnum(const std::shared_ptr<Package>& p, const std::shared_ptr<EnumType>& e, const CppCommon::Path& path)
{
std::string enum_name = *e->name + "Enum";
// Open the output file
CppCommon::Path output = path / (enum_name + ".kt");
Open(output);
// Generate enum header
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(p);
std::string enum_type = (e->base && !e->base->empty()) ? *e->base : "int32";
std::string enum_base_type = ConvertEnumType(enum_type);
std::string enum_mapping_type = ConvertEnumBase(enum_type);
std::string enum_to = ConvertEnumTo(enum_type);
// Generate enum body
WriteLine();
WriteLineIndent("@Suppress(\"EnumEntryName\", \"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\")");
WriteLineIndent("enum class " + enum_name);
WriteLineIndent("{");
Indent(1);
if (e->body)
{
int index = 0;
bool first = true;
std::string last = ConvertEnumConstant(enum_type, enum_type, "0", false);
for (const auto& value : e->body->values)
{
WriteIndent(std::string(first ? "" : ", ") + *value->name + "(");
if (value->value)
{
if (value->value->constant && !value->value->constant->empty())
{
index = 0;
last = ConvertEnumConstant(enum_type, enum_type, *value->value->constant, false);
Write(last + " + " + std::to_string(index++) + (IsUnsignedType(enum_type) ? "u" : ""));
}
else if (value->value->reference && !value->value->reference->empty())
{
index = 0;
last = ConvertEnumConstant(enum_type, "", *value->value->reference, false);
Write(last);
}
}
else
Write(last + " + " + std::to_string(index++) + (IsUnsignedType(enum_type) ? "u" : ""));
WriteLine(")");
first = false;
}
WriteLineIndent(";");
WriteLine();
}
// Generate enum value
WriteLineIndent("var raw: " + enum_mapping_type + " = " + ConvertEnumConstant(enum_type, enum_type, "0", false));
Indent(1);
WriteLineIndent("private set");
Indent(-1);
// Generate enum constructors
WriteLine();
if ((enum_type == "char") || (enum_type == "wchar"))
WriteLineIndent("constructor(value: Char) { this.raw = value" + enum_to + " }");
if (IsUnsignedType(enum_type))
{
WriteLineIndent("constructor(value: UByte) { this.raw = value" + enum_to + " }");
WriteLineIndent("constructor(value: UShort) { this.raw = value" + enum_to + " }");
WriteLineIndent("constructor(value: UInt) { this.raw = value" + enum_to + " }");
WriteLineIndent("constructor(value: ULong) { this.raw = value" + enum_to + " }");
}
else
{
WriteLineIndent("constructor(value: Byte) { this.raw = value" + enum_to + " }");
WriteLineIndent("constructor(value: Short) { this.raw = value" + enum_to + " }");
WriteLineIndent("constructor(value: Int) { this.raw = value" + enum_to + " }");
WriteLineIndent("constructor(value: Long) { this.raw = value" + enum_to + " }");
}
WriteLineIndent("constructor(value: " + enum_name + ") { this.raw = value.raw }");
// Generate enum toString() method
WriteLine();
WriteLineIndent("override fun toString(): String");
WriteLineIndent("{");
Indent(1);
if (e->body)
{
for (const auto& value : e->body->values)
WriteLineIndent("if (this == " + *value->name + ")" + " return \"" + *value->name + "\"");
}
WriteLineIndent("return \"<unknown>\"");
Indent(-1);
WriteLineIndent("}");
// Generate enum mapping
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("private val mapping = HashMap<" + enum_mapping_type + ", " + enum_name + ">()");
WriteLine();
WriteLineIndent("init");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("for (value in " + enum_name + ".values())");
Indent(1);
WriteLineIndent("mapping[value.raw] = value");
Indent(-1);
Indent(-1);
WriteLineIndent("}");
// Generate enum mapValue() method
WriteLine();
WriteLineIndent("fun mapValue(value: " + enum_mapping_type + "): " + enum_name + "?" +" { return mapping[value] }");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
// Generate enum footer
GenerateFooter();
// Close the output file
Close();
// Generate enum wrapper class
GenerateEnumClass(p, e, path);
// Generate enum JSON adapter
if (JSON())
GenerateEnumJson(p, e);
// Generate enum field model
GenerateFBEFieldModelEnumFlags(*p->name, *e->name, enum_type);
// Generate enum final model
if (Final())
GenerateFBEFinalModelEnumFlags(*p->name, *e->name, enum_type);
}
void GeneratorKotlin::GenerateEnumClass(const std::shared_ptr<Package>& p, const std::shared_ptr<EnumType>& e, const CppCommon::Path& path)
{
std::string enum_name = *e->name;
std::string enum_type_name = *e->name + "Enum";
// Open the output file
CppCommon::Path output = path / (enum_name + ".kt");
Open(output);
// Generate enum class header
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(p);
std::string enum_type = (e->base && !e->base->empty()) ? *e->base : "int32";
std::string enum_base_type = ConvertEnumType(enum_type);
std::string enum_to = ConvertEnumTo(enum_type);
// Generate enum class body
WriteLine();
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\")");
WriteLineIndent("class " + enum_name + " : Comparable<" + enum_name + ">");
WriteLineIndent("{");
Indent(1);
if (e->body)
{
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
for (const auto& value : e->body->values)
WriteLineIndent("val " + *value->name + " = " + enum_name + "(" + enum_type_name + "." + *value->name + ")");
Indent(-1);
WriteLineIndent("}");
WriteLine();
}
// Generate enum class value
WriteLineIndent("var value: " + enum_type_name + "?" + " = " + enum_type_name + ".values()[0]");
Indent(1);
WriteLineIndent("private set");
Indent(-1);
WriteLine();
// Generate enum raw value
WriteLineIndent("val raw: " + enum_base_type);
Indent(1);
WriteLineIndent("get() = value!!.raw");
Indent(-1);
WriteLine();
// Generate enum class constructors
WriteLineIndent("constructor()");
WriteLineIndent("constructor(value: " + enum_base_type + ") { setEnum(value) }");
WriteLineIndent("constructor(value: " + enum_type_name + ") { setEnum(value) }");
WriteLineIndent("constructor(value: " + enum_name + ") { setEnum(value) }");
WriteLine();
// Generate enum class setDefault() method
WriteLineIndent("fun setDefault() { setEnum(0" + enum_to + ") }");
WriteLine();
// Generate enum class setEnum() methods
WriteLineIndent("fun setEnum(value: " + enum_base_type + ") { this.value = " + enum_type_name + ".mapValue(value) }");
WriteLineIndent("fun setEnum(value: " + enum_type_name + ") { this.value = value }");
WriteLineIndent("fun setEnum(value: " + enum_name + ") { this.value = value.value }");
// Generate enum class compareTo() method
WriteLine();
WriteLineIndent("override fun compareTo(other: " + enum_name + "): Int");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if (value == null)");
Indent(1);
WriteLineIndent("return -1");
Indent(-1);
WriteLineIndent("if (other.value == null)");
Indent(1);
WriteLineIndent("return 1");
Indent(-1);
WriteLineIndent("return (value!!.raw - other.value!!.raw).toInt()");
Indent(-1);
WriteLineIndent("}");
// Generate enum class equals() method
WriteLine();
WriteLineIndent("override fun equals(other: Any?): Boolean");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if (other == null)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("if (!" + enum_name + "::class.java.isAssignableFrom(other.javaClass))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("val enm = other as " + enum_name + "? ?: return false");
WriteLine();
WriteLineIndent("if (enm.value == null)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("if (value!!.raw != enm.value!!.raw)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("}");
// Generate enum class hashCode() method
WriteLine();
WriteLineIndent("override fun hashCode(): Int");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var hash = 17");
WriteLineIndent("hash = hash * 31 + if (value != null) value!!.hashCode() else 0");
WriteLineIndent("return hash");
Indent(-1);
WriteLineIndent("}");
// Generate enum class toString() method
WriteLine();
WriteLineIndent("override fun toString(): String");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return if (value != null) value!!.toString() else \"<unknown>\"");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
// Generate enum class footer
GenerateFooter();
// Close the output file
Close();
}
void GeneratorKotlin::GenerateEnumJson(const std::shared_ptr<Package>& p, const std::shared_ptr<EnumType>& e)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
std::string enum_name = *e->name;
std::string adapter_name = *e->name + "Json";
// Open the output file
CppCommon::Path output = path / (adapter_name + ".kt");
Open(output);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate custom import
WriteLine();
WriteLineIndent("import com.google.gson.*");
std::string enum_type = (e->base && !e->base->empty()) ? *e->base : "int32";
// Generate JSON adapter body
WriteLine();
WriteLineIndent("class " + adapter_name + " : JsonSerializer<" + enum_name + ">, JsonDeserializer<" + enum_name + ">");
WriteLineIndent("{");
Indent(1);
// Generate JSON adapter serialize() method
WriteLineIndent("override fun serialize(src: " + enum_name + ", typeOfSrc: Type, context: JsonSerializationContext): JsonElement");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return JsonPrimitive(src.raw" + ConvertEnumFrom(enum_type) + ")");
Indent(-1);
WriteLineIndent("}");
// Generate JSON adapter deserialize() method
WriteLine();
WriteLineIndent("@Throws(JsonParseException::class)");
WriteLineIndent("override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext): " + enum_name);
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return " + enum_name + "(json.asJsonPrimitive." + ConvertEnumGet(enum_type) + ")");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
// Generate JSON adapter footer
GenerateFooter();
// Close the output file
Close();
}
void GeneratorKotlin::GenerateFlags(const std::shared_ptr<Package>& p, const std::shared_ptr<FlagsType>& f, const CppCommon::Path& path)
{
std::string flags_name = *f->name + "Enum";
// Open the output file
CppCommon::Path output = path / (flags_name + ".kt");
Open(output);
// Generate flags header
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(p);
std::string flags_type = (f->base && !f->base->empty()) ? *f->base : "int32";
std::string flags_base_type = ConvertEnumType(flags_type);
std::string flags_mapping_type = ConvertEnumBase(flags_type);
std::string flags_int = ConvertEnumFlags(flags_type);
std::string flags_to = ConvertEnumTo(flags_type);
// Generate flags body
WriteLine();
WriteLineIndent("@Suppress(\"EnumEntryName\", \"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\")");
WriteLineIndent("enum class " + flags_name);
WriteLineIndent("{");
Indent(1);
if (f->body)
{
bool first = true;
for (const auto& value : f->body->values)
{
WriteIndent(std::string(first ? "" : ", ") + *value->name + "(");
if (value->value)
{
if (value->value->constant && !value->value->constant->empty())
Write(ConvertEnumConstant(flags_type, flags_type, *value->value->constant, true));
else if (value->value->reference && !value->value->reference->empty())
Write(ConvertEnumConstant(flags_type, "", *value->value->reference, true));
}
WriteLine(")");
first = false;
}
WriteLineIndent(";");
WriteLine();
}
else
WriteIndent("unknown(0);");
// Generate flags class value
WriteLineIndent("var raw: " + flags_mapping_type + " = " + ConvertEnumConstant(flags_type, flags_type, "0", false));
Indent(1);
WriteLineIndent("private set");
Indent(-1);
// Generate flags class constructors
WriteLine();
if ((flags_type == "char") || (flags_type == "wchar"))
WriteLineIndent("constructor(value: Char) { this.raw = value" + flags_to + " }");
if (IsUnsignedType(flags_type))
{
WriteLineIndent("constructor(value: UByte) { this.raw = value" + flags_to + " }");
WriteLineIndent("constructor(value: UShort) { this.raw = value" + flags_to + " }");
WriteLineIndent("constructor(value: UInt) { this.raw = value" + flags_to + " }");
WriteLineIndent("constructor(value: ULong) { this.raw = value" + flags_to + " }");
}
else
{
WriteLineIndent("constructor(value: Byte) { this.raw = value" + flags_to + " }");
WriteLineIndent("constructor(value: Short) { this.raw = value" + flags_to + " }");
WriteLineIndent("constructor(value: Int) { this.raw = value" + flags_to + " }");
WriteLineIndent("constructor(value: Long) { this.raw = value" + flags_to + " }");
}
WriteLineIndent("constructor(value: " + flags_name + ") { this.raw = value.raw }");
// Generate flags hasFlags() methods
WriteLine();
WriteLineIndent("fun hasFlags(flags: " + flags_base_type + "): Boolean = ((raw" + flags_int + " and flags" + flags_int + ") != " + ConvertEnumConstant(flags_type, flags_type, "0", false) + ") && ((raw" + flags_int + " and flags" + flags_int + ") == flags" + flags_int + ")");
WriteLineIndent("fun hasFlags(flags: " + flags_name + "): Boolean = hasFlags(flags.raw)");
// Generate flags getAllSet(), getNoneSet(), getCurrentSet() methods
WriteLine();
WriteLineIndent("val allSet: EnumSet<" + flags_name + "> get() = EnumSet.allOf(" + flags_name + "::class.java)");
WriteLineIndent("val noneSet: EnumSet<" + flags_name + "> get() = EnumSet.noneOf(" + flags_name + "::class.java)");
WriteLineIndent("val currentSet: EnumSet<" + flags_name + "> get()");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val result = EnumSet.noneOf(" + flags_name + "::class.java)");
if (f->body)
{
for (const auto& value : f->body->values)
{
WriteLineIndent("if ((raw" + flags_int + " and " + *value->name + ".raw" + flags_int + ") != " + ConvertEnumConstant(flags_type, flags_type, "0", false) + ")");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("result.add(" + *value->name + ")");
Indent(-1);
WriteLineIndent("}");
}
}
WriteLineIndent("return result");
Indent(-1);
WriteLineIndent("}");
// Generate enum toString() method
WriteLine();
WriteLineIndent("override fun toString(): String");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val sb = StringBuilder()");
if (f->body && !f->body->values.empty())
{
WriteLineIndent("var first = true");
for (const auto& value : f->body->values)
{
WriteLineIndent("if (hasFlags(" + *value->name + "))");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("sb.append(if (first) \"\" else \"|\").append(\"" + *value->name + "\")");
WriteLineIndent("@Suppress(\"UNUSED_VALUE\")");
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
}
}
WriteLineIndent("return sb.toString()");
Indent(-1);
WriteLineIndent("}");
// Generate flags mapping
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("private val mapping = HashMap<" + flags_mapping_type + ", " + flags_name + ">()");
WriteLine();
WriteLineIndent("init");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("for (value in " + flags_name + ".values())");
Indent(1);
WriteLineIndent("mapping[value.raw] = value");
Indent(-1);
Indent(-1);
WriteLineIndent("}");
// Generate flags mapValue() method
WriteLine();
WriteLineIndent("fun mapValue(value: " + flags_mapping_type + "): " + flags_name + "?" +" { return mapping[value] }");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
// Generate flags footer
GenerateFooter();
// Close the output file
Close();
// Generate flags wrapper class
GenerateFlagsClass(p, f, path);
// Generate flags JSON adapter
if (JSON())
GenerateFlagsJson(p, f);
// Generate flags field model
GenerateFBEFieldModelEnumFlags(*p->name, *f->name, flags_type);
// Generate flags final model
if (Final())
GenerateFBEFinalModelEnumFlags(*p->name, *f->name, flags_type);
}
void GeneratorKotlin::GenerateFlagsClass(const std::shared_ptr<Package>& p, const std::shared_ptr<FlagsType>& f, const CppCommon::Path& path)
{
std::string flags_name = *f->name;
std::string flags_type_name = *f->name + "Enum";
// Open the output file
CppCommon::Path output = path / (flags_name + ".kt");
Open(output);
// Generate flags class header
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(p);
std::string flags_type = (f->base && !f->base->empty()) ? *f->base : "int32";
std::string flags_base_type = ConvertEnumType(flags_type);
std::string flags_int = ConvertEnumFlags(flags_type);
std::string flags_to = ConvertEnumTo(flags_type);
// Generate flags class body
WriteLine();
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\")");
WriteLineIndent("class " + flags_name + " : Comparable<" + flags_name + ">");
WriteLineIndent("{");
Indent(1);
if (f->body)
{
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
if (!f->body->values.empty())
{
for (const auto& value : f->body->values)
WriteLineIndent("val " + *value->name + " = " + flags_name + "(" + flags_type_name + "." + *value->name + ")");
WriteLine();
}
// Generate flags class fromSet() method
if (f->body->values.empty())
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun fromSet(set: EnumSet<" + flags_type_name + ">): " + flags_name);
WriteLineIndent("{");
Indent(1);
WriteLineIndent("@Suppress(\"CanBeVal\")");
WriteLineIndent("var result = " + ConvertEnumConstant(flags_type, flags_type, "0", false));
if (f->body)
{
for (const auto& value : f->body->values)
{
WriteLineIndent("if (set.contains(" + *value->name + ".value!!))");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("result = result" + flags_int + " or " + *value->name + ".raw" + flags_int);
Indent(-1);
WriteLineIndent("}");
}
}
WriteLineIndent("return " + flags_name + "(result" + flags_to + ")");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
WriteLine();
}
// Generate flags class value
WriteLineIndent("var value: " + flags_type_name + "?" + " = " + flags_type_name + ".values()[0]");
Indent(1);
WriteLineIndent("private set");
Indent(-1);
WriteLine();
// Generate flags raw value
WriteLineIndent("var raw: " + flags_base_type + " = value!!.raw");
Indent(1);
WriteLineIndent("private set");
Indent(-1);
WriteLine();
// Generate flags class constructors
WriteLineIndent("constructor()");
WriteLineIndent("constructor(value: " + flags_base_type + ") { setEnum(value) }");
WriteLineIndent("constructor(value: " + flags_type_name + ") { setEnum(value) }");
WriteLineIndent("constructor(value: EnumSet<" + flags_type_name + ">) { setEnum(value) }");
WriteLineIndent("constructor(value: " + flags_name + ") { setEnum(value) }");
WriteLine();
// Generate flags class setDefault() method
WriteLineIndent("fun setDefault() { setEnum(0" + flags_to + ") }");
WriteLine();
// Generate flags class setEnum() methods
WriteLineIndent("fun setEnum(value: " + flags_base_type + ") { this.raw = value; this.value = " + flags_type_name + ".mapValue(value) }");
WriteLineIndent("fun setEnum(value: " + flags_type_name + ") { this.value = value; this.raw = value.raw; }");
WriteLineIndent("fun setEnum(value: EnumSet<" + flags_type_name + ">) { setEnum(" + flags_name + ".fromSet(value)) }");
WriteLineIndent("fun setEnum(value: " + flags_name + ") { this.value = value.value; this.raw = value.raw }");
// Generate flags class hasFlags() methods
WriteLine();
WriteLineIndent("fun hasFlags(flags: " + flags_base_type + "): Boolean = ((raw" + flags_int + " and flags" + flags_int + ") != " + ConvertEnumConstant(flags_type, flags_type, "0", false) + ") && ((raw" + flags_int + " and flags" + flags_int + ") == flags" + flags_int + ")");
WriteLineIndent("fun hasFlags(flags: " + flags_type_name + "): Boolean = hasFlags(flags.raw)");
WriteLineIndent("fun hasFlags(flags: " + flags_name + "): Boolean = hasFlags(flags.raw)");
// Generate flags class setFlags() methods
WriteLine();
WriteLineIndent("fun setFlags(flags: " + flags_base_type + "): " + flags_name + " { setEnum((raw" + flags_int + " or flags" + flags_int + ")" + flags_to + "); return this }");
WriteLineIndent("fun setFlags(flags: " + flags_type_name + "): " + flags_name + " { setFlags(flags.raw); return this }");
WriteLineIndent("fun setFlags(flags: " + flags_name + "): " + flags_name + " { setFlags(flags.raw); return this }");
// Generate flags class removeFlags() methods
WriteLine();
WriteLineIndent("fun removeFlags(flags: " + flags_base_type + "): " + flags_name + " { setEnum((raw" + flags_int + " and flags" + flags_int + ".inv())" + flags_to + "); return this }");
WriteLineIndent("fun removeFlags(flags: " + flags_type_name + "): " + flags_name + " { removeFlags(flags.raw); return this }");
WriteLineIndent("fun removeFlags(flags: " + flags_name + "): " + flags_name + " { removeFlags(flags.raw); return this }");
// Generate flags class getAllSet(), getNoneSet() and getCurrentSet() methods
WriteLine();
WriteLineIndent("val allSet: EnumSet<" + flags_type_name + "> get() = value!!.allSet");
WriteLineIndent("val noneSet: EnumSet<" + flags_type_name + "> get() = value!!.noneSet");
WriteLineIndent("val currentSet: EnumSet<" + flags_type_name + "> get() = value!!.currentSet");
// Generate flags class compareTo() method
WriteLine();
WriteLineIndent("override fun compareTo(other: " + flags_name + "): Int");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return (raw - other.raw).toInt()");
Indent(-1);
WriteLineIndent("}");
// Generate flags class equals() method
WriteLine();
WriteLineIndent("override fun equals(other: Any?): Boolean");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if (other == null)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("if (!" + flags_name + "::class.java.isAssignableFrom(other.javaClass))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("val flg = other as " + flags_name + "? ?: return false");
WriteLine();
WriteLineIndent("if (raw != flg.raw)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("}");
// Generate flags class hashCode() method
WriteLine();
WriteLineIndent("override fun hashCode(): Int");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var hash = " + ConvertEnumConstant(flags_type, flags_type, "17", false));
WriteLineIndent("hash = hash * " + ConvertEnumConstant(flags_type, flags_type, "31", false) + " + raw" + flags_int);
WriteLineIndent("return hash.toInt()");
Indent(-1);
WriteLineIndent("}");
// Generate flags class toString() method
WriteLine();
WriteLineIndent("override fun toString(): String");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val sb = StringBuilder()");
if (f->body && !f->body->values.empty())
{
WriteLineIndent("var first = true");
for (const auto& value : f->body->values)
{
WriteLineIndent("if (hasFlags(" + *value->name + ".raw))");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("sb.append(if (first) \"\" else \"|\").append(\"" + *value->name + "\")");
WriteLineIndent("@Suppress(\"UNUSED_VALUE\")");
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
}
}
WriteLineIndent("return sb.toString()");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
// Generate flags class footer
GenerateFooter();
// Close the output file
Close();
}
void GeneratorKotlin::GenerateFlagsJson(const std::shared_ptr<Package>& p, const std::shared_ptr<FlagsType>& f)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
std::string flags_name = *f->name;
std::string adapter_name = *f->name + "Json";
// Open the output file
CppCommon::Path output = path / (adapter_name + ".kt");
Open(output);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate custom import
WriteLine();
WriteLineIndent("import com.google.gson.*");
std::string flags_type = (f->base && !f->base->empty()) ? *f->base : "int32";
// Generate JSON adapter body
WriteLine();
WriteLineIndent("class " + adapter_name + " : JsonSerializer<" + flags_name + ">, JsonDeserializer<" + flags_name + ">");
WriteLineIndent("{");
Indent(1);
// Generate JSON adapter serialize() method
WriteLine();
WriteLineIndent("@Override");
WriteLineIndent("override fun serialize(src: " + flags_name + ", typeOfSrc: Type, context: JsonSerializationContext): JsonElement");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return JsonPrimitive(src.raw" + ConvertEnumFrom(flags_type) + ")");
Indent(-1);
WriteLineIndent("}");
// Generate JSON adapter deserialize() method
WriteLine();
WriteLineIndent("@Throws(JsonParseException::class)");
WriteLineIndent("override fun deserialize(json: JsonElement, type: Type, context: JsonDeserializationContext):" + flags_name);
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return " + flags_name + "(json.asJsonPrimitive." + ConvertEnumGet(flags_type) + ")");
Indent(-1);
WriteLineIndent("}");
Indent(-1);
WriteLineIndent("}");
// Generate JSON adapter footer
GenerateFooter();
// Close the output file
Close();
}
void GeneratorKotlin::GenerateStruct(const std::shared_ptr<Package>& p, const std::shared_ptr<StructType>& s, const CppCommon::Path& path)
{
bool first;
// Open the output file
CppCommon::Path output = path / (*s->name + ".kt");
Open(output);
// Generate struct header
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(p);
// Generate struct begin
WriteLine();
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\")");
WriteIndent("open class " + *s->name);
if (s->base && !s->base->empty())
Write(" : " + ConvertTypeName(*s->base, false));
else
Write(" : Comparable<Any?>");
WriteLine();
WriteLineIndent("{");
Indent(1);
// Generate struct body
if (s->body && !s->body->fields.empty())
{
for (const auto& field : s->body->fields)
WriteLineIndent("var " + *field->name + ": " + ConvertTypeName(*field, false) + " = " + ConvertDefault(*field));
WriteLine();
}
// Generate struct default constructor
WriteLineIndent("constructor()");
// Generate struct initialization constructor
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
first = true;
WriteLine();
WriteIndent("constructor(");
if (s->base && !s->base->empty())
{
Write("parent: " + ConvertTypeName(*s->base, false));
first = false;
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
Write(std::string(first ? "" : ", ") + *field->name + ": " + ConvertTypeName(*field, false));
first = false;
}
}
Write(")");
if (s->base && !s->base->empty())
WriteLine(": super(parent)");
else
WriteLine();
WriteLineIndent("{");
Indent(1);
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent("this." + *field->name + " = " + *field->name);
Indent(-1);
WriteLineIndent("}");
}
// Generate struct copy constructor
WriteLine();
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteIndent("constructor(other: " + *s->name + ")");
if (s->base && !s->base->empty())
WriteLine(": super(other)");
else
WriteLine();
WriteLineIndent("{");
Indent(1);
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent("this." + *field->name + " = other." + *field->name);
Indent(-1);
WriteLineIndent("}");
// Generate struct clone() method
WriteLine();
if (s->base && !s->base->empty())
WriteLineIndent("override fun clone(): " + *s->name);
else
WriteLineIndent("open fun clone(): " + *s->name);
WriteLineIndent("{");
Indent(1);
WriteLineIndent("// Serialize the struct to the FBE stream");
WriteLineIndent("val writer = " + *p->name + ".fbe." + *s->name + "Model()");
WriteLineIndent("writer.serialize(this)");
WriteLine();
WriteLineIndent("// Deserialize the struct from the FBE stream");
WriteLineIndent("val reader = " + *p->name + ".fbe." + *s->name + "Model()");
WriteLineIndent("reader.attach(writer.buffer)");
WriteLineIndent("return reader.deserialize()");
Indent(-1);
WriteLineIndent("}");
// Generate struct compareTo() method
WriteLine();
WriteLineIndent("override fun compareTo(other: Any?): Int");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if (other == null)");
Indent(1);
WriteLineIndent("return -1");
Indent(-1);
WriteLine();
WriteLineIndent("if (!" + *s->name + "::class.java.isAssignableFrom(other.javaClass))");
Indent(1);
WriteLineIndent("return -1");
Indent(-1);
WriteLine();
WriteLineIndent("@Suppress(\"UNUSED_VARIABLE\")");
WriteLineIndent("val obj = other as " + *s->name + "? ?: return -1");
WriteLine();
WriteLineIndent("@Suppress(\"VARIABLE_WITH_REDUNDANT_INITIALIZER\", \"CanBeVal\", \"UnnecessaryVariable\")");
WriteLineIndent("var result = 0");
if (s->base && !s->base->empty())
{
WriteLineIndent("result = super.compareTo(obj)");
WriteLineIndent("if (result != 0)");
Indent(1);
WriteLineIndent("return result");
Indent(-1);
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
if (field->keys)
{
WriteLineIndent("result = " + *field->name + ".compareTo(obj." + *field->name + ")");
WriteLineIndent("if (result != 0)");
Indent(1);
WriteLineIndent("return result");
Indent(-1);
}
}
}
WriteLineIndent("return result");
Indent(-1);
WriteLineIndent("}");
// Generate struct equals() method
WriteLine();
WriteLineIndent("override fun equals(other: Any?): Boolean");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if (other == null)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("if (!" + *s->name + "::class.java.isAssignableFrom(other.javaClass))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("@Suppress(\"UNUSED_VARIABLE\")");
WriteLineIndent("val obj = other as " + *s->name + "? ?: return false");
WriteLine();
if (s->base && !s->base->empty())
{
WriteLineIndent("if (!super.equals(obj))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
if (field->keys)
{
if (IsPrimitiveType(*field->type, field->optional))
WriteLineIndent("if (" + *field->name + " != obj." + *field->name + ")");
else
WriteLineIndent("if (!" + *field->name + ".equals(obj." + *field->name + "))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
}
}
}
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("}");
// Generate struct hashCode() method
WriteLine();
WriteLineIndent("override fun hashCode(): Int");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("@Suppress(\"CanBeVal\", \"UnnecessaryVariable\")");
WriteLineIndent("var hash = 17");
if (s->base && !s->base->empty())
WriteLineIndent("hash = hash * 31 + super.hashCode()");
if (s->body)
{
for (const auto& field : s->body->fields)
if (field->keys)
WriteLineIndent("hash = hash * 31 + " + *field->name + ".hashCode()");
}
WriteLineIndent("return hash");
Indent(-1);
WriteLineIndent("}");
// Generate struct toString() method
WriteLine();
WriteLineIndent("override fun toString(): String");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val sb = StringBuilder()");
WriteLineIndent("sb.append(\"" + *s->name + "(\")");
first = true;
if (s->base && !s->base->empty())
{
WriteLineIndent("sb.append(super.toString())");
first = false;
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
if (field->array || field->vector)
{
WriteLineIndent("@Suppress(\"ConstantConditionIf\")");
WriteLineIndent("if (true)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var first = true");
WriteLineIndent("sb.append(\"" + std::string(first ? "" : ",") + *field->name + "=[\").append(" + *field->name + ".size" + ").append(\"][\")");
WriteLineIndent("for (item in " + *field->name + ")");
WriteLineIndent("{");
Indent(1);
WriteLineIndent(ConvertOutputStreamValue(*field->type, "item", field->optional, true, false));
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
WriteLineIndent("sb.append(\"]\")");
Indent(-1);
WriteLineIndent("}");
}
else if (field->list)
{
WriteLineIndent("@Suppress(\"ConstantConditionIf\")");
WriteLineIndent("if (true)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var first = true");
WriteLineIndent("sb.append(\"" + std::string(first ? "" : ",") + *field->name + "=[\").append(" + *field->name + ".size" + ").append(\"]<\")");
WriteLineIndent("for (item in " + *field->name + ")");
WriteLineIndent("{");
Indent(1);
WriteLineIndent(ConvertOutputStreamValue(*field->type, "item", field->optional, true, false));
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
WriteLineIndent("sb.append(\">\")");
Indent(-1);
WriteLineIndent("}");
}
else if (field->set)
{
WriteLineIndent("@Suppress(\"ConstantConditionIf\")");
WriteLineIndent("if (true)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var first = true");
WriteLineIndent("sb.append(\"" + std::string(first ? "" : ",") + *field->name + "=[\").append(" + *field->name + ".size" + ").append(\"]{\")");
WriteLineIndent("for (item in " + *field->name + ")");
WriteLineIndent("{");
Indent(1);
WriteLineIndent(ConvertOutputStreamValue(*field->type, "item", field->optional, true, false));
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
WriteLineIndent("sb.append(\"}\")");
Indent(-1);
WriteLineIndent("}");
}
else if (field->map)
{
WriteLineIndent("@Suppress(\"ConstantConditionIf\")");
WriteLineIndent("if (true)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var first = true");
WriteLineIndent("sb.append(\"" + std::string(first ? "" : ",") + *field->name + "=[\").append(" + *field->name + ".size" + ").append(\"]<{\")");
WriteLineIndent("for (item in " + *field->name + ".entries)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent(ConvertOutputStreamValue(*field->key, "item.key", false, true, false));
WriteLineIndent("sb.append(\"->\")");
WriteLineIndent(ConvertOutputStreamValue(*field->type, "item.value", field->optional, false, true));
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
WriteLineIndent("sb.append(\"}>\")");
Indent(-1);
WriteLineIndent("}");
}
else if (field->hash)
{
WriteLineIndent("@Suppress(\"ConstantConditionIf\")");
WriteLineIndent("if (true)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var first = true");
WriteLineIndent("sb.append(\"" + std::string(first ? "" : ",") + *field->name + "=[\").append(" + *field->name + ".size" + ").append(\"][{\")");
WriteLineIndent("for (item in " + *field->name + ".entries)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent(ConvertOutputStreamValue(*field->key, "item.key", false, true, false));
WriteLineIndent("sb.append(\"->\")");
WriteLineIndent(ConvertOutputStreamValue(*field->type, "item.value", field->optional, false, true));
WriteLineIndent("first = false");
Indent(-1);
WriteLineIndent("}");
WriteLineIndent("sb.append(\"}]\")");
Indent(-1);
WriteLineIndent("}");
}
else
WriteLineIndent("sb.append(\"" + std::string(first ? "" : ",") + *field->name + "=\"); " + ConvertOutputStreamValue(*field->type, *field->name, field->optional, false, true));
first = false;
}
}
WriteLineIndent("sb.append(\")\")");
WriteLineIndent("return sb.toString()");
Indent(-1);
WriteLineIndent("}");
// Generate struct JSON methods
if (JSON())
{
WriteLine();
WriteIndent(std::string((s->base && !s->base->empty()) ? "override" : "open") + " fun toJson(): String = " + *p->name + ".fbe.Json.engine.toJson(this)");
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("fun fromJson(json: String): " + *s->name + " = " + *p->name + ".fbe.Json.engine.fromJson(json, " + *s->name + "::class.java)");
Indent(-1);
WriteLineIndent("}");
}
// Generate struct end
Indent(-1);
WriteLineIndent("}");
// Generate struct footer
GenerateFooter();
// Close the output file
Close();
// Generate struct field models
GenerateStructFieldModel(p, s);
GenerateStructModel(p, s);
// Generate struct final models
if (Final())
{
GenerateStructFinalModel(p, s);
GenerateStructModelFinal(p, s);
}
}
void GeneratorKotlin::GenerateStructFieldModel(const std::shared_ptr<Package>& p, const std::shared_ptr<StructType>& s)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FieldModel" + *s->name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate struct field model begin
WriteLine();
WriteLineIndent("// Fast Binary Encoding " + *s->name + " field model");
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\", \"ReplaceGetOrSet\")");
WriteLineIndent("class FieldModel" + *s->name + "(buffer: Buffer, offset: Long) : FieldModel(buffer, offset)");
WriteLineIndent("{");
Indent(1);
// Generate struct field model accessors
std::string prev_offset("4");
std::string prev_size("4");
if (s->base && !s->base->empty())
{
WriteLineIndent("val parent: " + ConvertBaseFieldName(*s->base, false) + " = " + ConvertBaseFieldName(*s->base, false) + "(buffer, " + prev_offset + " + " + prev_size + ")");
prev_offset = "parent.fbeOffset";
prev_size = "parent.fbeBody - 4 - 4";
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
WriteLineIndent("val " + *field->name + ": " + ConvertTypeFieldDeclaration(*field, false) + " = " + ConvertTypeFieldInitialization(*field, prev_offset + " + " + prev_size, false));
prev_offset = *field->name + ".fbeOffset";
prev_size = *field->name + ".fbeSize";
}
}
// Generate struct field model FBE properties
WriteLine();
WriteLineIndent("// Field size");
WriteLineIndent("override val fbeSize: Long = 4");
WriteLine();
WriteLineIndent("// Field body size");
WriteLineIndent("val fbeBody: Long = (4 + 4");
Indent(1);
if (s->base && !s->base->empty())
WriteLineIndent("+ parent.fbeBody - 4 - 4");
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent("+ " + *field->name + ".fbeSize");
WriteLineIndent(")");
Indent(-1);
WriteLine();
WriteLineIndent("// Field extra size");
WriteLineIndent("override val fbeExtra: Long get()");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructOffset = readUInt32(fbeOffset).toLong()");
WriteLineIndent("if ((fbeStructOffset == 0L) || ((_buffer.offset + fbeStructOffset + 4) > _buffer.size))");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("_buffer.shift(fbeStructOffset)");
WriteLine();
WriteLineIndent("val fbeResult = (fbeBody");
Indent(1);
if (s->base && !s->base->empty())
WriteLineIndent("+ parent.fbeExtra");
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent("+ " + *field->name + ".fbeExtra");
WriteLineIndent(")");
Indent(-1);
WriteLine();
WriteLineIndent("_buffer.unshift(fbeStructOffset)");
WriteLine();
WriteLineIndent("return fbeResult");
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("// Field type");
WriteLineIndent("var fbeType: Long = fbeTypeConst");
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
if (s->base && !s->base->empty() && (s->type == 0))
WriteLineIndent("const val fbeTypeConst: Long = " + ConvertBaseFieldName(*s->base, false) + ".fbeTypeConst");
else
WriteLineIndent("const val fbeTypeConst: Long = " + std::to_string(s->type));
Indent(-1);
WriteLineIndent("}");
// Generate struct field model verify() methods
WriteLine();
WriteLineIndent("// Check if the struct value is valid");
WriteLineIndent("fun verify(fbeVerifyType: Boolean = true): Boolean");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)");
Indent(1);
WriteLineIndent("return true");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructOffset = readUInt32(fbeOffset).toLong()");
WriteLineIndent("if ((fbeStructOffset == 0L) || ((_buffer.offset + fbeStructOffset + 4 + 4) > _buffer.size))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructSize = readUInt32(fbeStructOffset).toLong()");
WriteLineIndent("if (fbeStructSize < (4 + 4))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructType = readUInt32(fbeStructOffset + 4).toLong()");
WriteLineIndent("if (fbeVerifyType && (fbeStructType != fbeType))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("_buffer.shift(fbeStructOffset)");
WriteLineIndent("val fbeResult = verifyFields(fbeStructSize)");
WriteLineIndent("_buffer.unshift(fbeStructOffset)");
WriteLineIndent("return fbeResult");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model verifyFields() method
WriteLine();
WriteLineIndent("// Check if the struct fields are valid");
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun verifyFields(fbeStructSize: Long): Boolean");
WriteLineIndent("{");
Indent(1);
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
WriteLineIndent("var fbeCurrentSize = 4L + 4L");
if (s->base && !s->base->empty())
{
WriteLine();
WriteLineIndent("if ((fbeCurrentSize + parent.fbeBody - 4 - 4) > fbeStructSize)");
Indent(1);
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("if (!parent.verifyFields(fbeStructSize))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("fbeCurrentSize += parent.fbeBody - 4 - 4");
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
WriteLine();
WriteLineIndent("if ((fbeCurrentSize + " + *field->name + ".fbeSize) > fbeStructSize)");
Indent(1);
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("if (!" + *field->name + ".verify())");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("fbeCurrentSize += " + *field->name + ".fbeSize");
}
}
WriteLine();
}
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model getBegin() method
WriteLine();
WriteLineIndent("// Get the struct value (begin phase)");
WriteLineIndent("fun getBegin(): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructOffset = readUInt32(fbeOffset).toLong()");
WriteLineIndent("assert((fbeStructOffset > 0) && ((_buffer.offset + fbeStructOffset + 4 + 4) <= _buffer.size)) { \"Model is broken!\" }");
WriteLineIndent("if ((fbeStructOffset == 0L) || ((_buffer.offset + fbeStructOffset + 4 + 4) > _buffer.size))");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructSize = readUInt32(fbeStructOffset).toLong()");
WriteLineIndent("assert(fbeStructSize >= (4 + 4)) { \"Model is broken!\" }");
WriteLineIndent("if (fbeStructSize < (4 + 4))");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("_buffer.shift(fbeStructOffset)");
WriteLineIndent("return fbeStructOffset");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model getEnd() method
WriteLine();
WriteLineIndent("// Get the struct value (end phase)");
WriteLineIndent("fun getEnd(fbeBegin: Long)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("_buffer.unshift(fbeBegin)");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model get() methods
WriteLine();
WriteLineIndent("// Get the struct value");
WriteLineIndent("fun get(fbeValue: " + *s->name + " = " + *s->name + "()): " + *s->name);
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val fbeBegin = getBegin()");
WriteLineIndent("if (fbeBegin == 0L)");
Indent(1);
WriteLineIndent("return fbeValue");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructSize = readUInt32(0).toLong()");
WriteLineIndent("getFields(fbeValue, fbeStructSize)");
WriteLineIndent("getEnd(fbeBegin)");
WriteLineIndent("return fbeValue");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model getFields() method
WriteLine();
WriteLineIndent("// Get the struct fields values");
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun getFields(fbeValue: " + *s->name + ", fbeStructSize: Long)");
WriteLineIndent("{");
Indent(1);
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
WriteLineIndent("var fbeCurrentSize = 4L + 4L");
if (s->base && !s->base->empty())
{
WriteLine();
WriteLineIndent("if ((fbeCurrentSize + parent.fbeBody - 4 - 4) <= fbeStructSize)");
Indent(1);
WriteLineIndent("parent.getFields(fbeValue, fbeStructSize)");
Indent(-1);
WriteLineIndent("fbeCurrentSize += parent.fbeBody - 4 - 4");
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
WriteLine();
WriteLineIndent("if ((fbeCurrentSize + " + *field->name + ".fbeSize) <= fbeStructSize)");
Indent(1);
if (field->array || field->vector || field->list || field->set || field->map || field->hash)
WriteLineIndent(*field->name + ".get(fbeValue." + *field->name + ")");
else
WriteLineIndent("fbeValue." + *field->name + " = " + *field->name + ".get(" + (field->value ? ConvertConstant(*field->type, *field->value, field->optional) : "") + ")");
Indent(-1);
WriteLineIndent("else");
Indent(1);
if (field->vector || field->list || field->set || field->map || field->hash)
WriteLineIndent("fbeValue." + *field->name + ".clear()");
else
WriteLineIndent("fbeValue." + *field->name + " = " + ConvertDefault(*field));
Indent(-1);
WriteLineIndent("fbeCurrentSize += " + *field->name + ".fbeSize");
}
}
}
Indent(-1);
WriteLineIndent("}");
// Generate struct field model setBegin() method
WriteLine();
WriteLineIndent("// Set the struct value (begin phase)");
WriteLineIndent("fun setBegin(): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("assert((_buffer.offset + fbeOffset + fbeSize) <= _buffer.size) { \"Model is broken!\" }");
WriteLineIndent("if ((_buffer.offset + fbeOffset + fbeSize) > _buffer.size)");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructSize = fbeBody");
WriteLineIndent("val fbeStructOffset = _buffer.allocate(fbeStructSize) - _buffer.offset");
WriteLineIndent("assert((fbeStructOffset > 0) && ((_buffer.offset + fbeStructOffset + fbeStructSize) <= _buffer.size)) { \"Model is broken!\" }");
WriteLineIndent("if ((fbeStructOffset <= 0) || ((_buffer.offset + fbeStructOffset + fbeStructSize) > _buffer.size))");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("write(fbeOffset, fbeStructOffset.toUInt())");
WriteLineIndent("write(fbeStructOffset, fbeStructSize.toUInt())");
WriteLineIndent("write(fbeStructOffset + 4, fbeType.toUInt())");
WriteLine();
WriteLineIndent("_buffer.shift(fbeStructOffset)");
WriteLineIndent("return fbeStructOffset");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model setEnd() method
WriteLine();
WriteLineIndent("// Set the struct value (end phase)");
WriteLineIndent("fun setEnd(fbeBegin: Long)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("_buffer.unshift(fbeBegin)");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model set() method
WriteLine();
WriteLineIndent("// Set the struct value");
WriteLineIndent("fun set(fbeValue: " + *s->name + ")");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val fbeBegin = setBegin()");
WriteLineIndent("if (fbeBegin == 0L)");
Indent(1);
WriteLineIndent("return");
Indent(-1);
WriteLine();
WriteLineIndent("setFields(fbeValue)");
WriteLineIndent("setEnd(fbeBegin)");
Indent(-1);
WriteLineIndent("}");
// Generate struct field model setFields() method
WriteLine();
WriteLineIndent("// Set the struct fields values");
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun setFields(fbeValue: " + *s->name + ")");
WriteLineIndent("{");
Indent(1);
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
if (s->base && !s->base->empty())
WriteLineIndent("parent.setFields(fbeValue)");
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent(*field->name + ".set(fbeValue." + *field->name + ")");
}
Indent(-1);
WriteLineIndent("}");
// Generate struct field model end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateStructModel(const std::shared_ptr<Package>& p, const std::shared_ptr<StructType>& s)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / (*s->name + "Model.kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate struct model begin
WriteLine();
WriteLineIndent("// Fast Binary Encoding " + *s->name + " model");
WriteLineIndent("class " + *s->name + "Model : Model");
WriteLineIndent("{");
Indent(1);
// Generate struct model accessor
WriteLineIndent("val model: FieldModel" + *s->name);
// Generate struct model constructors
WriteLine();
WriteLineIndent("constructor() { model = FieldModel" + *s->name + "(buffer, 4) }");
WriteLineIndent("constructor(buffer: Buffer) : super(buffer) { model = FieldModel" + *s->name + "(buffer, 4) }");
// Generate struct model FBE properties
WriteLine();
WriteLineIndent("// Model size");
WriteLineIndent("fun fbeSize(): Long = model.fbeSize + model.fbeExtra");
WriteLineIndent("// Model type");
WriteLineIndent("var fbeType: Long = fbeTypeConst");
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("const val fbeTypeConst: Long = FieldModel" + *s->name + ".fbeTypeConst");
Indent(-1);
WriteLineIndent("}");
// Generate struct model verify() method
WriteLine();
WriteLineIndent("// Check if the struct value is valid");
WriteLineIndent("fun verify(): Boolean");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if ((buffer.offset + model.fbeOffset - 4) > buffer.size)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeFullSize = readUInt32(model.fbeOffset - 4).toLong()");
WriteLineIndent("if (fbeFullSize < model.fbeSize)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("return model.verify()");
Indent(-1);
WriteLineIndent("}");
// Generate struct model createBegin() method
WriteLine();
WriteLineIndent("// Create a new model (begin phase)");
WriteLineIndent("fun createBegin(): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("return buffer.allocate(4 + model.fbeSize)");
Indent(-1);
WriteLineIndent("}");
// Generate struct model createEnd() method
WriteLine();
WriteLineIndent("// Create a new model (end phase)");
WriteLineIndent("fun createEnd(fbeBegin: Long): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val fbeEnd = buffer.size");
WriteLineIndent("val fbeFullSize = fbeEnd - fbeBegin");
WriteLineIndent("write(model.fbeOffset - 4, fbeFullSize.toUInt())");
WriteLineIndent("return fbeFullSize");
Indent(-1);
WriteLineIndent("}");
// Generate struct model serialize() method
WriteLine();
WriteLineIndent("// Serialize the struct value");
WriteLineIndent("fun serialize(value: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val fbeBegin = createBegin()");
WriteLineIndent("model.set(value)");
WriteLineIndent("return createEnd(fbeBegin)");
Indent(-1);
WriteLineIndent("}");
// Generate struct model deserialize() methods
WriteLine();
WriteLineIndent("// Deserialize the struct value");
WriteLineIndent("fun deserialize(): " + *s->name + " { val value = " + *s->name + "(); deserialize(value); return value }");
WriteLineIndent("@Suppress(\"UNUSED_VALUE\")");
WriteLineIndent("fun deserialize(value: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var valueRef = value");
WriteLine();
WriteLineIndent("if ((buffer.offset + model.fbeOffset - 4) > buffer.size)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("valueRef = " + *s->name + "()");
WriteLineIndent("return 0");
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("val fbeFullSize = readUInt32(model.fbeOffset - 4).toLong()");
WriteLineIndent("assert(fbeFullSize >= model.fbeSize) { \"Model is broken!\" }");
WriteLineIndent("if (fbeFullSize < model.fbeSize)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("valueRef = " + *s->name + "()");
WriteLineIndent("return 0");
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("valueRef = model.get(valueRef)");
WriteLineIndent("return fbeFullSize");
Indent(-1);
WriteLineIndent("}");
// Generate struct model next() method
WriteLine();
WriteLineIndent("// Move to the next struct value");
WriteLineIndent("fun next(prev: Long)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("model.fbeShift(prev)");
Indent(-1);
WriteLineIndent("}");
// Generate struct model end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateStructFinalModel(const std::shared_ptr<Package>& p, const std::shared_ptr<StructType>& s)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / ("FinalModel" + *s->name + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate struct final model begin
WriteLine();
WriteLineIndent("// Fast Binary Encoding " + *s->name + " final model");
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"RemoveRedundantCallsOfConversionMethods\", \"ReplaceGetOrSet\")");
WriteLineIndent("class FinalModel" + *s->name + "(buffer: Buffer, offset: Long) : FinalModel(buffer, offset)");
WriteLineIndent("{");
Indent(1);
// Generate struct final model accessors
if (s->base && !s->base->empty())
WriteLineIndent("val parent: " + ConvertBaseFieldName(*s->base, true) + " = " + ConvertBaseFieldName(*s->base, true) + "(buffer, 0)");
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent("val " + *field->name + ": " + ConvertTypeFieldDeclaration(*field, true) + " = " + ConvertTypeFieldInitialization(*field, "0", true));
// Generate struct final model FBE properties
WriteLine();
WriteLineIndent("// Get the allocation size");
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun fbeAllocationSize(fbeValue: " + *s->name + "): Long = (0");
Indent(1);
if (s->base && !s->base->empty())
WriteLineIndent("+ parent.fbeAllocationSize(fbeValue)");
if (s->body)
for (const auto& field : s->body->fields)
WriteLineIndent("+ " + *field->name + ".fbeAllocationSize(fbeValue." + *field->name + ")");
WriteLineIndent(")");
Indent(-1);
WriteLine();
WriteLineIndent("// Field type");
WriteLineIndent("var fbeType: Long = fbeTypeConst");
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
if (s->base && !s->base->empty() && (s->type == 0))
WriteLineIndent("const val fbeTypeConst: Long = " + ConvertBaseFieldName(*s->base, true) + ".fbeTypeConst");
else
WriteLineIndent("const val fbeTypeConst: Long = " + std::to_string(s->type));
Indent(-1);
WriteLineIndent("}");
// Generate struct final model verify() methods
WriteLine();
WriteLineIndent("// Check if the struct value is valid");
WriteLineIndent("override fun verify(): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("_buffer.shift(fbeOffset)");
WriteLineIndent("val fbeResult = verifyFields()");
WriteLineIndent("_buffer.unshift(fbeOffset)");
WriteLineIndent("return fbeResult");
Indent(-1);
WriteLineIndent("}");
// Generate struct final model verifyFields() method
WriteLine();
WriteLineIndent("// Check if the struct fields are valid");
WriteLineIndent("fun verifyFields(): Long");
WriteLineIndent("{");
Indent(1);
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
WriteLineIndent("var fbeCurrentOffset = 0L");
WriteLineIndent("@Suppress(\"VARIABLE_WITH_REDUNDANT_INITIALIZER\")");
WriteLineIndent("var fbeFieldSize = 0L");
if (s->base && !s->base->empty())
{
WriteLine();
WriteLineIndent("parent.fbeOffset = fbeCurrentOffset");
WriteLineIndent("fbeFieldSize = parent.verifyFields()");
WriteLineIndent("if (fbeFieldSize == Long.MAX_VALUE)");
Indent(1);
WriteLineIndent("return Long.MAX_VALUE");
Indent(-1);
WriteLineIndent("fbeCurrentOffset += fbeFieldSize");
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
WriteLine();
WriteLineIndent(*field->name + ".fbeOffset = fbeCurrentOffset");
WriteLineIndent("fbeFieldSize = " + *field->name + ".verify()");
WriteLineIndent("if (fbeFieldSize == Long.MAX_VALUE)");
Indent(1);
WriteLineIndent("return Long.MAX_VALUE");
Indent(-1);
WriteLineIndent("fbeCurrentOffset += fbeFieldSize");
}
}
WriteLine();
WriteLineIndent("return fbeCurrentOffset");
}
else
WriteLineIndent("return 0L");
Indent(-1);
WriteLineIndent("}");
// Generate struct final model get() methods
WriteLine();
WriteLineIndent("// Get the struct value");
WriteLineIndent("fun get(fbeSize: Size, fbeValue: " + *s->name + " = " + *s->name + "()): " + *s->name);
WriteLineIndent("{");
Indent(1);
WriteLineIndent("_buffer.shift(fbeOffset)");
WriteLineIndent("fbeSize.value = getFields(fbeValue)");
WriteLineIndent("_buffer.unshift(fbeOffset)");
WriteLineIndent("return fbeValue");
Indent(-1);
WriteLineIndent("}");
// Generate struct final model getFields() method
WriteLine();
WriteLineIndent("// Get the struct fields values");
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun getFields(fbeValue: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
WriteLineIndent("var fbeCurrentOffset = 0L");
WriteLineIndent("var fbeCurrentSize = 0L");
WriteLineIndent("val fbeFieldSize = Size(0)");
if (s->base && !s->base->empty())
{
WriteLine();
WriteLineIndent("parent.fbeOffset = fbeCurrentOffset");
WriteLineIndent("fbeFieldSize.value = parent.getFields(fbeValue)");
WriteLineIndent("fbeCurrentOffset += fbeFieldSize.value");
WriteLineIndent("fbeCurrentSize += fbeFieldSize.value");
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
WriteLine();
WriteLineIndent(*field->name + ".fbeOffset = fbeCurrentOffset");
if (field->array || field->vector || field->list || field->set || field->map || field->hash)
WriteLineIndent("fbeFieldSize.value = " + *field->name + ".get(fbeValue." + *field->name + ")");
else
WriteLineIndent("fbeValue." + *field->name + " = " + *field->name + ".get(fbeFieldSize)");
WriteLineIndent("fbeCurrentOffset += fbeFieldSize.value");
WriteLineIndent("fbeCurrentSize += fbeFieldSize.value");
}
}
WriteLine();
WriteLineIndent("return fbeCurrentSize");
}
else
WriteLineIndent("return 0L");
Indent(-1);
WriteLineIndent("}");
// Generate struct final model set() method
WriteLine();
WriteLineIndent("// Set the struct value");
WriteLineIndent("fun set(fbeValue: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("_buffer.shift(fbeOffset)");
WriteLineIndent("val fbeSize = setFields(fbeValue)");
WriteLineIndent("_buffer.unshift(fbeOffset)");
WriteLineIndent("return fbeSize");
Indent(-1);
WriteLineIndent("}");
// Generate struct final model setFields() method
WriteLine();
WriteLineIndent("// Set the struct fields values");
WriteLineIndent("@Suppress(\"UNUSED_PARAMETER\")");
WriteLineIndent("fun setFields(fbeValue: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
if ((s->base && !s->base->empty()) || (s->body && !s->body->fields.empty()))
{
WriteLineIndent("var fbeCurrentOffset = 0L");
WriteLineIndent("var fbeCurrentSize = 0L");
WriteLineIndent("val fbeFieldSize = Size(0)");
if (s->base && !s->base->empty())
{
WriteLine();
WriteLineIndent("parent.fbeOffset = fbeCurrentOffset");
WriteLineIndent("fbeFieldSize.value = parent.setFields(fbeValue)");
WriteLineIndent("fbeCurrentOffset += fbeFieldSize.value");
WriteLineIndent("fbeCurrentSize += fbeFieldSize.value");
}
if (s->body)
{
for (const auto& field : s->body->fields)
{
WriteLine();
WriteLineIndent(*field->name + ".fbeOffset = fbeCurrentOffset");
WriteLineIndent("fbeFieldSize.value = " + *field->name + ".set(fbeValue." + *field->name + ")");
WriteLineIndent("fbeCurrentOffset += fbeFieldSize.value");
WriteLineIndent("fbeCurrentSize += fbeFieldSize.value");
}
}
WriteLine();
WriteLineIndent("return fbeCurrentSize");
}
else
WriteLineIndent("return 0L");
Indent(-1);
WriteLineIndent("}");
// Generate struct final model end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateStructModelFinal(const std::shared_ptr<Package>& p, const std::shared_ptr<StructType>& s)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / (*s->name + "FinalModel.kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate struct model final begin
WriteLine();
WriteLineIndent("// Fast Binary Encoding " + *s->name + " final model");
WriteLineIndent("class " + *s->name + "FinalModel : Model");
WriteLineIndent("{");
Indent(1);
// Generate struct model final accessor
WriteLineIndent("private val _model: FinalModel" + *s->name);
// Generate struct model final constructors
WriteLine();
WriteLineIndent("constructor() { _model = FinalModel" + *s->name + "(buffer, 8) }");
WriteLineIndent("constructor(buffer: Buffer) : super(buffer) { _model = FinalModel" + *s->name + "(buffer, 8) }");
// Generate struct model final FBE properties
WriteLine();
WriteLineIndent("// Model type");
WriteLineIndent("var fbeType: Long = fbeTypeConst");
WriteLine();
WriteLineIndent("companion object");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("const val fbeTypeConst: Long = FinalModel" + *s->name + ".fbeTypeConst");
Indent(-1);
WriteLineIndent("}");
// Generate struct model final verify() method
WriteLine();
WriteLineIndent("// Check if the struct value is valid");
WriteLineIndent("fun verify(): Boolean");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("if ((buffer.offset + _model.fbeOffset) > buffer.size)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructSize = readUInt32(_model.fbeOffset - 8).toLong()");
WriteLineIndent("val fbeStructType = readUInt32(_model.fbeOffset - 4).toLong()");
WriteLineIndent("if ((fbeStructSize <= 0) || (fbeStructType != fbeType))");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLine();
WriteLineIndent("return ((8 + _model.verify()) == fbeStructSize)");
Indent(-1);
WriteLineIndent("}");
// Generate struct model final serialize() method
WriteLine();
WriteLineIndent("// Serialize the struct value");
WriteLineIndent("fun serialize(value: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val fbeInitialSize = buffer.size");
WriteLine();
WriteLineIndent("val fbeStructType = fbeType");
WriteLineIndent("var fbeStructSize = 8 + _model.fbeAllocationSize(value)");
WriteLineIndent("val fbeStructOffset = buffer.allocate(fbeStructSize) - buffer.offset");
WriteLineIndent("assert((buffer.offset + fbeStructOffset + fbeStructSize) <= buffer.size) { \"Model is broken!\" }");
WriteLineIndent("if ((buffer.offset + fbeStructOffset + fbeStructSize) > buffer.size)");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("fbeStructSize = 8 + _model.set(value)");
WriteLineIndent("buffer.resize(fbeInitialSize + fbeStructSize)");
WriteLine();
WriteLineIndent("write(_model.fbeOffset - 8, fbeStructSize.toUInt())");
WriteLineIndent("write(_model.fbeOffset - 4, fbeStructType.toUInt())");
WriteLine();
WriteLineIndent("return fbeStructSize");
Indent(-1);
WriteLineIndent("}");
// Generate struct model final deserialize() methods
WriteLine();
WriteLineIndent("// Deserialize the struct value");
WriteLineIndent("fun deserialize(): " + *s->name + " { val value = " + *s->name + "(); deserialize(value); return value }");
WriteLineIndent("@Suppress(\"UNUSED_VALUE\")");
WriteLineIndent("fun deserialize(value: " + *s->name + "): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("var valueRef = value");
WriteLine();
WriteLineIndent("assert((buffer.offset + _model.fbeOffset) <= buffer.size) { \"Model is broken!\" }");
WriteLineIndent("if ((buffer.offset + _model.fbeOffset) > buffer.size)");
Indent(1);
WriteLineIndent("return 0");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeStructSize = readUInt32(_model.fbeOffset - 8).toLong()");
WriteLineIndent("val fbeStructType = readUInt32(_model.fbeOffset - 4).toLong()");
WriteLineIndent("assert((fbeStructSize > 0) && (fbeStructType == fbeType)) { \"Model is broken!\" }");
WriteLineIndent("if ((fbeStructSize <= 0) || (fbeStructType != fbeType))");
Indent(1);
WriteLineIndent("return 8");
Indent(-1);
WriteLine();
WriteLineIndent("val fbeSize = Size(0)");
WriteLineIndent("valueRef = _model.get(fbeSize, valueRef)");
WriteLineIndent("return 8 + fbeSize.value");
Indent(-1);
WriteLineIndent("}");
// Generate struct model final next() method
WriteLine();
WriteLineIndent("// Move to the next struct value");
WriteLineIndent("fun next(prev: Long)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("_model.fbeShift(prev)");
Indent(-1);
WriteLineIndent("}");
// Generate struct model final end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateSender(const std::shared_ptr<Package>& p, bool final)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
std::string sender = (final ? "FinalSender" : "Sender");
std::string model = (final ? "FinalModel" : "Model");
// Open the file
CppCommon::Path file = path / (sender + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate sender begin
WriteLine();
if (final)
WriteLineIndent("// Fast Binary Encoding " + *p->name + " final sender");
else
WriteLineIndent("// Fast Binary Encoding " + *p->name + " sender");
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"PropertyName\")");
WriteLineIndent("open class " + sender + " : fbe.Sender");
WriteLineIndent("{");
Indent(1);
// Generate imported senders accessors
if (p->import)
{
WriteLineIndent("// Imported senders");
for (const auto& import : p->import->imports)
WriteLineIndent("val " + *import + "Sender: " + *import + ".fbe." + sender);
WriteLine();
}
// Generate sender models accessors
if (p->body)
{
WriteLineIndent("// Sender models accessors");
for (const auto& s : p->body->structs)
WriteLineIndent("val " + *s->name + "Model: " + *s->name + model);
WriteLine();
}
// Generate sender constructors
WriteLineIndent("constructor() : super(" + std::string(final ? "true" : "false") + ")");
WriteLineIndent("{");
Indent(1);
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + "Sender = " + *import + ".fbe." + sender + "(buffer)");
}
if (p->body)
{
for (const auto& s : p->body->structs)
WriteLineIndent(*s->name + "Model = " + *s->name + model + "(buffer)");
}
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("constructor(buffer: Buffer) : super(buffer, " + std::string(final ? "true" : "false") + ")");
WriteLineIndent("{");
Indent(1);
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + "Sender = " + *import + ".fbe." + sender + "(buffer)");
}
if (p->body)
{
for (const auto& s : p->body->structs)
WriteLineIndent(*s->name + "Model = " + *s->name + model + "(buffer)");
}
Indent(-1);
WriteLineIndent("}");
WriteLine();
// Generate sender methods
if (p->body)
{
for (const auto& s : p->body->structs)
{
std::string struct_name = *p->name + "." + *s->name;
WriteLineIndent("fun send(value: " + struct_name + "): Long");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("// Serialize the value into the FBE stream");
WriteLineIndent("val serialized = " + *s->name + "Model.serialize(value)");
WriteLineIndent("assert(serialized > 0) { \"" + *p->name + "." + *s->name + " serialization failed!\" }");
WriteLineIndent("assert(" + *s->name + "Model.verify()) { \"" + *p->name + "." + *s->name + " validation failed!\" }");
WriteLine();
WriteLineIndent("// Log the value");
WriteLineIndent("if (logging)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val message = value.toString()");
WriteLineIndent("onSendLog(message)");
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("// Send the serialized value");
WriteLineIndent("return sendSerialized(serialized)");
Indent(-1);
WriteLineIndent("}");
}
}
// Generate sender message handler
WriteLine();
WriteLineIndent("// Send message handler");
WriteLineIndent("override fun onSend(buffer: ByteArray, offset: Long, size: Long): Long { throw UnsupportedOperationException(\"" + *p->name + ".fbe.Sender.onSend() not implemented!\") }");
// Generate sender end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateReceiver(const std::shared_ptr<Package>& p, bool final)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
std::string receiver = (final ? "FinalReceiver" : "Receiver");
std::string model = (final ? "FinalModel" : "Model");
// Open the file
CppCommon::Path file = path / (receiver + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate receiver begin
WriteLine();
if (final)
WriteLineIndent("// Fast Binary Encoding " + *p->name + " final receiver");
else
WriteLineIndent("// Fast Binary Encoding " + *p->name + " receiver");
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"PrivatePropertyName\", \"UNUSED_PARAMETER\")");
WriteLineIndent("open class " + receiver + " : fbe.Receiver");
WriteLineIndent("{");
Indent(1);
// Generate imported receivers accessors
if (p->import)
{
WriteLineIndent("// Imported receivers");
for (const auto& import : p->import->imports)
WriteLineIndent("var " + *import + "Receiver: " + *import + ".fbe." + receiver + "? = null");
WriteLine();
}
// Generate receiver models accessors
if (p->body)
{
WriteLineIndent("// Receiver values accessors");
for (const auto& s : p->body->structs)
{
std::string struct_name = *p->name + "." + *s->name;
WriteLineIndent("private val " + *s->name + "Value: " + struct_name);
}
WriteLine();
WriteLineIndent("// Receiver models accessors");
for (const auto& s : p->body->structs)
WriteLineIndent("private val " + *s->name + "Model: " + *s->name + model);
WriteLine();
}
// Generate receiver constructors
WriteLineIndent("constructor() : super(" + std::string(final ? "true" : "false") + ")");
WriteLineIndent("{");
Indent(1);
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + "Receiver = " + *import + ".fbe." + receiver + "(buffer)");
}
if (p->body)
{
for (const auto& s : p->body->structs)
{
std::string struct_name = *p->name + "." + *s->name;
WriteLineIndent(*s->name + "Value = " + struct_name + "()");
WriteLineIndent(*s->name + "Model = " + *s->name + model + "()");
}
}
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("constructor(buffer: Buffer) : super(buffer, " + std::string(final ? "true" : "false") + ")");
WriteLineIndent("{");
Indent(1);
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + "Receiver = " + *import + ".fbe." + receiver + "(buffer)");
}
if (p->body)
{
for (const auto& s : p->body->structs)
{
std::string struct_name = *p->name + "." + *s->name;
WriteLineIndent(*s->name + "Value = " + struct_name + "()");
WriteLineIndent(*s->name + "Model = " + *s->name + model + "()");
}
}
Indent(-1);
WriteLineIndent("}");
WriteLine();
// Generate receiver handlers
if (p->body)
{
WriteLineIndent("// Receive handlers");
for (const auto& s : p->body->structs)
{
std::string struct_name = *p->name + "." + *s->name;
WriteLineIndent("protected open fun onReceive(value: " + struct_name + ") {}");
}
WriteLine();
}
// Generate receiver message handler
WriteLineIndent("override fun onReceive(type: Long, buffer: ByteArray, offset: Long, size: Long): Boolean");
WriteLineIndent("{");
Indent(1);
if (p->body)
{
WriteLineIndent("when (type)");
WriteLineIndent("{");
Indent(1);
for (const auto& s : p->body->structs)
{
WriteLineIndent(package + ".fbe." + *s->name + model + ".fbeTypeConst ->");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("// Deserialize the value from the FBE stream");
WriteLineIndent(*s->name + "Model.attach(buffer, offset)");
WriteLineIndent("assert(" + *s->name + "Model.verify()) { \"" + *p->name + "." + *s->name + " validation failed!\" }");
WriteLineIndent("val deserialized = " + *s->name + "Model.deserialize(" + *s->name + "Value)");
WriteLineIndent("assert(deserialized > 0) { \"" + *p->name + "." + *s->name + " deserialization failed!\" }");
WriteLine();
WriteLineIndent("// Log the value");
WriteLineIndent("if (logging)");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("val message = " + *s->name + "Value.toString()");
WriteLineIndent("onReceiveLog(message)");
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("// Call receive handler with deserialized value");
WriteLineIndent("onReceive(" + *s->name + "Value)");
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("}");
}
Indent(-1);
WriteLineIndent("}");
}
if (p->import)
{
WriteLine();
for (const auto& import : p->import->imports)
{
WriteLineIndent("if ((" + *import + "Receiver != null) && " + *import + "Receiver!!.onReceive(type, buffer, offset, size))");
Indent(1);
WriteLineIndent("return true");
Indent(-1);
}
}
WriteLine();
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("}");
// Generate receiver end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateProxy(const std::shared_ptr<Package>& p, bool final)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
std::string proxy = (final ? "FinalProxy" : "Proxy");
std::string model = (final ? "FinalModel" : "Model");
// Open the file
CppCommon::Path file = path / (proxy + ".kt");
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
// Generate proxy begin
WriteLine();
if (final)
WriteLineIndent("// Fast Binary Encoding " + *p->name + " final proxy");
else
WriteLineIndent("// Fast Binary Encoding " + *p->name + " proxy");
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\", \"PrivatePropertyName\", \"UNUSED_PARAMETER\")");
WriteLineIndent("open class " + proxy + " : fbe.Receiver");
WriteLineIndent("{");
Indent(1);
// Generate imported proxy accessors
if (p->import)
{
WriteLineIndent("// Imported proxy");
for (const auto& import : p->import->imports)
WriteLineIndent("var " + *import + "Proxy: " + *import + ".fbe." + proxy + "? = null");
WriteLine();
}
// Generate proxy models accessors
if (p->body)
{
WriteLineIndent("// Proxy models accessors");
for (const auto& s : p->body->structs)
WriteLineIndent("private val " + *s->name + "Model: " + *s->name + model);
WriteLine();
}
// Generate proxy constructors
WriteLineIndent("constructor() : super(" + std::string(final ? "true" : "false") + ")");
WriteLineIndent("{");
Indent(1);
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + "Proxy = " + *import + ".fbe." + proxy + "(buffer)");
}
if (p->body)
{
for (const auto& s : p->body->structs)
WriteLineIndent(*s->name + "Model = " + *s->name + model + "()");
}
Indent(-1);
WriteLineIndent("}");
WriteLine();
WriteLineIndent("constructor(buffer: Buffer) : super(buffer, " + std::string(final ? "true" : "false") + ")");
WriteLineIndent("{");
Indent(1);
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + "Proxy = " + *import + ".fbe." + proxy + "(buffer)");
}
if (p->body)
{
for (const auto& s : p->body->structs)
WriteLineIndent(*s->name + "Model = " + *s->name + model + "()");
}
Indent(-1);
WriteLineIndent("}");
WriteLine();
// Generate proxy handlers
if (p->body)
{
WriteLineIndent("// Proxy handlers");
for (const auto& s : p->body->structs)
{
std::string struct_model = *s->name + model;
WriteLineIndent("protected open fun onProxy(model: " + struct_model + ", type: Long, buffer: ByteArray, offset: Long, size: Long) {}");
}
WriteLine();
}
// Generate proxy message handler
WriteLineIndent("override fun onReceive(type: Long, buffer: ByteArray, offset: Long, size: Long): Boolean");
WriteLineIndent("{");
Indent(1);
if (p->body)
{
WriteLineIndent("when (type)");
WriteLineIndent("{");
Indent(1);
for (const auto& s : p->body->structs)
{
WriteLineIndent(package + ".fbe." + *s->name + model + ".fbeTypeConst ->");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("// Attach the FBE stream to the proxy model");
WriteLineIndent(*s->name + "Model.attach(buffer, offset)");
WriteLineIndent("assert(" + *s->name + "Model.verify()) { \"" + *p->name + "." + *s->name + " validation failed!\" }");
WriteLine();
WriteLineIndent("val fbeBegin = " + *s->name + "Model.model.getBegin()");
WriteLineIndent("if (fbeBegin == 0L)");
Indent(1);
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("// Call proxy handler");
WriteLineIndent("onProxy(" + *s->name + "Model, type, buffer, offset, size)");
WriteLineIndent(*s->name + "Model.model.getEnd(fbeBegin)");
WriteLineIndent("return true");
Indent(-1);
WriteLineIndent("}");
}
Indent(-1);
WriteLineIndent("}");
}
if (p->import)
{
WriteLine();
for (const auto& import : p->import->imports)
{
WriteLineIndent("if ((" + *import + "Proxy != null) && " + *import + "Proxy!!.onReceive(type, buffer, offset, size))");
Indent(1);
WriteLineIndent("return true");
Indent(-1);
}
}
WriteLine();
WriteLineIndent("return false");
Indent(-1);
WriteLineIndent("}");
// Generate proxy end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
void GeneratorKotlin::GenerateJson(const std::shared_ptr<Package>& p)
{
std::string package = *p->name;
CppCommon::Path path = (CppCommon::Path(_output) / package) / "fbe";
// Create package path
CppCommon::Directory::CreateTree(path);
// Open the file
CppCommon::Path file = path / "Json.kt";
Open(file);
// Generate headers
GenerateHeader(CppCommon::Path(_input).filename().string());
GenerateImports(package + ".fbe");
// Generate custom import
WriteLine();
WriteLineIndent("import fbe.*");
WriteLineIndent("import " + package + ".*");
WriteLine();
WriteLineIndent("import com.google.gson.*");
// Generate JSON engine begin
WriteLine();
WriteLineIndent("// Fast Binary Encoding " + *p->name + " JSON engine");
WriteLineIndent("object Json");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("// Get the JSON engine");
WriteLineIndent("val engine: Gson = register(GsonBuilder()).create()");
WriteLine();
// Generate JSON engine Register() method
WriteLineIndent("@Suppress(\"MemberVisibilityCanBePrivate\")");
WriteLineIndent("fun register(builder: GsonBuilder): GsonBuilder");
WriteLineIndent("{");
Indent(1);
WriteLineIndent("fbe.Json.register(builder)");
if (p->import)
{
for (const auto& import : p->import->imports)
WriteLineIndent(*import + ".fbe.Json.register(builder)");
}
if (p->body)
{
for (const auto& e : p->body->enums)
WriteLineIndent("builder.registerTypeAdapter(" + *e->name + "::class.java, " + *e->name + "Json())");
for (const auto& f : p->body->flags)
WriteLineIndent("builder.registerTypeAdapter(" + *f->name + "::class.java, " + *f->name + "Json())");
}
WriteLineIndent("return builder");
Indent(-1);
WriteLineIndent("}");
// Generate JSON engine end
Indent(-1);
WriteLineIndent("}");
// Generate footer
GenerateFooter();
// Close the file
Close();
}
bool GeneratorKotlin::IsKnownType(const std::string& type)
{
return ((type == "bool") ||
(type == "byte") || (type == "bytes") ||
(type == "char") || (type == "wchar") ||
(type == "int8") || (type == "uint8") ||
(type == "int16") || (type == "uint16") ||
(type == "int32") || (type == "uint32") ||
(type == "int64") || (type == "uint64") ||
(type == "float") || (type == "double") ||
(type == "decimal") || (type == "string") ||
(type == "timestamp") || (type == "uuid"));
}
bool GeneratorKotlin::IsPrimitiveType(const std::string& type, bool optional)
{
return ((type == "bool") || (type == "byte") ||
(type == "char") || (type == "wchar") ||
(type == "int8") || (type == "uint8") ||
(type == "int16") || (type == "uint16") ||
(type == "int32") || (type == "uint32") ||
(type == "int64") || (type == "uint64") ||
(type == "float") || (type == "double") ||
(type == "string"));
}
bool GeneratorKotlin::IsUnsignedType(const std::string& type)
{
return ((type == "uint8") || (type == "uint16") || (type == "uint32") || (type == "uint64"));
}
std::string GeneratorKotlin::ConvertEnumBase(const std::string& type)
{
if (type == "byte")
return "Byte";
else if (type == "char")
return "Byte";
else if (type == "wchar")
return "Int";
else if (type == "int8")
return "Byte";
else if (type == "uint8")
return "UByte";
else if (type == "int16")
return "Short";
else if (type == "uint16")
return "UShort";
else if (type == "int32")
return "Int";
else if (type == "uint32")
return "UInt";
else if (type == "int64")
return "Long";
else if (type == "uint64")
return "ULong";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumType(const std::string& type)
{
if (type == "byte")
return "Byte";
else if (type == "char")
return "Byte";
else if (type == "wchar")
return "Int";
else if (type == "int8")
return "Byte";
else if (type == "uint8")
return "UByte";
else if (type == "int16")
return "Short";
else if (type == "uint16")
return "UShort";
else if (type == "int32")
return "Int";
else if (type == "uint32")
return "UInt";
else if (type == "int64")
return "Long";
else if (type == "uint64")
return "ULong";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumSize(const std::string& type)
{
if (type == "byte")
return "1";
else if (type == "char")
return "1";
else if (type == "wchar")
return "4";
else if (type == "int8")
return "1";
else if (type == "uint8")
return "1";
else if (type == "int16")
return "2";
else if (type == "uint16")
return "2";
else if (type == "int32")
return "4";
else if (type == "uint32")
return "4";
else if (type == "int64")
return "8";
else if (type == "uint64")
return "8";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumGet(const std::string& type)
{
if (type == "byte")
return "asByte";
else if (type == "char")
return "asByte";
else if (type == "wchar")
return "asInt";
else if (type == "int8")
return "asByte";
else if (type == "uint8")
return "asByte.toUByte()";
else if (type == "int16")
return "asShort";
else if (type == "uint16")
return "asShort.toUShort()";
else if (type == "int32")
return "asInt";
else if (type == "uint32")
return "asInt.toUInt()";
else if (type == "int64")
return "asLong";
else if (type == "uint64")
return "asLong.toULong()";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumRead(const std::string& type)
{
if (type == "byte")
return "readByte";
else if (type == "char")
return "readInt8";
else if (type == "wchar")
return "readInt32";
else if (type == "int8")
return "readInt8";
else if (type == "uint8")
return "readUInt8";
else if (type == "int16")
return "readInt16";
else if (type == "uint16")
return "readUInt16";
else if (type == "int32")
return "readInt32";
else if (type == "uint32")
return "readUInt32";
else if (type == "int64")
return "readInt64";
else if (type == "uint64")
return "readUInt64";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumFrom(const std::string& type)
{
if (type == "uint8")
return ".toByte()";
else if (type == "uint16")
return ".toShort()";
else if (type == "uint32")
return ".toInt()";
else if (type == "uint64")
return ".toLong()";
return "";
}
std::string GeneratorKotlin::ConvertEnumTo(const std::string& type)
{
if (type == "byte")
return ".toByte()";
else if (type == "char")
return ".toByte()";
else if (type == "wchar")
return ".toInt()";
else if (type == "int8")
return ".toByte()";
else if (type == "uint8")
return ".toUByte()";
else if (type == "int16")
return ".toShort()";
else if (type == "uint16")
return ".toUShort()";
else if (type == "int32")
return ".toInt()";
else if (type == "uint32")
return ".toUInt()";
else if (type == "int64")
return ".toLong()";
else if (type == "uint64")
return ".toULong()";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumFlags(const std::string& type)
{
if (type == "byte")
return ".toInt()";
else if (type == "int8")
return ".toInt()";
else if (type == "uint8")
return ".toUInt()";
else if (type == "int16")
return ".toInt()";
else if (type == "uint16")
return ".toUInt()";
else if (type == "int32")
return ".toInt()";
else if (type == "uint32")
return ".toUInt()";
else if (type == "int64")
return ".toLong()";
else if (type == "uint64")
return ".toULong()";
yyerror("Unsupported enum base type - " + type);
return "";
}
std::string GeneratorKotlin::ConvertEnumConstant(const std::string& base, const std::string& type, const std::string& value, bool flag)
{
std::string result = value;
if (type.empty())
{
// Fill flags values
std::vector<std::string> flags = CppCommon::StringUtils::Split(value, '|', true);
// Generate flags combination
if (!flags.empty())
{
result = "";
bool first = true;
for (const auto& it : flags)
{
result += (first ? "" : " or ") + CppCommon::StringUtils::ToTrim(it) + ".raw" + (flag ? ConvertEnumFlags(base) : "");
first = false;
}
}
}
return ConvertEnumConstantPrefix(type) + result + ConvertEnumConstantSuffix(type);
}
std::string GeneratorKotlin::ConvertEnumConstantPrefix(const std::string& type)
{
return "";
}
std::string GeneratorKotlin::ConvertEnumConstantSuffix(const std::string& type)
{
if ((type == "uint8") || (type == "uint16") || (type == "uint32"))
return "u";
if (type == "int64")
return "L";
if (type == "uint64")
return "uL";
return "";
}
std::string GeneratorKotlin::ConvertPrimitiveTypeName(const std::string& type)
{
if (type == "bool")
return "Boolean";
else if (type == "byte")
return "Byte";
else if (type == "char")
return "Character";
else if (type == "wchar")
return "Character";
else if (type == "int8")
return "Byte";
else if (type == "uint8")
return "UByte";
else if (type == "int16")
return "Short";
else if (type == "uint16")
return "UShort";
else if (type == "int32")
return "Int";
else if (type == "uint32")
return "UInt";
else if (type == "int64")
return "Long";
else if (type == "uint64")
return "ULong";
else if (type == "float")
return "Float";
else if (type == "double")
return "Double";
return "";
}
std::string GeneratorKotlin::ConvertTypeName(const std::string& type, bool optional)
{
std::string opt = optional ? "?" : "";
if (type == "bool")
return "Boolean" + opt;
else if (type == "byte")
return "Byte" + opt;
else if (type == "bytes")
return "ByteArray" + opt;
else if (type == "char")
return "Char" + opt;
else if (type == "wchar")
return "Char" + opt;
else if (type == "int8")
return "Byte" + opt;
else if (type == "uint8")
return "UByte" + opt;
else if (type == "int16")
return "Short" + opt;
else if (type == "uint16")
return "UShort" + opt;
else if (type == "int32")
return "Int" + opt;
else if (type == "uint32")
return "UInt" + opt;
else if (type == "int64")
return "Long" + opt;
else if (type == "uint64")
return "ULong" + opt;
else if (type == "float")
return "Float" + opt;
else if (type == "double")
return "Double" + opt;
else if (type == "decimal")
return "BigDecimal" + opt;
else if (type == "string")
return "String" + opt;
else if (type == "timestamp")
return "Instant" + opt;
else if (type == "uuid")
return "UUID" + opt;
return type + opt;
}
std::string GeneratorKotlin::ConvertTypeName(const StructField& field, bool typeless)
{
if (field.array)
return "Array" + (typeless ? "" : ("<" + ConvertTypeName(*field.type, field.optional) + ">"));
else if (field.vector)
return "ArrayList" + (typeless ? "" : ("<" + ConvertTypeName(*field.type, field.optional) + ">"));
else if (field.list)
return "LinkedList" + (typeless ? "" : ("<" + ConvertTypeName(*field.type, field.optional) + ">"));
else if (field.set)
return "HashSet" + (typeless ? "" : ("<" + ConvertTypeName(*field.key, field.optional) + ">"));
else if (field.map)
return "TreeMap" + (typeless ? "" : ("<" + ConvertTypeName(*field.key, false) + ", " + ConvertTypeName(*field.type, field.optional) +">"));
else if (field.hash)
return "HashMap" + (typeless ? "" : ("<" + ConvertTypeName(*field.key, false) + ", " + ConvertTypeName(*field.type, field.optional) +">"));
return ConvertTypeName(*field.type, field.optional);
}
std::string GeneratorKotlin::ConvertBaseFieldName(const std::string& type, bool final)
{
std::string modelType = (final ? "Final" : "Field");
std::string ns = "";
std::string t = type;
size_t pos = type.find_last_of('.');
if (pos != std::string::npos)
{
ns.assign(type, 0, pos + 1);
ns.append("fbe.");
t.assign(type, pos + 1, type.size() - pos);
}
return ns + modelType + "Model" + ConvertTypeFieldName(t);
}
std::string GeneratorKotlin::ConvertTypeFieldName(const std::string& type)
{
if (type == "bool")
return "Boolean";
else if (type == "byte")
return "Byte";
else if (type == "bytes")
return "Bytes";
else if (type == "char")
return "Char";
else if (type == "wchar")
return "WChar";
else if (type == "int8")
return "Int8";
else if (type == "uint8")
return "UInt8";
else if (type == "int16")
return "Int16";
else if (type == "uint16")
return "UInt16";
else if (type == "int32")
return "Int32";
else if (type == "uint32")
return "UInt32";
else if (type == "int64")
return "Int64";
else if (type == "uint64")
return "UInt64";
else if (type == "float")
return "Float";
else if (type == "double")
return "Double";
else if (type == "decimal")
return "Decimal";
else if (type == "string")
return "String";
else if (type == "timestamp")
return "Timestamp";
else if (type == "uuid")
return "UUID";
std::string result = type;
CppCommon::StringUtils::ReplaceAll(result, ".", "");
return result;
}
std::string GeneratorKotlin::ConvertTypeFieldType(const std::string& type, bool optional)
{
std::string opt = optional ? "?" : "";
if (type == "bool")
return "Boolean" + opt;
else if (type == "byte")
return "Byte" + opt;
else if (type == "bytes")
return "ByteArray" + opt;
else if (type == "char")
return "Char" + opt;
else if (type == "wchar")
return "Char" + opt;
else if (type == "int8")
return "Byte" + opt;
else if (type == "uint8")
return "UByte" + opt;
else if (type == "int16")
return "Short" + opt;
else if (type == "uint16")
return "UShort" + opt;
else if (type == "int32")
return "Int" + opt;
else if (type == "uint32")
return "UInt" + opt;
else if (type == "int64")
return "Long" + opt;
else if (type == "uint64")
return "ULong" + opt;
else if (type == "float")
return "Float" + opt;
else if (type == "double")
return "Double" + opt;
else if (type == "decimal")
return "BigDecimal" + opt;
else if (type == "string")
return "String" + opt;
else if (type == "timestamp")
return "Instant" + opt;
else if (type == "uuid")
return "UUID" + opt;
std::string ns = "";
std::string t = type;
size_t pos = type.find_last_of('.');
if (pos != std::string::npos)
{
ns.assign(type, 0, pos + 1);
t.assign(type, pos + 1, type.size() - pos);
}
return ns + t + opt;
}
std::string GeneratorKotlin::ConvertTypeFieldDeclaration(const std::string& type, bool optional, bool final)
{
std::string modelType = (final ? "Final" : "Field");
std::string ns = "";
std::string opt = optional ? "Optional" : "";
std::string t = type;
size_t pos = type.find_last_of('.');
if (pos != std::string::npos)
{
ns.assign(type, 0, pos + 1);
ns.append("fbe.");
t.assign(type, pos + 1, type.size() - pos);
}
return ns + modelType + "Model" + opt + ConvertTypeFieldName(t);
}
std::string GeneratorKotlin::ConvertTypeFieldDeclaration(const StructField& field, bool final)
{
std::string modelType = (final ? "Final" : "Field");
if (field.array)
return modelType + "ModelArray" + std::string(field.optional ? "Optional" : "") + ConvertTypeFieldName(*field.type);
else if (field.vector || field.list || field.set)
return modelType + "ModelVector" + std::string(field.optional ? "Optional" : "") + ConvertTypeFieldName(*field.type);
else if (field.map || field.hash)
return modelType + "ModelMap" + ConvertTypeFieldName(*field.key) + std::string(field.optional ? "Optional" : "") + ConvertTypeFieldName(*field.type);
else if (field.optional)
return modelType + "ModelOptional" + ConvertTypeFieldName(*field.type);
return ConvertTypeFieldDeclaration(*field.type, field.optional, final);
}
std::string GeneratorKotlin::ConvertTypeFieldInitialization(const StructField& field, const std::string& offset, bool final)
{
std::string modelType = (final ? "Final" : "Field");
if (field.array)
return modelType + "ModelArray" + std::string(field.optional ? "Optional" : "") + ConvertTypeFieldName(*field.type) + "(buffer, " + offset + ", " + std::to_string(field.N) + ")";
else if (field.vector || field.list || field.set)
return modelType + "ModelVector" + std::string(field.optional ? "Optional" : "") + ConvertTypeFieldName(*field.type) + "(buffer, " + offset + ")";
else if (field.map || field.hash)
return modelType + "ModelMap" + ConvertTypeFieldName(*field.key) + std::string(field.optional ? "Optional" : "") + ConvertTypeFieldName(*field.type) + "(buffer, " + offset + ")";
else if (field.optional)
return modelType + "ModelOptional" + ConvertTypeFieldName(*field.type) + "(buffer, " + offset + ")";
std::string ns = "";
std::string t = *field.type;
std::string type = *field.type;
size_t pos = type.find_last_of('.');
if (pos != std::string::npos)
{
ns.assign(type, 0, pos + 1);
ns.append("fbe.");
t.assign(type, pos + 1, type.size() - pos);
}
return ns + modelType + "Model" + ConvertTypeFieldName(t) + "(buffer, " + offset + ")";
}
std::string GeneratorKotlin::ConvertConstant(const std::string& type, const std::string& value, bool optional)
{
if (value == "true")
return "true";
else if (value == "false")
return "false";
else if (value == "null")
return "null";
else if (value == "min")
{
if (type == "byte")
return ConvertConstantPrefix(type) + "0" + ConvertConstantSuffix(type);
else if (type == "int8")
return "Byte.MIN_VALUE";
else if (type == "uint8")
return "UByte.MIN_VALUE";
else if (type == "int16")
return "Short.MIN_VALUE";
else if (type == "uint16")
return "UShort.MIN_VALUE";
else if (type == "int32")
return "Int.MIN_VALUE";
else if (type == "uint32")
return "UInt.MIN_VALUE";
else if (type == "int64")
return "Long.MIN_VALUE";
else if (type == "uint64")
return "ULong.MIN_VALUE";
yyerror("Unsupported type " + type + " for 'min' constant");
return "";
}
else if (value == "max")
{
if (type == "byte")
return ConvertConstantPrefix(type) + "0xFF" + ConvertConstantSuffix(type);
else if (type == "int8")
return "Byte.MAX_VALUE";
else if (type == "uint8")
return "UByte.MAX_VALUE";
else if (type == "int16")
return "Short.MAX_VALUE";
else if (type == "uint16")
return "UShort.MAX_VALUE";
else if (type == "int32")
return "Int.MAX_VALUE";
else if (type == "uint32")
return "UInt.MAX_VALUE";
else if (type == "int64")
return "Long.MAX_VALUE";
else if (type == "uint64")
return "ULong.MAX_VALUE";
yyerror("Unsupported type " + type + " for 'max' constant");
return "";
}
else if (value == "epoch")
return "Instant.EPOCH";
else if (value == "utc")
return "Instant.now()";
else if (value == "uuid0")
return "fbe.UUIDGenerator.nil()";
else if (value == "uuid1")
return "fbe.UUIDGenerator.sequential()";
else if (value == "uuid4")
return "fbe.UUIDGenerator.random()";
std::string result = value;
if (!IsKnownType(type))
{
// Fill flags values
std::vector<std::string> flags = CppCommon::StringUtils::Split(value, '|', true);
// Generate flags combination
if (flags.size() > 1)
{
result = "";
bool first = true;
for (const auto& it : flags)
{
result += (first ? "" : ", ") + CppCommon::StringUtils::ToTrim(it) + ".value";
first = false;
}
result = type + ".fromSet(EnumSet.of(" + result + "))";
}
}
return ConvertConstantPrefix(type) + result + ConvertConstantSuffix(type);
}
std::string GeneratorKotlin::ConvertConstantPrefix(const std::string& type)
{
if (type == "decimal")
return "BigDecimal.valueOf(";
if (type == "uuid")
return "UUID.fromString(";
return "";
}
std::string GeneratorKotlin::ConvertConstantSuffix(const std::string& type)
{
if (type == "byte")
return ".toByte()";
if ((type == "char") || (type == "wchar"))
return ".toChar()";
if ((type == "uint8") || (type == "uint16") || (type == "uint32"))
return "u";
if (type == "int64")
return "L";
if (type == "uint64")
return "uL";
if (type == "float")
return "f";
if ((type == "decimal") || (type == "uuid"))
return ")";
return "";
}
std::string GeneratorKotlin::ConvertDefault(const std::string& type)
{
if (type == "bool")
return "false";
else if (type == "byte")
return "0.toByte()";
else if (type == "bytes")
return "ByteArray(0)";
else if ((type == "char") || (type == "wchar"))
return "'\\u0000'";
else if (type == "int8")
return "0.toByte()";
else if (type == "uint8")
return "0.toUByte()";
else if (type == "int16")
return "0.toShort()";
else if (type == "uint16")
return "0.toUShort()";
else if (type == "int32")
return "0";
else if (type == "uint32")
return "0u";
else if (type == "int64")
return "0L";
else if (type == "uint64")
return "0uL";
else if (type == "float")
return "0.0f";
else if (type == "double")
return "0.0";
else if (type == "decimal")
return "BigDecimal.valueOf(0L)";
else if (type == "string")
return "\"\"";
else if (type == "timestamp")
return "Instant.EPOCH";
else if (type == "uuid")
return "fbe.UUIDGenerator.nil()";
return type + "()";
}
std::string GeneratorKotlin::ConvertDefault(const StructField& field)
{
if (field.value)
return ConvertConstant(*field.type, *field.value, field.optional);
if (field.array)
if (field.optional)
return "arrayOfNulls<" + ConvertTypeName(*field.type, field.optional) + ">(" + std::to_string(field.N) + ")";
else
return "Array(" + std::to_string(field.N) + ") { " + ConvertDefault(*field.type) + " }";
else if (field.vector || field.list || field.set || field.map || field.hash)
return ConvertTypeName(field, true) + "()";
else if (field.optional)
return "null";
else if (!IsKnownType(*field.type))
return ConvertTypeName(field, true) + "()";
return ConvertDefault(*field.type);
}
std::string GeneratorKotlin::ConvertOutputStreamType(const std::string& type, const std::string& name, bool optional)
{
std::string opt = optional ? "!!" : "";
if (type == "bool")
return ".append(if (" + name + opt + ") \"true\" else \"false\")";
else if (type == "bytes")
return ".append(\"bytes[\").append(" + name + opt + ".size).append(\"]\")";
else if ((type == "char") || (type == "wchar"))
return ".append(\"'\").append(" + name + opt + ").append(\"'\")";
else if ((type == "string") || (type == "uuid"))
return ".append(\"\\\"\").append(" + name + opt + ").append(\"\\\"\")";
else if (type == "timestamp")
return ".append(" + name + opt + ".epochSecond * 1000000000 + " + name + opt + ".nano)";
else
return ".append(" + name + opt + ")";
}
std::string GeneratorKotlin::ConvertOutputStreamValue(const std::string& type, const std::string& name, bool optional, bool separate, bool nullable)
{
std::string comma = separate ? ".append(if (first) \"\" else \",\")" : "";
if (optional)
return "if (" + name + " != null) sb" + comma + ConvertOutputStreamType(type, name, nullable) + "; else sb" + comma + ".append(\"null\")";
else
return "sb" + comma + ConvertOutputStreamType(type, name, false);
}
} // namespace FBE
| [
"chronoxor@gmail.com"
] | chronoxor@gmail.com |
c4f5ae279d7ed47a9030caec289db1380b5754c2 | f1ba69d2123288aa08758b750f0514eff459643d | /MENUAREA.CPP | 4e8293a93ff600452293cfac3eb5f29e48787e35 | [] | no_license | galileoguzman/CONSOLE_Dummies | 471894be59169334d5b531813bb35287d5c60d5e | 1457bd6147a425de01e720ef3a50a7ac6996dd0d | refs/heads/master | 2021-01-10T11:13:20.232515 | 2016-02-11T06:26:18 | 2016-02-11T06:26:18 | 51,498,034 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,517 | cpp | #include<stdio.h>
#include<conio.h>
float triangulo(int,int);
float cuadrado(int);
float trapecio(int,int,int);
float esfera(int);
float hexagono(int,int);
float hexagono(int peri, int apo)
{
float areahexa;
areahexa=(peri*apo)/2;
return(areahexa);
}
float esfera(int r)
{
float areaesfe;
areaesfe=(r*r*3.1416)*4;
return(areaesfe);
}
float trapecio(int bma,int bme,int h)
{
float areatra;
areatra=(bma+bme*h)/2;
return(areatra);
}
float triangulo(int b,int a)
{
float area;
area=(b*a)/2;
return(area);
}
float cuadrado(int l)
{
float areacu;
areacu=l*l;
return(areacu);
}
main()
{
clrscr();
int base,altura,m,opcion,alt,bama,bame,radio,perimetro,apotema;
float resultado,resultadocu,atra,aesf,ahex;
textcolor(210);
cprintf("\n\n\t\t\t.......MENU.......\t\t\t");
textcolor(10);
cprintf("\n\t1.TRIANGULO\t\t\t\n");
cprintf("\n\t2.CUADRADO\t\t\t\t\n");
cprintf("\n\t3.TRAPECIO\t\t\t\t\n");
cprintf("\n\t4.ESFERA\t\t\t\t\n");
cprintf("\n\t5.HEXAGONO\t\t\t\t\n");
cprintf("\n\t6.EXIT\t\t\t\t\n");
cprintf("\tSELECCIONE UNA OPCION\n");
scanf("%d",&opcion);
textcolor(5);
switch(opcion)
{
case 1:
cprintf("dame la base\n");
scanf("%d",&base);
cprintf("dame la altura\n");
scanf("%d",&altura);
resultado=triangulo(base,altura);
printf("\n\t\tAREA: %f",resultado);
break;
case 2:
cprintf("dame el lado \n");
scanf("%d",&m);
resultadocu=cuadrado(m);
printf("\n\tAREA: %f",resultadocu);
break;
case 3:
cprintf("dame la base mayor\n");
scanf("%d",&bama);
cprintf("dame la base menor\n");
scanf("%d",&bame);
cprintf("dame la altura del trapacio\n");
scanf("%d",&alt);
atra=trapecio(bama,bame,alt);
printf("el area del trapcio es: %f",atra);
break;
case 4:
cprintf("dame el radio\n");
scanf("%d",&radio);
aesf=esfera(radio);
printf("el area de la esfera es %f\n",aesf);
break;
case 5:
cprintf("dame el perimetro del haxagono\n");
scanf("%d",&perimetro);
cprintf("dame el apotema del hexagono\n");
scanf("%d",&apotema);
ahex=hexagono(perimetro,apotema);
printf("el area del hexagono es: %f\n",ahex);
break;
default:
cprintf("\t\tEXIT");
}
getch();
return(0);
} | [
"galileoguzman@gmail.com"
] | galileoguzman@gmail.com |
0757f5b74a207c3483462db7216df41cc2168f49 | 8e9b7e24dd10c0994fda0f74a7f94c8264ea07e2 | /FactoryMethod2/buttons/IButton.h | 558e5415a83fa8b3d620af4156fc14b3e2e1ab2f | [] | no_license | akhtyamovpavel/PatternsExample | 763ffc2be32ffb8a86d3ee521f0bf0701ac059f2 | 465f944daf6909066c9f3b6b402e73484e07dd09 | refs/heads/master | 2021-04-26T23:06:09.185411 | 2018-03-26T10:27:53 | 2018-03-26T10:27:53 | 123,931,722 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 166 | h | //
// Created by Pavel Akhtyamov on 05/03/2018.
//
#pragma once
#include <string>
class IButton {
private:
public:
virtual std::string render() const = 0;
};
| [
"akhtyamovpavel@gmail.com"
] | akhtyamovpavel@gmail.com |
08289dc60f5da993b32a9abd485c1a27105925be | 9b86ce502728c18ef985913a7b5826c087bbb176 | /Source/SmartHamsterCage/Devices/I2C/OLED/SSD1306_Adapter.cpp | 916e2d3d552c5ef9876647395fb3a417e96e2279 | [] | no_license | dpozimski/smart-hamster-cage | 68fc16f26b1b1cdc66ad8481c1818b8a44f361f1 | 74c73b987138f98e553d3184033306a09e906f26 | refs/heads/master | 2020-03-07T10:10:55.141042 | 2018-06-24T10:47:23 | 2018-06-24T10:47:23 | 127,424,888 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 89 | cpp | /*
* SSD1306_Adapter.cpp
*
* Created: 15.05.2018 19:46:35
* Author: d.pozimski
*/
| [
"damian.pozimski@esky.com"
] | damian.pozimski@esky.com |
6801a6d55adb333eebacfc2821da802911e264d7 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/5d/a25c90f6aaa056/main.cpp | 390a93ba14b824d2f4e5688e93e273efaaf79a26 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | cpp | template <typename T>
void bar(T t) {
foo(t);
}
template <typename T>
void foo(T t) {}
int main() {
bar(42);
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
087033af47e26a857182370089ac19c80ed9800e | 4dd26c981ad19ff1ee560d6af0a76d04ee4ace6f | /学生信息管理系统/Student.cpp | c4cd10164b718a0b6c056f90419a5ef39c646492 | [] | no_license | w642833823/C-Project | fd3a195270a1da74692aa5ec53a8e4a4ffa4bd20 | 3924222d6051e6c5c39083587d24085972d1f248 | refs/heads/master | 2020-12-21T12:28:05.001215 | 2014-11-18T00:32:07 | 2014-11-18T00:32:07 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,154 | cpp | #include "Student.h"
#include <iostream>
using namespace std;
void Student::Setinformation(string num,string name,string birthday,string sex,
string political_app,string phone_num,string address)
{
Num = num;
Name = name;
Birthday = birthday;
Sex = sex;
Political_appearance = political_app;
Phone_number = phone_num;
Address = address;
}
void Student::SetNum()
{
int flag,nflag = 0;
string num;
do
{
flag = 0;
if (nflag) cout<<"格式错误..Again:";
cin>>num;
for(int i = 0;i<num.length();i++)
{
if(num[i] > '9'||num[i] < '0')
{
flag = 1;
nflag++;
break;
}
}
}while(flag);
if(!flag) Num = num;
}
void Student::SetBirthday()
{
int flag,nflag = 0;
string birthday;
do
{
flag = 0;
if (nflag) cout<<"格式错误..Again:";
cin>>birthday;
for(int i = 0;i<birthday.length();i++)
{
if((birthday[i] > '9'||birthday[i] < '0')&&birthday[i]!='/')
{
flag = 1;
nflag++;
break;
}
}
}while(flag);
if(!flag) Birthday = birthday;
}
void Student::SetPhone_number()
{
int flag,nflag = 0;
string phone_number;
do
{
flag = 0;
if (nflag) cout<<"格式错误..Again:";
cin>>phone_number;
for(int i = 0;i<phone_number.length();i++)
{
if(phone_number[i] > '9'||phone_number[i] < '0')
{
flag = 1;
nflag++;
break;
}
}
}while(flag);
if(!flag) Phone_number = phone_number;
}
void Student::Numshow(int Begin,int End)
{
cout<<"序号:"<<No<<endl;
cout<<"学号";
HANDLE ohandle = GetStdHandle(STD_OUTPUT_HANDLE);
for(int i = 0;i<Begin;i++) cout<<Num[i];
SetConsoleTextAttribute(ohandle,BACKGROUND_INTENSITY); //背景高亮
for(i = Begin;i<End;i++) cout<<Num[i];
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), //恢复默认系统颜色
FOREGROUND_RED| FOREGROUND_GREEN| FOREGROUND_BLUE);
for(i = End;i<Num.length();i++) cout<<Num[i];
cout<<" "
<<"姓名:"<<Name<<" "
<<"出生日期:"<<Birthday<<" "
<<"性别:"<<Sex<<" "
<<"政治面貌:"<<Political_appearance<<endl
<<"手机号码:"<<Phone_number<<" ";
cout<<endl<<endl;
}
void Student::Addressshow(int Begin,int End)
{
cout<<"序号:"<<No<<endl
<<"学号"<<Num<<" "
<<"姓名:"<<Name<<" "
<<"出生日期:"<<Birthday<<" "
<<"性别:"<<Sex<<" "
<<"政治面貌:"<<Political_appearance<<endl
<<"手机号码:"<<Phone_number<<" ";
HANDLE ohandle = GetStdHandle(STD_OUTPUT_HANDLE);
for(int i = 0;i<Begin;i++) cout<<Address[i];
SetConsoleTextAttribute(ohandle,BACKGROUND_INTENSITY); //背景高亮
for(i = Begin;i<End;i++) cout<<Address[i];
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), //恢复默认系统颜色
FOREGROUND_RED| FOREGROUND_GREEN| FOREGROUND_BLUE);
for(i = End;i<Address.length();i++) cout<<Address[i];
cout<<endl<<endl;
}
void Student::Show() //普通方式显示信息
{
cout<<"序号:"<<No<<endl
<<"学号"<<Num<<" "
<<"姓名:"<<Name<<" "
<<"出生日期:"<<Birthday<<" "
<<"性别:"<<Sex<<" "
<<"政治面貌:"<<Political_appearance<<endl
<<"手机号码:"<<Phone_number<<" "
<<"家庭地址:"<<Address<<endl<<endl;
}
| [
"liangzengguo@163.com"
] | liangzengguo@163.com |
e5e84656db286d3dce9cca3fbbe2ff6647ca722e | d07d9b402e86ed69a83a660581ed6e75904fdc1f | /DX12 GUI/DX12 GUI.cpp | 37f3cd7853d05d210f9a18d642690bfe50ec76a9 | [] | no_license | Gofrettin/DX12-Base--DXTK- | 99620aa1488728a4b9b2d860b1306804f8876f1c | 3f757afe51fec59fc140e226b2b22235c94e682f | refs/heads/master | 2021-06-10T09:09:12.794579 | 2016-10-19T13:27:27 | 2016-10-19T13:27:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
#include "stdafx.h"
#include "DX12.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int nCmdShow)
{
static bool Debug = true;
if (Debug)
{
AllocConsole();
freopen("CONOUT$", "w+", stdout);
ShowWindow(GetConsoleWindow(), SW_SHOW);
system("color A");
}
return DX12Manager::Initialize(300, 300, 1280, 720);
}
| [
"tonyx97@hotmail.es"
] | tonyx97@hotmail.es |
295cd9428bbc6a4b1ec2fd2d144c293d229e2c72 | 6b659151b3f1861577e6d7837e53c23a1e413c66 | /sift_bam_max_cov.cpp | 203d41b08f36ac0744d9e0845fb1f0e03cadc695 | [] | no_license | GeorgescuC/utils_cpp | 256f40b0d2977fa89cab899d4c5bb52707127506 | 3ced1d554e5f1244bb87dfa1092fe7e1af31737c | refs/heads/master | 2021-06-30T13:52:03.341517 | 2020-03-18T22:19:35 | 2020-03-18T22:19:35 | 229,152,919 | 0 | 1 | null | 2021-05-04T19:55:29 | 2019-12-19T23:07:13 | C++ | UTF-8 | C++ | false | false | 9,469 | cpp |
#include <stdio.h>
// #include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <stdint.h>
#include <limits.h>
#include <map>
#include <set>
#include <utility>
#include <vector>
#include "htslib/sam.h"
#include "htslib/bgzf.h"
enum test_op {
READ_COMPRESSED = 1,
WRITE_COMPRESSED = 2,
READ_CRAM = 4,
WRITE_CRAM = 8,
WRITE_UNCOMPRESSED = 16,
};
void insert_or_increment(std::map<int32_t, int32_t> & pos_map, int32_t rpos) {
auto it = pos_map.find(rpos);
if (it != pos_map.end()) {
++(it->second);
}
else {
pos_map.insert({rpos, 1});
}
}
int main(int argc, char *argv[])
{
samFile *in; // open input alignment file
int flag = 0;
int clevel = -1; // compression level
bam_hdr_t *input_header; // alignment header
htsFile *out;
char modew[800];
int exit_code = 0;
int coverage_limit = 100;
int similar_cigar_limit = INT_MAX;
const char *out_name = "-";
int c; // for parsing input arguments
// add option to keep only "proper pairs" (both reads mapped)
// add option to run strand specificlly
// add option for BAM index loading (+ generation if needed) to be able to run each chromosome on a seperate thread
// while ((c = getopt(argc, argv, "DSIt:i:bCul:o:N:BZ:@:M")) >= 0) {
while ((c = getopt(argc, argv, "c:o:i:")) >= 0) {
switch(c) {
// case 'b': ; break;
case 'c': coverage_limit = atoi(optarg); break;
case 'o': out_name = optarg; break;
case 'i': similar_cigar_limit = atoi(optarg); break;
}
}
if (argc == optind) { // missing input file, print help
fprintf(stderr, "Usage: sift_bam_max_cov [-c value] <in.bam>|<in.bam>\n");
fprintf(stderr, "\n");
fprintf(stderr, "-c: Max coverage value.\n");
fprintf(stderr, "-o: Output file name. Default is to stdout.\n");
fprintf(stderr, "-i: Max number of reads with an identical cigar starting at the some position to keep.\n");
fprintf(stderr, "File to process.\n");
fprintf(stderr, "\n");
return (1);
}
in = sam_open(argv[optind], "r");
const htsFormat *in_format = hts_get_format(in);
// Enable multi-threading (only effective when the library was compiled with -DBGZF_MT)
// bgzf_mt(in, n_threads, 0);
if (in == NULL) {
fprintf(stderr, "Error opening \"%s\"\n", argv[optind]);
return EXIT_FAILURE;
}
input_header = sam_hdr_read(in);
if (input_header == NULL) {
fprintf(stderr, "Couldn't read header for \"%s\"\n", argv[optind]);
return EXIT_FAILURE;
}
// check that sort order (SO) flag is set
std::string tmp_text(input_header->text, input_header->l_text);
size_t start_pos = tmp_text.find("@HD");
if (start_pos == std::string::npos) {
fprintf(stderr, "Error, missing @HD field in header.\n");
return EXIT_FAILURE;
}
size_t end_pos = tmp_text.find("\n", start_pos);
if (end_pos == std::string::npos) {
end_pos = tmp_text.length();
}
tmp_text = tmp_text.substr(start_pos, end_pos - start_pos);
start_pos = tmp_text.find("SO:");
if (start_pos == std::string::npos) {
fprintf(stderr, "Error, missing SO field in @HD header line.\n");
return EXIT_FAILURE;
}
tmp_text.find("coordinate", start_pos);
if (start_pos == std::string::npos) {
fprintf(stderr, "Error, file is not coordinate sorted.\n");
return EXIT_FAILURE;
}
strcpy(modew, "w");
if (clevel >= 0 && clevel <= 9) sprintf(modew + 1, "%d", clevel);
if (flag & WRITE_CRAM) strcat(modew, "c");
else if (flag & WRITE_COMPRESSED) strcat(modew, "b");
else if (flag & WRITE_UNCOMPRESSED) strcat(modew, "bu");
// out = hts_open(out_name, modew);
out = hts_open_format(out_name, modew, in_format);
if (out == NULL) {
fprintf(stderr, "Error opening standard output\n");
return EXIT_FAILURE;
}
if (sam_hdr_write(out, input_header) < 0) { // write header from input to output
fprintf(stderr, "Error writing output header.\n");
exit_code = 1;
}
// map for start/end positions of alignments that are already selected
std::map<int32_t, int32_t> starts;
std::map<int32_t, int32_t> ends;
// keep a set of mate reads we decided to keep when encountering the first read
std::set<std::string> mates_to_keep[input_header->n_targets];
std::map<std::vector<uint32_t>, int> current_cigar_counts;
bam1_t *aln = bam_init1(); //initialize an alignment
int32_t current_rname_index = 0; // index compared to header: input_header->target_name[current_rname_index]
int32_t current_coverage = 0;
int32_t current_pos = 0;
while(sam_read1(in, input_header, aln) > 0) {
if (current_rname_index != aln->core.tid) {
// should have finished writing reads from current_rname_index contig, so can just reset vars
current_coverage = 0;
starts.clear();
ends.clear();
mates_to_keep[current_rname_index].clear();
fprintf(stdout, "Done with chr %s.\n", input_header->target_name[current_rname_index]);
current_rname_index = aln->core.tid;
}
// make sure the read is mapped
if ((aln->core.flag & BAM_FUNMAP) != 0)
continue;
// make sure the alignment is not a secondary alignment or a supplementary alignment
if ((aln->core.flag & BAM_FSECONDARY) != 0 or (aln->core.flag & BAM_FSUPPLEMENTARY) != 0)
continue;
if (current_pos != aln->core.pos) { // left most position, does NOT need adjustment for reverse strand if summing their coverage
// add the range we want and then erase all the matching entries at once rather than 1 by 1
auto it = starts.begin();
if (it->first <= aln->core.pos) {
for (; it != starts.end(); ++it) {
if (it->first <= aln->core.pos) { // or equal because already selected reads take priority in coverage
current_coverage += it->second;
}
else break;
}
starts.erase(starts.begin(), it);
}
it = ends.begin();
if (it->first <= aln->core.pos) {
for (; it != ends.end(); ++it) {
if (it->first <= aln->core.pos) { // or equal because already selected reads take priority in coverage
current_coverage -= it->second;
}
else break;
}
ends.erase(ends.begin(), it);
}
current_cigar_counts.clear();
current_pos = aln->core.pos;
}
// if we are below the max coverage or the read has already been selected to keep through its pair
if ((current_coverage < coverage_limit) ||
(mates_to_keep[aln->core.tid].find(bam_get_qname(aln)) != mates_to_keep[aln->core.tid].end())) {
// get cigar
uint32_t *cigar = bam_get_cigar(aln);
if (similar_cigar_limit < coverage_limit) {
std::vector<uint32_t> tmp_cigar(aln->core.n_cigar);
std::copy(cigar, cigar + aln->core.n_cigar, tmp_cigar.begin());
auto it = current_cigar_counts.find(tmp_cigar);
if (it != current_cigar_counts.end()) { // found
if (it->second < similar_cigar_limit) {
it->second++;
}
else {
continue;
}
}
else {
current_cigar_counts.emplace(std::move(tmp_cigar), 1);
}
}
int32_t rpos = aln->core.pos; // update position on the ref with cigar
for (uint32_t k = 0; k < aln->core.n_cigar; ++k) {
if ((bam_cigar_type(bam_cigar_op(cigar[k]))&2)) { // consumes reference
if (bam_cigar_op(cigar[k]) == BAM_CREF_SKIP) {
insert_or_increment(ends, rpos);
rpos += bam_cigar_oplen(cigar[k]);
insert_or_increment(starts, rpos);
}
else {
rpos += bam_cigar_oplen(cigar[k]);
}
}
}
insert_or_increment(ends, rpos);
++current_coverage;
// save pair mate in their target reference id if not already passed (and cleared)
if (aln->core.mtid >= current_rname_index) {
mates_to_keep[aln->core.mtid].insert(bam_get_qname(aln));
}
// output the alignment
if (sam_write1(out, input_header, aln) == -1) {
fprintf(stderr, "Could not write selected record \"%s\"\n", bam_get_qname(aln));
return EXIT_FAILURE;
}
}
}
int ret;
ret = hts_close(in);
if (ret < 0) {
fprintf(stderr, "Error closing input.\n");
exit_code = EXIT_FAILURE;
}
ret = hts_close(out);
if (ret < 0) {
fprintf(stderr, "Error closing output.\n");
exit_code = EXIT_FAILURE;
}
return exit_code;
} | [
"GeorgescuC@users.noreply.github.com"
] | GeorgescuC@users.noreply.github.com |
79c3d8f7f8549265b188284b980dc2899688f64c | 556c1721f951639feafb448fbca702960b6c9e29 | /AppProjects/MyApplication/app/src/main/cpp/native-lib.cpp | ab5321d012bdd334da253170aed97b4ea86b26ab | [] | no_license | lokajits97/Party-Settler | 4aded20c676471073acd9772147887ebd46cc446 | def1a59c8f12fb346201d456deb2e19058966faf | refs/heads/master | 2020-03-28T00:04:36.304867 | 2018-09-04T16:09:55 | 2018-09-04T16:09:55 | 147,373,338 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cpp | #include <jni.h>
#include <string>
extern "C"
JNIEXPORT jstring JNICALL
Java_com_example_lokajit_myapplication_myIntake_stringFromJNI(
JNIEnv* env,
jobject /* this */) {
std::string hello = "Hello from C++";
return env->NewStringUTF(hello.c_str());
}
| [
"lokajits97@gmail.com"
] | lokajits97@gmail.com |
3d2ffd915d9efc6bd781090ea480d216a318cb4b | 418aa6c4486e255f482b6c9bee12a08cda829503 | /External/sfml/Window/SensorManager.hpp | db05bc4627dc8d4238a0e81c26ed6ff4ab4041c3 | [
"MIT"
] | permissive | jjuiddong/Common | b21c9a98474fc45aa30b316808498381c2030ad3 | 3097b60988464000e2885a07cdd6e433e43de386 | refs/heads/master | 2023-08-31T07:35:31.425468 | 2023-08-29T11:38:29 | 2023-08-29T11:38:29 | 77,737,521 | 3 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 4,703 | hpp | ////////////////////////////////////////////////////////////
//
// SFML - Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#ifndef SFML_SENSORMANAGER_HPP
#define SFML_SENSORMANAGER_HPP
////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include "Sensor.hpp"
#include "SensorImpl.hpp"
#include "../System/NonCopyable.hpp"
namespace sf
{
namespace priv
{
////////////////////////////////////////////////////////////
/// \brief Global sensor manager
///
////////////////////////////////////////////////////////////
class SensorManager : NonCopyable
{
public:
////////////////////////////////////////////////////////////
/// \brief Get the global unique instance of the manager
///
/// \return Unique instance of the sensor manager
///
////////////////////////////////////////////////////////////
static SensorManager& getInstance();
////////////////////////////////////////////////////////////
/// \brief Check if a sensor is available on the underlying platform
///
/// \param sensor Sensor to check
///
/// \return True if the sensor is available, false otherwise
///
////////////////////////////////////////////////////////////
bool isAvailable(Sensor::Type sensor);
////////////////////////////////////////////////////////////
/// \brief Enable or disable a sensor
///
/// \param sensor Sensor to modify
/// \param enabled Whether it should be enabled or not
///
////////////////////////////////////////////////////////////
void setEnabled(Sensor::Type sensor, bool enabled);
////////////////////////////////////////////////////////////
/// \brief Check if a sensor is enabled
///
/// \param sensor Sensor to check
///
/// \return True if the sensor is enabled, false otherwise
///
////////////////////////////////////////////////////////////
bool isEnabled(Sensor::Type sensor) const;
////////////////////////////////////////////////////////////
/// \brief Get the current value of a sensor
///
/// \param sensor Sensor to read
///
/// \return Current value of the sensor
///
////////////////////////////////////////////////////////////
std::array<float, 3> getValue(Sensor::Type sensor) const;
////////////////////////////////////////////////////////////
/// \brief Update the state of all the sensors
///
////////////////////////////////////////////////////////////
void update();
private:
////////////////////////////////////////////////////////////
/// \brief Default constructor
///
////////////////////////////////////////////////////////////
SensorManager();
////////////////////////////////////////////////////////////
/// \brief Destructor
///
////////////////////////////////////////////////////////////
~SensorManager();
////////////////////////////////////////////////////////////
/// \brief Sensor information and state
///
////////////////////////////////////////////////////////////
struct Item
{
bool available; ///< Is the sensor available on this device?
bool enabled; ///< Current enable state of the sensor
SensorImpl sensor; ///< Sensor implementation
std::array<float, 3> value; ///< The current sensor value
};
////////////////////////////////////////////////////////////
// Member data
////////////////////////////////////////////////////////////
Item m_sensors[Sensor::Count]; ///< Sensors information and state
};
} // namespace priv
} // namespace sf
#endif // SFML_SENSORMANAGER_HPP
| [
"jjuiddong@gmail.com"
] | jjuiddong@gmail.com |
a425b509857c63adb784141bf94c99596842f3fd | ea214c93202f76dd45d25cd75bb3abd7c588de97 | /leptjson/test.cc | 92027c69efeab33dc1758f347febd6485051061e | [] | no_license | zhouchuyi/leptfolly | e216f74f551d1e57c0b26916816b2a50685b1eef | a021690a4e92ed6e643baedb9d441eb7723d3194 | refs/heads/master | 2020-06-28T20:32:40.267968 | 2019-09-23T08:31:22 | 2019-09-23T08:31:22 | 200,334,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 152 | cc | #include<iostream>
int main(int argc, char const *argv[])
{
const char* str="\n";
if(str[0]=='\\')
std::cout<<*(str+1);
return 0;
}
| [
"237314511@qq.com"
] | 237314511@qq.com |
7686cf92da5fa6adf8d1433545db8d9fb69d8e99 | 0d5e63dfc10db869ba149f07e915326a542e318d | /process_simulator.cpp | ebfa1e0a61cb07f6a429502bc1704856b333287c | [] | no_license | xiaoguozhi/cpu_scheduler | 7cb6fbe14f857597919ec89d61bfe81fdf4efdd0 | 07f8aedb7c06b00d74cb18368e604e3c20b8f808 | refs/heads/master | 2020-04-02T05:28:36.212091 | 2012-12-31T19:56:27 | 2012-12-31T19:56:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,334 | cpp | //Thomas Zaorski
//RIN: 660747712
//EMAIL: zaorst@rpi.edu
#include <iostream>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <cmath>
#include <algorithm>
using namespace std;
//Initilizes variables related to statistical information
int context_switch = 14;
double total_turnaround = 0.0;
double total_wait = 0.0;
double total_initial = 0.0;
double max_turnaround = 0.0;
double min_turnaround = 5000.0;
double max_wait;
double min_wait;
double max_initial;
double min_initial;
//Creates Process class
class process {
private:
int arrival_time;
int burst_time;
int premp_time;
int burst_left;
bool been_seen;
int initial_wait;
int total_wait;
int priority;
int pid;
public:
process(int burst, int time, int id, int importance);
void set_arrival(int time);
void set_pid(int num);
int get_arrival();
int get_burst();
int get_priority();
int get_burst_left();
void dec_burst();
int get_initial_wait();
int get_total_wait();
void set_premp_time(int time);
void add_wait(int time);
bool get_seen();
void seen(int time);
int get_pid();
};
process::process(int burst, int time, int id, int importance)
{
pid = id;
burst_time = burst;
burst_left = burst;
arrival_time = time;
been_seen = false;
priority = importance;
initial_wait = 0;
total_wait = 0;
}
void process::set_pid(int num)
{
pid = num;
}
bool process::get_seen()
{
return been_seen;
}
int process::get_priority()
{
return priority;
}
int process::get_burst()
{
return burst_time;
}
int process::get_pid()
{
return pid;
}
void process::set_arrival(int time)
{
arrival_time = time;
}
int process::get_arrival()
{
return arrival_time;
}
int process::get_burst_left()
{
return burst_left;
}
void process::dec_burst()
{
burst_left = burst_left - 1;
}
int process::get_initial_wait()
{
return initial_wait;
}
int process::get_total_wait()
{
return total_wait;
}
void process::set_premp_time(int time)
{
premp_time = time;
}
void process::add_wait(int time)
{
total_wait = total_wait + time;
}
void process::seen(int time)
{
been_seen = true;
initial_wait = time;
total_wait = time;
}
bool sorter(process a, process b)
{
return a.get_burst() < b.get_burst();
}
bool sorter2(process a, process b)
{
return a.get_priority() < b.get_priority();
}
bool sorter3(process a, process b)
{
return a.get_arrival() < b.get_arrival();
}
//Prints statistics
void statistics(int num_processes)
{
cout << "Turnaround time: min ";
printf("%.3f", min_turnaround);
cout << "ms";
cout << "; avg ";
printf("%.3f", total_turnaround/num_processes);
cout << "ms";
cout << "; max ";
printf("%.3f", max_turnaround);
cout << "ms" << endl;
cout << "Initial wait time: min ";
printf("%.3f", min_initial);
cout << "ms";
cout << "; avg ";
printf("%.3f", total_initial/num_processes);
cout << "ms";
cout << "; max ";
printf("%.3f", max_initial);
cout << "ms" << endl;
cout << "Total wait time: min ";
printf("%.3f", min_wait);
cout << "ms";
cout << "; avg ";
printf("%.3f", total_wait/num_processes);
cout << "ms";
cout << "; max ";
printf("%.3f", max_wait);
cout << "ms" << endl;
total_turnaround = 0.0;
total_wait = 0.0;
total_initial = 0.0;
max_wait = 0.0;
min_wait = num_processes * 5000.0;
max_initial = 0.0;
min_initial = num_processes * 5000.0;
max_turnaround = 0.0;
min_turnaround = 5000.0 * num_processes;
cout << endl;
}
//Simulates first come first serve
void first_come_first_serve(vector <process> processes, int num_processes)
{
int num_completed = 0;
int clock = 0;
int last_pid = 0;
vector <process> queue;
bool cswitch = false;
unsigned int index = processes.size();
//Function runs until it detects it has completed every process
while(num_completed != num_processes)
{
index = processes.size();
for(unsigned int i = 0; i < index; i++)
{
if (processes[i].get_arrival() <= clock)
{
queue.push_back(processes[i]);
cout << "[time " << processes[i].get_arrival() << "ms] Process " << processes[i].get_pid() << " created (requires " << processes[i].get_burst() << "ms CPU time)" << endl;
processes.erase(processes.begin() + i);
index--;
i--;
}
}
if (queue.size() != 0)
{
if (cswitch)
{
cout << "[time " << clock - 7 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + 7;
cswitch = false;
}
if (queue[0].get_seen() == false)
{
//The initials will change in non zero arrival times
int arriv = clock - queue[0].get_arrival();
queue[0].seen(arriv);
total_initial += arriv;
if (arriv < min_initial)
min_initial = arriv;
if (arriv > max_initial)
max_initial = arriv;
//total_wait += clock;
cout << "[time " << clock << "ms] Process " << queue[0].get_pid() << " accessed CPU for the first time (initial wait time " << queue[0].get_initial_wait() << "ms)" << endl;
}
queue[0].dec_burst();
if (queue[0].get_burst_left() == 0)
{
int fwait = ((clock + 1) - queue[0].get_burst() - queue[0].get_arrival());
cout << "[time " << clock + 1 << "ms] Process " << queue[0].get_pid() << " completed its CPU burst (turnaround time " << ((clock + 1) - queue[0].get_arrival()) << "ms, initial wait time " << queue[0].get_initial_wait() << "ms, total wait time " << fwait << "ms)" << endl;
last_pid = queue[0].get_pid();
int turn = ((clock + 1) - queue[0].get_arrival());
total_turnaround += turn;
total_wait += fwait;
if (fwait < min_wait)
min_wait = fwait;
if (fwait > max_wait)
max_wait = fwait;
if (turn < min_turnaround)
min_turnaround = turn;
if (turn > max_turnaround)
max_turnaround = turn;
queue.erase(queue.begin());
num_completed++;
if (queue.size() != 0)
{
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
else
{
cswitch = true;
//Releases finished process
clock = clock + 7;
}
}
}
clock++;
}
}
//Simulates SJF non-preemptive
void shortest_job_first(vector <process> processes, int num_processes)
{
int num_completed = 0;
int clock = 0;
int last_pid = 0;
vector <process> queue;
vector <process> temp;
bool cswitch = false;
unsigned int index = processes.size();
while(num_completed != num_processes)
{
index = processes.size();
for(unsigned int i = 0; i < index; i++)
{
if (processes[i].get_arrival() <= clock)
{
temp.push_back(processes[i]);
cout << "[time " << clock << "ms] Process " << processes[i].get_pid() << " created (requires " << processes[i].get_burst() << "ms CPU time)" << endl;
processes.erase(processes.begin());
index--;
i--;
}
}
sort(temp.begin(), temp.end(), sorter);
for (unsigned int i = 0; i < temp.size(); i++)
{
queue.push_back(temp[i]);
}
temp.clear();
//Sorts the processes by burst time length, ignores the currently running process because it is non-preemptive
sort(queue.begin() + 1, queue.end(), sorter);
if (queue.size() != 0)
{
if (cswitch)
{
cout << "[time " << clock - 7 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + 7;
cswitch = false;
}
if (queue[0].get_seen() == false)
{
//Statistical info
int arriv = clock - queue[0].get_arrival();
queue[0].seen(arriv);
total_initial += arriv;
if (arriv < min_initial)
min_initial = arriv;
if (arriv > max_initial)
max_initial = arriv;
cout << "[time " << clock << "ms] Process " << queue[0].get_pid() << " accessed CPU for the first time (initial wait time " << queue[0].get_initial_wait() << "ms)" << endl;
}
queue[0].dec_burst();
if (queue[0].get_burst_left() == 0)
{
int fwait = ((clock + 1) - queue[0].get_burst() - queue[0].get_arrival());
cout << "[time " << clock + 1 << "ms] Process " << queue[0].get_pid() << " completed its CPU burst (turnaround time " << ((clock + 1) - queue[0].get_arrival()) << "ms, initial wait time " << queue[0].get_initial_wait() << "ms, total wait time " << fwait << "ms)" << endl;
last_pid = queue[0].get_pid();
int turn = ((clock + 1) - queue[0].get_arrival());
total_turnaround += turn;
total_wait += fwait;
if (fwait < min_wait)
min_wait = fwait;
if (fwait > max_wait)
max_wait = fwait;
if (turn < min_turnaround)
min_turnaround = turn;
if (turn > max_turnaround)
max_turnaround = turn;
queue.erase(queue.begin());
num_completed++;
if (queue.size() != 0)
{
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
else
{
cswitch = true;
//Releases finished process
clock = clock + 7;
}
}
}
clock++;
}
}
//Simulates Shortest Job remaining (preemptive SJF)
void shortest_job_remaining(vector <process> processes, int num_processes)
{
int num_completed = 0;
int clock = 0;
int last_pid = 0;
vector <process> queue;
bool cswitch = false;
unsigned int index = processes.size();
while(num_completed != num_processes)
{
index = processes.size();
for(unsigned int i = 0; i < index; i++)
{
if (processes[i].get_arrival() <= clock)
{
cout << "[time " << clock << "ms] Process " << processes[i].get_pid() << " created (requires " << processes[i].get_burst() << "ms CPU time)" << endl;
if (queue.size() != 0 && processes[i].get_burst() < queue[0].get_burst() && queue[0].get_burst_left() != queue[0].get_burst())
{
//Context switch on preemption
cout << "[time " << clock << "ms] Context switch (swapped out process " << queue[0].get_pid() << " for process " << processes[i].get_pid() << ")" << endl;
clock = clock + 14;
}
queue.push_back(processes[i]);
sort(queue.begin(), queue.end(), sorter);
processes.erase(processes.begin());
index--;
i--;
}
}
if (queue.size() != 0)
{
if (cswitch)
{
cout << "[time " << clock - 7 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + 7;
cswitch = false;
}
if (queue[0].get_seen() == false)
{
int arriv = clock - queue[0].get_arrival();
queue[0].seen(arriv);
total_initial += arriv;
if (arriv < min_initial)
min_initial = arriv;
if (arriv > max_initial)
max_initial = arriv;
cout << "[time " << clock << "ms] Process " << queue[0].get_pid() << " accessed CPU for the first time (initial wait time " << queue[0].get_initial_wait() << "ms)" << endl;
}
queue[0].dec_burst();
if (queue[0].get_burst_left() == 0)
{
int fwait = ((clock + 1) - queue[0].get_burst() - queue[0].get_arrival());
cout << "[time " << clock + 1 << "ms] Process " << queue[0].get_pid() << " completed its CPU burst (turnaround time " << ((clock + 1) - queue[0].get_arrival()) << "ms, initial wait time " << queue[0].get_initial_wait() << "ms, total wait time " << fwait << "ms)" << endl;
last_pid = queue[0].get_pid();
int turn = ((clock + 1) - queue[0].get_arrival());
total_turnaround += turn;
total_wait += fwait;
if (fwait < min_wait)
min_wait = fwait;
if (fwait > max_wait)
max_wait = fwait;
if (turn < min_turnaround)
min_turnaround = turn;
if (turn > max_turnaround)
max_turnaround = turn;
queue.erase(queue.begin());
num_completed++;
if (queue.size() != 0)
{
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
else
{
cswitch = true;
//Releases finished process
clock = clock + 7;
}
}
}
clock++;
}
}
//Simulates Round Robin Scheduling
void round_robin(vector <process> processes, int num_processes)
{
int num_completed = 0;
int clock = 0;
int last_pid = 0;
//Sets the timeslice size
int timeslice = 200;
int current_slice = 0;
vector <process> queue;
unsigned int index = processes.size();
bool cswitch = false;
while(num_completed != num_processes)
{
for(unsigned int i = 0; i < index; i++)
{
if (processes[i].get_arrival() <= clock)
{
queue.push_back(processes[i]);
cout << "[time " << clock << "ms] Process " << processes[i].get_pid() << " created (requires " << processes[i].get_burst() << "ms CPU time)" << endl;
processes.erase(processes.begin());
index--;
i--;
}
}
if (queue.size() != 0)
{
if (cswitch)
{
cout << "[time " << clock - 7 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + 7;
cswitch = false;
}
if (queue[0].get_seen() == false)
{
int initial = (clock - queue[0].get_arrival());
queue[0].seen(initial);
total_initial += initial;
if (initial < min_initial)
min_initial = initial;
if (initial > max_initial)
max_initial = initial;
cout << "[time " << clock << "ms] Process " << queue[0].get_pid() << " accessed CPU for the first time (initial wait time " << queue[0].get_initial_wait() << "ms)" << endl;
}
queue[0].dec_burst();
current_slice++;
if (queue[0].get_burst_left() == 0)
{
int total_wait_p = ((clock + 1) - queue[0].get_arrival() - queue[0].get_burst());
cout << "[time " << clock + 1 << "ms] Process " << queue[0].get_pid() << " completed its CPU burst (turnaround time " << ((clock + 1) - queue[0].get_arrival()) << "ms, initial wait time " << queue[0].get_initial_wait() << "ms, total wait time " << total_wait_p << "ms)" << endl;
last_pid = queue[0].get_pid();
int turnaround = ((clock + 1) - queue[0].get_arrival());
total_turnaround += turnaround;
total_wait += total_wait_p;
if (total_wait_p < min_wait)
min_wait = total_wait_p;
if (total_wait_p > max_wait)
max_wait = total_wait_p;
if ((turnaround) < min_turnaround)
min_turnaround = turnaround;
if ((turnaround) > max_turnaround)
max_turnaround = turnaround;
queue.erase(queue.begin());
num_completed++;
if (queue.size() != 0)
{
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
else
{
cswitch = true;
//Releases finished process
clock = clock + 7;
}
current_slice = 0;
}
else if (current_slice == timeslice) //When timeslice is over
{
last_pid = queue[0].get_pid();
queue.push_back(queue[0]);
queue.erase(queue.begin());
current_slice = 0;
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
}
clock++;
}
}
//Simulates priority scheduling
void priority(vector <process> processes, int num_processes)
{
int num_completed = 0;
int clock = 0;
int last_pid = 0;
//Sets the timeslice size
int timeslice = 200;
int current_slice = 0;
vector <process> queue;
vector <process> temp_queue;
unsigned int index = processes.size();
unsigned int index2;
bool cswitch = false;
int most_priority = 6;
while(num_completed != num_processes)
{
for(unsigned int i = 0; i < index; i++)
{
if (processes[i].get_arrival() <= clock)
{
temp_queue.push_back(processes[i]);
index2 = temp_queue.size();
cout << "[time " << clock << "ms] Process " << processes[i].get_pid() << " created (requires " << processes[i].get_burst() << "ms CPU time Priority: " << processes[i].get_priority() << ")" << endl;
sort(temp_queue.begin(), temp_queue.end(), sorter2);
//Finds highest priority present
if(processes[i].get_priority() < most_priority)
most_priority = processes[i].get_priority();
processes.erase(processes.begin());
index--;
i--;
}
}
index2 = temp_queue.size();
for(unsigned int i = 0; i < index2; i++)
{
if (temp_queue[i].get_priority() == most_priority)
{
if (queue.size() != 0 && temp_queue[i].get_priority() < queue[0].get_priority())
{
cout << "[time " << clock << "ms] Context switch (swapped out process " << queue[0].get_pid() << " for process " << temp_queue[i].get_pid() << ")" << endl;
clock = clock + 14;
for (unsigned int x = 0; x < queue.size(); x++)
{
temp_queue.push_back(queue[x]);
}
queue.clear();
}
queue.push_back(temp_queue[i]);
temp_queue.erase(temp_queue.begin());
index2--;
i--;
}
}
//Uses round robin for multiple processes with same highest priority
if (queue.size() != 0 && queue.size() > 1)
{
if (cswitch)
{
cout << "[time " << clock - 7 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + 7;
cswitch = false;
}
if (queue[0].get_seen() == false)
{
//The initials will change in non zero arrival times
int initial = (clock - queue[0].get_arrival());
queue[0].seen(initial);
total_initial += initial;
if (initial < min_initial)
min_initial = initial;
if (initial > max_initial)
max_initial = initial;
//total_wait += initial;
cout << "[time " << clock << "ms] Process " << queue[0].get_pid() << " accessed CPU for the first time (initial wait time " << queue[0].get_initial_wait() << "ms)" << endl;
}
queue[0].dec_burst();
current_slice++;
if (queue[0].get_burst_left() == 0)
{
int total_wait_p = ((clock + 1) - queue[0].get_arrival() - queue[0].get_burst());
cout << "[time " << clock + 1 << "ms] Process " << queue[0].get_pid() << " completed its CPU burst (turnaround time " << ((clock + 1) - queue[0].get_arrival()) << "ms, initial wait time " << queue[0].get_initial_wait() << "ms, total wait time " << total_wait_p << "ms)" << endl;
last_pid = queue[0].get_pid();
int turnaround = ((clock + 1) - queue[0].get_arrival());
total_turnaround += turnaround;
total_wait += total_wait_p;
if (total_wait_p < min_wait)
min_wait = total_wait_p;
if (total_wait_p > max_wait)
max_wait = total_wait_p;
if ((turnaround) < min_turnaround)
min_turnaround = turnaround;
if ((turnaround) > max_turnaround)
max_turnaround = turnaround;
queue.erase(queue.begin());
num_completed++;
if (queue.size() != 0)
{
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
else
{
cswitch = true;
//Releases finished process
clock = clock + 7;
if (temp_queue.size() != 0)
most_priority = temp_queue[0].get_priority();
else
most_priority++;
}
current_slice = 0;
}
else if (current_slice == timeslice)
{
last_pid = queue[0].get_pid();
queue.push_back(queue[0]);
queue.erase(queue.begin());
current_slice = 0;
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
}
else if (queue.size() == 1) //Process runs unhindered when theres only 1 process of highest priority
{
if (cswitch)
{
cout << "[time " << clock - 7 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + 7;
cswitch = false;
}
if (queue[0].get_seen() == false)
{
//The initials will change in non zero arrival times
int arriv = clock - queue[0].get_arrival();
queue[0].seen(arriv);
total_initial += arriv;
if (arriv < min_initial)
min_initial = arriv;
if (arriv > max_initial)
max_initial = arriv;
//total_wait += clock;
cout << "[time " << clock << "ms] Process " << queue[0].get_pid() << " accessed CPU for the first time (initial wait time " << queue[0].get_initial_wait() << "ms)" << endl;
}
queue[0].dec_burst();
if (queue[0].get_burst_left() == 0)
{
int fwait = ((clock + 1) - queue[0].get_burst() - queue[0].get_arrival());
cout << "[time " << clock + 1 << "ms] Process " << queue[0].get_pid() << " completed its CPU burst (turnaround time " << ((clock + 1) - queue[0].get_arrival()) << "ms, initial wait time " << queue[0].get_initial_wait() << "ms, total wait time " << fwait << "ms)" << endl;
last_pid = queue[0].get_pid();
int turn = ((clock + 1) - queue[0].get_arrival());
total_turnaround += turn;
total_wait += fwait;
if (fwait < min_wait)
min_wait = fwait;
if (fwait > max_wait)
max_wait = fwait;
if (turn < min_turnaround)
min_turnaround = turn;
if (turn > max_turnaround)
max_turnaround = turn;
queue.erase(queue.begin());
num_completed++;
if (queue.size() != 0)
{
cout << "[time " << clock + 1 << "ms] Context switch (swapped out process " << last_pid << " for process " << queue[0].get_pid() << ")" << endl;
clock = clock + context_switch;
}
else
{
cswitch = true;
//Releases finished process
clock = clock + 7;
if (temp_queue.size() != 0)
most_priority = temp_queue[0].get_priority();
else
most_priority++;
}
}
}
else if (queue.size() == 0)
{
if (temp_queue.size() != 0)
most_priority = temp_queue[0].get_priority();
else
most_priority++;
}
clock++;
}
}
int main()
{
//Sets number of processes
int num_processes = 20;
srand((unsigned)time(0));
int random_burst;
int importance;
//vector will serve as the ready queue
vector <process> processes;
//80% of processes have a semi random arrival time determined by exponential distribution
//20% of processes have 0 arrival time
int num_rand = num_processes * .8;
int num_zero = num_processes - num_rand;
//Creates processes with zero arrival time
for (int i = 0; i < num_zero; i++)
{
random_burst = (rand()%3500)+500;
importance = (rand()%5);
process temp(random_burst, 0, i+1, importance);
processes.push_back(temp);
}
//Creates processes with non zero arrival time
for(int i = 0; i < num_rand; i++)
{
random_burst = (rand()%3500)+500;
importance = (rand()%5);
double lambda = 0.001;
double r = ((double) rand()/(RAND_MAX));
double x = -(log(r)/lambda);
if ( x > 8000 ) { i--; continue; }
process temp(random_burst, (int)x, (num_zero + i+1), importance);
processes.push_back(temp);
}
//Sorts processes by arrival time
sort(processes.begin(), processes.end(), sorter3);
//Assigns pids 1 - n based on arrival time. Makes the output easier to follow
for (unsigned int i = 0; i < processes.size(); i++)
{
processes[i].set_pid(i+1);
}
//Sets variables for statistical information
max_wait = 0.0;
min_wait = num_processes * 5000.0;
max_initial = 0.0;
min_initial = num_processes * 5000.0;
cout << "First Come First Serve:" << endl << endl;
//FCFS
first_come_first_serve(processes, num_processes);
cout << endl;
//Statistics
statistics(num_processes);
cout << "Shortest Job First:" << endl << endl;
//Non-Preemptive SJF
shortest_job_first(processes, num_processes);
cout << endl;
statistics(num_processes);
cout << "Shortest Job Remaining or Preemptive Shortest Job First:" << endl << endl;
//Shortest_job_remaining or preemptive sjf
shortest_job_remaining(processes, num_processes);
cout << endl;
statistics(num_processes);
cout << "Round Robin:" << endl << endl;
//Round Robin
round_robin(processes, num_processes);
cout << endl;
statistics(num_processes);
cout << "Priority:" << endl << endl;
//Priority
priority(processes, num_processes);
cout << endl;
statistics(num_processes);
return 0;
}
| [
"zaorst@rpi.edu"
] | zaorst@rpi.edu |
7133e8bc7bc6009d62b27a2b4d7fcc15faf9e288 | d4ab9036934342a5488a35575aa64550de6dccf3 | /Assignment 1 Data struct/Assignement1/Outfit.h | 1fb415ceb328c1dfb34c92e7121ad48606f8499b | [] | no_license | yoongsoon/koh | 7ab34bd4c0763a054c0f956caba343424a231563 | f7e08e622868c59478a1e943bd58344f4354fe1e | refs/heads/master | 2020-07-11T04:12:49.044114 | 2016-12-05T08:07:53 | 2016-12-05T08:07:53 | 74,005,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 262 | h | #ifndef OUTFIT_H
#define OUTFIT_H
#include "Item.h"
class Outfit : public Item
{
public:
Outfit(const string &, const int &, const int &);
~Outfit();
virtual void receiveDamage(const int &);
int getSPECIAL() const;
protected:
const int kSPECIAL;
};
#endif | [
"yoongsoon@live.com"
] | yoongsoon@live.com |
f808082222d357b58353b493510a4cf3729e1673 | ad07b9cc798487b226e9d353cb0c2a565ec08564 | /app/src/main/cpp/IPlayer.h | 29edf70962581be3664bf39750f0d66ba4543724 | [] | no_license | SmallSevenFromCN/XPlay | 46fcb8523097a9d4c8db3e9da700a87c513541a0 | 86b442d514a15775635897fbe08e06e3e4925dbb | refs/heads/master | 2020-04-25T02:07:14.063902 | 2019-03-06T08:28:18 | 2019-03-06T08:28:18 | 172,428,151 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,035 | h | //
// Created by Administrator on 2019/2/27 0027.
//
#ifndef XPLAY_IPLAYER_H
#define XPLAY_IPLAYER_H
#include <mutex>
#include "XThread.h"
#include "XParameter.h"
class IDemux;
class IDecode;
class IResample;
class IVideoView;
class IAudioPlay;
class IPlayer : public XThread {
public:
static IPlayer *Get(unsigned char index = 0);
virtual bool Open(const char *path);
virtual void Close();
virtual bool Start();
virtual void InitView(void *win);
//获取当前的播放进度 0.0 ~ 1.0
virtual double PlayPos();
virtual bool Seek(double pos);
virtual void SetPause(bool isP);
//是否硬解码
bool isHardDecode = true;
//音频输入参数配置
XParameter outPara;
IDemux *demux = 0;
IDecode *vdecode = 0;
IDecode *adecode = 0;
IResample *resample = 0;
IVideoView *videoView = 0;
IAudioPlay *audioPlay = 0;
protected:
//用作音视频同步
void Main();
std::mutex mux;
IPlayer() {};
};
#endif //XPLAY_IPLAYER_H
| [
"1436533793@qq.com"
] | 1436533793@qq.com |
f6e4f006aa3f2ba83c71bc60c288637f17656592 | 7dfa21d74dae975082c6d5deaa01248bac1dcc26 | /torch/csrc/jit/fuser/kernel_cache.cpp | 44969000f56bd3e5b6a27b71808075ca0fb9f204 | [
"BSD-3-Clause",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | mruberry/pytorch | 88cf536ed58d20a409c1e5119be4ec04ec960082 | 19f73180cfb39eb67110d2a1d541975a49211453 | refs/heads/master | 2022-02-03T16:25:31.070089 | 2019-04-22T17:52:28 | 2019-04-22T17:58:15 | 130,132,886 | 4 | 1 | NOASSERTION | 2020-01-16T16:51:39 | 2018-04-18T23:24:38 | C++ | UTF-8 | C++ | false | false | 2,738 | cpp | #include <torch/csrc/jit/fuser/kernel_cache.h>
#include <torch/csrc/jit/passes/canonicalize.h>
#include <torch/csrc/jit/passes/shape_analysis.h>
#include <cstdint>
#include <mutex>
#include <unordered_map>
namespace torch {
namespace jit {
namespace fuser {
struct KernelCacheImpl {
// Note: std::unordered_map does not invalidate references even if rehashing
// occurs. This is a critical property for thread-safety.
std::mutex mutex_;
int64_t kernel_counter{0};
// Map of fusion key to KernelSpec
std::unordered_map<int64_t, KernelSpec> specMap_;
// Map of pretty-printed graph string to fusion key
// Used to check if a graph has already been cached in specMap_
std::unordered_map<std::string, int64_t> graphToKey_;
};
static KernelCacheImpl& getKernelCache() {
static KernelCacheImpl cache;
return cache;
}
int64_t debugNumCachedKernelSpecs() {
auto& cache = getKernelCache();
std::lock_guard<std::mutex> guard{cache.mutex_};
return cache.specMap_.size();
}
std::shared_ptr<Graph> normalizeGraphForCache(
const std::shared_ptr<Graph>& graph) {
auto result = Canonicalize(graph, /*keep_unique_names=*/false);
EraseShapeInformation(result);
return result;
}
// TODO: lookup by historic string key to start, then issue key
// as appropriate for faster lookup in the future
// precondition: graph has been normalized via normalizeGraphForCache
int64_t store(std::shared_ptr<Graph> graph) {
auto& cache = getKernelCache();
std::string repr = graph->toString();
std::lock_guard<std::mutex> guard{cache.mutex_};
const auto key = cache.kernel_counter++;
cache.specMap_.emplace(
std::piecewise_construct,
std::forward_as_tuple(key),
std::forward_as_tuple(key, graph));
cache.graphToKey_.emplace(std::make_pair(std::move(repr), key));
return key;
}
// XXX: Does not grab mutex
static at::optional<KernelSpec*> nolock_retrieve(
KernelCacheImpl& cache,
const int64_t key) {
auto it = cache.specMap_.find(key);
if (it == cache.specMap_.end())
return at::nullopt;
return &(it->second);
}
at::optional<KernelSpec*> retrieve(const int64_t key) {
auto& cache = getKernelCache();
std::lock_guard<std::mutex> guard{cache.mutex_};
return nolock_retrieve(cache, key);
}
// precondition: graph has been normalized via normalizeGraphForCache
at::optional<KernelSpec*> lookupGraph(std::shared_ptr<Graph> graph) {
auto& cache = getKernelCache();
std::string repr = graph->toString();
std::lock_guard<std::mutex> guard{cache.mutex_};
auto it = cache.graphToKey_.find(repr);
if (it == cache.graphToKey_.end())
return at::nullopt;
return nolock_retrieve(cache, it->second);
}
} // namespace fuser
} // namespace jit
} // namespace torch
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
440ccf190ed33a92621f747f1c49902f08c256db | e877f170f9a46811480177f956542ed576da8b6b | /MeshDS.h | fc38ae4628f7551387151686072dc63c48be7911 | [] | no_license | ameyakarve/dualDegreeProject | 42cf30b5b4b7e7d6a4c7ac692aa90de143afc616 | cdebdb2be75a44156efe8bbe9e03073ad5778e37 | refs/heads/master | 2021-01-10T22:02:46.749498 | 2014-01-29T19:58:51 | 2014-01-29T19:58:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | class Facet {
public:
int ID;
int vertices[3];
int edges[3];
vector <int> primaryNeighbours;
vector<int> secondaryNeighbours;
Vector normal;
};
class Edge {
public:
int ID;
int vertices[2];
bool isOuterBoundary;
bool isInnerBoundary;
vector <int> prevEdges;
vector <int> nextEdges;
Vector direction;
};
class Vertex {
public:
int ID;
vector <int> Edges;
vector <int> Facets;
double x;
double y;
double z;
} | [
"ameya.karve@gmail.com"
] | ameya.karve@gmail.com |
e3c29b8fd43e944fbcd57838508f9f9c0f14aaf7 | af6e73829b64c18a30d896f02b0360da12dd0ee4 | /xo.cpp | 3e8ae9329d35afa998946b01191005ac4a70807a | [] | no_license | RawanRefaat/XO-Game | 4b1897a93263c2a33453c5ef2e96f218fb7d2661 | 6803e2d98753c2334e9051523baabad32a3433f5 | refs/heads/master | 2023-08-24T12:26:37.918276 | 2021-10-06T01:07:57 | 2021-10-06T01:07:57 | 414,008,648 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,457 | cpp | //Member-function definitions. This file contains implementations
//of the member functions prototyped in game.h
#include <iostream>
#include "game.h" //includes definition of class firstGame
using namespace std;
//class constructor to initialize the board marks properly
firstGame::firstGame(){
mark='x';
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
board[i][j]='-'; }}
}
char firstGame::getMark(){
return mark;
}
//to print the whole board at any given time
void firstGame::print(){
cout << "-------------------" << endl;
for (int i=0;i<3;i++){
cout << "| ";
for (int j=0;j<3;j++){
cout << board[i][j] << " | ";
}
cout << endl;
cout << "-------------------" << endl;
}
}
//this function checks if there is a win in rows, columns or in slopes
bool firstGame::checkWin(){
if (firstGame::checkRow()|| firstGame::checkCol() || firstGame::checkSlope()){
return true;}
else
{return false;}
}
//checks every row in the board for a win
bool firstGame::checkRow(){
for (int i=0;i<3;i++){
if (board[i][0]!='-' && board[i][0]==board[i][1] && board[i][1]==board[i][2]){
return true;}}
return false;
}
//checks every column in the board for a win
bool firstGame::checkCol(){
for (int j=0;j<3;j++){
if (board[0][j]!='-' && board[0][j]==board[1][j] && board[1][j]==board[2][j]){
return true;}}
return false;
}
//checks any straight slopes in the board for a win
bool firstGame::checkSlope(){
if (board[0][0]!='-' && ((board[0][0]==board[1][1]&&board[1][1]==board[2][2]) || (board[0][2]==board[1][1]&&board[1][1]==board[2][0]))){
return true;}
else
return false;
}
//switches between the two players
void firstGame::switchPlayer(){
if(mark == 'x')
{mark = 'o';}
else
{mark = 'x';}
}
bool firstGame::markSpot(int row,int col){
if (board[row][col]=='-' && (row >= 0) && (row < 3) && (col >= 0) && (col < 3)){
board[row][col]=mark;
return true;}
return false;}
bool firstGame::full(){
int k=0;
for(int i=0; i<3; i++){
for (int j=0; j<3; j++){
if(board[i][j]=='x' || board[i][j]=='o')
{ k++; }}}
if (k==9)
{return true;}
else
{return false;}
}
void firstGame::printWinner(){
cout << "Player with the mark: " << mark << " Wins! Congratulations!" << endl;
}
| [
"rawan_refaat@yahoo.com"
] | rawan_refaat@yahoo.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.