text
stringlengths 8
6.88M
|
|---|
#ifndef NOFOCUSDELEGATE_H
#define NOFOCUSDELEGATE_H
#include <QPainter>
#include <QStyle>
#include <QStyledItemDelegate>
#include <QStyleOptionViewItem>
#include <QModelIndex>
class NoFocusDelegate : public QStyledItemDelegate
{
public:
virtual void paint(QPainter * painter, const QStyleOptionViewItem & option,
const QModelIndex & index) const
{
QStyleOptionViewItem itemOption(option);
if (itemOption.state & QStyle::State_HasFocus) {
itemOption.state = itemOption.state ^ QStyle::State_HasFocus;
}
QStyledItemDelegate::paint(painter, itemOption, index);
}
};
#endif // NOFOCUSDELEGATE_H
|
#pragma once
#if defined(_WIN32)
#define GLEW_STATIC
#include <GL/glew.h>
#endif
#if defined(__APPLE__)
#include <OpenGL/gl3.h>
#endif
#include "../ar.BaseInternal.h"
#include "../ar.ImageHelper.h"
static std::vector<GLenum> GLCheckError_Impl(const char *file, const int line)
{
std::vector<GLenum> codes;
GLenum __code = glGetError();
while (__code != GL_NO_ERROR) {
codes.push_back(__code);
#ifdef _DEBUG
printf("GLError filename = %s , line = %d, error = %d\n", file, line, __code);
#endif
__code = glGetError();
if (codes.size() > 128) break;
}
return codes;
}
#define GLCheckError() GLCheckError_Impl(__FILE__, __LINE__)
namespace ar
{
static void FlipYInternal(std::vector<uint8_t> &dst, const uint8_t* src, int32_t width, int32_t height, TextureFormat format)
{
auto pitch = ImageHelper::GetPitch(format);
auto size = width * height * pitch;
dst.resize(size);
for (auto y = 0; y < height; y++)
{
for (auto x = 0; x < width; x++)
{
for (auto p = 0; p < pitch; p++)
{
dst[p + (x + y * width) * pitch] = src[p + (x + (height - y - 1) * width) * pitch];
}
}
}
}
static void FlipYInternal(std::vector<Color> &dst, std::vector<Color> src, int32_t width, int32_t height)
{
auto size = width * height;
dst.resize(size);
for (auto y = 0; y < height; y++)
{
for (auto x = 0; x < width; x++)
{
dst[x + y * width] = src[x + (height - y - 1) * width];
}
}
}
}
|
#include <cstdio>
using namespace std;
/*/4
int main()
{
const int N = 20;
typedef int vetor[N];
int aux;
vetor v;
for(int i=0;i<N;i++){
v[i] = i;
printf("\nnumero: %d", i);
}
printf("\n\n");
for(int i=N-1;i>-1;i--){
printf("\nnumero: %d", v[i]);
}
return 0;
}
//5
int main(){
const int N = 20;
typedef int ArraySimple[N];
ArraySimple v;
int suma =0;
int promedio =0;
int cont = 0;
for(int i=0;i<N;i++){
v[i] = i;
}
for(int i=0;i<=N;i++){
if(v[i]%2 == 0){
suma += v[i];
}else{
promedio += v[i];
cont++;
}
}
printf("\nLa suma es %d", suma);
printf("\nEl promedio es %d", (promedio/cont));
for(int i=0;i<N;i++){
float d;
d = 1.15*v[i];
printf("\n\nnum: %f", d);
}
}
//6
int main(){
const int N=80;
typedef int vetor[N];
vetor urna;
int bola;
for(int i=0;i<N;i++){
urna[i] = 0;
}
do{
do{
printf("Introduzca una bola: ");
scanf("%d", &bola);
}while((bola<0)||(bola>N-1));
urna[bola] = urna[bola]+1;
}while(urna[33] != 3);
for(int i=0;i<N;i++){
printf("\nLa bola %d sale %d veces", i, urna[i] );
}
}
const int N=50;
struct Vector{
int v[N];
int numEls;
};
int buscar(const Vector &vect, int elem);
int main(){
Vector vect;
int i =0;
printf("numEl: ");
scanf("%d", &vect.numEls);
for(int i = 0; i <vect.numEls; i++){
vect.v[i] = i;
printf("v[i]: %d", vect.v[i]);
}
int num=0;
num = buscar(vect, 5);
printf("num: %d", num);
}
int buscar(const Vector &vect, int elem){
int num;
for(int i=0;i<vect.numEls-1;i++){
if(vect.v[i] == elem){
num = i;
}else{
num -1;
}
}return num;
}
const int N=50;
struct Vector{
int v[N];
int numEls;
};
int maximo(const Vector &v);
int main(){
Vector vect;
int a;
printf("Num elem: ");
do{
scanf("%d", &vect.numEls);
}while((vect.numEls < 0)&&(vect.numEls > N));
for(int i=0;i<vect.numEls;i++){
vect.v[i] = i;
printf("%d,", vect.v[i]);
}
printf("\n\n");
vect.v[5] = 30;
for(int i=0;i<vect.numEls;i++){
printf("%d,", vect.v[i]);
}
a = maximo(vect);
printf("\n\nPOSICION DEL MAXIMO: %d", a);
}
int maximo(const Vector &v){
int maximo = -1;
int devo = 0;
for(int i=0;i < v.numEls;i++){
if(v.v[i] > maximo){
maximo = v.v[i];
devo = i;
}
}return devo;
}
*/
//9
static const int N=5;
struct emp{
int vect[N];
int numEls;
};
void juntaEmp(emp a, emp b);
int main(){
emp Empresa1;
emp Empresa2;
emp Empresa3;
Empresa1.numEls = 3;
Empresa2.numEls = 3;
Empresa1.vect[0] = 11111111;
Empresa1.vect[1] = 33333333;
Empresa1.vect[2] = 55555555;
Empresa2.vect[0] = 22222222;
Empresa2.vect[1] = 44444444;
Empresa2.vect[2] = 66666666;
for(int i=0;i<3;i++){printf("\n emp1: %d", Empresa1.vect[i]);}
for(int i=0;i<3;i++){printf("\n emp2: %d", Empresa2.vect[i]);}
Empresa3.numEls = Empresa1.numEls + Empresa2.numEls;
printf("\n mezcla: %d", Empresa3.numEls);
|
// Created on: 1992-06-04
// Created by: Jacques GOUSSARD
// Copyright (c) 1992-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter_HeaderFile
#define _Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <TColgp_Array1OfPnt2d.hxx>
#include <TColStd_Array1OfReal.hxx>
#include <TColStd_Array1OfInteger.hxx>
#include <Standard_Boolean.hxx>
#include <Intf_Polygon2d.hxx>
class Standard_OutOfRange;
class Adaptor2d_Curve2d;
class Geom2dInt_Geom2dCurveTool;
class IntRes2d_Domain;
class Bnd_Box2d;
class gp_Pnt2d;
class Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter : public Intf_Polygon2d
{
public:
DEFINE_STANDARD_ALLOC
//! Compute a polygon on the domain of the curve.
Standard_EXPORT Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter(const Adaptor2d_Curve2d& Curve, const Standard_Integer NbPnt, const IntRes2d_Domain& Domain, const Standard_Real Tol);
//! The current polygon is modified if most
//! of the points of the polygon are
//! outside the box <OtherBox>. In this
//! situation, bounds are computed to build
//! a polygon inside or near the OtherBox.
Standard_EXPORT void ComputeWithBox (const Adaptor2d_Curve2d& Curve, const Bnd_Box2d& OtherBox);
virtual Standard_Real DeflectionOverEstimation() const Standard_OVERRIDE;
void SetDeflectionOverEstimation (const Standard_Real x);
void Closed (const Standard_Boolean clos);
//! Returns True if the polyline is closed.
virtual Standard_Boolean Closed () const Standard_OVERRIDE { return ClosedPolygon; }
//! Give the number of Segments in the polyline.
virtual Standard_Integer NbSegments() const Standard_OVERRIDE;
//! Returns the points of the segment <Index> in the Polygon.
Standard_EXPORT virtual void Segment (const Standard_Integer theIndex, gp_Pnt2d& theBegin, gp_Pnt2d& theEnd) const Standard_OVERRIDE;
//! Returns the parameter (On the curve)
//! of the first point of the Polygon
Standard_Real InfParameter() const;
//! Returns the parameter (On the curve)
//! of the last point of the Polygon
Standard_Real SupParameter() const;
Standard_EXPORT Standard_Boolean AutoIntersectionIsPossible() const;
//! Give an approximation of the parameter on the curve
//! according to the discretization of the Curve.
Standard_EXPORT Standard_Real ApproxParamOnCurve (const Standard_Integer Index, const Standard_Real ParamOnLine) const;
Standard_Integer CalculRegion (const Standard_Real x, const Standard_Real y, const Standard_Real x1, const Standard_Real x2, const Standard_Real y1, const Standard_Real y2) const;
Standard_EXPORT void Dump() const;
protected:
private:
Standard_Real TheDeflection;
Standard_Integer NbPntIn;
Standard_Integer TheMaxNbPoints;
TColgp_Array1OfPnt2d ThePnts;
TColStd_Array1OfReal TheParams;
TColStd_Array1OfInteger TheIndex;
Standard_Boolean ClosedPolygon;
Standard_Real Binf;
Standard_Real Bsup;
};
#define TheCurve Adaptor2d_Curve2d
#define TheCurve_hxx <Adaptor2d_Curve2d.hxx>
#define TheCurveTool Geom2dInt_Geom2dCurveTool
#define TheCurveTool_hxx <Geom2dInt_Geom2dCurveTool.hxx>
#define IntCurve_Polygon2dGen Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter
#define IntCurve_Polygon2dGen_hxx <Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter.hxx>
#include <IntCurve_Polygon2dGen.lxx>
#undef TheCurve
#undef TheCurve_hxx
#undef TheCurveTool
#undef TheCurveTool_hxx
#undef IntCurve_Polygon2dGen
#undef IntCurve_Polygon2dGen_hxx
#endif // _Geom2dInt_ThePolygon2dOfTheIntPCurvePCurveOfGInter_HeaderFile
|
#include "GameCmd.h"
#include "CDLReactor.h"
#include "Despatch.h"
#include "BackConnect.h"
#include "Logger.h"
#include "Configure.h"
static std::map<int, BackNodes*> _nodes_map;
static InputPacket pPacket;
//=================ConnectHandler=========================
ConnectHandler::ConnectHandler( Connector* connector )
{
this->connector = connector;
}
ConnectHandler::~ConnectHandler( )
{
// this->_decode = NULL;
}
static void registAlloc(int id,CDLSocketHandler* handler)
{
OutputPacket OutPkg;
OutPkg.Begin(ALLOC_REGIST);
OutPkg.WriteInt(Configure::getInstance()->m_nServerId);
OutPkg.End();
if (handler && handler->Send(OutPkg.packet_buf(), OutPkg.packet_size()) > 0)
{
LOGGER(E_LOG_INFO) << "HallServer Regist";
}
}
int ConnectHandler::OnConnected()
{
LOGGER(E_LOG_INFO) << "Connect Server " << connector->ip << ":" << connector->port << " fd = " << netfd;
this->connector->isConnected = true;
registAlloc(1,this);
return 0;
}
int ConnectHandler::OnClose()
{
LOGGER(E_LOG_INFO) << "Connect Close " << connector->ip << ":" << connector->port << " fd = " << netfd;
this->connector->isConnected = false;
this->connector->handler = NULL;
return 0;
}
int ConnectHandler::OnPacketComplete(const char* data, int len)
{
pPacket.Copy(data,len);
short cmd = pPacket.GetCmdType() ;
/*if (pPacket.CrevasseBuffer() == -1)
{
_LOG_ERROR_( "[DATA CrevasseBuffer ERROR] data decrypt error \n" );
return -1;
}*/
LOGGER(E_LOG_DEBUG) << "BackNode Recv Packet Cmd=" << cmd;
return Despatch::getInstance()->doBackResponse(this,&pPacket);
}
//====================Connector===================== ===
Connector::Connector(int id)
{
this->id = id;
this->isConnected = false;
this->fd=0;
this->suspended= false ;
}
Connector::~Connector()
{
}
int Connector::connect(const char* ip, short port)
{
//建立连接
strcpy(this->ip, ip);
this->port = port;
ConnectHandler * phandler = new ConnectHandler(this);
if( CDLReactor::Instance()->Connect(phandler,ip,port) < 0 )
{
delete phandler;
LOGGER(E_LOG_ERROR) << "Connect BackServer error " << ip << ":" << port;
return -1;
}
else
{
this->handler = phandler;
return 0;
}
}
int Connector::reconnect()
{
return connect(this->ip, this->port);
}
int Connector::send(OutputPacket* outPack, bool isEncrypt)
{
if(isEncrypt)
outPack->EncryptBuffer();
if(this->handler)
return this->handler->Send(outPack->packet_buf(),outPack->packet_size());
else
return -1;
}
int Connector::send(char* buff, int len)
{
if(this->handler)
return this->handler->Send( buff, len );
else
return -1;
}
void Connector::heartbeat()
{
OutputPacket OutPkg;
OutPkg.Begin(ALLOC_HEART_BEAT);
OutPkg.WriteInt(Configure::getInstance()->m_nServerId);
OutPkg.WriteString("AllocServer HeartBeat");
OutPkg.End();
this->send(&OutPkg, false);
}
//=================BackNodes=========================
BackNodes::BackNodes(int id)
{
this->id = id;
conn_size=0;
memset(connectors, 0, sizeof(Connector*)*MAX_BACK_CONN);
this->StartTimer(10000);
}
BackNodes::~BackNodes()
{
}
int BackNodes::addNode(Node* node)
{
return connect(node ->id, node ->ip,node ->port);
}
int BackNodes::connect(int ID,char* host, int port)
{
if(ID<0 || ID>(MAX_BACK_CONN-1))
{
return -1;
}
Connector * conn = new Connector(ID);
if (conn->connect(host, port)==-1)
{
delete conn;
return -1;
}
else
{
conn_size ++;
connectors[ID] = conn;
return 0;
}
}
int BackNodes::send(int id,OutputPacket* outPack, bool isEncrypt )
{
if(id>0 && id<MAX_BACK_CONN)
{
Connector* pconnect = this->connectors[id];
if( pconnect && pconnect->isActive() && !pconnect->isSuspended() )
return pconnect->send( outPack, isEncrypt);
}
return -1;
}
int BackNodes::send(OutputPacket* outPack, bool isEncrypt)
{
for(int i=1; i<=conn_size; i++)
{
Connector* pconnect = this->connectors[i];
if( pconnect && pconnect->isActive() && !pconnect->isSuspended())
return pconnect->send(outPack, isEncrypt);
}
return -1;
}
int BackNodes::send(InputPacket* inputPack)
{
LOGGER(E_LOG_DEBUG) << "conn_size = " << conn_size << " send";
for(int i=1; i<=conn_size; i++)
{
Connector* pconnect = this->connectors[i];
if( pconnect && pconnect->isActive() && !pconnect->isSuspended())
return pconnect->send(inputPack->packet_buf(),inputPack->packet_size());
}
return -1;
}
void BackConnectManager::addNodes(int id, BackNodes* backnodes)
{
_nodes_map[id] = backnodes;
}
BackNodes* BackConnectManager::getNodes(int id)
{
if(id<0)
{
return NULL;
}
return _nodes_map[id];
}
//=================BackNodes=========================
int BackNodes::ProcessOnTimerOut()
{
for(int i=1; i<=this->conn_size; ++i)
{
Connector* pconnect = this->connectors[i];
if(pconnect && pconnect->isActive())
{
//发心跳包
pconnect->heartbeat();
LOGGER(E_LOG_DEBUG) << "node id =" << this->id << " connect id = " << pconnect->id;
}
else
{
//重连接
pconnect->reconnect();
LOGGER(E_LOG_DEBUG) << "node id = " << this->id << " pconnect id = " << pconnect->id << " reconnect";
}
}
StartTimer(10000);
return 0;
}
std::map<int, BackNodes*> * BackConnectManager::getNodess()
{
return &_nodes_map;
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define show(x) for(auto i: x){cout << i << " ";}
typedef long long ll;
int main()
{
ll n;
cin >> n;
ll ans = 0;
ll div10 = 10;
if (n%2 != 1){
while(n/div10 > 0){
ans += n/div10;
div10 *= 5;
}
}
cout << ans << endl;
}
|
// RAVEN BEGIN
// ddynerman: note that this file is no longer merged with Doom3 updates
//
// MERGE_DATE 09/30/2004
#ifndef __MULTIPLAYERGAME_H__
#define __MULTIPLAYERGAME_H__
/*
===============================================================================
Quake IV multiplayer
===============================================================================
*/
#include "mp/Buying.h"
class idPlayer;
class rvCTF_AssaultPoint;
class rvItemCTFFlag;
typedef enum {
GAME_SP,
GAME_DM,
GAME_TOURNEY,
GAME_TDM,
// bdube: added ctf
GAME_CTF,
// ddynerman: new gametypes
GAME_1F_CTF,
GAME_ARENA_CTF,
GAME_ARENA_1F_CTF, // is not used, but leaving it in the list so I don't offset GAME_DEADZONE
// RITUAL BEGIN
// squirrel: added DeadZone multiplayer mode
GAME_DEADZONE,
NUM_GAME_TYPES,
// RITUAL END
} gameType_t;
// ddynerman: teams
typedef enum {
TEAM_NONE = -1,
TEAM_MARINE,
TEAM_STROGG,
TEAM_MAX,
} team_t;
// shouchard: server admin command types
typedef enum {
SERVER_ADMIN_KICK,
SERVER_ADMIN_BAN,
SERVER_ADMIN_REMOVE_BAN,
SERVER_ADMIN_FORCE_SWITCH,
} serverAdmin_t;
// shouchard: vote struct for packing up interface values to be handled later
// note that we have two mechanisms for dealing with vote data that
// should be consolidated: this one that handles the interface and
// multi-field votes and the one that handles console commands and
// single line votes.
struct voteStruct_t {
int m_fieldFlags; // flags for which fields are valid
int m_kick; // id of the player
idStr m_map; // name of the map
int m_gameType; // game type enum
int m_timeLimit;
int m_fragLimit;
int m_tourneyLimit;
int m_captureLimit;
int m_buying;
int m_teamBalance;
int m_controlTime;
// restart is a flag only
// nextmap is a flag only but we don't technically support it (but doom had it so it's here)
};
typedef enum {
VOTEFLAG_RESTART = 0x0001,
VOTEFLAG_BUYING = 0x0002,
VOTEFLAG_TEAMBALANCE = 0x0004,
VOTEFLAG_SHUFFLE = 0x0008,
VOTEFLAG_KICK = 0x0010,
VOTEFLAG_MAP = 0x0020,
VOTEFLAG_GAMETYPE = 0x0040,
VOTEFLAG_TIMELIMIT = 0x0080,
VOTEFLAG_TOURNEYLIMIT = 0x0100,
VOTEFLAG_CAPTURELIMIT = 0x0200,
VOTEFLAG_FRAGLIMIT = 0x0400,
VOTEFLAG_CONTROLTIME = 0x0800,
} voteFlag_t;
#define NUM_VOTES 11
#define MAX_PRINT_LEN 128
// more compact than a chat line
typedef enum {
MSG_SUICIDE = 0,
MSG_KILLED,
MSG_KILLEDTEAM,
MSG_DIED,
MSG_VOTE,
MSG_VOTEPASSED,
MSG_VOTEFAILED,
MSG_SUDDENDEATH,
MSG_FORCEREADY,
MSG_JOINEDSPEC,
MSG_TIMELIMIT,
MSG_FRAGLIMIT,
MSG_CAPTURELIMIT,
MSG_TELEFRAGGED,
MSG_JOINTEAM,
MSG_HOLYSHIT,
MSG_COUNT
} msg_evt_t;
typedef enum {
PLAYER_VOTE_NONE,
PLAYER_VOTE_NO,
PLAYER_VOTE_YES,
PLAYER_VOTE_WAIT // mark a player allowed to vote
} playerVote_t;
typedef enum {
PRM_AUTO,
PRM_SCORE,
PRM_TEAM_SCORE,
PRM_TEAM_SCORE_PLUS_SCORE,
PRM_WINS
} playerRankMode_t;
enum announcerSound_t {
// General announcements
AS_GENERAL_ONE,
AS_GENERAL_TWO,
AS_GENERAL_THREE,
AS_GENERAL_YOU_WIN,
AS_GENERAL_YOU_LOSE,
AS_GENERAL_FIGHT,
AS_GENERAL_SUDDEN_DEATH,
AS_GENERAL_VOTE_FAILED,
AS_GENERAL_VOTE_PASSED,
AS_GENERAL_VOTE_NOW,
AS_GENERAL_ONE_FRAG,
AS_GENERAL_TWO_FRAGS,
AS_GENERAL_THREE_FRAGS,
AS_GENERAL_ONE_MINUTE,
AS_GENERAL_FIVE_MINUTE,
AS_GENERAL_PREPARE_TO_FIGHT,
AS_GENERAL_QUAD_DAMAGE,
AS_GENERAL_REGENERATION,
AS_GENERAL_HASTE,
AS_GENERAL_INVISIBILITY,
// DM announcements
AS_DM_YOU_TIED_LEAD,
AS_DM_YOU_HAVE_TAKEN_LEAD,
AS_DM_YOU_LOST_LEAD,
// Team announcements
AS_TEAM_ENEMY_SCORES,
AS_TEAM_YOU_SCORE,
AS_TEAM_TEAMS_TIED,
AS_TEAM_STROGG_LEAD,
AS_TEAM_MARINES_LEAD,
AS_TEAM_JOIN_MARINE,
AS_TEAM_JOIN_STROGG,
// CTF announcements
AS_CTF_YOU_HAVE_FLAG,
AS_CTF_YOUR_TEAM_HAS_FLAG,
AS_CTF_ENEMY_HAS_FLAG,
AS_CTF_YOUR_TEAM_DROPS_FLAG,
AS_CTF_ENEMY_DROPS_FLAG,
AS_CTF_YOUR_FLAG_RETURNED,
AS_CTF_ENEMY_RETURNS_FLAG,
// Tourney announcements
AS_TOURNEY_ADVANCE,
AS_TOURNEY_JOIN_ARENA_ONE,
AS_TOURNEY_JOIN_ARENA_TWO,
AS_TOURNEY_JOIN_ARENA_THREE,
AS_TOURNEY_JOIN_ARENA_FOUR,
AS_TOURNEY_JOIN_ARENA_FIVE,
AS_TOURNEY_JOIN_ARENA_SIX,
AS_TOURNEY_JOIN_ARENA_SEVEN,
AS_TOURNEY_JOIN_ARENA_EIGHT,
AS_TOURNEY_JOIN_ARENA_WAITING,
AS_TOURNEY_DONE,
AS_TOURNEY_START,
AS_TOURNEY_ELIMINATED,
AS_TOURNEY_WON,
AS_TOURNEY_PRELIMS,
AS_TOURNEY_QUARTER_FINALS,
AS_TOURNEY_SEMI_FINALS,
AS_TOURNEY_FINAL_MATCH,
AS_GENERAL_TEAM_AMMOREGEN,
AS_GENERAL_TEAM_DOUBLER,
AS_NUM_SOUNDS
};
typedef struct mpPlayerState_s {
int ping; // player ping
int fragCount; // kills
int teamFragCount; // teamplay awards
int deadZoneScore; // Score in dead zone
int wins;
playerVote_t vote; // player's vote
bool scoreBoardUp; // toggle based on player scoreboard button, used to activate de-activate the scoreboard gui
bool ingame;
} mpPlayerState_t;
const int MAX_INSTANCES = 8;
const int NUM_CHAT_NOTIFY = 5;
const int CHAT_FADE_TIME = 400;
const int FRAGLIMIT_DELAY = 2000;
const int CAPTURELIMIT_DELAY = 750;
const int MP_PLAYER_MINFRAGS = -100;
const int MP_PLAYER_MAXFRAGS = 999;
const int MP_PLAYER_MAXWINS = 100;
const int MP_PLAYER_MAXPING = 999;
const int MP_PLAYER_MAXKILLS = 999;
const int MP_PLAYER_MAXDEATHS = 999;
const int MAX_AP = 5;
const int CHAT_HISTORY_SIZE = 2048;
const int RCON_HISTORY_SIZE = 4096;
const int KILL_NOTIFICATION_LEN = 256;
//RAVEN BEGIN
//asalmon: update stats for Xenon
#ifdef _XENON
const int XENON_STAT_UPDATE_INTERVAL = 1000;
#endif
const int ASYNC_PLAYER_FRAG_BITS = -idMath::BitsForInteger( MP_PLAYER_MAXFRAGS - MP_PLAYER_MINFRAGS ); // player can have negative frags
const int ASYNC_PLAYER_WINS_BITS = idMath::BitsForInteger( MP_PLAYER_MAXWINS );
const int ASYNC_PLAYER_PING_BITS = idMath::BitsForInteger( MP_PLAYER_MAXPING );
const int ASYNC_PLAYER_INSTANCE_BITS = idMath::BitsForInteger( MAX_INSTANCES );
const int ASYNC_PLAYER_DEATH_BITS = idMath::BitsForInteger( MP_PLAYER_MAXDEATHS );
const int ASYNC_PLAYER_KILL_BITS = idMath::BitsForInteger( MP_PLAYER_MAXKILLS );
//RAVEN END
//RITUAL BEGIN
const int MAX_TEAM_POWERUPS = 5;
//RITUAL END
// ddynerman: game state
#include "mp/GameState.h"
typedef struct mpChatLine_s {
idStr line;
short fade; // starts high and decreases, line is removed once reached 0
} mpChatLine_t;
typedef struct mpBanInfo_s {
idStr name;
char guid[ CLIENT_GUID_LENGTH ];
// unsigned char ip[ 15 ];
} mpBanInfo_t;
class idPhysics_Player;
class idMultiplayerGame {
// rvGameState manages our state
friend class rvGameState;
public:
idMultiplayerGame();
void Shutdown( void );
// resets everything and prepares for a match
void Reset( void );
// RAVEN BEGIN
// mwhitlock: Dynamic memory consolidation
// Made this public so that level heap can be emptied.
void Clear( void );
// RAVEN END
// setup local data for a new player
void SpawnPlayer( int clientNum );
// Run the MP Game
void Run( void );
// Run the local client
void ClientRun( void );
void ClientEndFrame( void );
// Run common code (client & server)
void CommonRun( void );
// draws mp hud, scoredboard, etc..
bool Draw( int clientNum );
// updates a player vote
void PlayerVote( int clientNum, playerVote_t vote );
// updates frag counts and potentially ends the match in sudden death
void PlayerDeath( idPlayer *dead, idPlayer *killer, int methodOfDeath );
void AddChatLine( const char *fmt, ... ) id_attribute((format(printf,2,3)));
// RITUAL BEGIN
// squirrel: Mode-agnostic buymenus
void OnBuyModeTeamVictory( int winningTeam );
// squirrel: added DeadZone multiplayer mode
void OnDeadZoneTeamVictory( int winningTeam );
// RITUAL END
void UpdateMainGui( void );
// RAVEN BEGIN
// bdube: global pickup sounds (powerups, etc)
// Global item acquire sounds
void PlayGlobalItemAcquireSound ( int entityDefIndex );
bool CanTalk( idPlayer *from, idPlayer *to, bool echo );
void ReceiveAndForwardVoiceData( int clientNum, const idBitMsg &inMsg, int messageType );
#ifdef _USE_VOICECHAT
// jscott: game side voice comms
void XmitVoiceData( void );
void ReceiveAndPlayVoiceData( const idBitMsg &inMsg );
#endif
// jshepard: selects a map at random that will run with the current game type
bool PickMap( idStr gameType, bool checkOnly = false );
void ClearVote( int clientNum = -1 );
void ResetRconGuiStatus( void );
// RAVEN END
idUserInterface* StartMenu( void );
const char* HandleGuiCommands( const char *menuCommand );
void WriteToSnapshot( idBitMsgDelta &msg ) const;
void ReadFromSnapshot( const idBitMsgDelta &msg );
void ShuffleTeams( void );
void SetGameType( void );
void SetMatchStartedTime( int time ) { matchStartedTime = time; }
rvGameState* GetGameState( void );
void PrintMessageEvent( int to, msg_evt_t evt, int parm1 = -1, int parm2 = -1 );
void PrintMessage( int to, const char* message );
void DisconnectClient( int clientNum );
static void ForceReady_f( const idCmdArgs &args );
static void DropWeapon_f( const idCmdArgs &args );
static void MessageMode_f( const idCmdArgs &args );
static void VoiceChat_f( const idCmdArgs &args );
static void VoiceChatTeam_f( const idCmdArgs &args );
// RAVEN BEGIN
// shouchard: added console commands to mute/unmute voice chat
static void VoiceMute_f( const idCmdArgs &args );
static void VoiceUnmute_f( const idCmdArgs &args );
// jshepard: command wrappers
static void ForceTeamChange_f( const idCmdArgs& args );
static void RemoveClientFromBanList_f( const idCmdArgs& args );
// autobalance helper for the guis
static void CheckTeamBalance_f( const idCmdArgs &args );
// activates the admin console when a rcon password challenge returns.
void ProcessRconReturn( bool success );
// RAVEN END
typedef enum {
VOTE_RESTART = 0,
VOTE_TIMELIMIT,
VOTE_FRAGLIMIT,
VOTE_GAMETYPE,
VOTE_KICK,
VOTE_MAP,
VOTE_BUYING,
VOTE_NEXTMAP,
// RAVEN BEGIN
// shouchard: added capturelimit, round limit, and autobalance to vote flags
VOTE_CAPTURELIMIT,
VOTE_ROUNDLIMIT,
VOTE_AUTOBALANCE,
VOTE_MULTIFIELD, // all the "packed" vote functions
// RAVEN END
VOTE_CONTROLTIME,
VOTE_COUNT,
VOTE_NONE
} vote_flags_t;
typedef enum {
VOTE_UPDATE,
VOTE_FAILED,
VOTE_PASSED, // passed, but no reset yet
VOTE_ABORTED,
VOTE_RESET // tell clients to reset vote state
} vote_result_t;
// RAVEN BEGIN
// shouchard: added enum to remove magic numbers
typedef enum {
VOTE_GAMETYPE_DM = 0,
VOTE_GAMETYPE_TOURNEY,
VOTE_GAMETYPE_TDM,
VOTE_GAMETYPE_CTF,
VOTE_GAMETYPE_ARENA_CTF,
//RITUAL BEGIN
//
VOTE_GAMETYPE_DEADZONE,
//RITUAL END
VOTE_GAMETYPE_COUNT
} vote_gametype_t;
// RAVEN END
static void Vote_f( const idCmdArgs &args );
static void CallVote_f( const idCmdArgs &args );
void ClientCallVote( vote_flags_t voteIndex, const char *voteValue );
void ServerCallVote( int clientNum, const idBitMsg &msg );
void ClientStartVote( int clientNum, const char *voteString );
void ServerStartVote( int clientNum, vote_flags_t voteIndex, const char *voteValue );
// RAVEN BEGIN
// shouchard: multiline vote support
void ClientUpdateVote( vote_result_t result, int yesCount, int noCount, const voteStruct_t &voteData );
// RAVEN END
void CastVote( int clientNum, bool vote );
void ExecuteVote( void );
// RAVEN BEGIN
// shouchard: multiline vote handlers
void ClientCallPackedVote( const voteStruct_t &voteData );
void ServerCallPackedVote( int clientNum, const idBitMsg &msg );
void ClientStartPackedVote( int clientNum, const voteStruct_t &voteData );
void ServerStartPackedVote( int clientNum, const voteStruct_t &voteData );
void ExecutePackedVote( void );
const char * LocalizeGametype( void );
// RAVEN END
void WantKilled( int clientNum );
int NumActualClients( bool countSpectators, int *teamcount = NULL );
void DropWeapon( int clientNum );
void MapRestart( void );
void JoinTeam( const char* team );
// called by idPlayer whenever it detects a team change (init or switch)
void SwitchToTeam( int clientNum, int oldteam, int newteam );
bool IsPureReady( void ) const;
void ProcessChatMessage( int clientNum, bool team, const char *name, const char *text, const char *sound );
void ProcessVoiceChat( int clientNum, bool team, int index );
// RAVEN BEGIN
// shouchard: added commands to mute/unmute voice chat
void ClientVoiceMute( int clientNum, bool mute );
int GetClientNumFromPlayerName( const char *playerName );
void ServerHandleVoiceMuting( int clientSrc, int clientDest, bool mute );
// shouchard: fixing a bug in multiplayer where round timer sounds (5 minute
// warning, etc.) don't go away at the end of the round.
void ClearAnnouncerSounds( void );
// shouchard: server admin stuff
typedef struct
{
bool restartMap;
idStr mapName;
int gameType;
int captureLimit;
int fragLimit;
int tourneyLimit;
int timeLimit;
int minPlayers;
int controlTime;
bool buying;
bool autoBalance;
bool shuffleTeams;
} serverAdminData_t;
void HandleServerAdminBanPlayer( int clientNum );
void HandleServerAdminRemoveBan( const char * info );
void HandleServerAdminKickPlayer( int clientNum );
void HandleServerAdminForceTeamSwitch( int clientNum );
bool HandleServerAdminCommands( serverAdminData_t &data );
// RAVEN END
// RITUAL BEGIN
typedef struct mpTeamPowerups_s {
int powerup;
int time;
bool update;
int endTime;
} mpTeamPowerups_t;
mpTeamPowerups_t teamPowerups[TEAM_MAX][MAX_TEAM_POWERUPS];
void AddTeamPowerup(int powerup, int time, int team);
void UpdateTeamPowerups();
void SetUpdateForTeamPowerups(int team);
// RITUAL END
void Precache( void );
// throttle UI switch rates
void ThrottleUserInfo( void );
void ToggleSpectate( void );
void ToggleReady( void );
void ToggleTeam( void );
void ClearFrags( int clientNum );
void EnterGame( int clientNum );
bool CanPlay( idPlayer *p );
bool IsInGame( int clientNum );
bool WantRespawn( idPlayer *p );
void ServerWriteInitialReliableMessages( int clientNum );
void ClientReadStartState( const idBitMsg &msg );
void ServerClientConnect( int clientNum );
void PlayerStats( int clientNum, char *data, const int len );
void AddTeamScore ( int team, int amount );
void AddPlayerScore( idPlayer* player, int amount );
void AddPlayerTeamScore( idPlayer* player, int amount );
void AddPlayerWin( idPlayer* player, int amount );
void SetPlayerTeamScore( idPlayer* player, int value );
void SetPlayerDeadZoneScore( idPlayer* player, float value );
void SetPlayerScore( idPlayer* player, int value );
void SetPlayerWin( idPlayer* player, int value );
void SetHudOverlay( idUserInterface* overlay, int duration );
void ClearMap ( void );
void EnableDamage( bool enable = true );
idPlayer* GetRankedPlayer( int i );
int GetRankedPlayerScore( int i );
int GetNumRankedPlayers( void );
idPlayer* GetUnrankedPlayer( int i );
int GetNumUnrankedPlayers( void );
int GetScore( int i );
int GetScore( idPlayer* player );
int GetTeamScore( int i );
int GetTeamScore( idPlayer* player );
int GetWins( int i );
int GetWins( idPlayer* player );
// asalmon: Get the score for a team.
int GetScoreForTeam( int i );
int GetTeamsTotalFrags( int i );
int GetTeamsTotalScore( int i );
idUserInterface *GetMainGUI() {return mainGui;}
float GetPlayerDeadZoneScore(idPlayer* player);
int TeamLeader( void );
int GetPlayerTime( idPlayer* player );
const char* GetLongGametypeName( const char* gametype );
int GameTypeToVote( const char *gameType );
void ReceiveRemoteConsoleOutput( const char* output );
void ClientSetInstance( const idBitMsg& msg );
void ServerSetInstance( int instance );
void AddPrivatePlayer( int clientId );
void RemovePrivatePlayer( int clientId );
//RAVEN BEGIN
//asalmon: Xenon scoreboard update
#ifdef _XENON
void UpdateXenonScoreboard( idUserInterface *scoreBoard );
int lastScoreUpdate;
// mekberg: for selecting local player
void SelectLocalPlayer( idUserInterface *scoreBoard );
#endif
//RAVEN END
int VerifyTeamSwitch( int wantTeam, idPlayer *player );
void RemoveAnnouncerSound( int type );
void RemoveAnnouncerSoundRange( int startType, int endType );
void ScheduleAnnouncerSound ( announcerSound_t sound, float time, int instance = -1, bool allowOverride = false );
void ScheduleTimeAnnouncements( void );
// RAVEN END
void SendDeathMessage( idPlayer *attacker, idPlayer *victim, int methodOfDeath );
void ReceiveDeathMessage( idPlayer *attacker, int attackerScore, idPlayer *victim, int victimScore, int methodOfDeath );
rvCTF_AssaultPoint* NextAP( int team );
int OpposingTeam( int team );
idList<idEntityPtr<rvCTF_AssaultPoint> > assaultPoints;
// Buying Manager - authority for buying system game balance constants (awards,
// costs, etc.)
riBuyingManager mpBuyingManager;
idUserInterface* statSummary; // stat summary
rvTourneyGUI tourneyGUI;
void ShowStatSummary( void );
bool CanCapture( int team );
void FlagCaptured( idPlayer *player );
void UpdatePlayerRanks( playerRankMode_t rankMode = PRM_AUTO );
void UpdateTeamRanks( void );
void UpdateHud( idUserInterface* _mphud );
idPlayer * FragLimitHit( void );
idPlayer * FragLeader( void );
bool TimeLimitHit( void );
int GetCurrentMenu( void ) { return currentMenu; }
void SetFlagEntity( idEntity* ent, int team );
idEntity* GetFlagEntity( int team );
void WriteNetworkInfo( idFile *file, int clientNum );
void ReadNetworkInfo( idFile* file, int clientNum );
void SetShaderParms( renderView_t *view );
// RITUAL BEGIN
// squirrel: added DeadZone multiplayer mode
int NumberOfPlayersOnTeam( int team );
int NumberOfAlivePlayersOnTeam( int team );
void ReportZoneControllingPlayer( idPlayer* player );
void ReportZoneController(int team, int pCount, int situation, idEntity* zoneTrigger = 0);
bool IsValidTeam(int team);
void ControlZoneStateChanged( int team );
int powerupCount;
int prevAnnouncerSnd;
int defaultWinner;
int deadZonePowerupCount;
dzState_t dzState[ TEAM_MAX ];
float marineScoreBarPulseAmount;
float stroggScoreBarPulseAmount;
// RITUAL END
// RITUAL BEGIN
// squirrel: Mode-agnostic buymenus
bool isBuyingAllowedRightNow;
void OpenLocalBuyMenu( void );
void RedrawLocalBuyMenu( void );
void GiveCashToTeam( int team, float cashAmount );
bool IsBuyingAllowedInTheCurrentGameMode( void );
bool IsBuyingAllowedRightNow( void );
// RITUAL END
static const char* teamNames[ TEAM_MAX ];
private:
static const char *MPGuis[];
static const char *ThrottleVars[];
static const char *ThrottleVarsInEnglish[];
static const int ThrottleDelay[];
char killNotificationMsg[ KILL_NOTIFICATION_LEN ];
int pingUpdateTime; // time to update ping
mpPlayerState_t playerState[ MAX_CLIENTS ];
// game state
rvGameState* gameState;
// vote vars
vote_flags_t vote; // active vote or VOTE_NONE
int voteTimeOut; // when the current vote expires
int voteExecTime; // delay between vote passed msg and execute
int yesVotes; // counter for yes votes
int noVotes; // and for no votes
idStr voteValue; // the data voted upon ( server )
idStr voteString; // the vote string ( client )
bool voted; // hide vote box ( client )
int kickVoteMap[ MAX_CLIENTS ];
// RAVEN BEGIN
// shouchard: names for kickVoteMap
idStr kickVoteMapNames[ MAX_CLIENTS ];
voteStruct_t currentVoteData; // used for multi-field votes
// RAVEN END
idStr localisedGametype;
// time related
int matchStartedTime; // time current match started
// guis
// RITUAL BEGIN
// squirrel: added DeadZone multiplayer mode
//int sqRoundNumber; // round number in DeadZone; match expires when this equals "sq_numRoundsPerMatch" (cvar)
// squirrel: Mode-agnostic buymenus
idUserInterface *buyMenu; // buy menu
// RITUAL END
idUserInterface *scoreBoard; // scoreboard
idUserInterface *mainGui; // ready / nick / votes etc.
idListGUI *mapList;
idUserInterface *msgmodeGui; // message mode
int currentMenu; // 0 - none, 1 - mainGui, 2 - msgmodeGui
int nextMenu; // if 0, will do mainGui
bool bCurrentMenuMsg; // send menu state updates to server
enum {
MPLIGHT_CTF_MARINE,
MPLIGHT_CTF_STROGG,
MPLIGHT_QUAD,
MPLIGHT_HASTE,
MPLIGHT_REGEN,
MPLIGHT_MAX
};
int lightHandles[ MPLIGHT_MAX ];
renderLight_t lights[ MPLIGHT_MAX ];
// chat buffer
idStr chatHistory;
// rcon buffer
idStr rconHistory;
//RAVEN BEGIN
//asalmon: Need to refresh stats periodically if the player is looking at stats
int currentStatClient;
int currentStatTeam;
//RAVEN END
public:
// current player rankings
idList<rvPair<idPlayer*, int> > rankedPlayers;
idList<idPlayer*> unrankedPlayers;
rvPair<int, int> rankedTeams[ TEAM_MAX ];
private:
int lastVOAnnounce;
int lastReadyToggleTime;
bool pureReady; // defaults to false, set to true once server game is running with pure checksums
bool currentSoundOverride;
int switchThrottle[ 3 ];
int voiceChatThrottle;
void SetupBuyMenuItems();
idList<int> privateClientIds;
int privatePlayers;
// player who's rank info we're displaying
idEntityPtr<idPlayer> rankTextPlayer;
idEntityPtr<idEntity> flagEntities[ TEAM_MAX ];
idEntityPtr<idPlayer> flagCarriers[ TEAM_MAX ];
// updates the passed gui with current score information
void UpdateRankColor( idUserInterface *gui, const char *mask, int i, const idVec3 &vec );
// bdube: test scoreboard
void UpdateTestScoreboard( idUserInterface *scoreBoard );
// ddynerman: gametype specific scoreboard
void UpdateScoreboard( idUserInterface *scoreBoard );
void UpdateDMScoreboard( idUserInterface *scoreBoard );
void UpdateTeamScoreboard( idUserInterface *scoreBoard );
void UpdateSummaryBoard( idUserInterface *scoreBoard );
int GetPlayerRank( idPlayer* player, bool& isTied );
char* GetPlayerRankText( idPlayer* player );
char* GetPlayerRankText( int rank, bool tied, int score );
const char* BuildSummaryListString( idPlayer* player, int rankedScore );
void UpdatePrivatePlayerCount( void );
typedef struct announcerSoundNode_s {
announcerSound_t soundShader;
float time;
idLinkList<announcerSoundNode_s> announcerSoundNode;
int instance;
bool allowOverride;
} announcerSoundNode_t;
idLinkList<announcerSoundNode_t> announcerSoundQueue;
announcerSound_t lastAnnouncerSound;
static const char* announcerSoundDefs[ AS_NUM_SOUNDS ];
float announcerPlayTime;
void PlayAnnouncerSounds ( void );
int teamScore[ TEAM_MAX ];
int teamDeadZoneScore[ TEAM_MAX];
void ClearTeamScores ( void );
void UpdateLeader( idPlayer* oldLeader );
void ClearGuis( void );
void DrawScoreBoard( idPlayer *player );
void CheckVote( void );
bool AllPlayersReady( idStr* reason = NULL );
const char * GameTime( void );
bool EnoughClientsToPlay( void );
void DrawStatSummary( void );
// go through the clients, and see if they want to be respawned, and if the game allows it
// called during normal gameplay for death -> respawn cycles
// and for a spectator who want back in the game (see param)
void CheckRespawns( idPlayer *spectator = NULL );
void FreeLight ( int lightID );
void UpdateLight ( int lightID, idPlayer *player );
void CheckSpecialLights( void );
void ForceReady();
// when clients disconnect or join spectate during game, check if we need to end the game
void CheckAbortGame( void );
void MessageMode( const idCmdArgs &args );
void DisableMenu( void );
void SetMapShot( void );
// scores in TDM
void VoiceChat( const idCmdArgs &args, bool team );
// RAVEN BEGIN
// mekberg: added
void UpdateMPSettingsModel( idUserInterface* currentGui );
// RAVEN END
void WriteStartState( int clientNum, idBitMsg &msg, bool withLocalClient );
};
ID_INLINE bool idMultiplayerGame::IsPureReady( void ) const {
return pureReady;
}
ID_INLINE void idMultiplayerGame::ClearFrags( int clientNum ) {
playerState[ clientNum ].fragCount = 0;
}
ID_INLINE bool idMultiplayerGame::IsInGame( int clientNum ) {
return playerState[ clientNum ].ingame;
}
ID_INLINE int idMultiplayerGame::OpposingTeam( int team ) {
return (team == TEAM_STROGG ? TEAM_MARINE : TEAM_STROGG);
}
ID_INLINE idPlayer* idMultiplayerGame::GetRankedPlayer( int i ) {
if( i >= 0 && i < rankedPlayers.Num() ) {
return rankedPlayers[ i ].First();
} else {
return NULL;
}
}
ID_INLINE int idMultiplayerGame::GetRankedPlayerScore( int i ) {
if( i >= 0 && i < rankedPlayers.Num() ) {
return rankedPlayers[ i ].Second();
} else {
return 0;
}
}
ID_INLINE int idMultiplayerGame::GetNumUnrankedPlayers( void ) {
return unrankedPlayers.Num();
}
ID_INLINE idPlayer* idMultiplayerGame::GetUnrankedPlayer( int i ) {
if( i >= 0 && i < unrankedPlayers.Num() ) {
return unrankedPlayers[ i ];
} else {
return NULL;
}
}
ID_INLINE int idMultiplayerGame::GetNumRankedPlayers( void ) {
return rankedPlayers.Num();
}
ID_INLINE int idMultiplayerGame::GetTeamScore( int i ) {
return playerState[ i ].teamFragCount;
}
ID_INLINE int idMultiplayerGame::GetScore( int i ) {
return playerState[ i ].fragCount;
}
ID_INLINE int idMultiplayerGame::GetWins( int i ) {
return playerState[ i ].wins;
}
ID_INLINE void idMultiplayerGame::ResetRconGuiStatus( void ) {
if( mainGui) {
mainGui->SetStateInt( "password_valid", 0 );
}
}
// asalmon: needed access team scores for rich presence
ID_INLINE int idMultiplayerGame::GetScoreForTeam( int i ) {
if( i < 0 || i > TEAM_MAX ) {
return 0;
}
return teamScore[ i ];
}
ID_INLINE int idMultiplayerGame::TeamLeader( void ) {
if( teamScore[ TEAM_MARINE ] == teamScore[ TEAM_STROGG ] ) {
return -1;
} else {
return ( teamScore[ TEAM_MARINE ] > teamScore[ TEAM_STROGG ] ? TEAM_MARINE : TEAM_STROGG );
}
}
int ComparePlayersByScore( const void* left, const void* right );
int CompareTeamsByScore( const void* left, const void* right );
#endif /* !__MULTIPLAYERGAME_H__ */
// RAVEN END
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "Button1.h"
#include "ButtonInteractorComponent.h"
#include "Button1ActionComponent.h"
AButton1::AButton1() {
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = false;
if (!RootComponent)
{
RootComponent = CreateDefaultSubobject<USceneComponent>(TEXT("Root Component"));
}
InteractorComponent = CreateDefaultSubobject<UButtonInteractorComponent>(TEXT("Button Interactor Component"));
InteractorComponent->bIsPickable = false;
InteractorComponent->bIsInteractable = true;
ActionComponent = CreateDefaultSubobject<UButton1ActionComponent>(TEXT("Button 1 Action Component"));
Info = CreateDefaultSubobject<UObjectInfo>(TEXT("Object Infos"));
Info->Name = "Button 1";
Info->ObjectId = "button1";
Info->Description = "First button";
Info->MeshReference = "/Game/Asset/Sphere/Sphere_1.Sphere";
Info->ImageReference = "none";
}
|
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
for(int i=1000;i<10000;i++){
int a,b,c,d;
a=i/1000;
b=i/100%10;
c=i/10%10;
d=i%10;
if(a==d&&b==c){
printf("%d\n",i);
}
}
return 0;
}
|
#ifndef __VIVADO_SYNTH__
#include <fstream>
using namespace std;
// Debug utility
ofstream* global_debug_handle;
#endif //__VIVADO_SYNTH__
#include "blur_xy_16_unrolled_8_opt_compute_units.h"
#include "hw_classes.h"
struct blurx_blurx_update_0_write0_merged_banks_2_cache {
// RAM Box: {[0, 1920], [0, 1079]}
// Capacity: 2
// # of read delays: 2
hw_uint<16> f0;
hw_uint<16> f2;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct blurx_blurx_update_0_write1_merged_banks_2_cache {
// RAM Box: {[0, 1921], [0, 1079]}
// Capacity: 2
// # of read delays: 2
hw_uint<16> f0;
hw_uint<16> f2;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_1() {
return f2;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 1
f2 = f0;
// cap: 1
f0 = value;
}
};
struct blurx_blurx_update_0_write2_merged_banks_1_cache {
// RAM Box: {[0, 1922], [0, 1079]}
// Capacity: 2
// # of read delays: 2
fifo<hw_uint<16>, 2> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(1 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct blurx_blurx_update_0_write3_merged_banks_1_cache {
// RAM Box: {[0, 1923], [0, 1079]}
// Capacity: 2
// # of read delays: 2
fifo<hw_uint<16>, 2> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(1 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct blurx_blurx_update_0_write4_merged_banks_1_cache {
// RAM Box: {[0, 1924], [0, 1079]}
// Capacity: 2
// # of read delays: 2
fifo<hw_uint<16>, 2> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(1 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct blurx_blurx_update_0_write5_merged_banks_1_cache {
// RAM Box: {[0, 1925], [0, 1079]}
// Capacity: 2
// # of read delays: 2
fifo<hw_uint<16>, 2> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(1 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct blurx_blurx_update_0_write6_merged_banks_1_cache {
// RAM Box: {[0, 1926], [0, 1079]}
// Capacity: 2
// # of read delays: 2
fifo<hw_uint<16>, 2> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(1 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct blurx_blurx_update_0_write7_merged_banks_1_cache {
// RAM Box: {[0, 1927], [0, 1079]}
// Capacity: 2
// # of read delays: 2
fifo<hw_uint<16>, 2> f;
inline hw_uint<16> peek(const int offset) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.peek(1 - offset);
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f.push(value);
}
};
struct blurx_cache {
blurx_blurx_update_0_write0_merged_banks_2_cache blurx_blurx_update_0_write0_merged_banks_2;
blurx_blurx_update_0_write1_merged_banks_2_cache blurx_blurx_update_0_write1_merged_banks_2;
blurx_blurx_update_0_write2_merged_banks_1_cache blurx_blurx_update_0_write2_merged_banks_1;
blurx_blurx_update_0_write3_merged_banks_1_cache blurx_blurx_update_0_write3_merged_banks_1;
blurx_blurx_update_0_write4_merged_banks_1_cache blurx_blurx_update_0_write4_merged_banks_1;
blurx_blurx_update_0_write5_merged_banks_1_cache blurx_blurx_update_0_write5_merged_banks_1;
blurx_blurx_update_0_write6_merged_banks_1_cache blurx_blurx_update_0_write6_merged_banks_1;
blurx_blurx_update_0_write7_merged_banks_1_cache blurx_blurx_update_0_write7_merged_banks_1;
};
inline void blurx_blurx_update_0_write0_write(hw_uint<16>& blurx_blurx_update_0_write0, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write0_merged_banks_2.push(blurx_blurx_update_0_write0);
}
inline void blurx_blurx_update_0_write1_write(hw_uint<16>& blurx_blurx_update_0_write1, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write1_merged_banks_2.push(blurx_blurx_update_0_write1);
}
inline void blurx_blurx_update_0_write2_write(hw_uint<16>& blurx_blurx_update_0_write2, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write2_merged_banks_1.push(blurx_blurx_update_0_write2);
}
inline void blurx_blurx_update_0_write3_write(hw_uint<16>& blurx_blurx_update_0_write3, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write3_merged_banks_1.push(blurx_blurx_update_0_write3);
}
inline void blurx_blurx_update_0_write4_write(hw_uint<16>& blurx_blurx_update_0_write4, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write4_merged_banks_1.push(blurx_blurx_update_0_write4);
}
inline void blurx_blurx_update_0_write5_write(hw_uint<16>& blurx_blurx_update_0_write5, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write5_merged_banks_1.push(blurx_blurx_update_0_write5);
}
inline void blurx_blurx_update_0_write6_write(hw_uint<16>& blurx_blurx_update_0_write6, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write6_merged_banks_1.push(blurx_blurx_update_0_write6);
}
inline void blurx_blurx_update_0_write7_write(hw_uint<16>& blurx_blurx_update_0_write7, blurx_cache& blurx, int d0, int d1) {
blurx.blurx_blurx_update_0_write7_merged_banks_1.push(blurx_blurx_update_0_write7);
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd0_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd0 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write0 = blurx.blurx_blurx_update_0_write0_merged_banks_2.peek_1();
return value_blurx_blurx_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd1_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd1 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[1 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write1 = blurx.blurx_blurx_update_0_write1_merged_banks_2.peek_1();
return value_blurx_blurx_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd2_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd2 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[2 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write2 = blurx.blurx_blurx_update_0_write2_merged_banks_1.peek(/* one reader or all rams */ 1);
return value_blurx_blurx_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd3_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd3 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[3 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write3 = blurx.blurx_blurx_update_0_write3_merged_banks_1.peek(/* one reader or all rams */ 1);
return value_blurx_blurx_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd4_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd4 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[4 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write4 = blurx.blurx_blurx_update_0_write4_merged_banks_1.peek(/* one reader or all rams */ 1);
return value_blurx_blurx_update_0_write4;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd5_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd5 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[5 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write5 = blurx.blurx_blurx_update_0_write5_merged_banks_1.peek(/* one reader or all rams */ 1);
return value_blurx_blurx_update_0_write5;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd6_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd6 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[6 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write6 = blurx.blurx_blurx_update_0_write6_merged_banks_1.peek(/* one reader or all rams */ 1);
return value_blurx_blurx_update_0_write6;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd7_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd7 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[7 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { blur_xy_16_unrolled_8_update_0[d0, d1] -> 1 : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
auto value_blurx_blurx_update_0_write7 = blurx.blurx_blurx_update_0_write7_merged_banks_1.peek(/* one reader or all rams */ 1);
return value_blurx_blurx_update_0_write7;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd8_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd8 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[8 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_blurx_blurx_update_0_write0 = blurx.blurx_blurx_update_0_write0_merged_banks_2.peek_0();
return value_blurx_blurx_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blur_xy_16_unrolled_8_rd9_select(blurx_cache& blurx, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blur_xy_16_unrolled_8_rd9 read pattern: { blur_xy_16_unrolled_8_update_0[d0, d1] -> blurx[9 + 8d0, d1] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Read schedule : { blur_xy_16_unrolled_8_update_0[d0, d1] -> [2 + d1, 1 + d0, 3] : 0 <= d0 <= 239 and 0 <= d1 <= 1079 }
// Write schedule: { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// DD fold: { }
auto value_blurx_blurx_update_0_write1 = blurx.blurx_blurx_update_0_write1_merged_banks_2.peek_0();
return value_blurx_blurx_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// blur_xy_16_unrolled_8_update_0_read
// blur_xy_16_unrolled_8_rd0
// blur_xy_16_unrolled_8_rd1
// blur_xy_16_unrolled_8_rd2
// blur_xy_16_unrolled_8_rd3
// blur_xy_16_unrolled_8_rd4
// blur_xy_16_unrolled_8_rd5
// blur_xy_16_unrolled_8_rd6
// blur_xy_16_unrolled_8_rd7
// blur_xy_16_unrolled_8_rd8
// blur_xy_16_unrolled_8_rd9
inline hw_uint<160> blurx_blur_xy_16_unrolled_8_update_0_read_bundle_read(blurx_cache& blurx, int d0, int d1) {
// # of ports in bundle: 10
// blur_xy_16_unrolled_8_rd0
// blur_xy_16_unrolled_8_rd1
// blur_xy_16_unrolled_8_rd2
// blur_xy_16_unrolled_8_rd3
// blur_xy_16_unrolled_8_rd4
// blur_xy_16_unrolled_8_rd5
// blur_xy_16_unrolled_8_rd6
// blur_xy_16_unrolled_8_rd7
// blur_xy_16_unrolled_8_rd8
// blur_xy_16_unrolled_8_rd9
hw_uint<160> result;
hw_uint<16> blur_xy_16_unrolled_8_rd0_res = blur_xy_16_unrolled_8_rd0_select(blurx, d0, d1);
set_at<0, 160>(result, blur_xy_16_unrolled_8_rd0_res);
hw_uint<16> blur_xy_16_unrolled_8_rd1_res = blur_xy_16_unrolled_8_rd1_select(blurx, d0, d1);
set_at<16, 160>(result, blur_xy_16_unrolled_8_rd1_res);
hw_uint<16> blur_xy_16_unrolled_8_rd2_res = blur_xy_16_unrolled_8_rd2_select(blurx, d0, d1);
set_at<32, 160>(result, blur_xy_16_unrolled_8_rd2_res);
hw_uint<16> blur_xy_16_unrolled_8_rd3_res = blur_xy_16_unrolled_8_rd3_select(blurx, d0, d1);
set_at<48, 160>(result, blur_xy_16_unrolled_8_rd3_res);
hw_uint<16> blur_xy_16_unrolled_8_rd4_res = blur_xy_16_unrolled_8_rd4_select(blurx, d0, d1);
set_at<64, 160>(result, blur_xy_16_unrolled_8_rd4_res);
hw_uint<16> blur_xy_16_unrolled_8_rd5_res = blur_xy_16_unrolled_8_rd5_select(blurx, d0, d1);
set_at<80, 160>(result, blur_xy_16_unrolled_8_rd5_res);
hw_uint<16> blur_xy_16_unrolled_8_rd6_res = blur_xy_16_unrolled_8_rd6_select(blurx, d0, d1);
set_at<96, 160>(result, blur_xy_16_unrolled_8_rd6_res);
hw_uint<16> blur_xy_16_unrolled_8_rd7_res = blur_xy_16_unrolled_8_rd7_select(blurx, d0, d1);
set_at<112, 160>(result, blur_xy_16_unrolled_8_rd7_res);
hw_uint<16> blur_xy_16_unrolled_8_rd8_res = blur_xy_16_unrolled_8_rd8_select(blurx, d0, d1);
set_at<128, 160>(result, blur_xy_16_unrolled_8_rd8_res);
hw_uint<16> blur_xy_16_unrolled_8_rd9_res = blur_xy_16_unrolled_8_rd9_select(blurx, d0, d1);
set_at<144, 160>(result, blur_xy_16_unrolled_8_rd9_res);
return result;
}
// blurx_update_0_write
// blurx_blurx_update_0_write0
// blurx_blurx_update_0_write1
// blurx_blurx_update_0_write2
// blurx_blurx_update_0_write3
// blurx_blurx_update_0_write4
// blurx_blurx_update_0_write5
// blurx_blurx_update_0_write6
// blurx_blurx_update_0_write7
inline void blurx_blurx_update_0_write_bundle_write(hw_uint<128>& blurx_update_0_write, blurx_cache& blurx, int d0, int d1) {
hw_uint<16> blurx_blurx_update_0_write0_res = blurx_update_0_write.extract<0, 15>();
blurx_blurx_update_0_write0_write(blurx_blurx_update_0_write0_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write1_res = blurx_update_0_write.extract<16, 31>();
blurx_blurx_update_0_write1_write(blurx_blurx_update_0_write1_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write2_res = blurx_update_0_write.extract<32, 47>();
blurx_blurx_update_0_write2_write(blurx_blurx_update_0_write2_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write3_res = blurx_update_0_write.extract<48, 63>();
blurx_blurx_update_0_write3_write(blurx_blurx_update_0_write3_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write4_res = blurx_update_0_write.extract<64, 79>();
blurx_blurx_update_0_write4_write(blurx_blurx_update_0_write4_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write5_res = blurx_update_0_write.extract<80, 95>();
blurx_blurx_update_0_write5_write(blurx_blurx_update_0_write5_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write6_res = blurx_update_0_write.extract<96, 111>();
blurx_blurx_update_0_write6_write(blurx_blurx_update_0_write6_res, blurx, d0, d1);
hw_uint<16> blurx_blurx_update_0_write7_res = blurx_update_0_write.extract<112, 127>();
blurx_blurx_update_0_write7_write(blurx_blurx_update_0_write7_res, blurx, d0, d1);
}
#include "hw_classes.h"
struct input_input_update_0_write0_merged_banks_3_cache {
// RAM Box: {[0, 1920], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write1_merged_banks_3_cache {
// RAM Box: {[0, 1921], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write2_merged_banks_3_cache {
// RAM Box: {[0, 1922], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write3_merged_banks_3_cache {
// RAM Box: {[0, 1923], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write4_merged_banks_3_cache {
// RAM Box: {[0, 1924], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write5_merged_banks_3_cache {
// RAM Box: {[0, 1925], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write6_merged_banks_3_cache {
// RAM Box: {[0, 1926], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_input_update_0_write7_merged_banks_3_cache {
// RAM Box: {[0, 1927], [0, 1081]}
// Capacity: 483
// # of read delays: 3
hw_uint<16> f0;
fifo<hw_uint<16>, 240> f1;
hw_uint<16> f2;
fifo<hw_uint<16>, 240> f3;
hw_uint<16> f4;
inline hw_uint<16> peek_0() {
return f0;
}
inline hw_uint<16> peek_240() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f1.back();
}
inline hw_uint<16> peek_241() {
return f2;
}
inline hw_uint<16> peek_481() {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
return f3.back();
}
inline hw_uint<16> peek_482() {
return f4;
}
inline void push(const hw_uint<16> value) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f4 = f3.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f3.push(f2);
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 1 reading from capacity: 240
f2 = f1.back();
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// cap: 240 reading from capacity: 1
f1.push(f0);
// cap: 1
f0 = value;
}
};
struct input_cache {
input_input_update_0_write0_merged_banks_3_cache input_input_update_0_write0_merged_banks_3;
input_input_update_0_write1_merged_banks_3_cache input_input_update_0_write1_merged_banks_3;
input_input_update_0_write2_merged_banks_3_cache input_input_update_0_write2_merged_banks_3;
input_input_update_0_write3_merged_banks_3_cache input_input_update_0_write3_merged_banks_3;
input_input_update_0_write4_merged_banks_3_cache input_input_update_0_write4_merged_banks_3;
input_input_update_0_write5_merged_banks_3_cache input_input_update_0_write5_merged_banks_3;
input_input_update_0_write6_merged_banks_3_cache input_input_update_0_write6_merged_banks_3;
input_input_update_0_write7_merged_banks_3_cache input_input_update_0_write7_merged_banks_3;
};
inline void input_input_update_0_write0_write(hw_uint<16>& input_input_update_0_write0, input_cache& input, int d0, int d1) {
input.input_input_update_0_write0_merged_banks_3.push(input_input_update_0_write0);
}
inline void input_input_update_0_write1_write(hw_uint<16>& input_input_update_0_write1, input_cache& input, int d0, int d1) {
input.input_input_update_0_write1_merged_banks_3.push(input_input_update_0_write1);
}
inline void input_input_update_0_write2_write(hw_uint<16>& input_input_update_0_write2, input_cache& input, int d0, int d1) {
input.input_input_update_0_write2_merged_banks_3.push(input_input_update_0_write2);
}
inline void input_input_update_0_write3_write(hw_uint<16>& input_input_update_0_write3, input_cache& input, int d0, int d1) {
input.input_input_update_0_write3_merged_banks_3.push(input_input_update_0_write3);
}
inline void input_input_update_0_write4_write(hw_uint<16>& input_input_update_0_write4, input_cache& input, int d0, int d1) {
input.input_input_update_0_write4_merged_banks_3.push(input_input_update_0_write4);
}
inline void input_input_update_0_write5_write(hw_uint<16>& input_input_update_0_write5, input_cache& input, int d0, int d1) {
input.input_input_update_0_write5_merged_banks_3.push(input_input_update_0_write5);
}
inline void input_input_update_0_write6_write(hw_uint<16>& input_input_update_0_write6, input_cache& input, int d0, int d1) {
input.input_input_update_0_write6_merged_banks_3.push(input_input_update_0_write6);
}
inline void input_input_update_0_write7_write(hw_uint<16>& input_input_update_0_write7, input_cache& input, int d0, int d1) {
input.input_input_update_0_write7_merged_banks_3.push(input_input_update_0_write7);
}
inline hw_uint<16> blurx_rd0_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd0 read pattern: { blurx_update_0[d0, d1] -> input[8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_3.peek_482();
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd1_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd1 read pattern: { blurx_update_0[d0, d1] -> input[8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_3.peek_241();
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd10_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd10 read pattern: { blurx_update_0[d0, d1] -> input[3 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write3 = input.input_input_update_0_write3_merged_banks_3.peek_241();
return value_input_input_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd11_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd11 read pattern: { blurx_update_0[d0, d1] -> input[3 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write3 = input.input_input_update_0_write3_merged_banks_3.peek_0();
return value_input_input_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd12_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd12 read pattern: { blurx_update_0[d0, d1] -> input[4 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write4 = input.input_input_update_0_write4_merged_banks_3.peek_482();
return value_input_input_update_0_write4;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd13_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd13 read pattern: { blurx_update_0[d0, d1] -> input[4 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write4 = input.input_input_update_0_write4_merged_banks_3.peek_241();
return value_input_input_update_0_write4;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd14_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd14 read pattern: { blurx_update_0[d0, d1] -> input[4 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write4 = input.input_input_update_0_write4_merged_banks_3.peek_0();
return value_input_input_update_0_write4;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd15_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd15 read pattern: { blurx_update_0[d0, d1] -> input[5 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write5 = input.input_input_update_0_write5_merged_banks_3.peek_482();
return value_input_input_update_0_write5;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd16_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd16 read pattern: { blurx_update_0[d0, d1] -> input[5 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write5 = input.input_input_update_0_write5_merged_banks_3.peek_241();
return value_input_input_update_0_write5;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd17_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd17 read pattern: { blurx_update_0[d0, d1] -> input[5 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write5 = input.input_input_update_0_write5_merged_banks_3.peek_0();
return value_input_input_update_0_write5;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd18_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd18 read pattern: { blurx_update_0[d0, d1] -> input[6 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write6 = input.input_input_update_0_write6_merged_banks_3.peek_482();
return value_input_input_update_0_write6;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd19_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd19 read pattern: { blurx_update_0[d0, d1] -> input[6 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write6 = input.input_input_update_0_write6_merged_banks_3.peek_241();
return value_input_input_update_0_write6;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd2_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd2 read pattern: { blurx_update_0[d0, d1] -> input[8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write0 = input.input_input_update_0_write0_merged_banks_3.peek_0();
return value_input_input_update_0_write0;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd20_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd20 read pattern: { blurx_update_0[d0, d1] -> input[6 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write6 = input.input_input_update_0_write6_merged_banks_3.peek_0();
return value_input_input_update_0_write6;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd21_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd21 read pattern: { blurx_update_0[d0, d1] -> input[7 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write7 = input.input_input_update_0_write7_merged_banks_3.peek_482();
return value_input_input_update_0_write7;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd22_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd22 read pattern: { blurx_update_0[d0, d1] -> input[7 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write7 = input.input_input_update_0_write7_merged_banks_3.peek_241();
return value_input_input_update_0_write7;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd23_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd23 read pattern: { blurx_update_0[d0, d1] -> input[7 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write7 = input.input_input_update_0_write7_merged_banks_3.peek_0();
return value_input_input_update_0_write7;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd3_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd3 read pattern: { blurx_update_0[d0, d1] -> input[1 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write1 = input.input_input_update_0_write1_merged_banks_3.peek_482();
return value_input_input_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd4_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd4 read pattern: { blurx_update_0[d0, d1] -> input[1 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write1 = input.input_input_update_0_write1_merged_banks_3.peek_241();
return value_input_input_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd5_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd5 read pattern: { blurx_update_0[d0, d1] -> input[1 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write1 = input.input_input_update_0_write1_merged_banks_3.peek_0();
return value_input_input_update_0_write1;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd6_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd6 read pattern: { blurx_update_0[d0, d1] -> input[2 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write2 = input.input_input_update_0_write2_merged_banks_3.peek_482();
return value_input_input_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd7_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd7 read pattern: { blurx_update_0[d0, d1] -> input[2 + 8d0, 1 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 241 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (1 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 241 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write2 = input.input_input_update_0_write2_merged_banks_3.peek_241();
return value_input_input_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd8_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd8 read pattern: { blurx_update_0[d0, d1] -> input[2 + 8d0, 2 + d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { }
auto value_input_input_update_0_write2 = input.input_input_update_0_write2_merged_banks_3.peek_0();
return value_input_input_update_0_write2;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
inline hw_uint<16> blurx_rd9_select(input_cache& input, int d0, int d1) {
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
// blurx_rd9 read pattern: { blurx_update_0[d0, d1] -> input[3 + 8d0, d1] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Read schedule : { blurx_update_0[d0, d1] -> [2 + d1, d0, 2] : 0 <= d0 <= 240 and 0 <= d1 <= 1079 }
// Write schedule: { input_update_0[d0, d1] -> [d1, d0, 1] : 0 <= d0 <= 240 and 0 <= d1 <= 1081 }
// DD fold: { blurx_update_0[d0, d1] -> 482 : 0 < d0 <= 239 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> (242 + d0) : d0 = 240 and 0 <= d1 <= 1079; blurx_update_0[d0, d1] -> 482 : d0 = 0 and 0 <= d1 <= 1079 }
auto value_input_input_update_0_write3 = input.input_input_update_0_write3_merged_banks_3.peek_482();
return value_input_input_update_0_write3;
#ifndef __VIVADO_SYNTH__
cout << "Error: Unsupported offsets: " << " d0 = " << d0 << " d1 = " << d1 << endl;
assert(false);
return 0;
#endif //__VIVADO_SYNTH__
}
// # of bundles = 2
// blurx_update_0_read
// blurx_rd0
// blurx_rd1
// blurx_rd2
// blurx_rd3
// blurx_rd4
// blurx_rd5
// blurx_rd6
// blurx_rd7
// blurx_rd8
// blurx_rd9
// blurx_rd10
// blurx_rd11
// blurx_rd12
// blurx_rd13
// blurx_rd14
// blurx_rd15
// blurx_rd16
// blurx_rd17
// blurx_rd18
// blurx_rd19
// blurx_rd20
// blurx_rd21
// blurx_rd22
// blurx_rd23
inline hw_uint<384> input_blurx_update_0_read_bundle_read(input_cache& input, int d0, int d1) {
// # of ports in bundle: 24
// blurx_rd0
// blurx_rd1
// blurx_rd2
// blurx_rd3
// blurx_rd4
// blurx_rd5
// blurx_rd6
// blurx_rd7
// blurx_rd8
// blurx_rd9
// blurx_rd10
// blurx_rd11
// blurx_rd12
// blurx_rd13
// blurx_rd14
// blurx_rd15
// blurx_rd16
// blurx_rd17
// blurx_rd18
// blurx_rd19
// blurx_rd20
// blurx_rd21
// blurx_rd22
// blurx_rd23
hw_uint<384> result;
hw_uint<16> blurx_rd0_res = blurx_rd0_select(input, d0, d1);
set_at<0, 384>(result, blurx_rd0_res);
hw_uint<16> blurx_rd1_res = blurx_rd1_select(input, d0, d1);
set_at<16, 384>(result, blurx_rd1_res);
hw_uint<16> blurx_rd2_res = blurx_rd2_select(input, d0, d1);
set_at<32, 384>(result, blurx_rd2_res);
hw_uint<16> blurx_rd3_res = blurx_rd3_select(input, d0, d1);
set_at<48, 384>(result, blurx_rd3_res);
hw_uint<16> blurx_rd4_res = blurx_rd4_select(input, d0, d1);
set_at<64, 384>(result, blurx_rd4_res);
hw_uint<16> blurx_rd5_res = blurx_rd5_select(input, d0, d1);
set_at<80, 384>(result, blurx_rd5_res);
hw_uint<16> blurx_rd6_res = blurx_rd6_select(input, d0, d1);
set_at<96, 384>(result, blurx_rd6_res);
hw_uint<16> blurx_rd7_res = blurx_rd7_select(input, d0, d1);
set_at<112, 384>(result, blurx_rd7_res);
hw_uint<16> blurx_rd8_res = blurx_rd8_select(input, d0, d1);
set_at<128, 384>(result, blurx_rd8_res);
hw_uint<16> blurx_rd9_res = blurx_rd9_select(input, d0, d1);
set_at<144, 384>(result, blurx_rd9_res);
hw_uint<16> blurx_rd10_res = blurx_rd10_select(input, d0, d1);
set_at<160, 384>(result, blurx_rd10_res);
hw_uint<16> blurx_rd11_res = blurx_rd11_select(input, d0, d1);
set_at<176, 384>(result, blurx_rd11_res);
hw_uint<16> blurx_rd12_res = blurx_rd12_select(input, d0, d1);
set_at<192, 384>(result, blurx_rd12_res);
hw_uint<16> blurx_rd13_res = blurx_rd13_select(input, d0, d1);
set_at<208, 384>(result, blurx_rd13_res);
hw_uint<16> blurx_rd14_res = blurx_rd14_select(input, d0, d1);
set_at<224, 384>(result, blurx_rd14_res);
hw_uint<16> blurx_rd15_res = blurx_rd15_select(input, d0, d1);
set_at<240, 384>(result, blurx_rd15_res);
hw_uint<16> blurx_rd16_res = blurx_rd16_select(input, d0, d1);
set_at<256, 384>(result, blurx_rd16_res);
hw_uint<16> blurx_rd17_res = blurx_rd17_select(input, d0, d1);
set_at<272, 384>(result, blurx_rd17_res);
hw_uint<16> blurx_rd18_res = blurx_rd18_select(input, d0, d1);
set_at<288, 384>(result, blurx_rd18_res);
hw_uint<16> blurx_rd19_res = blurx_rd19_select(input, d0, d1);
set_at<304, 384>(result, blurx_rd19_res);
hw_uint<16> blurx_rd20_res = blurx_rd20_select(input, d0, d1);
set_at<320, 384>(result, blurx_rd20_res);
hw_uint<16> blurx_rd21_res = blurx_rd21_select(input, d0, d1);
set_at<336, 384>(result, blurx_rd21_res);
hw_uint<16> blurx_rd22_res = blurx_rd22_select(input, d0, d1);
set_at<352, 384>(result, blurx_rd22_res);
hw_uint<16> blurx_rd23_res = blurx_rd23_select(input, d0, d1);
set_at<368, 384>(result, blurx_rd23_res);
return result;
}
// input_update_0_write
// input_input_update_0_write0
// input_input_update_0_write1
// input_input_update_0_write2
// input_input_update_0_write3
// input_input_update_0_write4
// input_input_update_0_write5
// input_input_update_0_write6
// input_input_update_0_write7
inline void input_input_update_0_write_bundle_write(hw_uint<128>& input_update_0_write, input_cache& input, int d0, int d1) {
hw_uint<16> input_input_update_0_write0_res = input_update_0_write.extract<0, 15>();
input_input_update_0_write0_write(input_input_update_0_write0_res, input, d0, d1);
hw_uint<16> input_input_update_0_write1_res = input_update_0_write.extract<16, 31>();
input_input_update_0_write1_write(input_input_update_0_write1_res, input, d0, d1);
hw_uint<16> input_input_update_0_write2_res = input_update_0_write.extract<32, 47>();
input_input_update_0_write2_write(input_input_update_0_write2_res, input, d0, d1);
hw_uint<16> input_input_update_0_write3_res = input_update_0_write.extract<48, 63>();
input_input_update_0_write3_write(input_input_update_0_write3_res, input, d0, d1);
hw_uint<16> input_input_update_0_write4_res = input_update_0_write.extract<64, 79>();
input_input_update_0_write4_write(input_input_update_0_write4_res, input, d0, d1);
hw_uint<16> input_input_update_0_write5_res = input_update_0_write.extract<80, 95>();
input_input_update_0_write5_write(input_input_update_0_write5_res, input, d0, d1);
hw_uint<16> input_input_update_0_write6_res = input_update_0_write.extract<96, 111>();
input_input_update_0_write6_write(input_input_update_0_write6_res, input, d0, d1);
hw_uint<16> input_input_update_0_write7_res = input_update_0_write.extract<112, 127>();
input_input_update_0_write7_write(input_input_update_0_write7_res, input, d0, d1);
}
// Operation logic
inline void blurx_update_0(input_cache& input, blurx_cache& blurx, int d0, int d1) {
// Consume: input
auto input_0_c__0_value = input_blurx_update_0_read_bundle_read(input/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "blurx_update_0_input," << d0<< "," << d1<< "," << input_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = blurx_generated_compute_unrolled_8(input_0_c__0_value);
// Produce: blurx
blurx_blurx_update_0_write_bundle_write(compute_result, blurx, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<128> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
hw_uint<16> debug_compute_result_lane_2;
set_at<0, 16, 16>(debug_compute_result_lane_2, debug_compute_result.extract<32, 47>());
hw_uint<16> debug_compute_result_lane_3;
set_at<0, 16, 16>(debug_compute_result_lane_3, debug_compute_result.extract<48, 63>());
hw_uint<16> debug_compute_result_lane_4;
set_at<0, 16, 16>(debug_compute_result_lane_4, debug_compute_result.extract<64, 79>());
hw_uint<16> debug_compute_result_lane_5;
set_at<0, 16, 16>(debug_compute_result_lane_5, debug_compute_result.extract<80, 95>());
hw_uint<16> debug_compute_result_lane_6;
set_at<0, 16, 16>(debug_compute_result_lane_6, debug_compute_result.extract<96, 111>());
hw_uint<16> debug_compute_result_lane_7;
set_at<0, 16, 16>(debug_compute_result_lane_7, debug_compute_result.extract<112, 127>());
*global_debug_handle << "blurx_update_0," << (8*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 2) << ", " << d1<< "," << debug_compute_result_lane_2 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 3) << ", " << d1<< "," << debug_compute_result_lane_3 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 4) << ", " << d1<< "," << debug_compute_result_lane_4 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 5) << ", " << d1<< "," << debug_compute_result_lane_5 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 6) << ", " << d1<< "," << debug_compute_result_lane_6 << endl;
*global_debug_handle << "blurx_update_0," << (8*d0 + 7) << ", " << d1<< "," << debug_compute_result_lane_7 << endl;
#endif //__VIVADO_SYNTH__
}
inline void blur_xy_16_unrolled_8_update_0(blurx_cache& blurx, HWStream<hw_uint<128> >& /* buffer_args num ports = 8 */blur_xy_16_unrolled_8, int d0, int d1) {
// Consume: blurx
auto blurx_0_c__0_value = blurx_blur_xy_16_unrolled_8_update_0_read_bundle_read(blurx/* source_delay */, d0, d1);
#ifndef __VIVADO_SYNTH__
*global_debug_handle << "blur_xy_16_unrolled_8_update_0_blurx," << d0<< "," << d1<< "," << blurx_0_c__0_value << endl;
#endif //__VIVADO_SYNTH__
auto compute_result = blur_xy_16_unrolled_8_generated_compute_unrolled_8(blurx_0_c__0_value);
// Produce: blur_xy_16_unrolled_8
blur_xy_16_unrolled_8.write(compute_result);
#ifndef __VIVADO_SYNTH__
hw_uint<128> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
hw_uint<16> debug_compute_result_lane_2;
set_at<0, 16, 16>(debug_compute_result_lane_2, debug_compute_result.extract<32, 47>());
hw_uint<16> debug_compute_result_lane_3;
set_at<0, 16, 16>(debug_compute_result_lane_3, debug_compute_result.extract<48, 63>());
hw_uint<16> debug_compute_result_lane_4;
set_at<0, 16, 16>(debug_compute_result_lane_4, debug_compute_result.extract<64, 79>());
hw_uint<16> debug_compute_result_lane_5;
set_at<0, 16, 16>(debug_compute_result_lane_5, debug_compute_result.extract<80, 95>());
hw_uint<16> debug_compute_result_lane_6;
set_at<0, 16, 16>(debug_compute_result_lane_6, debug_compute_result.extract<96, 111>());
hw_uint<16> debug_compute_result_lane_7;
set_at<0, 16, 16>(debug_compute_result_lane_7, debug_compute_result.extract<112, 127>());
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 2) << ", " << d1<< "," << debug_compute_result_lane_2 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 3) << ", " << d1<< "," << debug_compute_result_lane_3 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 4) << ", " << d1<< "," << debug_compute_result_lane_4 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 5) << ", " << d1<< "," << debug_compute_result_lane_5 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 6) << ", " << d1<< "," << debug_compute_result_lane_6 << endl;
*global_debug_handle << "blur_xy_16_unrolled_8_update_0," << (8*d0 + 7) << ", " << d1<< "," << debug_compute_result_lane_7 << endl;
#endif //__VIVADO_SYNTH__
}
inline void input_update_0(HWStream<hw_uint<128> >& /* buffer_args num ports = 8 */input_arg, input_cache& input, int d0, int d1) {
// Consume: input_arg
auto input_arg_0_c__0_value = input_arg.read();
auto compute_result = input_generated_compute_unrolled_8(input_arg_0_c__0_value);
// Produce: input
input_input_update_0_write_bundle_write(compute_result, input, d0, d1);
#ifndef __VIVADO_SYNTH__
hw_uint<128> debug_compute_result(compute_result);
hw_uint<16> debug_compute_result_lane_0;
set_at<0, 16, 16>(debug_compute_result_lane_0, debug_compute_result.extract<0, 15>());
hw_uint<16> debug_compute_result_lane_1;
set_at<0, 16, 16>(debug_compute_result_lane_1, debug_compute_result.extract<16, 31>());
hw_uint<16> debug_compute_result_lane_2;
set_at<0, 16, 16>(debug_compute_result_lane_2, debug_compute_result.extract<32, 47>());
hw_uint<16> debug_compute_result_lane_3;
set_at<0, 16, 16>(debug_compute_result_lane_3, debug_compute_result.extract<48, 63>());
hw_uint<16> debug_compute_result_lane_4;
set_at<0, 16, 16>(debug_compute_result_lane_4, debug_compute_result.extract<64, 79>());
hw_uint<16> debug_compute_result_lane_5;
set_at<0, 16, 16>(debug_compute_result_lane_5, debug_compute_result.extract<80, 95>());
hw_uint<16> debug_compute_result_lane_6;
set_at<0, 16, 16>(debug_compute_result_lane_6, debug_compute_result.extract<96, 111>());
hw_uint<16> debug_compute_result_lane_7;
set_at<0, 16, 16>(debug_compute_result_lane_7, debug_compute_result.extract<112, 127>());
*global_debug_handle << "input_update_0," << (8*d0 + 0) << ", " << d1<< "," << debug_compute_result_lane_0 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 1) << ", " << d1<< "," << debug_compute_result_lane_1 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 2) << ", " << d1<< "," << debug_compute_result_lane_2 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 3) << ", " << d1<< "," << debug_compute_result_lane_3 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 4) << ", " << d1<< "," << debug_compute_result_lane_4 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 5) << ", " << d1<< "," << debug_compute_result_lane_5 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 6) << ", " << d1<< "," << debug_compute_result_lane_6 << endl;
*global_debug_handle << "input_update_0," << (8*d0 + 7) << ", " << d1<< "," << debug_compute_result_lane_7 << endl;
#endif //__VIVADO_SYNTH__
}
// Driver function
void blur_xy_16_unrolled_8_opt(HWStream<hw_uint<128> >& /* get_args num ports = 8 */input_arg, HWStream<hw_uint<128> >& /* get_args num ports = 8 */blur_xy_16_unrolled_8) {
#ifndef __VIVADO_SYNTH__
ofstream debug_file("blur_xy_16_unrolled_8_opt_debug.csv");
global_debug_handle = &debug_file;
#endif //__VIVADO_SYNTH__
blurx_cache blurx;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
input_cache input;
#ifdef __VIVADO_SYNTH__
#endif //__VIVADO_SYNTH__
#ifdef __VIVADO_SYNTH__
#pragma HLS inline recursive
#endif // __VIVADO_SYNTH__
for (int c0 = 0; c0 <= 1081; c0++) {
for (int c1 = 0; c1 <= 240; c1++) {
#ifdef __VIVADO_SYNTH__
#pragma HLS pipeline II=1
#endif // __VIVADO_SYNTH__
if ((0 <= c1 && c1 <= 240) && ((c1 - 0) % 1 == 0) && (0 <= c0 && c0 <= 1081) && ((c0 - 0) % 1 == 0)) {
input_update_0(input_arg, input, (c1 - 0) / 1, (c0 - 0) / 1);
}
if ((0 <= c1 && c1 <= 240) && ((c1 - 0) % 1 == 0) && (2 <= c0 && c0 <= 1081) && ((c0 - 2) % 1 == 0)) {
blurx_update_0(input, blurx, (c1 - 0) / 1, (c0 - 2) / 1);
}
if ((1 <= c1 && c1 <= 240) && ((c1 - 1) % 1 == 0) && (2 <= c0 && c0 <= 1081) && ((c0 - 2) % 1 == 0)) {
blur_xy_16_unrolled_8_update_0(blurx, blur_xy_16_unrolled_8, (c1 - 1) / 1, (c0 - 2) / 1);
}
}
}
#ifndef __VIVADO_SYNTH__
debug_file.close();
#endif //__VIVADO_SYNTH__
}
#ifdef __VIVADO_SYNTH__
#include "blur_xy_16_unrolled_8_opt.h"
#define INPUT_SIZE 2086096
#define OUTPUT_SIZE 2073600
extern "C" {
static void read_input(hw_uint<128>* input, HWStream<hw_uint<128> >& v, const int size) {
for (int i = 0; i < INPUT_SIZE; i++) {
#pragma HLS pipeline II=1
v.write(input[i]);
}
}
static void write_output(hw_uint<128>* output, HWStream<hw_uint<128> >& v, const int size) {
for (int i = 0; i < OUTPUT_SIZE; i++) {
#pragma HLS pipeline II=1
output[i] = v.read();
}
}
void blur_xy_16_unrolled_8_opt_accel(hw_uint<128>* input_update_0_read, hw_uint<128>* blur_xy_16_unrolled_8_update_0_write, const int size) {
#pragma HLS dataflow
#pragma HLS INTERFACE m_axi port = input_update_0_read offset = slave bundle = gmem
#pragma HLS INTERFACE m_axi port = blur_xy_16_unrolled_8_update_0_write offset = slave bundle = gmem
#pragma HLS INTERFACE s_axilite port = input_update_0_read bundle = control
#pragma HLS INTERFACE s_axilite port = blur_xy_16_unrolled_8_update_0_write bundle = control
#pragma HLS INTERFACE s_axilite port = size bundle = control
#pragma HLS INTERFACE s_axilite port = return bundle = control
static HWStream<hw_uint<128> > input_update_0_read_channel;
static HWStream<hw_uint<128> > blur_xy_16_unrolled_8_update_0_write_channel;
read_input(input_update_0_read, input_update_0_read_channel, size);
blur_xy_16_unrolled_8_opt(input_update_0_read_channel, blur_xy_16_unrolled_8_update_0_write_channel);
write_output(blur_xy_16_unrolled_8_update_0_write, blur_xy_16_unrolled_8_update_0_write_channel, size);
}
}
#endif //__VIVADO_SYNTH__
|
#pragma once
#include "MainHeader.h"
#include "tiny_obj_loader.h"
#include "Gizmos.h"
#include "Input.h"
#include "Camera.h"
#include "FlyCam.h"
#include "Entity.h"
#include "Application.h"
#include "ParticleEmitter.h"
#include <imgui.h>
#include "GPUParticleEmitter.h"
#include "Shader.h"
class Application3D : public aie::Application {
public:
//const static Application3D* instance;
// our vertex and index buffers
unsigned int m_vao;
unsigned int m_vbo;
unsigned int m_ibo;
// the frame buffer object
unsigned int m_fbo;
unsigned int m_fboDepth;
unsigned int m_fboTexture;
unsigned int m_texture,specMap;
glm::vec3 sunPos;
glm::vec3 sunCol;
std::vector<OpenGLInfo> m_glInfo;
// obj mesh data is stored here after being loaded
tinyobj::attrib_t attribs;
std::vector<tinyobj::shape_t> shapes;
std::vector<tinyobj::shape_t> allShapes;
glm::mat4 modelPos;
ParticleEmitter* m_emitter;
Application3D();
virtual ~Application3D();
void FrameBufferStartup();
virtual bool startup();
virtual void shutdown();
void CreateTextureShader();
void CreateParticleShader();
void CreateBufferShader();
void LoadImageTextures();
void LoadObj();
void LoadObj(const char* location);
void CreateOpenGlBuffers(tinyobj::attrib_t & attribs, std::vector<tinyobj::shape_t>& shapes);
virtual void update(float deltaTime);
virtual void draw();
void RenderCulling(Entity entity);
unsigned int GetProgromID();
protected:
glm::mat4 m_viewMatrix;
glm::mat4 m_projectionMatrix;
};
|
#include <bits/stdc++.h>
using namespace std;
#define TESTC ""
#define PROBLEM "167"
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
vector <int> table[8];
int column[8],Left[15],Right[15];
int tmp[8];
void Queen(int k){
if( k == 8 ){
for(int j = 0 ; j < 8 ; j++){
table[j].push_back(tmp[j]);
}
return;
}
for(int i = 0 ; i < 8 ; i++ ){
int l = k+i;
int r = k-i+7;
if( column[i] == 0 && Left[l] == 0 && Right[r] == 0 ){
column[i] = 1 , Left[l] = 1 , Right[r] = 1;
tmp[k] = i;
Queen(k+1);
column[i] = 0 , Left[l] = 0 , Right[r] = 0;
}
}
}
int main(int argc, char const *argv[])
{
#ifdef DBG
freopen("uva" PROBLEM TESTC ".in", "r", stdin);
freopen("uva" PROBLEM ".out", "w", stdout);
#endif
memset(column,0,sizeof(column));
memset(Left,0,sizeof(Left));
memset(Right,0,sizeof(Right));
Queen(0);
int test[8][8];
int times,i,j;
scanf("%d",×);
while( times-- ){
for( i = 0 ; i < 8 ; i++ ){
for( j = 0 ; j < 8 ; j++ ){
scanf("%d",&test[i][j]);
}
}
int tmp = 0,ans = 0;
for( i = 0 ; i < 92 ; i++ ){
tmp = 0;
for( j = 0 ; j < 8 ; j++ ){
tmp = tmp + test[j][table[j][i]];
}
if(tmp > ans)
ans = tmp;
}
printf("%5d\n",ans );
}
return 0;
}
|
#pragma once
#include "Fornitual.h"
class Bed :
virtual public Fornitual
{
public:
Bed(float l, float w, float h);
void sleep();
};
|
#ifndef CSHAPE_H
#define CSHAPE_H
// system includes
#include <iostream>
#include <map>
// project includes
#include "xmlParser.h"
// forward declaration
class CShape;
// typedef
typedef CShape* (*CreateFromXmlType )( XMLNode& ) ;
class CShape
{
public:
CShape () : mVisible(true) { gTotalShapes++; }
virtual ~CShape() { ; }
virtual void Draw() const = 0;
static int CreatedShapes() { return gTotalShapes; }
virtual void SaveXml ( XMLNode& ) = 0;
typedef std::map< std::string, CreateFromXmlType > CreationMapType;
typedef CreationMapType::iterator CreationMapIter;
static CreationMapType gCreateFromXmlMap;
private:
bool mVisible;
static int gTotalShapes;
};
#endif // CSHAPE_H
|
#include "util.h"
std::vector<std::string> util::tokenize(std::string s, std::string del)
{
std::vector<std::string> ret;
int start = 0;
int end = s.find(del);
while (end != std::string::npos) {
ret.push_back(s.substr(start, end - start));
start = end + del.size();
end = s.find(del, start);
}
ret.push_back(s.substr(start, end - start));
return ret;
}
|
#pragma once
#include "ErrorCode.h"
namespace arithmetic_parser
{
struct ErrorData
{
ErrorCode m_error_code;
int m_error_start_index;
int m_error_end_index;
//string description of the error
ErrorData() = default;
ErrorData(const ErrorData&) = default;
ErrorData(ErrorCode error_code, int error_start_index);
ErrorData(ErrorCode error_code, int error_start_index, int error_end_index);
};
}
|
#ifndef FILENETWORKMANAGER_H
#define FILENETWORKMANAGER_H
#include <QtCore>
#include <QtNetwork>
#include <QNetworkAccessManager>
#include <QProgressBar>
#include "commons.h"
class FileNetworkManager : public QNetworkAccessManager
{
Q_OBJECT
public:
explicit FileNetworkManager(QString address, QPair<QString, QString> tokenPair, QObject *parent = 0);
explicit FileNetworkManager(QStringList fileList, QString address, QObject *parent = 0, bool isUpload = false);
explicit FileNetworkManager(QByteArray byteArray, QString address, QObject *parent = 0);
explicit FileNetworkManager(QString address, QString fileName, QString filePath, QPair<QString, QString> tokenPair,
QString belongId, QString fileType, QObject *parent = 0);
~FileNetworkManager();
void execute();
void upload();
void change();
void add74Book();
void deleteExeute();
void appendFile();
qint64 m_hasSize;
int m_exist;
QProgressBar *m_pBar;
int m_statusCode;
QByteArray m_bytes;
QBuffer *m_buffer;
void uploadBuffer();
void stopWork();
signals:
void replyFileFinished(int statusCode, QByteArray baJson);
void sendRate(QString rate);
void speedChanged(int exist, QString speedStr);
private slots:
void replyFinished(QNetworkReply *reply);
void readyRead();
void onUploadProgress(qint64 bytesSent, qint64 bytesTotal);
void speed();
private:
QNetworkReply *m_pReply;
QStringList m_fileList;
QByteArray m_byteArray;
QString m_address;
QString m_fileName;
QString m_filePath;
bool m_isUpload;
QPair<QString, QString> m_tokenPair;
QString m_belongId;
QString m_fileType;
qint64 foreSize;
qint64 nowSize;
qint64 remainingSize;
QTimer *timer;
QNetworkRequest requestSetRawHeader(QNetworkRequest request);
};
#endif // FILENETWORKMANAGER_H
|
//
// Created by Lee on 2019-04-23.
//
#include "PhotoThumbnailForUpload.h"
#include <QDebug>
#include <QUrl>
#include <QStandardPaths>
#include <QFileDialog>
#include <QProcess>
#include <src/image/ImagePool.h>
#include <src/util/ThumbnailMaker.h>
#include <src/util/ImageFileManager.h>
#include <src/util/ImageDownloader.h>
PhotoThumbnailForUpload::PhotoThumbnailForUpload(QWidget *parent,
PhotoGroup *group,
PhotoManager *photoManager) : QWidget(parent) {
groupId = group->getId();
groupName = group->getName();
this->photoManager = photoManager;
photoGroup = group;
pushButton = new QPushButton(this);
pushButton->resize(475, 475);
QLabel * textLabel = new QLabel(pushButton);
textLabel->setText(group->getName());
QRect tmpRect = pushButton->geometry();
tmpRect.moveTo(tmpRect.x() + 232, tmpRect.y());
tmpRect.setSize(QSize(475, 25));
textLabel->setGeometry(tmpRect);
this->resize(475, 475);
photos = group->getPhotoList();
updateThumbnail();
connect(pushButton, SIGNAL(released()), this, SLOT(handleButton()));
}
QString PhotoThumbnailForUpload::getGroupName() {
return groupName;
}
void PhotoThumbnailForUpload::updateThumbnail() {
ThumbnailMaker::makeThumbnailOfPhotoGroup(photos, pushButton, thumbnails);
this->update();
}
void PhotoThumbnailForUpload::handleButton() {
Photo photo = ImageFileManager::uploadPhotoFileToGithub(this);
photo = photoManager->updatePhoto(photo, groupName);
photos.insert(photos.begin(), photo);
updateThumbnail();
qDebug() << photo.getUrl();
}
|
#include <iostream>
int main()
{
int p, q;
std::cin >> p >> q;
if (p == q )
{
std::cout << 0;
}
else
{
std::cout << 1;
}
return 0;
}
|
#include "BlackScholesDiscreteDivPut.h"
BlackScholesDiscreteDivPut::BlackScholesDiscreteDivPut(double _S0, double _E, double _r, double _sigma, double _T, int dividend_number, Dividend<double> **dividends) :
BlackScholesMertonPut(_S0, _E, _r, _sigma, _T), dividend_number(dividend_number), dividends(dividends) {}
double BlackScholesDiscreteDivPut::calculate(const double t) {
this->S0 -= discDiv.present_div_sum(this->T, this->r, this->dividends, this->dividend_number);
return BlackScholesMertonPut::calculate(t);
}
|
#include "SystemTimer.h"
#ifndef __SystemTimer_H
#error [E030] Не определен заголовочный файл SystemTimer.h
#endif
uint64_t SystemTimer::ticks = 0;
//-----------public----------------------------
void SystemTimer::init10msInterrupt()
{
OCR2 = 158-1; // Записываю регистр сравнения //
TCCR2 = 0; // Выход таймера отключен //
TCCR2 = 1<<WGM21; // Режим CTC - сброс при совпадении //
TCCR2 |= (1<<CS22)|(1<<CS21)|(1<<CS20); // Коэффициент предделителя = 1024 //
TIMSK = (1<<OCIE2); // Разрешаю прерывание при совпадении регистров //
}
//---------private------------------------------
void SystemTimer::handleTickInterrupt()
{
ticks++;
}
uint64_t SystemTimer::getTicks()
{
return ticks;
}
|
// Copyright (c) 2013 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _BRepMesh_FastDiscret_HeaderFile
#define _BRepMesh_FastDiscret_HeaderFile
#include <IMeshTools_Parameters.hxx>
class Standard_DEPRECATED("The class BRepMesh_FastDiscret is deprecated. Please use IMeshTools package") BRepMesh_FastDiscret
{
public:
Standard_DEPRECATED("The class BRepMesh_FastDiscret is deprecated. Please use IMeshTools package")
typedef IMeshTools_Parameters Parameters;
};
#endif
|
#pragma once
#include <math/hitable.h>
/* Holds all the shapes in the scene. */
class ShapeList {
public:
__device__ ShapeList() = default;
__device__ ShapeList(Hitable** objs, int count) :
object_list(objs), object_count(count) {}
__device__ ~ShapeList() = default;
/* Casts a ray and returns if it hit any object. */
__device__ bool cast_ray(const Ray& r, float t_min, float t_max, HitDesc& d)
{
HitDesc temp_d;
bool hit_object = false;
double closest_object_hit = t_max;
for (int i = 0; i < object_count; i++) {
Hitable* object = object_list[i];
if (object->hit(r, t_min, closest_object_hit, temp_d)) {
hit_object = true;
closest_object_hit = temp_d.t;
d = temp_d;
}
}
return hit_object;
}
public:
Hitable** object_list;
int object_count = 0;
};
|
//
// Created by abel_ on 03-09-2022.
//
#include <bits/stdc++.h>
using namespace std;
void printDuplicates(int arr[],int n){
unordered_set<int> intSet;
unordered_set<int> duplicateSet;
for(int i=0;i<n;i++){
if(intSet.find(arr[i]) != intSet.end()) {
intSet.insert(arr[i]);
}else{
duplicateSet.insert(arr[i]);
}
}
cout << "Duplicates are : ";
for(auto it = duplicateSet.begin();it != duplicateSet.end();it++){
cout << *it << " ";
}
}
int main(){
int arr[] = {1,2,3,1,3,6,6};
int n = sizeof(arr)/sizeof(arr[0]);
printDuplicates(arr,n);
return 0;
}
|
/*In this lets see about INHERITANCE in C++ Program.*/
/*The most important features of OOPs is INHERITANCE.*/
/*Inheritance make easy to create and maintain an application.*/
/*Inheritance are mainly used for Code Reuseability and fast implementation of time*/
/*The process of using the data member of a class which is already created is called INHERITANCE.*/
/*That is an existing class in a program is called as BASE class / PARENT class*/
/*The class whic is drived from existing class in a program is called as DERIVED class / CHILD class*/
/*Inheritance is simple considereed as a "is a " relationship .*/
/*In this lets see about Multiple Inheritance in c++ program.*/
/*Multiple Inheritance is the process of driving a DERIVED class from two or more BASE class in a program.*/
/*synatx for creating a derived class from base class is
class_name derived_class_name : access_specifier base_class_name1 , access_specifier base_class_name2
{
access_specifier:
DataType member1 ;
DataType member ;
DataType member3 ;
.
.
.
DataType memberN ;
};
*/
/*including preprocessor / headerfile in the program*/
#include <iostream>
#include <string>
/*using namespace*/
using namespace std ;
/*creating the BASE class of the function.*/
class StudentName
{
public:
string Name;
};
/*creating the BASE class of the function.*/
class StudentRollNo
{
public:
int RollNo;
};
/*Creating a DERIVED class from the BASE Class of the function.*/
class AccessStudent : public StudentName , public StudentRollNo
{
public :
void getStudent();
void printStudent();
};
void AccessStudent :: getStudent()
{
cout << "\nEnter Student Name : ";
cin >> Name ;
cout << "\nEnter Student RollNo : ";
cin >> RollNo ;
}
void AccessStudent :: printStudent()
{
cout<< "\nStudent Name is : " << Name << endl ;
cout<< "\nStudent RollNo is : " << RollNo << endl ;
}
/*Main funtion of the program.*/
int main()
{
AccessStudent student1 ;
AccessStudent student2 ;
cout<<"\nEnter the Details of First Student....."<< endl ;
student1.getStudent();
cout<<"\nEnter the Details of Second Student....."<< endl ;
student2.getStudent();
cout<<"\nPrinting the Details of First Student....."<< endl ;
student1.printStudent();
cout<<"\nPrinting the Details of Second Student....."<< endl ;
student2.printStudent();
}
|
#ifndef IS_PRIME_HPP
#define IS_PRIME_HPP
#include <cmath>
namespace Extra::Math
{
static bool isPrime(size_t num)
{
const size_t boundary = static_cast<size_t>(sqrt(num));
for (size_t i = 2; i <= boundary; ++i)
if (num % i == 0)
return false;
return num >= 2;
}
}
#endif /* end of include guard : IS_PRIME_HPP */
|
#pragma once
// includes system
#include <cstdlib>
#include <string>
// includes project
#include "integrator.h"
#include "nbody.h"
#include "parameter.h"
#include "red_type.h"
using namespace std;
class options
{
public:
options(int argc, const char** argv);
~options();
nbody* create_nbody();
integrator* create_integrator(nbody* nbd, ttt_t dt);
bool continue_simulation; //!< Continues a simulation from its last saved output
bool verbose; //!< Print every event to the log file
bool print_to_screen; //!< Print every event to the standard output stream (cout)
bool ef; //!< Extend the file names with command line information. Only for developer and debugger purposes.
ttt_t info_dt; //!< The time interval in seconds between two subsequent information print to the screen (default value is 5 sec)
ttt_t dump_dt; //!< The time interval in seconds between two subsequent data dump to the hdd (default value is 3600 sec)
uint32_t id_dev; //!< The id of the device which will execute the code
uint32_t n_change_to_cpu; //!< The threshold value for the total number of SI bodies to change to the CPU
computing_device_t comp_dev; //!< The computing device to carry out the calculations (cpu or gpu)
gas_disk_model_t g_disk_model;
parameter* param;
string out_fn[OUTPUT_NAME_N]; //!< Array for the output filenames
string in_fn[INPUT_NAME_N]; //!< Array for the input filenames
string dir[DIRECTORY_NAME_N]; //!< Array for the input and output directories
private:
void create_default();
void parse(int argc, const char** argv);
void print_usage();
};
|
#include "kg/util/log.hh"
#include <iostream>
kg::log::~log() {
std::clog << _stream.str() << std::endl;
}
|
#include<iostream>
using namespace std;
const int SIZE = 26;
struct node {
node* next[SIZE];
int strings;
node()
{
for (int i = 0; i < SIZE; i++) {
next[i] = nullptr;
}
strings = 0;
}
};
void add(struct node* root, string key)
{
struct node* cur_v = root;
for (int i = 0; i < key.length(); i++) {
char c = key[i];
if (cur_v->next[c - 'a'] == nullptr) {
cur_v->next[c - 'a'] = new node();
}
cur_v = cur_v->next[c - 'a'];
}
cur_v->strings++;
}
bool has(struct node* root, string key)
{
struct node *cur_v = root;
for (int i = 0; i < key.length(); i++) {
cur_v = cur_v->next[key[i] - 'a'];
if (cur_v == nullptr) {
return false;
}
}
return cur_v->strings > 0;
}
int main()
{
struct node* root = new node();
add(root, "qwe123");
add(root, "zxc");
cout<<has(root, "qwe123")<<endl;
cout<<has(root, "few")<<endl;
}
|
#include <iostream>
#include <config.hpp>
#include <generic_handler.hpp>
namespace util {
config::config(std::string bind_hostname, int bind_port, int thread_pool_size) {
bind_hostname_ = bind_hostname;
bind_port_ = bind_port;
thread_pool_size_ = thread_pool_size;
}
config::config() {}
void config::print_config() {
std::cout << "bind_hostname: " << bind_hostname_ << "\n";
std::cout << "bind_port: " << bind_port_ << "\n";
std::cout << "thread_pool_size: " << thread_pool_size_ << "\n";
}
std::string config::get_bind_hostname() {
return bind_hostname_;
}
int config::get_bind_port() {
return bind_port_;
}
int config::get_thread_pool_size() {
return thread_pool_size_;
}
void config::set_handler(request_handler::generic_handler* handler){
handler_ = handler;
}
request_handler::generic_handler* config::get_handler() {
return handler_;
}
}
|
/*
* =====================================================================================
*
* Filename: exercise3.cc
*
* Description: the exercise 3 of chapter 3 function objects
*
* Version: 1.0
* Created: 05/24/2014 18:16:53
* Revision: none
* Compiler: gcc
*
* Author: Zhile Zou (Robin), zouzhile@yahoo-inc.com
* Organization: Yahoo!
*
* =====================================================================================
*/
#include <vector>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <boost/function.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/bind.hpp>
using namespace std;
void call(boost::function<int (const char*)> func, const char data[]) {
cout << (func)(data) << endl;
}
int main()
{
vector<boost::function<int (const char*)> > processors;
boost::function<int (const char*)> func = atoi;
processors.push_back(func);
func = strlen;
processors.push_back(strlen);
const char data[] = "1.23";
std::for_each(processors.begin(), processors.end(), boost::bind(call, _1, data));
}
|
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <stdlib.h>
#include <stdio.h>
#include <algorithm>
#include<vector>
//Masoud QashQaei 9150022
using namespace std;
struct Building
{
int left; // x coordinate of left side
int ht; // height
int right; // x coordinate of right side
};
class Strip
{
int left; // x coordinate of left side
int ht; // height
public:
Strip(int l=0, int h=0)
{
left = l;
ht = h;
}
friend class SkyLine;
};
class SkyLine
{
Strip *arr; // Array of strips
int capacity; // Capacity of strip array
int n; // Actual number of strips in array
public:
~SkyLine() { delete[] arr; }
int count() { return n; }
SkyLine* Merge(SkyLine *other);
SkyLine(int cap)
{
capacity = cap;
arr = new Strip[cap];
n = 0;
}
void append(Strip *st)
{
if (n>0 && arr[n-1].ht == st->ht)
return;
if (n>0 && arr[n-1].left == st->left)
{
arr[n-1].ht = max(arr[n-1].ht, st->ht);
return;
}
arr[n] = *st;
n++;
}
void print()
{
for (int i=0; i<n; i++)
{
cout << " (" << arr[i].left << ", "
<< arr[i].ht << "), ";
}
}
};
SkyLine *findSkyline(Building arr[], int l, int h)
{
if (l == h)
{
SkyLine *res = new SkyLine(2);
res->append(new Strip(arr[l].left, arr[l].ht));
res->append(new Strip(arr[l].right, 0));
return res;
}
int mid = (l + h)/2;
SkyLine *sl = findSkyline(arr, l, mid);
SkyLine *sr = findSkyline(arr, mid+1, h);
SkyLine *res = sl->Merge(sr);
delete sl;
delete sr;
return res;
}
SkyLine *SkyLine::Merge(SkyLine *other)
{
SkyLine *res = new SkyLine(this->n + other->n);
int h1 = 0, h2 = 0;
// Indexes of strips in two skylines
int i = 0, j = 0;
while (i < this->n && j < other->n)
{
if (this->arr[i].left < other->arr[j].left)
{
int x1 = this->arr[i].left;
h1 = this->arr[i].ht;
int maxh = max(h1, h2);
res->append(new Strip(x1, maxh));
i++;
}
else
{
int x2 = other->arr[j].left;
h2 = other->arr[j].ht;
int maxh = max(h1, h2);
res->append(new Strip(x2, maxh));
j++;
}
}
while (i < this->n)
{
res->append(&arr[i]);
i++;
}
while (j < other->n)
{
res->append(&other->arr[j]);
j++;
}
return res;
}
bool IsParenthesesOrDash(char c)
{
switch(c)
{
case ',':
return true;
default:
return false;
}
}
int main()
{
ifstream file("skyline.txt");
string str;
int i=0;
int n;
int j=0;
int b[1000];
char cNum[10] ;
string test;
if(file.is_open()){
getline(file,str);
int a= atoi(str.c_str());
Building arr[a];
int y=0;
while(getline(file,str))
{
str.erase(remove_if(str.begin(), str.end(), &IsParenthesesOrDash), str.end());
stringstream stream(str);
vector<int> values;
int n;
int b[3];
int r=0;
while(stream >> n){
values.push_back(n);
b[r]=n;
// cout<<b[r]<<endl;
r++;
}
arr[y]={b[r-3],b[r-2],b[r-1]};
y++;
}
n = sizeof(arr)/sizeof(arr[0]);
SkyLine *ptr = findSkyline(arr, 0, n-1);
cout << " Skyline for given buildings is \n";
ptr->print();
}
return 0;
}
|
#ifndef euclidean_h
#define euclidean_h
#include <vector>
#include <tr1/array>
#include <tr1/memory>
#include "Manifold.h"
#include <Eigen/Dense>
using Eigen::Matrix3d;
using Eigen::Vector3d;
class R2xS1 : public Manifold {
public:
class PointOfReference;
class Point : public Manifold::Point {
public:
R2xS1* getSpace();
Point(double x, double y, double z, R2xS1* space);
Point();
friend class PointOfReference;
//Point midpoint(Point point);
private:
std::tr1::array<double,3> coordinates;
R2xS1* space;
};
class PointOfReference : public Manifold::PointOfReference { //Add manifold
public:
PointOfReference(R2xS1* space);
~PointOfReference();
std::vector<Vector3d> vectorsFromPoint(std::tr1::shared_ptr<Manifold::Point> point);
std::tr1::shared_ptr<Manifold::Point> pointFromVector(Vector3d vector);
Manifold::Point* getPosition();
//void setPosition(Manifold::Point* position);
void move(Vector3d dir);
void rotate(Matrix3d rot);
private:
Point position;
Matrix3d orientation;
};
// typedef std::tr1::array<std::tr1::shared_ptr<Manifold::Point>,3> Triangle;
Triangle makeTriangle(); //For debug purposes
// std::vector<Triangle> triforce(Triangle);
};
#endif
|
#include "clientele.h"
#include "personne.h"
#include "QSqlQueryModel"
Clientele::Clientele()
{
}
Clientele::Clientele(QString Prenom,QString Nom,QString Num_Tel,QString CIN,QString Adresse,int ID,QString courriel,int ID_client,int Age,QString Date_N,QString Date_D,QString Date_F,QString Taille,QString Poids,int Number):Personne(Prenom,Nom,Num_Tel,CIN,Adresse,ID,courriel)
{this->ID_client=ID_client;
this->Age=Age;
this->Date_D=Date_D;
this->Date_F=Date_F;
this->Date_N=Date_N;
this->Taille=Taille;
this->Poids=Poids;
this->Number=Number;
}
bool Clientele:: AjoutClientele(Clientele *CL)
{
//Personne::AjoutPersonne();
QSqlQuery query;
QString IDD= QString::number(CL->getID_client());
QString NUM= QString::number(CL->getNumber());
QString AGE= QString::number(CL->getAge());
QString str= "insert into Client values('"+IDD+"','"+AGE+"','"+CL->getDate_N()+"','"+CL->getDate_D()+"','"+CL->getDate_F()+"','"+CL->getTaille()+"','"+CL->getPoids()+"','"+NUM+"')";
qDebug()<<str;
if (query.exec(str))
return true;
else
return false;
}
QSqlQueryModel * Clientele::AfficherClientele()
{
QSqlQueryModel * model= new QSqlQueryModel();
model->setQuery("select Nom,Prenom,Num_Tel,CIN,Adresse,ID_client,Age,Date_N,Date_D,Date_F,Taille,Poids,Number,courriel from Personne p , Client c where (p.ID=c.ID_client)");
model->setHeaderData(0, Qt::Horizontal, QObject::tr("NOM"));
model->setHeaderData(1, Qt::Horizontal, QObject::tr("PRENOM"));
model->setHeaderData(2, Qt::Horizontal, QObject::tr("NUM_TEL"));
return model;
}
QSqlQueryModel * Clientele::RechercherClientele(int ID_client)
{
QSqlQueryModel * model= new QSqlQueryModel();
QString str="select * from Personne p,Client c where ( (p.ID=c.ID_client)and (c.ID_client="+QString::number(ID_client)+"))";
qDebug()<<str;
// QString str="select * from Client where ID_client="+QString::number(ID_client);
model->setQuery(str);
return model;
}
bool Clientele::SupprimerClientele(int ID_client)
{
QSqlQuery query;
QString str="delete from Client where ID_client ="+QString::number( ID_client);
qDebug()<<str;
bool res = query.exec(str);
return res;
}
bool Clientele::ModifierClientele(Clientele *CL)
{
createConnection();
QSqlQuery query;
QString IDD= QString::number(CL->getID());
QString num= QString::number(CL->getNumber());
QString AGE= QString::number(CL->getAge());
QString str=("update Client set ID_client="+IDD+""",Age='"+AGE+"'"",Date_N='"+CL->getDate_N()+"'"",Date_D='"+CL->getDate_D()+"'"
",Date_F='"+CL->getDate_F()+"'"
",Taille='"+CL->getTaille()+"'"
",Poids='"+CL->getPoids()+"'"
",Number='"+num+"'where ID_client='"+IDD+"'");
qDebug()<<str;
bool res =query.exec(str);
return res;
}
|
#include <ros.h>
#include <std_msgs/Int8.h>
#include <beginner_tutorials/Num.h>
#include <custom_messages/driveMessage.h>
#include <std_msgs/UInt8.h>
/**
* This tutorial demonstrates simple receipt of messages over the ROS system.
*/
//void chatterCallback(const std_msgs::String::ConstPtr& msg)
//{
// ROS_INFO("I heard: [%s]", msg->data.c_str());
//}
ros::NodeHandle n;
int ENABLE = 1 ; // this becomes LOW when the emergency messge is recieved
unsigned int TOGGLE_STATE = 1;
//Both these pins are of different timers. Must set the frequencies individually
int steeringPin = 6; // steering pwm pin.
int throttlePin = 5; // throttle pwm pin
int debugPin = 2;
const int32_t pwm_frequency = 100; //frequency (in Hz)
const int pwm_res = 16; //res in bits
void emergency_listen(const std_msgs::UInt8& msg)
{
//ROS_INFO("I heard: [%d]", msg.data);
if(msg.data) {
ENABLE = 0;
}
else
ENABLE = 1;
}
void chatterCallback_driveMessage(const custom_messages::driveMessage& msg)
{
if(ENABLE){
digitalWrite(debugPin,TOGGLE_STATE);
if(TOGGLE_STATE)
TOGGLE_STATE = 0;
else
TOGGLE_STATE = 1;
//analogWiteFrequency(pin, Duty_cycle);
analogWriteFrequency(steeringPin,msg.steering);
analogWriteFrequency(throttlePin,msg.throttle);
// delay(10);
// digitalWrite(debugPin,LOW);
// ROS_INFO("I heard: Steering = [%d]; & Throttle = [%d]", msg.steering, msg.throttle);
// else
// ROS_INFO("I heard an EMERGENCY STOP");
}
}
ros::Subscriber<custom_messages::driveMessage> sub("chatter",&chatterCallback_driveMessage);
ros::Subscriber <std_msgs::UInt8> emergency_sub("nine11", &emergency_listen);
//void chatterCallback(const std_msgs::Int8::ConstPtr& msg)
//{
// ROS_INFO("I heard: [%d]", msg->data);
//}
//
//void chatterCallback_myMessage(const beginner_tutorials::Num::ConstPtr& msg)
//{
// ROS_INFO("I heard: [%d]", msg->num);
//}
//int main(int argc, char **argv)
void setup()
{
pinMode(debugPin,OUTPUT);
digitalWrite(debugPin,HIGH);
delay(1000);
digitalWrite(debugPin,LOW);
n.initNode();
n.subscribe(sub);
n.subscribe(emergency_sub);
analogWriteResolution(pwm_res);
analogWriteFrequency(throttlePin,pwm_frequency);
analogWriteFrequency(steeringPin,pwm_frequency);
}
void loop(){
n.spinOnce();
}
|
//
// BlendMode.h
// Odin.MacOSX
//
// Created by Daniel on 25/10/15.
// Copyright (c) 2015 DG. All rights reserved.
//
#ifndef __Odin_MacOSX__BlendMode__
#define __Odin_MacOSX__BlendMode__
namespace odin
{
namespace render
{
class BlendMode
{
public:
enum Factor
{
Zero,
One,
SrcColor,
OneMinusSrcColor,
DstColor,
OneMinusDstColor,
SrcAlpha,
OneMinusSrcAlpha,
DstAlpha,
OneMinusDstAlpha
};
enum Equation
{
Add,
Subtract
};
BlendMode();
BlendMode(Factor sourceFactor, Factor destinationFactor, Equation blendEquation = Add);
BlendMode(Factor colorSourceFactor, Factor colorDestinationFactor, Equation colorBlendEquation,
Factor alphaSourceFactor, Factor alphaDestinationFactor, Equation alphaBlendEquation);
void apply() const;
void disable() const;
static const BlendMode BlendAlpha;
static const BlendMode BlendAdd;
static const BlendMode BlendMultiply;
static const BlendMode BlendNone;
Factor colorSrcFactor;
Factor colorDstFactor;
Equation colorEquation;
Factor alphaSrcFactor;
Factor alphaDstFactor;
Equation alphaEquation;
};
}
}
#endif /* defined(__Odin_MacOSX__BlendMode__) */
|
#include "screen.h"
#include "Camera.h"
#include "ShaderProgram.h"
#include "texture.h"
#include "cubeData.h"
#include "planeData.h"
#include "Model.h"
#include "Mesh.h"
#include "Light.h"
#include "utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <string>
#include <vector>
#include <glad\glad.h>
#include <GLFW\glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace std;
// Global state
Camera freeLookCam;
Screen screen;
void mouse_callback(GLFWwindow * window, double xpos, double ypos);
void processInput(GLFWwindow * window, double deltaTime);
int main()
{
// Screen initialization
if (screenInit(&screen, mouse_callback) < 0)
{
printf("Error initialization the screen!");
return -1;
}
freeLookCam.Position = glm::vec3(0.0f, 0.0f, 10.0f);
ShaderProgram lampProgram("basic_vertex.glsl", "lamp_frag.glsl");
ShaderProgram texProgram("basic_vertex.glsl", "texture_phong_frag.glsl");
Texture joey, containerTwo, containerTwoSpecular, moonman;
textureInit(&joey, "joey.jpg", TextureType::DIFFUSE_AND_SPECULAR, true);
textureInit(&moonman, "moonman.png", TextureType::DIFFUSE_AND_SPECULAR, true, true);
textureInit(&containerTwo, "container2.png", TextureType::DIFFUSE, true, true);
textureInit(&containerTwoSpecular, "container2_specular.png", TextureType::SPECULAR, true, true);
vector<Vertex> planeVertices;
vector<GLuint> planeIndices;
generatePlaneData(planeVertices, planeIndices, 20, 20);
vector<Texture> planeTextures = {
moonman
};
Mesh planeMesh(planeVertices, planeIndices, planeTextures);
vector<Vertex> cubeVertices;
vector<GLuint> cubeIndices;
generateCubeData(cubeVertices, cubeIndices);
vector<Texture> cubeTextures = {
containerTwo,
containerTwoSpecular
};
Mesh containerMesh(cubeVertices, cubeIndices, cubeTextures);
#define NUM_LIGHTS 5
Mesh lampMeshes[NUM_LIGHTS] = {
Mesh(cubeVertices, cubeIndices, vector<Texture>()),
Mesh(cubeVertices, cubeIndices, vector<Texture>()),
Mesh(cubeVertices, cubeIndices, vector<Texture>()),
Mesh(cubeVertices, cubeIndices, vector<Texture>()),
Mesh(cubeVertices, cubeIndices, vector<Texture>()),
};
glm::vec3 lightPositions[NUM_LIGHTS] = {
glm::vec3(-8.0f, 1.0f, 8.0f),
glm::vec3(-8.0f, 1.0f, -8.0f),
glm::vec3( 8.0f, 1.0f, -8.0f),
glm::vec3( 8.0f, 1.0f, 8.0f),
glm::vec3( 0.0f, 0.0f, 0.0f),
};
glm::vec3 lightColors[NUM_LIGHTS] = {
glm::vec3(1.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f),
glm::vec3(0.0f, 0.0f, 1.0f),
glm::vec3(0.0f, 1.0f, 1.0f),
glm::vec3(1.0f, 1.0f, 1.0f),
};
vector<Light> pointLights(NUM_LIGHTS);
for (unsigned int i = 0; i < NUM_LIGHTS; i++)
pointLights[i] = Light::PointLight(lightPositions[i], lightColors[i]);
Light dirLight = Light::DirectionalLight(glm::vec3(-0.2f, -1.0f, -0.3f), glm::vec3(1.0f));
Light spotLight = Light::SpotLight(glm::vec3(0.0f), glm::vec3(0.0f));
Model nanosuit("C:/Users/Boromir/Downloads/nanosuit/nanosuit.obj");
Model suzanne("C:/Program Files/Assimp/test/models/BLEND/Suzanne_248.blend");
glm::mat4 projectionMat = glm::perspective(glm::radians(freeLookCam.GetFov()), (float)screen.width / (float)screen.height, 0.1f, 100.0f);
double deltaTime = 0.0f;
double lastFrame = 0.0f;
while (!screenShouldClose(&screen))
{
// Delta calculations
double currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
printf("\rFPS: %f", 1.0 / deltaTime);
// Event handling
processInput(screen.window, deltaTime);
// Clear
screenClear(&screen);
// Uniforms & Rendering
float movementAmt = sin((float)glfwGetTime()) * 2.0f + 0.5f;
float rotAmt = sin((float)glfwGetTime() * 0.5f + 1.0f);
glm::mat4 modelMat;
glm::mat4 viewMat = freeLookCam.GetViewMatrix();
lampProgram.Use();
for (int i = 0; i < NUM_LIGHTS; i++)
{
modelMat = glm::mat4();
if (i < 4)
{
modelMat = glm::translate(modelMat, lightPositions[i] + glm::vec3(0.0f, movementAmt, 0.0f));
}
modelMat = glm::scale(modelMat, glm::vec3(0.2f));
lampProgram.SetUniform("model", modelMat);
lampProgram.SetUniform("view", viewMat);
lampProgram.SetUniform("projection", projectionMat);
lampProgram.SetUniform("color", lightColors[i]);
lampMeshes[i].Draw(lampProgram);
}
texProgram.Use();
for (unsigned int i = 0; i < pointLights.size() - 1; i++)
{
pointLights[i].Position = lightPositions[i] + glm::vec3(0.0f, movementAmt, 0.0f);
}
spotLight.Position = freeLookCam.Position;
spotLight.Direction = freeLookCam.Front;
texProgram.SetUniform("dirLight", dirLight);
texProgram.SetUniform("pointLights", pointLights);
texProgram.SetUniform("spotLight", spotLight);
modelMat = glm::mat4();
modelMat = glm::translate(modelMat, glm::vec3(0.0f, -2.0f, -5.0f));
modelMat = glm::scale(modelMat, glm::vec3(0.25f));
texProgram.SetUniform("material.shininess", 32.0f);
texProgram.SetUniform("model", modelMat);
texProgram.SetUniform("view", viewMat);
texProgram.SetUniform("projection", projectionMat);
nanosuit.Draw(texProgram);
modelMat = glm::mat4();
modelMat = glm::translate(modelMat, glm::vec3(0.0f, -2.0f, 0.0f));
texProgram.SetUniform("material.shininess", 32.0f);
texProgram.SetUniform("model", modelMat);
texProgram.SetUniform("view", viewMat);
texProgram.SetUniform("projection", projectionMat);
planeMesh.Draw(texProgram);
modelMat = glm::mat4();
modelMat = glm::translate(modelMat, glm::vec3(movementAmt * 2.0f, 2.0f, 0.0f));
modelMat = glm::rotate(modelMat, rotAmt, glm::vec3(1.0f, 1.0f, 0.0f));
texProgram.SetUniform("material.shininess", 32.0f);
texProgram.SetUniform("model", modelMat);
texProgram.SetUniform("view", viewMat);
texProgram.SetUniform("projection", projectionMat);
containerMesh.Draw(texProgram);
// TODO: consider moving Material and Transformation data be part of the Model/Mesh
modelMat = glm::mat4();
modelMat = glm::translate(modelMat, glm::vec3(0.0f, 2.0f, 10.0f + movementAmt * 1.5f));
modelMat = glm::rotate(modelMat, -90.0f, glm::vec3(1.0f, 0.0f, 0.0f));
texProgram.SetUniform("material.shininess", 32.0f);
texProgram.SetUniform("model", modelMat);
texProgram.SetUniform("view", viewMat);
texProgram.SetUniform("projection", projectionMat);
suzanne.Draw(texProgram);
// Swap buffers
screenSwapAndPoll(&screen);
}
MyUtils::glCheckError();
textureFree(&joey);
textureFree(&containerTwo);
textureFree(&containerTwoSpecular);
textureFree(&moonman);
screenFree(&screen);
return 0;
}
void mouse_callback(GLFWwindow * window, double xpos, double ypos)
{
if (!screen.mouseCaptured)
{
screen.lastX = xpos;
screen.lastY = ypos;
screen.mouseCaptured = true;
}
float xOff = xpos - screen.lastX;
float yOff = screen.lastY - ypos;
screen.lastX = xpos;
screen.lastY = ypos;
freeLookCam.ProcessMouseMovement(xOff, yOff);
}
void processInput(GLFWwindow * window, double deltaTime)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_F9) == GLFW_PRESS)
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
if (glfwGetKey(window, GLFW_KEY_F10) == GLFW_PRESS)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
freeLookCam.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
freeLookCam.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
freeLookCam.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
freeLookCam.ProcessKeyboard(RIGHT, deltaTime);
}
|
//看讨论区 找到一个感觉很厉害的 98%
//128 ms 84.62 % 测了好多次 最高就是前面 最低16% 这个系统无敌了
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
vector<int> result;
nums.push_back(nums.size()+1);
for(int i = 0; i < nums.size()-1;++i){
nums[abs(nums[i])] = -nums[abs(nums[i])];
if(nums[abs(nums[i])] > 0){
result.push_back(abs(nums [i]));
}
}
return result;
}
};
/*
//10000表示这个值取了但是这个位置没数 9999表示这个值取了位置也有数了
//这个题 改了一上午一下午 没改好, 晚上重新思考了一遍然后重新写就好了 但是这个题他的答案顺序非得要求和他的顺序一样,简直无话可说,他的标准答案又不是排序过的
//相比之下,你的不是一个接一个遍历过来的 你的是跳来跳去的 对比之下看出了差距
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
if(nums.size()==0){
return nums;
}
nums.push_back(10000);
vector<int> result;
int temp = nums[0];
nums[0] = 10000;
int j = 1;
while(j<nums.size()){
if(nums[temp]==9999){
result.push_back(temp);
while(nums[j]==10000||nums[j]==9999){
++j;
}
temp = nums[j];
nums[j] = 10000;
}else if(nums[temp]==10000){
nums[temp] = 9999;
while(nums[j]==10000||nums[j]==9999){
++j;
}
temp = nums[j];
nums[j] = 10000;
}else{
int temp2 = nums[temp];
nums[temp] = 9999;
temp = temp2;
}
}
return result;
}
};
*/
|
#ifndef PRODUCTWIDGET_H
#define PRODUCTWIDGET_H
#include <QMainWindow>
#include <QDebug>
#include "product.h"
namespace Ui {
class ProductWidget;
}
class ProductWidget : public QMainWindow
{
Q_OBJECT
public:
explicit ProductWidget(QWidget *parent = nullptr);
~ProductWidget();
void addInformation(const Product &product);
private slots:
void on_numberProducts_valueChanged(const QString &arg1);
void on_addPB_clicked();
signals:
void addItem(QString id, int amount);
private:
Ui::ProductWidget *ui;
QString productId;
};
#endif // PRODUCTWIDGET_H
|
#pragma once
class Vector2
{
public:
double X;
double Y;
Vector2(double x, double y) : X(x), Y(y) {}
double Distance(Vector2 a, Vector2 b) {
Vector2 result = a - b;
return result.X + result.Y;
}
Vector2& operator+=(const Vector2& a)
{
this->X += a.X;
this->Y += a.Y;
return *this;
}
Vector2& operator-=(const Vector2& a)
{
this->X -= a.X;
this->Y -= a.Y;
return *this;
}
friend Vector2 operator-(Vector2 a, const Vector2& b)
{
a -= b;
return a;
}
friend Vector2 operator+(Vector2 a, const Vector2& b)
{
a += b;
return a;
}
};
|
/* Copyright (c) 2017 u-blox
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <mutex>
#include <thread>
#include <semaphore.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <utils.h>
#include <log.h>
/* ----------------------------------------------------------------
* COMPILE-TIME MACROS
* -------------------------------------------------------------- */
// The maximum length of a path (including trailing slash).
#define LOGGING_MAX_LEN_PATH 56
// The maximum length of a file name (including extension).
#define LOGGING_MAX_LEN_FILE_NAME 8
#define LOGGING_MAX_LEN_FILE_PATH (LOGGING_MAX_LEN_PATH + LOGGING_MAX_LEN_FILE_NAME)
// The maximum length of the URL of the logging server (including port).
#define LOGGING_MAX_LEN_SERVER_URL 128
// The TCP buffer size for log file uploads.
// Note: chose a small value here since the logs are small
// and it avoids a large malloc().
// Note: must be a multiple of a LogEntry size, otherwise
// the overhang can be lost
#define LOGGING_TCP_BUFFER_SIZE (20 * sizeof (LogEntry))
/* ----------------------------------------------------------------
* TYPES
* -------------------------------------------------------------- */
// Type used to pass parameters to the log file upload callback.
typedef struct {
const char *pCurrentLogFile;
} LogFileUploadData;
/* ----------------------------------------------------------------
* VARIABLES
* -------------------------------------------------------------- */
// The strings associated with the enum values.
extern const char *gLogStrings[];
extern const int gNumLogStrings;
// Mutex to arbitrate logging.
// The callback which writes logging to disk
// will attempt to lock this mutex while the
// function that prints out the log owns the
// mutex. Note that the logging functions
// themselves shouldn't wait on it (they have
// no reason to as the buffering should
// handle any overlap); they MUST return quickly.
static std::mutex gLogMutex;
// The number of calls to writeLog().
static int gNumWrites = 0;
// A logging buffer.
static LogEntry *gpLog = NULL;
static LogEntry *gpLogNextEmpty = NULL;
static LogEntry const *gpLogFirstFull = NULL;
// A file to write logs to.
static FILE *gpFile = NULL;
// The path where log files are kept.
static char gLogPath[LOGGING_MAX_LEN_PATH + 1];
// The name of the current log file.
static char gCurrentLogFileName[LOGGING_MAX_LEN_FILE_PATH + 1];
// The address of the logging server.
static struct sockaddr_in *gpLoggingServer = NULL;
// A thread to run the log upload process.
static std::thread *gpLogUploadThread = NULL;
// Semaphore to stop the log upload task.
static sem_t gStopLogUploadTask;
// A buffer to hold some data that is required by the
// log file upload thread.
static LogFileUploadData *gpLogFileUploadData = NULL;
/* ----------------------------------------------------------------
* STATIC FUNCTIONS
* -------------------------------------------------------------- */
// Print a single item from a log.
static void printLogItem(const LogEntry *pItem, unsigned int itemIndex)
{
if (pItem->event > gNumLogStrings) {
printf("%.3f: out of range event at entry %d (%d when max is %d)\n",
(double) pItem->timestamp / 1000, itemIndex, pItem->event, gNumLogStrings);
} else {
printf ("%6.3f: %s [%d] %d (%#x)\n", (double) pItem->timestamp / 1000,
gLogStrings[pItem->event], pItem->event, pItem->parameter, pItem->parameter);
}
}
// Open a log file, storing its name in gCurrentLogFileName
// and returning a handle to it.
static FILE *newLogFile()
{
FILE *pFile = NULL;
for (unsigned int x = 0; (x < 1000) && (pFile == NULL); x++) {
sprintf(gCurrentLogFileName, "%s/%04d.log", gLogPath, x);
// Try to open the file to see if it exists
pFile = fopen(gCurrentLogFileName, "r");
// If it doesn't exist, use it, otherwise close
// it and go around again
if (pFile == NULL) {
printf("Log file will be \"%s\".\n", gCurrentLogFileName);
pFile = fopen (gCurrentLogFileName, "wb+");
if (pFile != NULL) {
LOG(EVENT_LOG_FILE_OPEN, 0);
} else {
LOG(EVENT_LOG_FILE_OPEN_FAILURE, errno);
printf("Error initialising log file (%s).\n", strerror(errno));
}
} else {
fclose(pFile);
pFile = NULL;
}
}
return pFile;
}
// Function to sit in a thread and upload log files.
static void logFileUploadTask()
{
DIR *pDir;
int x = 0;
int y;
int z;
struct dirent *pDirEnt;
FILE *pFile = NULL;
int sock;
struct timeval tv;
int sendCount;
int sendTotalThisFile;
int size;
char *pReadBuffer = new char[LOGGING_TCP_BUFFER_SIZE];
char fileNameBuffer[LOGGING_MAX_LEN_FILE_PATH];
assert(gpLogFileUploadData != NULL);
tv.tv_sec = 10; /* 10 second timeout */
LOG(EVENT_DIR_OPEN, 0);
pDir = opendir(gLogPath);
if (pDir != NULL) {
// Send those log files, using a different TCP
// connection for each one so that the logging server
// stores them in separate files
while (((pDirEnt = readdir(pDir)) != NULL) && (sem_trywait(&gStopLogUploadTask) != 0)) {
// Open the file, provided it's not the one we're currently logging to
if (((strcmp(pDirEnt->d_name, ".") != 0) && (strcmp(pDirEnt->d_name, "..") != 0)) &&
(pDirEnt->d_type == DT_REG) &&
((gpLogFileUploadData->pCurrentLogFile == NULL) ||
(strcmp(pDirEnt->d_name, gpLogFileUploadData->pCurrentLogFile) != 0))) {
x++;
LOG(EVENT_SOCKET_OPENING, y);
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock >= 0) {
LOG(EVENT_SOCKET_OPENED, x);
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (void *) &tv, sizeof(tv));
LOG(EVENT_SOCKET_CONNECTING, x);
y = connect(sock, (struct sockaddr *) gpLoggingServer, sizeof(struct sockaddr));
if (y >= 0) {
LOG(EVENT_SOCKET_CONNECTED, x);
LOG(EVENT_LOG_UPLOAD_STARTING, x);
sprintf(fileNameBuffer, "%s/%s", gLogPath, pDirEnt->d_name);
pFile = fopen(fileNameBuffer, "r");
if (pFile != NULL) {
LOG(EVENT_LOG_FILE_OPEN, 0);
sendTotalThisFile = 0;
do {
// Read the file and send it
size = fread(pReadBuffer, 1, LOGGING_TCP_BUFFER_SIZE, pFile);
sendCount = 0;
while (sendCount < size) {
z = send(sock, pReadBuffer + sendCount, size - sendCount, 0);
if (z > 0) {
sendCount += z;
sendTotalThisFile += z;
LOG(EVENT_LOG_FILE_BYTE_COUNT, sendTotalThisFile);
}
}
} while (size > 0);
LOG(EVENT_LOG_FILE_UPLOAD_COMPLETED, x);
// The file has now been sent, so close the socket
close(sock);
// If the upload succeeded, delete the file
if (feof(pFile)) {
if (remove(fileNameBuffer) == 0) {
LOG(EVENT_FILE_DELETED, 0);
} else {
LOG(EVENT_FILE_DELETE_FAILURE, 0);
}
}
LOG(EVENT_LOG_FILE_CLOSE, 0);
fclose(pFile);
// Give the server time to write the file
sleep(1);
} else {
LOG(EVENT_LOG_FILE_OPEN_FAILURE, errno);
}
} else {
LOG(EVENT_SOCKET_CONNECT_FAILURE, errno);
}
} else {
LOG(EVENT_SOCKET_OPENING_FAILURE, errno);
}
}
}
} else {
LOG(EVENT_DIR_OPEN_FAILURE, (int) pDir);
}
LOG(EVENT_LOG_UPLOAD_TASK_COMPLETED, 0);
printf("[Log file upload background task has completed]\n");
// Clear up locals
delete[] pReadBuffer;
// Clear up globals
delete gpLogFileUploadData;
gpLogFileUploadData = NULL;
delete gpLoggingServer;
gpLoggingServer = NULL;
sem_destroy(&gStopLogUploadTask);
}
/* ----------------------------------------------------------------
* PUBLIC FUNCTIONS
* -------------------------------------------------------------- */
// Initialise logging.
void initLog(void *pBuffer)
{
gpLog = (LogEntry *) pBuffer;
gpLogNextEmpty = gpLog;
gpLogFirstFull = gpLog;
LOG(EVENT_LOG_START, LOG_VERSION);
}
// Initialise the log file.
bool initLogFile(const char *pPath)
{
bool goodPath = true;
int x;
// Save the path
if (pPath == NULL) {
gLogPath[0] = 0;
} else {
if (strlen(pPath) < sizeof (gCurrentLogFileName) - LOGGING_MAX_LEN_FILE_NAME) {
strcpy(gLogPath, pPath);
x = strlen(gLogPath);
// Remove any trailing slash
if (gLogPath[x - 1] == '/') {
gLogPath[x - 1] = 0;
}
} else {
goodPath = false;
}
}
if (goodPath) {
gpFile = newLogFile();
}
return (gpFile != NULL);
}
// Upload previous log files.
bool beginLogFileUpload(const char *pLoggingServerUrl)
{
bool success = false;
char *pBuf = new char[LOGGING_MAX_LEN_SERVER_URL];
DIR *pDir;
struct dirent *pDirEnt;
struct hostent *pHostEntries = NULL;
int port;
int x;
int y;
int z = 0;
const char *pCurrentLogFile = NULL;
if (gpLogUploadThread == NULL) {
// First, determine if there are any log files to be uploaded.
LOG(EVENT_DIR_OPEN, 0);
pDir = opendir(gLogPath);
if (pDir != NULL) {
// Point to the name portion of the current log file
// (format "*/xxxx.log")
pCurrentLogFile = strstr(gCurrentLogFileName, ".log");
if (pCurrentLogFile != NULL) {
pCurrentLogFile -= 4; // Point to the start of the file name
}
while ((pDirEnt = readdir(pDir)) != NULL) {
// Open the file, provided it's not the one we're currently logging to
if (((strcmp(pDirEnt->d_name, ".") != 0) && (strcmp(pDirEnt->d_name, "..") != 0)) &&
(pDirEnt->d_type == DT_REG) &&
((pCurrentLogFile == NULL) || (strcmp(pDirEnt->d_name, pCurrentLogFile) != 0))) {
z++;
}
}
LOG(EVENT_LOG_FILES_TO_UPLOAD, z);
printf("[%d log file(s) to upload]\n", z);
if (z > 0) {
gpLoggingServer = new struct sockaddr_in;
getAddressFromUrl(pLoggingServerUrl, pBuf, LOGGING_MAX_LEN_SERVER_URL);
LOG(EVENT_DNS_LOOKUP, 0);
printf("[Looking for logging server URL \"%s\"...]\n", pBuf);
pHostEntries = gethostbyname(pBuf);
if (pHostEntries != NULL) {
// Copy the network address to sockaddr_in structure
memcpy(&(gpLoggingServer->sin_addr), pHostEntries->h_addr_list[0], pHostEntries->h_length);
gpLoggingServer->sin_family = AF_INET;
printf("[Found it at IP address %s]\n", inet_ntoa(gpLoggingServer->sin_addr));
if (getPortFromUrl(pLoggingServerUrl, &port)) {
gpLoggingServer->sin_port = htons(port);
printf("[Logging server port is %d]\n", port);
} else {
printf("[WARNING: no port number was specified in the logging server URL (\"%s\")]\n",
pLoggingServerUrl);
}
} else {
LOG(EVENT_DNS_LOOKUP_FAILURE, h_errno);
printf("[Unable to locate logging server \"%s\"]\n", pLoggingServerUrl);
}
gpLogFileUploadData = new LogFileUploadData();
gpLogFileUploadData->pCurrentLogFile = pCurrentLogFile;
// Note: gpLogFileUploadData will be destroyed by the log file upload thread when it finishes
sem_init(&gStopLogUploadTask, false, 0);
gpLogUploadThread = new std::thread(logFileUploadTask);
if (gpLogUploadThread != NULL) {
printf("[Log file upload background task is now running]\n");
success = true;
} else {
delete gpLogFileUploadData;
gpLogFileUploadData = NULL;
sem_destroy(&gStopLogUploadTask);
printf("[Unable to instantiate thread to upload files to logging server]\n");
}
} else {
success = true; // Nothing to do
}
} else {
LOG(EVENT_DIR_OPEN_FAILURE, x);
printf("[Unable to open path \"%s\" (error %d)]\n", gLogPath, x);
}
} else {
printf("[Log file upload task already running]\n");
}
delete[] pBuf;
return success;
}
// Stop uploading previous log files, returning memory.
void stopLogFileUpload()
{
if (gpLogUploadThread != NULL) {
sem_post(&gStopLogUploadTask);
gpLogUploadThread->join();
delete gpLogUploadThread;
gpLogUploadThread = NULL;
}
if (gpLogFileUploadData != NULL) {
delete gpLogFileUploadData;
gpLogFileUploadData = NULL;
}
if (gpLoggingServer != NULL) {
delete gpLoggingServer;
gpLoggingServer = NULL;
}
}
// Log an event plus parameter.
// Note: ideally we'd mutex in here but I don't
// want any overheads or any cause for delay
// so please just cope with any very occasional
// logging corruption which may occur
void LOG(LogEvent event, int parameter)
{
if (gpLogNextEmpty) {
gpLogNextEmpty->timestamp = getUSeconds();
gpLogNextEmpty->event = (int) event;
gpLogNextEmpty->parameter = parameter;
if (gpLogNextEmpty < gpLog + MAX_NUM_LOG_ENTRIES - 1) {
gpLogNextEmpty++;
} else {
gpLogNextEmpty = gpLog;
}
if (gpLogNextEmpty == gpLogFirstFull) {
// Logging has wrapped, so move the
// first pointer on to reflect the
// overwrite
if (gpLogFirstFull < gpLog + MAX_NUM_LOG_ENTRIES - 1) {
gpLogFirstFull++;
} else {
gpLogFirstFull = gpLog;
}
}
}
}
// Flush the log file.
// Note: log file mutex must be locked before calling.
void flushLog()
{
if (gpFile != NULL) {
fclose(gpFile);
gpFile = fopen(gCurrentLogFileName, "ab+");
}
}
// This should be called periodically to write the log
// to file, if a filename was provided to initLog().
void writeLogCallback(size_t timerId, void *pUserData)
{
if (gLogMutex.try_lock()) {
if (gpFile != NULL) {
gNumWrites++;
while (gpLogNextEmpty != gpLogFirstFull) {
fwrite(gpLogFirstFull, sizeof(LogEntry), 1, gpFile);
if (gpLogFirstFull < gpLog + MAX_NUM_LOG_ENTRIES - 1) {
gpLogFirstFull++;
} else {
gpLogFirstFull = gpLog;
}
}
if (gNumWrites > LOGGING_NUM_WRITES_BEFORE_FLUSH) {
gNumWrites = 0;
flushLog();
}
}
gLogMutex.unlock();
}
}
// Close down logging.
void deinitLog()
{
stopLogFileUpload(); // Just in case
LOG(EVENT_LOG_STOP, LOG_VERSION);
if (gpFile != NULL) {
writeLogCallback(0, NULL);
flushLog(); // Just in case
LOG(EVENT_LOG_FILE_CLOSE, 0);
fclose(gpFile);
gpFile = NULL;
}
// Don't reset the variables
// here so that printLog() still
// works afterwards if we're just
// logging to RAM rather than
// to file.
}
// Print out the log.
void printLog()
{
const LogEntry *pItem = gpLogNextEmpty;
LogEntry fileItem;
bool loggingToFile = false;
FILE *pFile = gpFile;
unsigned int x = 0;
gLogMutex.lock();
printf ("------------- Log starts -------------\n");
if (pFile != NULL) {
// If we were logging to file, read it back
// First need to flush the file to disk
loggingToFile = true;
fclose(gpFile);
gpFile = NULL;
LOG(EVENT_LOG_FILE_CLOSE, 0);
pFile = fopen(gCurrentLogFileName, "rb");
if (pFile != NULL) {
LOG(EVENT_LOG_FILE_OPEN, 0);
while (fread(&fileItem, sizeof(fileItem), 1, pFile) == 1) {
printLogItem(&fileItem, x);
x++;
}
// If we're not at the end of the file, there must have been an error
if (!feof(pFile)) {
perror ("Error reading portion of log stored in file system");
}
fclose(pFile);
LOG(EVENT_LOG_FILE_CLOSE, 0);
} else {
perror ("Error opening portion of log stored in file system");
}
}
// Print the log items remaining in RAM
pItem = gpLogFirstFull;
x = 0;
while (pItem != gpLogNextEmpty) {
printLogItem(pItem, x);
x++;
pItem++;
if (pItem >= gpLog + MAX_NUM_LOG_ENTRIES) {
pItem = gpLog;
}
}
// Allow writeLog() to resume with the same file name
if (loggingToFile) {
gpFile = fopen(gCurrentLogFileName, "ab+");
if (gpFile) {
LOG(EVENT_LOG_FILE_OPEN, 0);
} else {
LOG(EVENT_LOG_FILE_OPEN_FAILURE, errno);
printf("Error initialising log file (%s).\n", strerror(errno));
}
}
printf ("-------------- Log ends --------------\n");
gLogMutex.unlock();
}
// End of file
|
// MainToolView.cpp : 实现文件
//
#include "stdafx.h"
#include "OgreEditor.h"
#include "MainToolView.h"
#include "ObjectDialog.h"
#include "TerrainDialog.h"
#include "DisplayDialog.h"
#include "LayerDialog.h"
// CMainToolView
IMPLEMENT_DYNCREATE(CMainToolView, CXTTabView)
CMainToolView::CMainToolView()
{
// TODO: add construction code here
m_iHitTest = -1;
m_nIDEvent = 20;
m_bXPBorder = true;
}
CMainToolView::~CMainToolView()
{
}
BOOL CMainToolView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return CXTTabView::PreCreateWindow(cs);
}
void CMainToolView::DoDataExchange(CDataExchange* pDX)
{
CXTTabView::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CMainToolView, CXTTabView)
//{{AFX_MSG_MAP(CTabbedViewView)
ON_WM_CREATE()
ON_WM_MOUSEMOVE()
////}}AFX_MSG_MAP
//ON_COMMAND(XT_IDC_TAB_CLOSE, OnCloseTab)
END_MESSAGE_MAP()
// CMainToolView 诊断
#ifdef _DEBUG
void CMainToolView::AssertValid() const
{
CXTTabView::AssertValid();
}
#ifndef _WIN32_WCE
void CMainToolView::Dump(CDumpContext& dc) const
{
CXTTabView::Dump(dc);
}
#endif
#endif //_DEBUG
// CMainToolView 消息处理程序
/////////////////////////////////////////////////////////////////////////////
// CMainToolView message handlers
int CMainToolView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CXTTabView::OnCreate(lpCreateStruct) == -1)
return -1;
//// Register as a drop target
//m_dropTarget.Register(this);
//DragAcceptFiles();
for ( int i = 0; i < E_ROLLUP_CTRL_NUM; i++ )
{
GetEditor()->SetRollupCtrl( (E_ROLLUP_CTRLS)i, &m_RollupCtrl[i]);
}
// Create the image list used by the tab control.
if (!m_imageList.Create( IDB_IMAGELIST, 16, 1, RGB( 0x00,0xFF,0x00 )))
{
TRACE0("Failed to create image list.\n");
return -1;
}
if (!m_RollupCtrl[E_OBJECT_CTRL].Create(WS_VISIBLE|WS_CHILD, CRect(0,0,0,0), this, 1))
{
TRACE0("Failed to create Object control.\n");
return -1;
}
int id = m_RollupCtrl[E_OBJECT_CTRL].InsertPage("对象分类", IDD_OBJECTS, RUNTIME_CLASS(CObjectDialog), 1);
m_RollupCtrl[E_OBJECT_CTRL].ExpandPage(id);
if (!m_RollupCtrl[E_TERRAIN_CTRL].Create(WS_VISIBLE|WS_CHILD, CRect(0,0,0,0), this, 2))
{
TRACE0("Failed to create Terrain control.\n");
return -1;
}
id = m_RollupCtrl[E_TERRAIN_CTRL].InsertPage("地形编辑", IDD_TERRAIN, RUNTIME_CLASS(CTerrainDialog), 1);
m_RollupCtrl[E_TERRAIN_CTRL].ExpandPage(id);
if (!m_RollupCtrl[E_DISPLAY_CTRL].Create(WS_VISIBLE|WS_CHILD, CRect(0,0,0,0), this, 3))
{
TRACE0("Failed to create Display control.\n");
return -1;
}
id = m_RollupCtrl[E_DISPLAY_CTRL].InsertPage("显示对象", IDD_DISPLAY, RUNTIME_CLASS(CDisplayDialog), 1);
m_RollupCtrl[E_DISPLAY_CTRL].ExpandPage(id);
if (!m_RollupCtrl[E_LAYER_CTRL].Create(WS_VISIBLE|WS_CHILD, CRect(0,0,0,0), this, 4))
{
TRACE0("Failed to create Layer control.\n");
return -1;
}
id = m_RollupCtrl[E_LAYER_CTRL].InsertPage("层级列表", IDD_LAYER, RUNTIME_CLASS(CLayerDialog), 1);
m_RollupCtrl[E_LAYER_CTRL].ExpandPage(id);
AddControl(_T("对象"), &m_RollupCtrl[E_OBJECT_CTRL]);
AddControl(_T("地形"), &m_RollupCtrl[E_TERRAIN_CTRL]);
AddControl(_T("显示"), &m_RollupCtrl[E_DISPLAY_CTRL]);
AddControl(_T("层级"), &m_RollupCtrl[E_LAYER_CTRL]);
// Set the tab controls image list.
GetTabCtrl().SetImageList(&m_imageList);
// Set the active view to the second tab.
SetActiveView(0);
return 0;
}
void CMainToolView::SetTabIcon(int iTab, int iImage)
{
TC_ITEM tci;
tci.mask = TCIF_IMAGE;
GetTabCtrl().GetItem(iTab, &tci);
tci.iImage = iImage;
GetTabCtrl().SetItem(iTab, &tci);
}
void CMainToolView::SetTabIcon(int iTab, HICON hIcon)
{
CImageList* pImageList = GetTabCtrl().GetImageList();
SetTabIcon(iTab, pImageList->Add(hIcon));
}
void CMainToolView::OnSelChanging()
{
CXTTabView::OnSelChanging();
// TODO: Add your code to handle tab selection.
}
void CMainToolView::OnSelChange()
{
CXTTabView::OnSelChange();
// TODO: Add your code to handle tab selection.
}
void CMainToolView::OnInitialUpdate()
{
CXTTabView::OnInitialUpdate();
// TODO: Add your specialized code here and/or call the base class
}
void CMainToolView::OnFileOpen()
{
// TODO: Add your command handler code here
}
void CMainToolView::OnRButtonDown(UINT /*nFlags*/, CPoint point)
{
// Get the tab index based upon the cursor position.
m_iHitTest = GetTabFromPoint(point);
if (m_iHitTest == -1)
return;
//CMenu popupMenu;
//VERIFY(popupMenu.CreatePopupMenu());
//popupMenu.AppendMenu(MF_STRING, ID_TAB_ACTIVATE, _T("Active View Tab"));
//popupMenu.AppendMenu(MF_SEPARATOR);
//popupMenu.AppendMenu(MF_STRING, ID_TAB_CLOSE, _T("&Close"));
//popupMenu.AppendMenu(MF_STRING, ID_TAB_SAVE, _T("&Save\tCtrl+S"));
//popupMenu.AppendMenu(MF_STRING, ID_TAB_SAVE_AS, _T("Save &As..."));
//popupMenu.AppendMenu(MF_SEPARATOR);
//popupMenu.AppendMenu(MF_STRING, ID_TAB_PRINT, _T("&Print\tCtrl+P"));
//popupMenu.AppendMenu(MF_STRING, ID_TAB_PRINT_PREVIEW, _T("Print Pre&view"));
//::SetMenuDefaultItem(popupMenu.m_hMenu, 0, TRUE);
//CPoint pt = point;
//ClientToScreen(&pt);
//popupMenu.TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON,
// pt.x, pt.y, this);
//popupMenu.DestroyMenu();
}
void CMainToolView::OnCancelMode()
{
CXTTabView::OnCancelMode();
// TODO: Add your message handler code here
}
void CMainToolView::OnTabActivate()
{
// TRACE0("CTabbedViewView::OnTabActivate()\n");
SetActiveView(m_iHitTest);
}
void CMainToolView::OnTabClose()
{
// TRACE0("CTabbedViewView::OnTabClose()\n");
//if (GetTabCtrl().GetItemCount() == 1)
//{
// AfxMessageBox( IDS_CANNOTDEL );
//}
//else
//{
// DeleteView(m_iHitTest);
//}
}
void CMainToolView::OnTimer(UINT_PTR nIDEvent)
{
if (m_nIDEvent == nIDEvent)
{
CPoint point;
::GetCursorPos(&point);
ScreenToClient(&point);
if (m_point == point)
{
CTabCtrl& tabCtrl = GetTabCtrl();
CRect rcItem;
int iItem;
for (iItem = 0; iItem < tabCtrl.GetItemCount(); ++iItem )
{
tabCtrl.GetItemRect(iItem, &rcItem);
if (rcItem.PtInRect(m_point) && tabCtrl.GetCurSel() != iItem)
{
SetActiveView(iItem);
break;
}
}
}
KillTimer(m_nIDEvent);
}
else
{
CXTTabView::OnTimer(nIDEvent);
}
}
void CMainToolView::OnMouseMove(UINT nFlags, CPoint point)
{
CXTTabView::OnMouseMove(nFlags, point);
m_point = point;
SetTimer(m_nIDEvent, 2500, NULL);
}
void CMainToolView::UpdateTabBorders()
{
BOOL bIsOfficeTheme = XTThemeManager()->GetTheme() != xtThemeOffice2000;
DWORD dwAdd = bIsOfficeTheme ? 0 : WS_EX_CLIENTEDGE;
DWORD dwRemove = bIsOfficeTheme ? WS_EX_CLIENTEDGE : 0;
for ( int i = 0; i < E_ROLLUP_CTRL_NUM; i++ )
{
if (::IsWindow(m_RollupCtrl[i].m_hWnd))
{
m_RollupCtrl[i].ModifyStyleEx(dwRemove, dwAdd);
}
}
CRect r;
GetWindowRect(&r);
SetWindowPos(NULL, 0,0,r.Width()+1,r.Height(),
SWP_FRAMECHANGED|SWP_NOMOVE);
SetWindowPos(NULL, 0,0,r.Width(),r.Height(),
SWP_FRAMECHANGED|SWP_NOMOVE);
}
void CMainToolView::OnCloseTab()
{
//if (GetTabCtrl().GetItemCount() == 1)
//{
// AfxMessageBox( IDS_CANNOTDEL );
//}
//else
//{
// DeleteView(GetTabCtrl().GetCurSel());
//}
}
DROPEFFECT CMainToolView::OnDragOver(COleDataObject* pDataObject, DWORD dwKeyState, CPoint point)
{
::GetCursorPos(&point);
ScreenToClient(&point);
CTabCtrl& tabCtrl = GetTabCtrl();
CRect rcItem;
for (int iItem = 0; iItem < tabCtrl.GetItemCount(); ++iItem )
{
tabCtrl.GetItemRect(iItem, &rcItem);
if (rcItem.PtInRect(point) && tabCtrl.GetCurSel() != iItem)
{
SetActiveView(iItem);
break;
}
}
return CXTTabView::OnDragOver(pDataObject, dwKeyState, point);
}
void CMainToolView::OnDropFiles(HDROP hDropInfo)
{
CPoint point;
::GetCursorPos(&point);
ScreenToClient(&point);
CTabCtrl& tabCtrl = GetTabCtrl();
CRect rcItem;
for (int iItem = 0; iItem < tabCtrl.GetItemCount(); ++iItem )
{
tabCtrl.GetItemRect(iItem, &rcItem);
if (rcItem.PtInRect(point))
{
SetActiveView(iItem);
CWnd* pView = GetView(iItem);
if (pView && ::IsWindow(pView->m_hWnd))
pView->PostMessage(WM_DROPFILES, (WPARAM)hDropInfo, 0L);
break;
}
}
CXTTabView::OnDropFiles(hDropInfo);
}
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <folly/portability/GTest.h>
#include <quic/codec/QuicPacketBuilder.h>
#include <quic/codec/QuicPacketRebuilder.h>
#include <quic/codec/QuicWriteCodec.h>
#include <quic/codec/test/Mocks.h>
#include <quic/common/test/TestUtils.h>
#include <quic/fizz/server/handshake/FizzServerQuicHandshakeContext.h>
#include <quic/server/state/ServerStateMachine.h>
#include <quic/state/QuicStateFunctions.h>
#include <quic/state/QuicStreamFunctions.h>
#include <quic/state/StateData.h>
#include <quic/state/stream/StreamSendHandlers.h>
#include <quic/state/stream/StreamStateFunctions.h>
using namespace testing;
namespace quic {
namespace test {
OutstandingPacketWrapper makeDummyOutstandingPacket(
const RegularQuicWritePacket& writePacket,
uint64_t totalBytesSentOnConnection) {
OutstandingPacketWrapper packet(
writePacket,
Clock::now(),
1000,
0,
false,
totalBytesSentOnConnection,
0,
0,
0,
LossState(),
0,
OutstandingPacketMetadata::DetailsPerStream());
return packet;
}
class QuicPacketRebuilderTest : public Test {};
TEST_F(QuicPacketRebuilderTest, RebuildEmpty) {
RegularQuicPacketBuilder regularBuilder(
kDefaultUDPSendPacketLen,
ShortHeader(ProtectionType::KeyPhaseZero, getTestConnectionId(), 0),
0 /* largestAcked */);
regularBuilder.encodePacketHeader();
QuicConnectionStateBase conn(QuicNodeType::Client);
PacketRebuilder rebuilder(regularBuilder, conn);
auto packet = std::move(regularBuilder).buildPacket();
EXPECT_TRUE(packet.packet.frames.empty());
EXPECT_FALSE(packet.header->empty());
EXPECT_TRUE(packet.body->empty());
}
TEST_F(QuicPacketRebuilderTest, RebuildSmallInitial) {
auto srcConnId = getTestConnectionId(0);
auto dstConnId = getTestConnectionId(1);
QuicVersion version = QuicVersion::MVFST;
PacketNum num = 1;
LongHeader initialHeader1(
LongHeader::Types::Initial, srcConnId, dstConnId, num, version, "");
LongHeader initialHeader2(
LongHeader::Types::Initial, srcConnId, dstConnId, num + 1, version, "");
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(initialHeader1), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(initialHeader2), 0);
PingFrame pingFrame{};
writeFrame(pingFrame, regularBuilder1);
MaxStreamsFrame maxStreamsFrame(4321, true);
writeFrame(QuicSimpleFrame(maxStreamsFrame), regularBuilder1);
regularBuilder1.encodePacketHeader();
QuicConnectionStateBase conn(QuicNodeType::Client);
PacketRebuilder rebuilder(regularBuilder2, conn);
auto packet = std::move(regularBuilder1).buildPacket();
auto outstanding = makeDummyOutstandingPacket(packet.packet, 1000);
EXPECT_FALSE(packet.header->empty());
ASSERT_EQ(packet.packet.frames.size(), 2);
EXPECT_FALSE(packet.body->empty());
regularBuilder2.encodePacketHeader();
ASSERT_TRUE(rebuilder.rebuildFromPacket(outstanding).has_value());
auto rebuilt = std::move(regularBuilder2).buildPacket();
EXPECT_FALSE(rebuilt.header->empty());
ASSERT_EQ(rebuilt.packet.frames.size(), 3);
auto padding = rebuilt.packet.frames.back().asPaddingFrame();
ASSERT_TRUE(padding != nullptr);
EXPECT_GT(padding->numFrames, 1000);
EXPECT_FALSE(rebuilt.body->empty());
EXPECT_GT(rebuilt.body->computeChainDataLength(), 1200);
}
TEST_F(QuicPacketRebuilderTest, RebuildPacket) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder1.encodePacketHeader();
// Get a bunch frames
ConnectionCloseFrame connCloseFrame(
QuicErrorCode(TransportErrorCode::FRAME_ENCODING_ERROR),
"The sun is in the sky.",
FrameType::ACK);
MaxStreamsFrame maxStreamsFrame(4321, true);
AckBlocks ackBlocks;
ackBlocks.insert(10, 100);
ackBlocks.insert(200, 1000);
WriteAckFrameState writeAckState = {.acks = ackBlocks};
// WriteAckFrameMetaData ackMeta(ackBlocks, 0us, kDefaultAckDelayExponent);
WriteAckFrameMetaData ackMeta = {
.ackState = writeAckState,
.ackDelay = 0us,
.ackDelayExponent = static_cast<uint8_t>(kDefaultAckDelayExponent)};
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(10);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
auto streamId = stream->id;
auto buf =
folly::IOBuf::copyBuffer("You can't deny you are looking for the sunset");
MaxDataFrame maxDataFrame(1000);
MaxStreamDataFrame maxStreamDataFrame(streamId, 2000);
uint64_t cryptoOffset = 0;
auto cryptoBuf = folly::IOBuf::copyBuffer("NewSessionTicket");
PingFrame pingFrame{};
// Write them with a regular builder
// Write the ACK frame first since it has special rebuilder handling.
writeAckFrame(ackMeta, regularBuilder1);
writeFrame(connCloseFrame, regularBuilder1);
writeFrame(QuicSimpleFrame(maxStreamsFrame), regularBuilder1);
writeFrame(pingFrame, regularBuilder1);
writeStreamFrameHeader(
regularBuilder1,
streamId,
0,
buf->computeChainDataLength(),
buf->computeChainDataLength(),
true,
folly::none /* skipLenHint */);
writeStreamFrameData(
regularBuilder1, buf->clone(), buf->computeChainDataLength());
writeFrame(maxDataFrame, regularBuilder1);
writeFrame(maxStreamDataFrame, regularBuilder1);
writeCryptoFrame(cryptoOffset, cryptoBuf->clone(), regularBuilder1);
auto packet1 = std::move(regularBuilder1).buildPacket();
ASSERT_EQ(8, packet1.packet.frames.size());
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(
std::make_unique<StreamBuffer>(buf->clone(), 0, true)));
conn.cryptoState->oneRttStream.retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(
std::make_unique<StreamBuffer>(cryptoBuf->clone(), 0, true)));
// Write an updated ackState that should be used when rebuilding the AckFrame
conn.ackStates.appDataAckState.acks.insert(1000, 1200);
conn.ackStates.appDataAckState.largestRecvdPacketTime.assign(
quic::Clock::now());
// rebuild a packet from the built out packet
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000);
EXPECT_TRUE(rebuilder.rebuildFromPacket(outstanding).has_value());
auto packet2 = std::move(regularBuilder2).buildPacket();
// rebuilder writes frames to regularBuilder2
EXPECT_EQ(packet1.packet.frames.size(), packet2.packet.frames.size());
auto expectedConnFlowControlValue = std::max(
conn.flowControlState.sumCurReadOffset + conn.flowControlState.windowSize,
conn.flowControlState.advertisedMaxOffset);
auto expectedStreamFlowControlValue = std::max(
stream->currentReadOffset + stream->flowControlState.windowSize,
stream->flowControlState.advertisedMaxOffset);
for (const auto& frame : packet2.packet.frames) {
switch (frame.type()) {
case QuicWriteFrame::Type::ConnectionCloseFrame: {
const ConnectionCloseFrame& closeFrame =
*frame.asConnectionCloseFrame();
const TransportErrorCode* transportErrorCode =
closeFrame.errorCode.asTransportErrorCode();
EXPECT_EQ(
TransportErrorCode::FRAME_ENCODING_ERROR, *transportErrorCode);
EXPECT_EQ("The sun is in the sky.", closeFrame.reasonPhrase);
EXPECT_EQ(FrameType::ACK, closeFrame.closingFrameType);
break;
}
case QuicWriteFrame::Type::PingFrame:
EXPECT_NE(frame.asPingFrame(), nullptr);
break;
case QuicWriteFrame::Type::QuicSimpleFrame: {
const QuicSimpleFrame& simpleFrame = *frame.asQuicSimpleFrame();
switch (simpleFrame.type()) {
case QuicSimpleFrame::Type::MaxStreamsFrame: {
const MaxStreamsFrame* maxStreamFrame =
simpleFrame.asMaxStreamsFrame();
EXPECT_NE(maxStreamFrame, nullptr);
EXPECT_EQ(4321, maxStreamFrame->maxStreams);
break;
}
default:
EXPECT_TRUE(false); /* fail if this happens */
}
break;
}
case QuicWriteFrame::Type::WriteAckFrame: {
const WriteAckFrame& ack = *frame.asWriteAckFrame();
EXPECT_EQ(1, ack.ackBlocks.size());
EXPECT_EQ(Interval<PacketNum>(1000, 1200), ack.ackBlocks.back());
break;
}
case QuicWriteFrame::Type::WriteStreamFrame: {
const WriteStreamFrame& streamFrame = *frame.asWriteStreamFrame();
EXPECT_EQ(streamId, streamFrame.streamId);
EXPECT_EQ(0, streamFrame.offset);
EXPECT_EQ(buf->computeChainDataLength(), streamFrame.len);
EXPECT_EQ(true, streamFrame.fin);
break;
}
case QuicWriteFrame::Type::WriteCryptoFrame: {
const WriteCryptoFrame& cryptoFrame = *frame.asWriteCryptoFrame();
EXPECT_EQ(cryptoFrame.offset, cryptoOffset);
EXPECT_EQ(cryptoFrame.len, cryptoBuf->computeChainDataLength());
break;
}
case QuicWriteFrame::Type::MaxDataFrame: {
const MaxDataFrame& maxData = *frame.asMaxDataFrame();
EXPECT_EQ(expectedConnFlowControlValue, maxData.maximumData);
break;
}
case QuicWriteFrame::Type::MaxStreamDataFrame: {
const MaxStreamDataFrame& maxStreamData = *frame.asMaxStreamDataFrame();
EXPECT_EQ(streamId, maxStreamData.streamId);
EXPECT_EQ(expectedStreamFlowControlValue, maxStreamData.maximumData);
break;
}
default:
EXPECT_TRUE(false); /* should never happen*/
}
}
EXPECT_TRUE(folly::IOBufEqualTo()(*packet1.header, *packet2.header));
// TODO: I don't have a good way to verify body without decode them
}
TEST_F(QuicPacketRebuilderTest, RebuildAfterResetStream) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder1.encodePacketHeader();
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(10);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
auto streamId = stream->id;
auto buf = folly::IOBuf::copyBuffer("A million miles away.");
writeStreamFrameHeader(
regularBuilder1,
streamId,
0,
buf->computeChainDataLength(),
buf->computeChainDataLength(),
true,
folly::none /* skipLenHint */);
writeStreamFrameData(
regularBuilder1, buf->clone(), buf->computeChainDataLength());
auto packet1 = std::move(regularBuilder1).buildPacket();
ASSERT_EQ(1, packet1.packet.frames.size());
// Then we reset the stream
sendRstSMHandler(*stream, GenericApplicationErrorCode::UNKNOWN);
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000);
EXPECT_FALSE(rebuilder.rebuildFromPacket(outstanding).has_value());
}
TEST_F(QuicPacketRebuilderTest, FinOnlyStreamRebuild) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder1.encodePacketHeader();
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(10);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
auto streamId = stream->id;
// Write them with a regular builder
writeStreamFrameHeader(
regularBuilder1, streamId, 0, 0, 0, true, folly::none /* skipLenHint */);
auto packet1 = std::move(regularBuilder1).buildPacket();
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(std::make_unique<StreamBuffer>(nullptr, 0, true)));
// rebuild a packet from the built out packet
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
auto outstanding = makeDummyOutstandingPacket(packet1.packet, 2000);
EXPECT_TRUE(rebuilder.rebuildFromPacket(outstanding).has_value());
auto packet2 = std::move(regularBuilder2).buildPacket();
EXPECT_EQ(packet1.packet.frames.size(), packet2.packet.frames.size());
EXPECT_TRUE(
0 ==
memcmp(
packet1.packet.frames.data(),
packet2.packet.frames.data(),
packet1.packet.frames.size()));
EXPECT_TRUE(folly::IOBufEqualTo()(*packet1.header, *packet2.header));
// Once we start to use the correct ack delay value in AckFrames, this needs
// to be changed:
EXPECT_TRUE(folly::IOBufEqualTo()(*packet1.body, *packet2.body));
}
TEST_F(QuicPacketRebuilderTest, RebuildDataStreamAndEmptyCryptoStream) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder1.encodePacketHeader();
// Get a bunch frames
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(10);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
StreamId streamId = stream->id;
auto buf =
folly::IOBuf::copyBuffer("You can't deny you are looking for the sunset");
uint64_t cryptoOffset = 0;
auto cryptoBuf = folly::IOBuf::copyBuffer("NewSessionTicket");
// Write them with a regular builder
writeStreamFrameHeader(
regularBuilder1,
streamId,
0,
buf->computeChainDataLength(),
buf->computeChainDataLength(),
true,
folly::none /* skipLenHint */);
writeStreamFrameData(
regularBuilder1, buf->clone(), buf->computeChainDataLength());
writeCryptoFrame(cryptoOffset, cryptoBuf->clone(), regularBuilder1);
auto packet1 = std::move(regularBuilder1).buildPacket();
ASSERT_EQ(2, packet1.packet.frames.size());
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(
std::make_unique<StreamBuffer>(buf->clone(), 0, true)));
// Do not add the buf to crypto stream's retransmission buffer,
// imagine it was cleared
// rebuild a packet from the built out packet
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000);
EXPECT_TRUE(rebuilder.rebuildFromPacket(outstanding).has_value());
auto packet2 = std::move(regularBuilder2).buildPacket();
// rebuilder writes frames to regularBuilder2
EXPECT_EQ(packet1.packet.frames.size(), packet2.packet.frames.size() + 1);
for (const auto& frame : packet2.packet.frames) {
const WriteStreamFrame* streamFrame = frame.asWriteStreamFrame();
if (!streamFrame) {
EXPECT_TRUE(false); /* should never happen*/
}
EXPECT_EQ(streamId, streamFrame->streamId);
EXPECT_EQ(0, streamFrame->offset);
EXPECT_EQ(buf->computeChainDataLength(), streamFrame->len);
EXPECT_EQ(true, streamFrame->fin);
}
EXPECT_TRUE(folly::IOBufEqualTo()(*packet1.header, *packet2.header));
}
TEST_F(QuicPacketRebuilderTest, CannotRebuildEmptyCryptoStream) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder1.encodePacketHeader();
// Get a bunch frames
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
uint64_t cryptoOffset = 0;
auto cryptoBuf = folly::IOBuf::copyBuffer("NewSessionTicket");
// Write them with a regular builder
writeCryptoFrame(cryptoOffset, cryptoBuf->clone(), regularBuilder1);
auto packet1 = std::move(regularBuilder1).buildPacket();
ASSERT_EQ(1, packet1.packet.frames.size());
// Do not add the buf to crypto stream's retransmission buffer,
// imagine it was cleared
// rebuild a packet from the built out packet
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000);
EXPECT_FALSE(rebuilder.rebuildFromPacket(outstanding).has_value());
}
TEST_F(QuicPacketRebuilderTest, CannotRebuild) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder1(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder1.encodePacketHeader();
// Get a bunch frames
ConnectionCloseFrame connCloseFrame(
QuicErrorCode(TransportErrorCode::FRAME_ENCODING_ERROR),
"The sun is in the sky.",
FrameType::ACK);
StreamsBlockedFrame maxStreamIdFrame(0x1024, true);
AckBlocks ackBlocks;
ackBlocks.insert(10, 100);
ackBlocks.insert(200, 1000);
WriteAckFrameState writeAckState = {.acks = ackBlocks};
WriteAckFrameMetaData ackMeta = {
.ackState = writeAckState,
.ackDelay = 0us,
.ackDelayExponent = static_cast<uint8_t>(kDefaultAckDelayExponent)};
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(10);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
auto streamId = stream->id;
auto buf =
folly::IOBuf::copyBuffer("You can't deny you are looking for the sunset");
PingFrame pingFrame;
// Write them with a regular builder
writeFrame(connCloseFrame, regularBuilder1);
writeFrame(maxStreamIdFrame, regularBuilder1);
writeFrame(pingFrame, regularBuilder1);
writeAckFrame(ackMeta, regularBuilder1);
writeStreamFrameHeader(
regularBuilder1,
streamId,
0,
buf->computeChainDataLength(),
buf->computeChainDataLength(),
true,
folly::none /* skipLenHint */);
writeStreamFrameData(
regularBuilder1, buf->clone(), buf->computeChainDataLength());
auto packet1 = std::move(regularBuilder1).buildPacket();
ASSERT_EQ(5, packet1.packet.frames.size());
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(
std::make_unique<StreamBuffer>(buf->clone(), 0, true)));
// new builder has a much smaller writable bytes limit
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
(packet1.header->computeChainDataLength() +
packet1.body->computeChainDataLength()) /
2,
std::move(shortHeader2),
0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
auto outstanding = makeDummyOutstandingPacket(packet1.packet, 1000);
EXPECT_FALSE(rebuilder.rebuildFromPacket(outstanding).has_value());
}
TEST_F(QuicPacketRebuilderTest, CloneCounter) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0 /* largestAcked */);
regularBuilder.encodePacketHeader();
MaxDataFrame maxDataFrame(31415926);
writeFrame(maxDataFrame, regularBuilder);
auto packet = std::move(regularBuilder).buildPacket();
auto outstandingPacket = makeDummyOutstandingPacket(packet.packet, 1000);
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0 /* largestAcked */);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
rebuilder.rebuildFromPacket(outstandingPacket);
EXPECT_TRUE(outstandingPacket.associatedEvent.has_value());
EXPECT_EQ(1, conn.outstandings.numClonedPackets());
}
TEST_F(QuicPacketRebuilderTest, PurePingWontRebuild) {
ShortHeader shortHeader1(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder(
kDefaultUDPSendPacketLen, std::move(shortHeader1), 0);
regularBuilder.encodePacketHeader();
PingFrame pingFrame;
writeFrame(pingFrame, regularBuilder);
auto packet = std::move(regularBuilder).buildPacket();
auto outstandingPacket = makeDummyOutstandingPacket(packet.packet, 50);
EXPECT_EQ(1, outstandingPacket.packet.frames.size());
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
ShortHeader shortHeader2(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder2(
kDefaultUDPSendPacketLen, std::move(shortHeader2), 0);
regularBuilder2.encodePacketHeader();
PacketRebuilder rebuilder(regularBuilder2, conn);
EXPECT_EQ(folly::none, rebuilder.rebuildFromPacket(outstandingPacket));
EXPECT_FALSE(outstandingPacket.associatedEvent.has_value());
EXPECT_EQ(0, conn.outstandings.numClonedPackets());
}
TEST_F(QuicPacketRebuilderTest, LastStreamFrameSkipLen) {
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(100);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
auto streamId = stream->id;
auto buf1 =
folly::IOBuf::copyBuffer("Remember your days are fully numbered.");
auto buf2 = folly::IOBuf::copyBuffer("Just march on");
ShortHeader shortHeader(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder(
kDefaultUDPSendPacketLen, std::move(shortHeader), 0);
regularBuilder.encodePacketHeader();
writeStreamFrameHeader(
regularBuilder,
streamId,
0,
buf1->computeChainDataLength(),
buf1->computeChainDataLength(),
false,
folly::none);
writeStreamFrameData(
regularBuilder, buf1->clone(), buf1->computeChainDataLength());
writeStreamFrameHeader(
regularBuilder,
streamId,
buf1->computeChainDataLength(),
buf2->computeChainDataLength(),
buf2->computeChainDataLength(),
true,
folly::none);
writeStreamFrameData(
regularBuilder, buf2->clone(), buf2->computeChainDataLength());
auto packet = std::move(regularBuilder).buildPacket();
auto outstandingPacket = makeDummyOutstandingPacket(packet.packet, 1200);
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(
std::make_unique<StreamBuffer>(buf1->clone(), 0, false)));
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(buf1->computeChainDataLength()),
std::forward_as_tuple(std::make_unique<StreamBuffer>(
buf2->clone(), buf1->computeChainDataLength(), true)));
MockQuicPacketBuilder mockBuilder;
size_t packetLimit = 1200;
EXPECT_CALL(mockBuilder, remainingSpaceInPkt()).WillRepeatedly(Invoke([&]() {
return packetLimit;
}));
// write data twice
EXPECT_CALL(mockBuilder, insert(_, _))
.Times(2)
.WillRepeatedly(
Invoke([&](const BufQueue&, size_t limit) { packetLimit -= limit; }));
// Append frame twice
EXPECT_CALL(mockBuilder, appendFrame(_)).Times(2);
// initial byte:
EXPECT_CALL(mockBuilder, writeBEUint8(_))
.Times(2)
.WillRepeatedly(Invoke([&](uint8_t) { packetLimit--; }));
// Write streamId twice, offset once, then data len only once:
EXPECT_CALL(mockBuilder, write(_))
.Times(4)
.WillRepeatedly(Invoke([&](const QuicInteger& quicInt) {
packetLimit -= quicInt.getSize();
}));
PacketRebuilder rebuilder(mockBuilder, conn);
EXPECT_TRUE(rebuilder.rebuildFromPacket(outstandingPacket).has_value());
}
TEST_F(QuicPacketRebuilderTest, LastStreamFrameFinOnlySkipLen) {
QuicServerConnectionState conn(
FizzServerQuicHandshakeContext::Builder().build());
conn.streamManager->setMaxLocalBidirectionalStreams(100);
auto stream = conn.streamManager->createNextBidirectionalStream().value();
auto streamId = stream->id;
auto buf1 =
folly::IOBuf::copyBuffer("Remember your days are fully numbered.");
ShortHeader shortHeader(
ProtectionType::KeyPhaseZero, getTestConnectionId(), 0);
RegularQuicPacketBuilder regularBuilder(
kDefaultUDPSendPacketLen, std::move(shortHeader), 0);
regularBuilder.encodePacketHeader();
writeStreamFrameHeader(
regularBuilder,
streamId,
0,
buf1->computeChainDataLength(),
buf1->computeChainDataLength(),
false,
folly::none);
writeStreamFrameData(
regularBuilder, buf1->clone(), buf1->computeChainDataLength());
writeStreamFrameHeader(
regularBuilder,
streamId,
buf1->computeChainDataLength(),
0,
0,
true,
folly::none);
writeStreamFrameData(regularBuilder, nullptr, 0);
auto packet = std::move(regularBuilder).buildPacket();
auto outstandingPacket = makeDummyOutstandingPacket(packet.packet, 1200);
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(0),
std::forward_as_tuple(
std::make_unique<StreamBuffer>(buf1->clone(), 0, false)));
stream->retransmissionBuffer.emplace(
std::piecewise_construct,
std::forward_as_tuple(buf1->computeChainDataLength()),
std::forward_as_tuple(std::make_unique<StreamBuffer>(
nullptr, buf1->computeChainDataLength(), true)));
MockQuicPacketBuilder mockBuilder;
size_t packetLimit = 1200;
EXPECT_CALL(mockBuilder, remainingSpaceInPkt()).WillRepeatedly(Invoke([&]() {
return packetLimit;
}));
// write data only
EXPECT_CALL(mockBuilder, insert(_, _))
.Times(1)
.WillOnce(
Invoke([&](const BufQueue&, size_t limit) { packetLimit -= limit; }));
// Append frame twice
EXPECT_CALL(mockBuilder, appendFrame(_)).Times(2);
// initial byte:
EXPECT_CALL(mockBuilder, writeBEUint8(_))
.Times(2)
.WillRepeatedly(Invoke([&](uint8_t) { packetLimit--; }));
// Write streamId twice, offset once, then data len twice:
EXPECT_CALL(mockBuilder, write(_))
.Times(5)
.WillRepeatedly(Invoke([&](const QuicInteger& quicInt) {
packetLimit -= quicInt.getSize();
}));
PacketRebuilder rebuilder(mockBuilder, conn);
EXPECT_TRUE(rebuilder.rebuildFromPacket(outstandingPacket).has_value());
}
} // namespace test
} // namespace quic
|
#ifndef RPC_SOCKET_HPP
#define RPC_SOCKET_HPP
#include <vector>
#include <cstddef>
#include "tcb/span.hpp"
#include "uvw.hpp"
#include "common/async.hpp"
namespace rpc {
class generic_socket {
protected:
bool _is_open;
bool _is_connected;
bool _handshake_finished;
size_t next_message_id;
std::vector<std::byte> message_piece;
std::function<void(rpc_message&&)> _on_message;
std::function<void(tcb::span<const std::byte>)> _on_incoming_handshake;
public:
inline generic_socket(bool is_preconnected, std::function<void(rpc_message&&)> on_message, std::function<void(tcb::span<const std::byte>)> on_incoming_handshake): _is_open(true), _is_connected(is_preconnected), _handshake_finished(false), next_message_id(0), _on_message(on_message), _on_incoming_handshake(on_incoming_handshake) {
}
virtual ~generic_socket() = default;
virtual void write(std::vector<std::byte> data) = 0;
virtual void stop() = 0;
inline bool is_open() const {
return _is_open;
}
inline bool is_connected() const {
return _is_connected;
}
inline bool handshake_finished() const {
return _handshake_finished;
}
inline void reply(uint64_t message_id, std::vector<std::byte> response) {
rpc_message message;
message.message_size = 0;
message.method_id = -1;
message.message_id = message_id;
message.args = std::move(response);
message.message_size = serialize(message).size();
write(serialize(message));
}
inline void report_error(uint64_t message_id, const std::string& text) {
rpc_message message;
message.message_size = 0;
message.method_id = -2;
message.message_id = message_id;
message.args = serialize(text);
message.message_size = serialize(message).size();
write(serialize(message));
}
inline void invoke(int32_t method_id, uint64_t message_id, std::vector<std::byte> args) {
rpc_message message;
message.message_size = 0;
message.method_id = method_id;
message.message_id = message_id;
message.args = std::move(args);
message.message_size = serialize(message).size();
write(serialize(message));
}
};
template<typename Handle> class socket: public generic_socket {
std::shared_ptr<Handle> handle;
std::optional<typename Handle::template Connection<uvw::ConnectEvent>> connect_handler;
typename Handle::template Connection<uvw::EndEvent> end_handler;
typename Handle::template Connection<uvw::DataEvent> data_handler;
typename Handle::template Connection<uvw::ErrorEvent> error_handler;
public:
socket(std::shared_ptr<Handle> handle_, bool is_preconnected, std::function<void(rpc_message&&)> on_message, std::function<void(tcb::span<const std::byte>)> on_incoming_handshake): generic_socket(is_preconnected, on_message, on_incoming_handshake), handle(std::move(handle_)) {
if(!_is_connected) {
connect_handler = handle->template on<uvw::ConnectEvent>([this](const uvw::ConnectEvent&, Handle& handle) {
_is_connected = true;
handle.read();
});
}
end_handler = handle->template on<uvw::EndEvent>([this](const uvw::EndEvent&, Handle& handle) {
_is_open = false;
_is_connected = false;
handle.close();
});
data_handler = handle->template on<uvw::DataEvent>([this](const uvw::DataEvent& ev, Handle& handle) {
try {
on_data(tcb::span<const std::byte>(reinterpret_cast<const std::byte*>(ev.data.get()), ev.length));
} catch(std::exception& ex) {
std::cerr << "Exception on socket on_data: " << ex.what() << std::endl;
stop();
}
});
error_handler = handle->template on<uvw::ErrorEvent>([this](const uvw::ErrorEvent&, Handle& handle) {
_is_open = false;
_is_connected = false;
handle.close();
});
}
~socket() {
if(connect_handler) {
handle->erase(*connect_handler);
}
handle->erase(end_handler);
handle->erase(data_handler);
handle->erase(error_handler);
}
void on_data(tcb::span<const std::byte> data) {
message_piece.insert(message_piece.end(), data.begin(), data.end());
if(!_handshake_finished) {
if(message_piece.size() < 8) {
return;
}
generic_hello hello_header = deserialize<generic_hello>(tcb::span{message_piece.data(), message_piece.data() + 8});
if(
std::tolower(static_cast<unsigned char>(hello_header.magic[0])) != 's' ||
std::tolower(static_cast<unsigned char>(hello_header.magic[1])) != 'm' ||
std::tolower(static_cast<unsigned char>(hello_header.magic[2])) != 'o' ||
std::tolower(static_cast<unsigned char>(hello_header.magic[3])) != 'l'
) {
std::cerr << "Failure on socket: invalid magic" << std::endl;
stop();
return;
}
if(hello_header.hello_size > 8 * 1024) {
std::cerr << "Failure on socket: too long hello" << std::endl;
stop();
return;
}
if(message_piece.size() < hello_header.hello_size) {
return;
}
_on_incoming_handshake(tcb::span{message_piece.data(), message_piece.data() + hello_header.hello_size});
message_piece.erase(message_piece.begin(), message_piece.begin() + hello_header.hello_size);
_handshake_finished = true;
}
while(message_piece.size() >= 4) {
uint32_t message_size = deserialize<uint32_t>(tcb::span{message_piece.data(), message_piece.data() + 4});
if(message_piece.size() < message_size) {
break;
}
rpc_message message = deserialize<rpc_message>(tcb::span{message_piece.data(), message_piece.data() + message_size});
message_piece.erase(message_piece.begin(), message_piece.begin() + message_size);
on_message(std::move(message));
}
}
void on_message(rpc_message&& message) {
_on_message(std::move(message));
}
virtual void write(std::vector<std::byte> data) {
if(!_is_connected) {
throw std::runtime_error("Socket not connected");
}
std::byte* ptr = data.data();
size_t size = data.size();
auto deleter = [data = std::move(data)](char*) {
};
handle->write(std::unique_ptr<char[], decltype(deleter)>(reinterpret_cast<char*>(ptr), deleter), size);
}
virtual void stop() {
if(_is_connected) {
handle->shutdown();
_is_connected = false;
}
if(_is_open) {
handle->stop();
handle->close();
_is_open = false;
}
}
};
}
#endif
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Patryk Obara (pobara)
*/
#include "core/pch.h"
#include "platforms/quix/desktop_pi_impl/UnixDesktopColorChooser.h"
#include "platforms/quix/toolkits/ToolkitLibrary.h"
#include "platforms/quix/toolkits/ToolkitColorChooser.h"
#include "platforms/unix/base/x11/x11_dialog.h"
#include "platforms/unix/base/x11/x11_globals.h"
#include "platforms/unix/base/x11/x11_opwindow.h"
#include "platforms/unix/base/x11/x11_widget.h"
#include "platforms/unix/base/x11/x11_widgetlist.h"
BOOL UnixDesktopColorChooser::m_color_chooser_dialog_is_active = FALSE;
UnixDesktopColorChooser::UnixDesktopColorChooser(
ToolkitColorChooser *toolkit_chooser)
: m_chooser(toolkit_chooser)
{
OP_ASSERT(m_chooser);
}
UnixDesktopColorChooser::~UnixDesktopColorChooser()
{
OP_DELETE(m_chooser);
}
OP_STATUS UnixDesktopColorChooser::Show(COLORREF initial_color,
OpColorChooserListener *listener,
DesktopWindow *parent)
{
X11Dialog::PrepareForShowingDialog(false);
OP_ASSERT(listener);
OP_ASSERT(parent);
if(!m_chooser || m_color_chooser_dialog_is_active)
return OpStatus::ERR;
X11Widget *widget = NULL;
X11Types::Window x11_parent_id = 0;
if(parent)
{
// same trick in UnixDesktopFileChooser
X11OpWindow* native_window = static_cast<X11OpWindow*>(parent->GetOpWindow());
if(native_window && !native_window->IsToplevel())
native_window = native_window->GetNativeWindow();
widget = native_window->GetOuterWidget();
x11_parent_id = widget ? widget->GetWindowHandle() : 0;
}
// set our brand new dialog to be modal for it's parent:
if (g_toolkit_library->BlockOperaInputOnDialogs())
g_x11->GetWidgetList()->SetModalToolkitParent(widget);
m_color_chooser_dialog_is_active = TRUE;
BOOL ok = m_chooser->Show(x11_parent_id, (UINT32)initial_color);
m_color_chooser_dialog_is_active = FALSE;
if (ok)
listener->OnColorSelected((COLORREF)m_chooser->GetColor());
// disable modality
g_x11->GetWidgetList()->SetModalToolkitParent(NULL);
return OpStatus::OK;
}
|
//算法:暴力枚举
//暴力三层循环枚举所有情况
//然后判断是否合法
#include<cstdio>
using namespace std;
int n,ans;
int a,b,c,d,e,f;
int abs(int x)
{
return x<0?x*(-1):x;
}
int main()
{
scanf("%d%d%d%d%d%d%d",&n,&a,&b,&c,&d,&e,&f);
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
for(int k=1;k<=n;k++)
if(((abs(i-a)<=2||abs(i-a)>=n-2)&&(abs(j-b)<=2||abs(j-b)>=n-2)&&(abs(k-c)<=2||abs(k-c)>=n-2))||((abs(i-d)<=2||abs(i-d)>=n-2)&&(abs(j-e)<=2||abs(j-e)>=n-2)&&(abs(k-f)<=2||abs(k-f)>=n-2)))ans++;//由题意得,符合条件,方案数加一
printf("%d",ans);
}
|
/*
Crayfish - A collection of tools for TUFLOW and other hydraulic modelling packages
Copyright (C) 2016 Lutra Consulting
info at lutraconsulting dot co dot uk
Lutra Consulting
23 Chestnut Close
Burgess Hill
West Sussex
RH15 8HN
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "crayfish_eNp.h"
#include "math.h"
#include <QPointF>
#include <QVector3D>
#include <QVector2D>
#include <QPolygonF>
#include <limits>
static double ENP_contangent(QPointF a, QPointF b, QPointF c) {
//http://geometry.caltech.edu/pubs/MHBD02.pdf
QVector3D ba (b-a);
QVector3D bc (b-c);
double dp = QVector3D::dotProduct(bc, ba);
QVector3D cp = QVector3D::crossProduct(bc, ba);
return dp/cp.length();
}
bool ENP_physicalToLogical(const QPolygonF& pX, QPointF pP, QVector<double>& lam)
{
//http://geometry.caltech.edu/pubs/MHBD02.pdf
if (pX.size() < 3 || pX.size() != lam.size())
return false;
if (!pX.containsPoint(pP, Qt::WindingFill)) {
return false;
}
double weightSum = 0;
int prev = pX.size() -1;
int next = 1;
for (int i=0; i<pX.size(); i++)
{
double cotPrev = ENP_contangent(pP, pX[i], pX[prev]);
double cotNext = ENP_contangent(pP, pX[i], pX[next]);
double len2 = QVector2D(pX[i] - pP).lengthSquared();
lam[i] = (cotPrev + cotNext) / len2;
weightSum += lam[i];
++prev;
if (prev == pX.size()) prev = 0;
++next;
if (next == pX.size()) next = 0;
}
for (QVector<double>::iterator lamit=lam.begin(); lamit!=lam.end(); ++lamit)
{
*lamit = (*lamit)/weightSum;
}
return true;
}
static void ENP_centroid_step(const QPolygonF& pX, double& cx, double& cy, double& signedArea, int i, int i1)
{
double x0 = 0.0; // Current vertex X
double y0 = 0.0; // Current vertex Y
double x1 = 0.0; // Next vertex X
double y1 = 0.0; // Next vertex Y
double a = 0.0; // Partial signed area
x0 = pX[i].x();
y0 = pX[i].y();
x1 = pX[i1].x();
y1 = pX[i1].y();
a = x0*y1 - x1*y0;
signedArea += a;
cx += (x0 + x1)*a;
cy += (y0 + y1)*a;
}
void ENP_centroid(const QPolygonF& pX, double& cx, double& cy)
{
// http://stackoverflow.com/questions/2792443/finding-the-centroid-of-a-polygon/2792459#2792459
cx = 0;
cy = 0;
if (pX.isEmpty())
return;
double signedArea = 0.0;
// For all vertices except last
int i=0;
for (; i<pX.size()-1; ++i)
{
ENP_centroid_step(pX, cx, cy, signedArea, i, i+1);
}
// Do last vertex separately to avoid performing an expensive
// modulus operation in each iteration.
ENP_centroid_step(pX, cx, cy, signedArea, i, 0);
signedArea *= 0.5;
cx /= (6.0*signedArea);
cy /= (6.0*signedArea);
}
|
#ifndef HEAP_H_
#define HEAP_H_
#include "DBFile.h"
class Heap: public DBFile {
public:
Heap();
~Heap();
int Close ();
void Add (Record& me);
void MoveFirst();
int GetNext (Record &fetchme, CNF &cnf, Record &literal);
protected:
void readMode();
};
inline void Heap::readMode() {
if (mode == read)
return;
mode = read;
if (!page.is_empty())
file.addPage(&page);
}
#endif
|
#ifndef PLAYER_H
#define PLAYER_H
#include "Object.h"
class Vector;
class Player : public Object
{
public:
explicit Player(const char*);
Player(const Player&);
virtual void update(void);
char whichClass(void);
protected:
void decelerate(void);
void autoMove(void);
private:
Vector* route;
short routeNum;
short routeIndex;
};
#endif
|
#pragma once
class CMath {
public:
static const float PI;
static float DegToRad(float deg)
{
return deg * (PI / 180.0f);
}
static float RadToDeg(float rad)
{
return rad / (PI / 180.0f);
}
static inline float Lerp(float rate, float t0, float t1)
{
return t0 + (t1 - t0)*rate;
}
};
|
#include <ostream>
#include "knock.h"
void toggle_am_pm(){
if(am == 1){
am = 0;
}
else if(am == 0){
am = 1;
}
}
/*
* Resets the time to midnight
*/
void reset(){
hours = 12;
minutes = 0;
seconds = 0;
am = 1;
}
/*
* Advances the time of the clock by one second
*/
void advance_one_sec(){
seconds++;
if(seconds == 60){
minutes++;
seconds = 0;
if(minutes == 60){
min = 0;
hours++;
if hours == 13 {
hours = 1;
am = !am;
}
}
}
}
/*
* Advances the time of the clock by n seconds
*/
void advance_n_secs(unsigned int n){
seconds++;
if(seconds == 60){
minutes++;
seconds = 0;
if(minutes == 60){
min = 0;
hours++;
if hours == 13 {
hours = 1;
am = !am;
}
}
}
}
/*
* Getter for hours field
*/
unsigned int get_hours() const{
return hours;
}
/*
* Setter for hours field; throws an invalid_argument exception
* if hrs is not a legal hours value
*/
void set_hours(unsigned int hrs){
if(hrs > 12){
throw std::invalid_argument("hours cannot be more than 12");
}else hourse = hrs;
}
/*
* Getter for minutes field
*/
unsigned int get_minutes() const{
return minutes;
}
/*
* Setter for minutes field; throws an invalid_argument exception
* if mins is not a legal minutes value
*/
void set_minutes(unsigned int mins){
if(mins > 60){
throw std::invalid_argument("mins cannot be more than 60");
}else minutes = hrs;
};
/*
* Getter for seconds field
*/
unsigned int get_seconds() const{
return seconds;
}
/*
* Setter for seconds field; throws an invalid_argument exception
* if secs is not a legal seconds value
*/
void set_seconds(unsigned int secs){
if(secs > 60){
throw std::invalid_argument("secs cannot be more than 60");
}else seconds = secs;
};
/*
* Getter for am field
*/
bool is_am() const{
return am;
};
/*
* Setter for am field
*/
void set_am(bool am_val){
am = am_val;
};
/*
* Print function - helper for output operator
*/
void print(std::ostream& out) const {
char buff[11];
std::sprintf(buff, "%02d:%02d:%02d%cm", hours, minutes, seconds,
( am ? 'a' : 'p' ));
out << buff;
}
/*
* Destructor
*/
~am_pm_clock();
};
inline std::ostream& operator << (std::ostream& out, const am_pm_clock& clock) {
clock.print(out);
return out;
}
int main{
return 0;
}
|
#include <SFML/Graphics.hpp>
#include "Player.h"
#include "TileMap.h"
#include "Enemy.h"
#include <iostream>
int main()
{
sf::Clock clock;
std::vector<std::vector<int>> level =
{
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 },
{ 4, 0, 0, 1, 0, 0, 0, 2, 0, 4 },
{ 4, 0, 0, 1, 1, 1, 0, 0, 0, 4 },
{ 4, 0, 0, 0, 0, 1, 1, 1, 1, 4 },
{ 4, 0, 0, 0, 0, 0, 0, 0, 0, 4 },
{ 4, 0, 0, 0, 2, 3, 3, 3, 3, 4 },
{ 4, 0, 0, 0, 0, 3, 0, 0, 2, 4 },
{ 4, 1, 0, 0, 3, 3, 2, 2, 2, 4 },
{ 4, 1, 0, 0, 3, 0, 2, 2, 2, 4 },
{ 4, 1, 0, 3, 3, 0, 0, 2, 0, 4 },
{ 4, 1, 0, 3, 0, 0, 0, 0, 0, 4 },
{ 4, 1, 0, 3, 1, 1, 1, 1, 0, 4 },
{ 4, 1, 2, 3 ,1, 1, 1, 1, 0, 4 },
{ 4, 1, 0, 3, 1, 1, 1, 1, 1, 4 },
{ 4, 1, 0, 3, 0, 2, 1, 1, 1, 4 },
{ 4, 1, 0, 3, 0, 0, 2, 1, 1, 4 },
{ 4, 1, 0, 3, 0, 0, 0, 1, 1, 4 },
{ 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }
};
sf::RenderWindow window(sf::VideoMode(800, 600), "Gaem");
Player player(sf::Vector2f(192, 192), 5, 100, "../sprites/Knight.png");
Enemy enemy(sf::Vector2f(192 + 128 * 2, 192 + 128 * 2), 5, 100, "../sprites/Knight.png");
window.setFramerateLimit(60);
TileMap map;
if (!map.load("../tileset/tileset.png", level)) return 1;
while (window.isOpen())
{
window.clear();
window.setView(sf::View(player.pos, static_cast<sf::Vector2f>(window.getSize())));
window.draw(map);
map.restrictMovement(player);
map.restrictMovement(enemy);
enemy.update(window, window, clock.getElapsedTime(), player);
player.update(window, window, clock.restart());
window.display();
}
return 0;
}
|
//===========================================================================
//! @file shadow_map.h
//! @brief シャドウマップ管理
//===========================================================================
#pragma once
//===========================================================================
//! @class ShadowMap
//===========================================================================
class ShadowMap
{
public:
//-----------------------------------------------------------------------
//! @name 初期化
//-----------------------------------------------------------------------
//@{
//! @brief コンストラクタ
ShadowMap() = default;
//! @brief デストラクタ
~ShadowMap() = default;
//@}
//---------------------------------------------------------------------------
//! @name タスク
//---------------------------------------------------------------------------
//@{
//! @brief 初期化
bool initialize(s32 resolution = 4096);
//! @brief 解放
void finalize();
//! @brief シャドウパスの開始
void begin(const Light& light);
//! @brief シャドウパスの終了
void end();
//@}
//---------------------------------------------------------------------------
//! @name 取得
//---------------------------------------------------------------------------
//@{
//! @brief デプステクスチャ取得
gpu::Texture* getDepthTexture();
//@}
private:
gpu::ConstantBuffer<cbShadow> cbShadow_; //!< 影用定数バッファ
std::unique_ptr<gpu::Texture> depthTexture_; //!< 影用デプステクスチャ
u32 gpuSlot = 8; //!< GPUスロット番号
s32 resolution_ = 2048; //!< 解像度
};
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2010 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#include "platforms/windows/WindowsShortcut.h"
#include "adjunct/desktop_util/shortcuts/DesktopShortcutInfo.h"
#include "adjunct/quick/managers/FavIconManager.h"
#include "modules/pi/opbitmap.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/path.h"
#include "platforms/windows/pi/WindowsOpDesktopResources.h"
#include "platforms/windows/utils/win_icon.h"
#include "platforms/windows/win_handy.h"
#include "platforms/windows/utils/com_helpers.h"
WindowsShortcut::WindowsShortcut()
: m_shortcut_info(NULL)
{
}
OP_STATUS WindowsShortcut::Init(const DesktopShortcutInfo& shortcut_info)
{
m_shortcut_info = &shortcut_info;
RETURN_IF_ERROR(MakePaths());
return OpStatus::OK;
}
OP_STATUS WindowsShortcut::Init(const DesktopShortcutInfo& shortcut_info,
const OpStringC& shortcut_path)
{
RETURN_IF_ERROR(Init(shortcut_info));
RETURN_IF_ERROR(m_shortcut_path.Set(shortcut_path));
return OpStatus::OK;
}
OpStringC WindowsShortcut::GetShortcutFilePath() const
{
return m_shortcut_path;
}
OP_STATUS WindowsShortcut::MakePaths()
{
OP_ASSERT(NULL != m_shortcut_info);
switch (m_shortcut_info->m_destination)
{
case DesktopShortcutInfo::SC_DEST_DESKTOP:
RETURN_IF_ERROR(WindowsOpDesktopResources::GetFolderPath(FOLDERID_Desktop, CSIDL_DESKTOPDIRECTORY, m_shortcut_path));
break;
case DesktopShortcutInfo::SC_DEST_COMMON_DESKTOP:
RETURN_IF_ERROR(WindowsOpDesktopResources::GetFolderPath(FOLDERID_PublicDesktop, CSIDL_COMMON_DESKTOPDIRECTORY, m_shortcut_path));
break;
case DesktopShortcutInfo::SC_DEST_MENU:
RETURN_IF_ERROR(WindowsOpDesktopResources::GetFolderPath(FOLDERID_Programs, CSIDL_PROGRAMS, m_shortcut_path));
break;
case DesktopShortcutInfo::SC_DEST_COMMON_MENU:
RETURN_IF_ERROR(WindowsOpDesktopResources::GetFolderPath(FOLDERID_CommonPrograms, CSIDL_COMMON_PROGRAMS, m_shortcut_path));
break;
case DesktopShortcutInfo::SC_DEST_QUICK_LAUNCH:
RETURN_IF_ERROR(WindowsOpDesktopResources::GetFolderPath(FOLDERID_QuickLaunch, CSIDL_APPDATA, m_shortcut_path));
if (!IsSystemWinVista())
{
RETURN_IF_ERROR(m_shortcut_path.Append("\\Microsoft\\Internet Explorer\\Quick Launch"));
OpFile quick_launch_folder;
RETURN_IF_ERROR(quick_launch_folder.Construct(m_shortcut_path));
BOOL exists;
if (OpStatus::IsError(quick_launch_folder.Exists(exists)) || !exists)
RETURN_IF_ERROR(quick_launch_folder.MakeDirectory());
}
break;
case DesktopShortcutInfo::SC_DEST_TEMP:
{
OpFile temp;
RETURN_IF_ERROR(temp.Construct(UNI_L(""), OPFILE_TEMP_FOLDER));
RETURN_IF_ERROR(m_shortcut_path.Set(temp.GetFullPath()));
}
break;
case DesktopShortcutInfo::SC_DEST_NONE:
m_shortcut_path.Empty();
break;
default:
OP_ASSERT(!"Unknown shortcut destination");
return OpStatus::ERR;
}
if (m_shortcut_path.HasContent())
{
RETURN_IF_ERROR(m_shortcut_path.AppendFormat(UNI_L("\\%s.lnk"),
m_shortcut_info->m_file_name.CStr()));
}
return OpStatus::OK;
}
OP_STATUS WindowsShortcut::Deploy()
{
OP_ASSERT(NULL != m_shortcut_info);
OP_ASSERT(m_shortcut_path.HasContent());
if (m_shortcut_path.IsEmpty())
{
return OpStatus::ERR_NULL_POINTER;
}
OP_STATUS result = OpStatus::ERR;
m_hr = S_OK;
m_err_loc = 0;
OpComPtr<IShellLink> shell_link;
OpComPtr<IPersistFile> persist_file;
do
{
HRESULT m_hr = shell_link.CoCreateInstance(CLSID_ShellLink);
if(FAILED(m_hr))
break;
m_err_loc++;
m_hr = shell_link->SetPath(m_shortcut_info->m_command.CStr());
if(FAILED(m_hr))
break;
m_err_loc++;
m_hr = shell_link->SetWorkingDirectory(m_shortcut_info->m_working_dir_path.CStr());
if(FAILED(m_hr))
break;
m_err_loc++;
m_hr = shell_link->SetDescription(m_shortcut_info->m_comment.CStr());
if(FAILED(m_hr))
break;
m_err_loc++;
if(m_shortcut_info->m_icon_name.HasContent())
{
m_hr = shell_link->SetIconLocation(m_shortcut_info->m_icon_name.CStr(), m_shortcut_info->m_icon_index);
if(FAILED(m_hr))
break;
m_err_loc++;
}
m_hr = shell_link.QueryInterface<IPersistFile>(&persist_file);
if(FAILED(m_hr))
break;
m_err_loc++;
m_hr = persist_file->Save(m_shortcut_path.CStr(), TRUE);
if(FAILED(m_hr))
break;
m_err_loc++;
result = OpStatus::OK;
}
while (FALSE);
return result;
}
OP_STATUS WindowsShortcut::ExecuteContextmenuVerb(const uni_char *app_path, const char *verb)
{
// This method accepts only full/absolute path to an application
uni_char* path_sep = uni_strrchr(app_path, UNI_L(PATHSEPCHAR));
if (!path_sep || *(path_sep+1) == '\0')
return OpStatus::ERR;
OpString file_part;
RETURN_IF_ERROR(file_part.Set(path_sep + 1)); //Take out the path seperator
OpString dir_part;
RETURN_IF_ERROR(dir_part.Set(app_path, path_sep - app_path));
OP_STATUS status = OpStatus::ERR;
LPSHELLFOLDER pdf = NULL, psf = NULL;
LPITEMIDLIST pidl = NULL, pitm = NULL;
LPCONTEXTMENU pcm = NULL;
HMENU hmenu = NULL;
if (SUCCEEDED(SHGetDesktopFolder(&pdf))
&& SUCCEEDED(pdf->ParseDisplayName(NULL, NULL, dir_part.CStr(), NULL, &pidl, NULL))
&& SUCCEEDED(pdf->BindToObject(pidl, NULL, IID_IShellFolder, (void **)&psf))
&& SUCCEEDED(psf->ParseDisplayName(NULL, NULL, file_part.CStr(), NULL, &pitm, NULL))
&& SUCCEEDED(psf->GetUIObjectOf(NULL, 1, (LPCITEMIDLIST *)&pitm, IID_IContextMenu, NULL, (void **)&pcm))
&& (hmenu = CreatePopupMenu()) != NULL
&& SUCCEEDED(pcm->QueryContextMenu(hmenu, 0, 1, INT_MAX, CMF_NORMAL)))
{
CMINVOKECOMMANDINFO ici = { sizeof(CMINVOKECOMMANDINFO), 0 };
ici.hwnd = NULL;
ici.lpVerb = verb;
if (SUCCEEDED(pcm->InvokeCommand(&ici)))
status = OpStatus::OK;
}
if (hmenu)
DestroyMenu(hmenu);
if (pcm)
pcm->Release();
if (pitm)
CoTaskMemFree(pitm);
if (psf)
psf->Release();
if (pidl)
CoTaskMemFree(pidl);
if (pdf)
pdf->Release();
return status;
}
/*
All currently pinned programs have a symbolic link in the folder
C:\Users\Username\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar.
Solution to check if a program is pinned or not is to look if one of the symbolic links is
pointing to the program's executable:
1. Get the first symbolic link from the '...\TaskBar' folder
2. Retrieve the path to the exe the symbolic link is pointing to
3. Compare the path with the path I am looking for, if equal, stop and return true
4. If not, get the next symbolic link
*/
OP_STATUS WindowsShortcut::CheckIfApplicationIsPinned(const uni_char *app_abs_path, BOOL &is_pinned)
{
is_pinned = FALSE;
OP_STATUS status = OpStatus::ERR;
WIN32_FIND_DATA ffd;
HANDLE hFind = INVALID_HANDLE_VALUE;
//Get User Pinned folder:
//C:\Users\Username\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned
OpString user_pinned_path;
RETURN_IF_ERROR(WindowsOpDesktopResources::GetFolderPath(FOLDERID_UserPinned, 0, user_pinned_path, FALSE));
//Append '\TaskBar\*.lnk'
OpString user_pinned_path_ex;
RETURN_IF_ERROR(user_pinned_path_ex.Set(user_pinned_path));
RETURN_IF_ERROR(user_pinned_path_ex.Append(UNI_L("\\TaskBar\\*.lnk")));
//Get all symbolic links in the directory until a link is pointing to 'app_abs_path'
hFind = FindFirstFile(user_pinned_path_ex.CStr(), &ffd);
if (hFind == INVALID_HANDLE_VALUE)
return OpStatus::ERR;
do
{
if (!(ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
//Create a string with the complete path to the link
OpString link_path;
if (OpStatus::IsError(link_path.Set(user_pinned_path))
|| OpStatus::IsError(link_path.Append(L"\\TaskBar\\"))
|| OpStatus::IsError(link_path.Append(ffd.cFileName)))
break;
//Get the path the link is pointing to
OpString link_target;
if (OpStatus::IsSuccess(GetPathLinkIsPointingTo(link_path, link_target))
&& link_target.HasContent())
{
//If the returned path is the same as 'app_abs_path', leave the loop
if (link_target.CompareI(app_abs_path) == 0)
{
is_pinned = TRUE;
status = OpStatus::OK;
break;
}
}
}
}
while (FindNextFile(hFind, &ffd) != 0);
FindClose(hFind);
return status;
}
//Get the path a given symbolic link is pointing to, using IShellLink
OP_STATUS WindowsShortcut::GetPathLinkIsPointingTo(const OpString &link_file, OpString &app_path)
{
OP_STATUS status = OpStatus::ERR;
uni_char path[MAX_PATH];
IShellLink* psl = NULL;
IPersistFile* ppf = NULL;
if (SUCCEEDED(CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, (LPVOID*)&psl))
&& SUCCEEDED(psl->QueryInterface(IID_IPersistFile, (void**)&ppf))
&& SUCCEEDED(ppf->Load(link_file.CStr(), STGM_READ))
&& SUCCEEDED(psl->Resolve(NULL, SLR_NO_UI))
&& SUCCEEDED(psl->GetPath(path, MAX_PATH, NULL, SLGP_UNCPRIORITY)))
{
if (OpStatus::IsSuccess(app_path.Set(path)))
status = OpStatus::OK;
}
if (ppf)
ppf->Release();
if (psl)
psl->Release();
return status;
}
|
#ifndef _POOL_H_
#define _POOL_H_
#include <map>
#include <vector>
#include <random>
#include <assert.h>
#include "Profile.h"
using namespace std;
class Pool{
private:
// vector< map<unsigned int, unsigned int> > mutations_map;
// Version con vector posicionale en lugar de mapa
// Aqui el id del alelo es directamente la posicion
vector< vector<unsigned int> > mutations_map;
// vector<unsigned int> next_allele;
public:
Pool();
Pool(Profile *profile);
virtual ~Pool();
unsigned int getNumMarkers();
unsigned int getNewAllele(unsigned int marker_pos, unsigned int allele);
unsigned int getParent(unsigned int marker_pos, unsigned int allele);
unsigned int getNumAlleles(unsigned int marker_pos);
// unsigned int getAllele(unsigned int marker, unsigned int pos);
// unsigned int getNextAllele(unsigned int marker){
// return next_allele[marker];
// }
// Metodo de debug
void print(){
// cout << "Pool::print - n_markers: " << mutations_map.size() << " (next_allele.size(): " << next_allele.size() << ")\n";
cout << "Pool::print - n_markers: " << mutations_map.size() << "\n";
for( unsigned int i = 0; i < mutations_map.size(); ++i ){
cout << "Pool::print - mutations[" << i << "]: " << mutations_map[i].size() << "\n";
// cout << "Pool::print - next_allele[" << i << "]: " << next_allele[i] << "\n";
}
cout << "Pool::print - End\n";
}
};
#endif
|
#ifndef ECCEZIONI_H
#define ECCEZIONI_H
#include <string>
using std::string;
class eccezioni {
private:
string error;
protected:
eccezioni(string a): error(a) {}
public:
string to_string_error() const;
};
class input_error : public eccezioni{
public :
input_error(string a = "Errore input." ) : eccezioni(a) {}
};
class not_implicit : public eccezioni{
public :
not_implicit(string a = "Retta non nella forma prevista." ) : eccezioni(a) {}
};
class irregular_pol : public eccezioni {
public :
irregular_pol(string a = "Poligono non regolare."):eccezioni(a) {}
};
class num_lati : public eccezioni{
public :
num_lati(string a = "Numero punti non gestibile.\n Rappresenta un punto alla volta."):eccezioni(a) {}
};
#endif // ECCEZIONI_H
|
#include <iostream>
#include <fstream>
#include <Windows.h>
#include <sstream>
#include <string>
#include <cerrno>
#include <WinUser.h>
#include "ArgumentsParsing.h"
#include "ErrorCode.h"
#include "Utils.h"
#include "Version.h"
#include "resource.h"
namespace arithmetic_parser
{
bool FindOption(const std::map<CmdOption, OptionInput>& option_inputs, const CmdOption option_to_find, OptionInput& option)
{
const auto search = option_inputs.find(option_to_find);
if (search != option_inputs.end())
{
option = search->second;
return true;
}
return false;
}
void ShowVersion()
{
std::cout << "Arithmetic Parser v" << MAJOR_VERSION << "." << MINOR_VERSION << "." << BUILD_VERSION << std::endl;
std::cout << "Copyright (C) " << YEAR << " " << AUTHOR << "." << std::endl;
}
void ShowHelp()
{
ShowVersion();
std::cout << std::endl;
auto resource_id = IDR_HELP_TEXT;
auto hResource = FindResource(nullptr, MAKEINTRESOURCE(resource_id), "TEXT");
auto hMemory = LoadResource(nullptr, hResource);
size_t size_bytes = SizeofResource(nullptr, hResource);
void* ptr = LockResource(hMemory);
std::string_view dst;
if (ptr != nullptr)
{
dst = std::string_view(reinterpret_cast<char*>(ptr), size_bytes);
FreeResource(hResource);
}
std::cout << dst;
}
bool SaveResult(const std::string& file_path, double result) noexcept
{
try
{
std::ofstream save_stream;
save_stream.open(file_path.c_str(), std::ios::out | std::ios::app);
save_stream << result << std::endl;
save_stream.close();
return true;
}
catch (std::exception& exception)
{
std::cout << exception.what() << std::endl;
return false;
}
}
void CopyToTheClipboard(const double result)
{
auto str = std::to_string(result);
HWND hwnd = GetDesktopWindow();
OpenClipboard(hwnd);
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, str.size());
if (!hg)
{
CloseClipboard();
return;
}
memcpy(GlobalLock(hg), str.c_str(), str.size());
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
GlobalFree(hg);
}
bool GetInput(const std::map<CmdOption, OptionInput>& option_inputs, std::string& input)
{
OptionInput file_option_input;
auto readFromFile = FindOption(option_inputs, CmdOption::File, file_option_input);
OptionInput expr_option_input;
auto readFromCmd = FindOption(option_inputs, CmdOption::Expression, expr_option_input);
if (readFromCmd && readFromFile)
{
std::cout << "Expression is specified from command line and from file. Only one expression source is allowed.";
return false;
}
if (readFromFile)
{
auto load_path = file_option_input.arguments[0];
if (LoadExpression(load_path, input))
{
return true;
}
else
{
return false;
}
}
if (readFromCmd)
{
input = expr_option_input.arguments[0];
return true;
}
}
bool LoadExpression(const std::string& file_path, std::string& input)
{
std::ifstream load_stream;
load_stream.open(file_path, std::ios::in);
if (!load_stream)
return false;
std::ostringstream contents;
contents << load_stream.rdbuf();
load_stream.close();
input = contents.str();
return true;
}
void RemoveCharactersFromString(std::string& s, const char* characters)
{
for (size_t i = 0; i < strlen(characters); ++i)
{
s.erase(std::remove(s.begin(), s.end(), characters[i]), s.end());
}
}
}
|
/*
Copyright (c) 2006-2022 Xavier Leclercq
Released under the MIT License
See https://github.com/ishiko-cpp/test-framework/blob/main/LICENSE.txt
*/
#include "Test.hpp"
#include "TestSequence.hpp"
#include "DebugHeap.hpp"
#include <boost/filesystem/operations.hpp>
#include <boost/range/algorithm.hpp>
using namespace Ishiko;
void Test::Observer::onLifecycleEvent(const Test& source, EEventType type)
{
}
void Test::Observer::onCheckFailed(const Test& source, const std::string& message, const char* file, int line)
{
}
void Test::Observer::onExceptionThrown(const Test& source, std::exception_ptr exception)
{
}
void Test::Observers::add(std::shared_ptr<Observer> observer)
{
auto it = boost::range::find_if(m_observers,
[&observer](const std::pair<std::weak_ptr<Observer>, size_t>& o)
{
return (o.first.lock() == observer);
}
);
if (it != m_observers.end())
{
++it->second;
}
else
{
m_observers.push_back(std::pair<std::weak_ptr<Observer>, size_t>(observer, 1));
}
}
void Test::Observers::remove(std::shared_ptr<Observer> observer)
{
auto it = boost::range::find_if(m_observers,
[&observer](const std::pair<std::weak_ptr<Observer>, size_t>& o)
{
return (o.first.lock() == observer);
}
);
if (it != m_observers.end())
{
--it->second;
if (it->second == 0)
{
m_observers.erase(it);
}
}
}
void Test::Observers::notifyLifecycleEvent(const Test& source, Observer::EEventType type)
{
for (std::pair<std::weak_ptr<Observer>, size_t>& o : m_observers)
{
std::shared_ptr<Observer> observer = o.first.lock();
if (observer)
{
observer->onLifecycleEvent(source, type);
}
else
{
removeDeletedObservers();
}
}
}
void Test::Observers::notifyCheckFailed(const Test& source, const std::string& message, const char* file, int line)
{
for (std::pair<std::weak_ptr<Observer>, size_t>& o : m_observers)
{
std::shared_ptr<Observer> observer = o.first.lock();
if (observer)
{
observer->onCheckFailed(source, message, file, line);
}
else
{
removeDeletedObservers();
}
}
}
void Test::Observers::notifyExceptionThrown(const Test& source, std::exception_ptr exception)
{
for (std::pair<std::weak_ptr<Observer>, size_t>& o : m_observers)
{
std::shared_ptr<Observer> observer = o.first.lock();
if (observer)
{
observer->onExceptionThrown(source, exception);
}
else
{
removeDeletedObservers();
}
}
}
void Test::Observers::removeDeletedObservers()
{
auto it = std::remove_if(m_observers.begin(), m_observers.end(),
[](const std::pair<std::weak_ptr<Observer>, size_t>& o)
{
return o.first.expired();
}
);
m_observers.erase(it, m_observers.end());
}
Test::Test(const TestNumber& number, const std::string& name)
: m_number(number), m_name(name), m_result(TestResult::unknown),
m_context(&TestContext::DefaultTestContext()), m_memoryLeakCheck(true), m_runFct(0)
{
}
Test::Test(const TestNumber& number, const std::string& name, const TestContext& context)
: m_number(number), m_name(name), m_result(TestResult::unknown), m_context(&context),
m_memoryLeakCheck(true), m_runFct(0)
{
}
Test::Test(const TestNumber& number, const std::string& name, TestResult result)
: m_number(number), m_name(name), m_result(result), m_context(&TestContext::DefaultTestContext()),
m_memoryLeakCheck(true), m_runFct(0)
{
}
Test::Test(const TestNumber& number, const std::string& name, TestResult result, const TestContext& context)
: m_number(number), m_name(name), m_result(result), m_context(&context), m_memoryLeakCheck(true), m_runFct(0)
{
}
Test::Test(const TestNumber& number, const std::string& name, std::function<void(Test& test)> runFct)
: m_number(number), m_name(name), m_result(TestResult::unknown),
m_context(&TestContext::DefaultTestContext()), m_memoryLeakCheck(true), m_runFct(runFct)
{
}
Test::Test(const TestNumber& number, const std::string& name, std::function<void(Test& test)> runFct,
const TestContext& context)
: m_number(number), m_name(name), m_result(TestResult::unknown), m_context(&context), m_memoryLeakCheck(true),
m_runFct(runFct)
{
}
const TestNumber& Test::number() const
{
return m_number;
}
void Test::setNumber(const TestNumber& number)
{
m_number = number;
}
const std::string& Test::name() const
{
return m_name;
}
TestResult Test::result() const
{
return m_result;
}
void Test::setResult(TestResult result)
{
m_result = result;
}
bool Test::passed() const
{
return (m_result == TestResult::passed);
}
bool Test::skipped() const
{
return (m_result == TestResult::skipped);
}
void Test::getPassRate(size_t& unknown, size_t& passed, size_t& passedButMemoryLeaks, size_t& exception,
size_t& failed, size_t& skipped, size_t& total) const
{
unknown = 0;
passed = 0;
passedButMemoryLeaks = 0;
exception = 0;
failed = 0;
skipped = 0;
total = 1;
switch (m_result)
{
case TestResult::unknown:
unknown = 1;
break;
case TestResult::passed:
passed = 1;
break;
case TestResult::passedButMemoryLeaks:
passedButMemoryLeaks = 1;
break;
case TestResult::exception:
exception = 1;
break;
case TestResult::failed:
failed = 1;
break;
case TestResult::skipped:
skipped = 1;
break;
}
}
void Test::abort(const char* file, int line)
{
fail(file, line);
throw AbortException();
}
void Test::abort(const std::string& message, const char* file, int line)
{
fail(message, file, line);
throw AbortException();
}
void Test::abortIf(bool condition, const char* file, int line)
{
if (condition)
{
fail(file, line);
throw AbortException();
}
}
void Test::fail(const char* file, int line)
{
fail("", file, line);
}
void Test::fail(const std::string& message, const char* file, int line)
{
m_result = TestResult::failed;
m_observers.notifyCheckFailed(*this, message, file, line);
}
void Test::failIf(bool condition, const char* file, int line)
{
if (condition)
{
fail(file, line);
}
}
void Test::pass()
{
if (m_result == TestResult::unknown)
{
m_result = TestResult::passed;
}
}
void Test::skip()
{
if (m_result == TestResult::unknown)
{
m_result = TestResult::skipped;
}
throw AbortException();
}
void Test::appendCheck(std::shared_ptr<TestCheck> check)
{
m_checks.push_back(check);
}
const TestContext& Test::context() const
{
return m_context;
}
TestContext& Test::context()
{
return m_context;
}
void Test::run()
{
m_executionStartTime = SystemTime::Now();
notify(Observer::eTestStart);
setup();
DebugHeap::HeapState heapStateBefore;
try
{
doRun();
if (m_result == TestResult::unknown)
{
// The function didn't fail but at no point did it mark the test as passed either so we consider this a
// failure.
fail("Test completed without being marked passed or failed", __FILE__, __LINE__);
}
}
catch (const AbortException&)
{
// abort() was called, the exception is only used as a way to interrupt the test.
}
catch (...)
{
m_observers.notifyExceptionThrown(*this, std::current_exception());
m_result = TestResult::exception;
}
DebugHeap::HeapState heapStateAfter;
if (m_memoryLeakCheck && (heapStateBefore.allocatedSize() != heapStateAfter.allocatedSize())
&& (m_result == TestResult::passed))
{
m_result = TestResult::passedButMemoryLeaks;
}
teardown();
m_executionEndTime = SystemTime::Now();
notify(Observer::eTestEnd);
}
void Test::addSetupAction(std::shared_ptr<TestSetupAction> action)
{
m_setupActions.push_back(action);
}
void Test::addTeardownAction(std::shared_ptr<TestTeardownAction> action)
{
m_teardownActions.push_back(action);
}
void Test::traverse(std::function<void(const Test& test)> function) const
{
function(*this);
}
Test::Observers& Test::observers()
{
return m_observers;
}
void Test::addToJUnitXMLTestReport(JUnitXMLWriter& writer) const
{
writer.writeTestCaseStart("unknown", m_name);
switch (m_result)
{
case TestResult::passed:
// Do nothing
break;
case TestResult::failed:
{
// TODO: this assume we enforce consistency between test failure and check->result(). Need to enforce that
// in Test::run().
bool atLeastOneTestCheckFailed = false;
for (const std::shared_ptr<TestCheck>& check : m_checks)
{
if (check->result() != TestCheck::Result::passed)
{
writer.writeFailureStart();
check->addToJUnitXMLTestReport(writer);
writer.writeFailureEnd();
atLeastOneTestCheckFailed = true;
}
}
// If the failure is not due to one the checks, we still want to make sure we mark the test as failed.
if (!atLeastOneTestCheckFailed)
{
writer.writeFailureStart();
writer.writeFailureEnd();
}
}
break;
case TestResult::skipped:
writer.writeSkippedStart();
writer.writeSkippedEnd();
break;
default:
writer.writeFailureStart();
writer.writeFailureEnd();
}
writer.writeTestCaseEnd();
}
void Test::setup()
{
boost::filesystem::path outputDirectory = m_context.getOutputDirectory();
if (outputDirectory != "")
{
boost::filesystem::create_directories(outputDirectory);
}
for (size_t i = 0; i < m_setupActions.size(); ++i)
{
m_setupActions[i]->setup();
}
}
void Test::doRun()
{
if (m_runFct)
{
m_runFct(*this);
}
}
void Test::teardown()
{
for (size_t i = 0; i < m_teardownActions.size(); ++i)
{
m_teardownActions[i]->teardown();
}
}
void Test::notify(Observer::EEventType type)
{
m_observers.notifyLifecycleEvent(*this, type);
}
|
int motor_one1=9;
int motor_one2=10;
int motor_two1=5;
int motor_two2=3;
char command;
void setup() {
Serial.begin(9600);// put your setup code here, to run once:
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(5,OUTPUT);
pinMode(3,OUTPUT);
}
void loop() {
while(Serial.available()>0){
command=Serial.read();
if(command=='F')
{
analogWrite(9,255);
analogWrite(10,0);
analogWrite(5,255);
analogWrite(3,0);
}
else if(command=='L')
{
analogWrite(9,0);
analogWrite(10,255);
analogWrite(5,255);
analogWrite(3,0);
}
else if(command=='B')
{
analogWrite(9,0);
analogWrite(10,255);
analogWrite(5,0);
analogWrite(3,255);
}else if(command=='R')
{
analogWrite(9,255);
analogWrite(10,0);
analogWrite(5,0);
analogWrite(3,255);
}
else if(command=='G')
{
analogWrite(9,200);
analogWrite(10,0);
analogWrite(5,255);
analogWrite(3,0);
}
else if(command=='I')
{
analogWrite(9,255);
analogWrite(10,0);
analogWrite(5,200);
analogWrite(3,0);
}
else if(command=='H')
{
analogWrite(9,0);
analogWrite(10,200);
analogWrite(5,0);
analogWrite(3,255);
}
else if(command=='J')
{
analogWrite(9,0);
analogWrite(10,255);
analogWrite(5,0);
analogWrite(3,200);
}
else if(command=='S')
{
analogWrite(9,0);
analogWrite(10,0);
analogWrite(5,0);
analogWrite(3,0);
}}}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2007-2008 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
/** \file
*
* \brief Implement callstack handeling functionality
*
* Implement functionality and API declared in \c memory_callstack.cpp
* for \c OpCallStack and \c OpCallStackManager classes.
*
* \author Morten Rolland, mortenro@opera.com
*/
#include "core/pch.h"
#ifdef MEMTOOLS_CALLSTACK_MANAGER
#include "modules/memtools/memtools_callstack.h"
#include "modules/memtools/memtools_codeloc.h"
OpCallStack::OpCallStack(const UINTPTR* stk, int size, int id) :
next(0), size(size), id(id), status(0)
{
// FIXME: OOM handeling for device-testing needed.
stack = (UINTPTR*)op_debug_malloc(size * sizeof(UINTPTR));
op_memcpy(stack, stk, sizeof(UINTPTR) * size);
}
void OpCallStack::AnnounceCallStack(void)
{
if ( ! status )
{
char buffer[2048]; // ARRAY OK 2008-06-06 mortenro
char tmp[64]; // ARRAY OK 2008-06-06 mortenro
OP_ASSERT(size <= 80); // Max 80 * 19 bytes == 1520 bytes in buffer
if ( size > 0 )
{
op_sprintf(buffer, "%p", (void*)stack[0]);
#ifdef MEMTOOLS_ENABLE_CODELOC
// This will prime the OpCodeLocation database
OpCodeLocationManager::GetCodeLocation(stack[0]);
#endif
for ( int k = 1; k < size; k++ )
{
op_sprintf(tmp, ",%p", (void*)stack[k]);
op_strcat(buffer, tmp);
#ifdef MEMTOOLS_ENABLE_CODELOC
// This will prime the OpCodeLocation database
OpCodeLocationManager::GetCodeLocation(stack[k]);
#endif
}
}
else
{
buffer[0] = 0;
}
log_printf("MEM: 0x%x call-stack %s\n", id, buffer);
status = 1;
}
#ifdef MEMTOOLS_ENABLE_CODELOC
OpCodeLocationManager::AnnounceCodeLocation();
OpCodeLocationManager::AnnounceCodeLocation();
OpCodeLocationManager::AnnounceCodeLocation();
OpCodeLocationManager::AnnounceCodeLocation();
OpCodeLocationManager::AnnounceCodeLocation();
#endif
}
OpCallStackManager::OpCallStackManager(int hashtable_size) :
hashtable_size(hashtable_size), next_id(1)
{
// FIXME: OOM handeling for device testing
hashtable = (OpCallStack**)
op_debug_malloc(hashtable_size * sizeof(OpCallStack*));
for ( int k = 0; k < hashtable_size; k++ )
hashtable[k] = 0;
}
OpCallStack* OpCallStackManager::GetCallStack(const UINTPTR* stack,
int size)
{
OpMemoryStateInit(); // Just to be sure
OpCallStackManager* csm = g_memtools_callstackmgr;
if ( csm == 0 )
csm = g_memtools_callstackmgr = new OpCallStackManager(100003);
// FIXME: Return a static "OOM" object instead on error
if ( csm == 0 || csm->hashtable == 0 )
return 0;
// Compute a hash-key, and reduce the size of the call-stack if
// it has empty slots (stop at first NULL address)
UINTPTR hashkey = 0;
for ( int k = 0; k < size; k++ )
{
if ( stack[k] == 0 )
{
if ( k == 0 )
size = 1;
else
size = k;
break;
}
#ifdef SIXTY_FOUR_BIT
hashkey = (hashkey << 17) ^ (hashkey >> 47) ^ stack[k];
#else
hashkey = (hashkey << 13) ^ (hashkey >> 19) ^ stack[k];
#endif
}
int idx = hashkey % csm->hashtable_size;
OpCallStack* cs = csm->hashtable[idx];
OpCallStack* last = 0;
while ( cs != 0 )
{
if ( cs->size == size && cs->stack[0] == stack[0]
&& !op_memcmp(cs->stack, stack, sizeof(UINTPTR) * size) )
return cs;
last = cs;
cs = cs->next;
}
int id = csm->next_id++;
OpCallStack* create = new OpCallStack(stack, size, id);
// FIXME: Return static OOM object if create is NULL
if ( last != 0 )
last->next = create;
else
csm->hashtable[idx] = create;
return create;
}
#endif // MEMTOOLS_CALLSTACK_MANAGER
|
#include <DXLib.h>
#include "WindowInformation.h"
#include "GameManager.h"
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdshow ) {
SetWindowText( "闇音" );
Sounder::Set3DSoundOneMetre( 0.2f );
ChangeWindowMode( TRUE );
SetAlwaysRunFlag( TRUE ); //別のウィンドウに切り替えても処理が継続される関数
SetWindowSize( SCREEN_WIDTH, SCREEN_HEIGHT );
SetGraphMode( SCREEN_WIDTH, SCREEN_HEIGHT, 32 ); //画像の解像度を設定する関数
SetEnableXAudioFlag( TRUE ); //サウンドの再生にXAudio2を使用するかどうかを設定する
if ( DxLib_Init( ) == -1 ) {
return -1;
}
GameManager gameManager;
while( 1 ) {
if ( ScreenFlip( ) != 0 || ProcessMessage( ) != 0 || ClearDrawScreen( ) != 0 ) {
break;
}
gameManager.Main( );
gameManager.GetInputChecker( )->UpdateDevice( ); //キー・パット入力受付
if ( gameManager.GetInputChecker( )->GetKey( KEY_INPUT_ESCAPE ) > 1 ) { //escapeキーを押したら強制終了
break;
}
}
DxLib_End( );
return 0;
}
|
#ifndef TIMBER_H
#define TIMBER_H
#include <string>
using namespace std;
class Timber
{
private:
float pricePerMeter;
int width;
int length;
int totalWoodMeters;
public:
Timber();
Timber(int width, int length, float pricePerMeter, int totalWoodMeters);
~Timber();
void setPricePerMeter(float pricePerMeter);
void setWidth(int width);
void setLength(int length);
void setTotalWoodMeters(int totalWoodMeters);
float getPricePerMeter();
int getWidth();
int getLength();
int getTotalWoodMeters();
bool operator==(const Timber& ved);
string toString();
};
#endif
|
#pragma once
#include "..\Entity\GameSystem.h"
#include "..\..\SDL2_mixer-2.0.0\SDL_mixer.h"
#include "AssetManager.h"
class SoundSystem :
public GameSystem
{
public:
SoundSystem(void);
virtual ~SoundSystem(void);
virtual void Init();
virtual void Update();
void PlaySound(const wchar_t* name);
void PlaySound(const wchar_t* name, float volume);
};
extern SoundSystem sfxMan;
|
#include <chuffed/branching/branching.h>
#include <chuffed/core/engine.h>
#include <chuffed/core/propagator.h>
#include <chuffed/globals/mddglobals.h>
#include <cassert>
#include <cstdio>
#include <iostream>
static void skipComments(std::istream& i) {
assert(i.peek() == '#');
while (i.peek() != '\n' && i.peek() != EOF) {
i.ignore();
}
}
class Cross : public Problem {
public:
int nvars;
int dom;
int nrels;
int ncons;
vec<IntVar*> x;
Cross() {
// Generate instance
while (std::cin.peek() == '#') {
skipComments(std::cin);
}
std::cin >> nvars;
std::cin >> dom;
std::cin >> nrels;
std::cin >> ncons;
for (int i = 0; i < nvars; i++) {
x.push(newIntVar(0, dom - 1));
x.last()->specialiseToEL();
}
vec<vec<vec<int> > > tables;
for (int i = 0; i < nrels; i++) {
tables.push();
vec<vec<int> >& tuples(tables.last());
int arity;
std::cin >> arity;
while (std::cin.peek() != ';') {
tuples.push();
while (std::cin.peek() != ';' && std::cin.peek() != '|') {
tuples.last().push();
std::cin >> tuples.last().last();
}
if (std::cin.peek() == '|') {
std::cin.ignore();
}
}
std::cin.ignore();
}
for (int i = 0; i < ncons; i++) {
vec<IntVar*> w;
int rel;
std::cin >> rel;
while (std::cin.peek() != ';') {
int v;
std::cin >> v;
w.push(x[v]);
}
std::cin.ignore();
if (!so.mdd) {
table(w, tables[rel]);
} else {
mdd_table(w, tables[rel], MDDOpts());
}
}
vec<IntVar*> pref_order;
for (int i = 0; i < x.size(); i++) {
pref_order.push(x[i]);
}
branch(pref_order, VAR_INORDER, VAL_MIN);
// branch(pref_order, VAR_MIN_MIN, VAL_SPLIT_MIN);
}
void print(std::ostream& os) override {
for (int i = 0; i < nvars; i++) {
int v = x[i]->getVal();
os << i << ": " << v << "\n";
}
}
};
int main(int argc, char** argv) {
parseOptions(argc, argv);
engine.solve(new Cross());
return 0;
}
|
/*
* Heuristic.h
*
* Created on: 17 Jun 2015
* Author: Jack
*/
#ifndef HEURISTIC_H_
#define HEURISTIC_H_
#include "DraughtsModule.h"
#include "BinConvert.h"
#include "Utils.h"
#include <sstream>
enum HeuristicParameter {
PARAM_MEN,
PARAM_KINGS,
PARAM_ENEMY_MEN,
PARAM_ENEMY_KINGS,
PARAM_SAFE_MEN,
PARAM_SAFE_KINGS,
PARAM_MEN_DIST,
PARAM_PROMOTION_SPACE,
PARAM_WIN,
PARAM_TOTAL
};
class Heuristic {
private:
float values[PARAM_TOTAL];
int fitness;
public:
static const int BITS = 16;
static const int DP_INDEX = 8;
Heuristic();
double function(Board board, cellState colour);
void setValue(HeuristicParameter param, float val);
std::string toString();
std::vector<bool> getChromosome();
void setFromChromosome(std::vector<bool> chrom);
int getFitness();
void setFitness(int fitness);
};
#endif /* HEURISTIC_H_ */
|
#include "Session.h"
Session::Session(unsigned int sessionKey, NetManager * cnet)
: m_sessionKey(sessionKey), m_cnet(cnet)
{
}
Session::~Session()
{
}
void Session::AddHost(const HostID & hid)
{
if(!m_hosts.contains(hid))
{
m_hosts.append(hid);
}
}
void Session::SendToAll(const Packet * pkt)
{
QListIterator<HostID> itor(m_hosts);
while(itor.hasNext())
{
m_cnet->SendTo(pkt, itor.next());
}
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// Eigen is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// Alternatively, you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation; either version 2 of
// the License, or (at your option) any later version.
//
// Eigen is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License or the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License and a copy of the GNU General Public License along with
// Eigen. If not, see <http://www.gnu.org/licenses/>.
#define EIGEN_DEBUG_ASSIGN
#include "main.h"
#include <typeinfo>
template<typename Dst, typename Src>
bool test_assign(const Dst&, const Src&, int traversal, int unrolling)
{
ei_assign_traits<Dst,Src>::debug();
return ei_assign_traits<Dst,Src>::Traversal==traversal
&& ei_assign_traits<Dst,Src>::Unrolling==unrolling;
}
template<typename Dst, typename Src>
bool test_assign(int traversal, int unrolling)
{
ei_assign_traits<Dst,Src>::debug();
return ei_assign_traits<Dst,Src>::Traversal==traversal
&& ei_assign_traits<Dst,Src>::Unrolling==unrolling;
}
template<typename Xpr>
bool test_redux(const Xpr&, int traversal, int unrolling)
{
typedef ei_redux_traits<ei_scalar_sum_op<typename Xpr::Scalar>,Xpr> traits;
return traits::Traversal==traversal && traits::Unrolling==unrolling;
}
void test_vectorization_logic()
{
#ifdef EIGEN_VECTORIZE
VERIFY(test_assign(Vector4f(),Vector4f(),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f()+Vector4f(),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f().cwiseProduct(Vector4f()),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Vector4f(),Vector4f().cast<float>(),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f(),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f()+Matrix4f(),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix4f(),Matrix4f().cwiseProduct(Matrix4f()),
InnerVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,16,16>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
InnerVectorizedTraversal,InnerUnrolling));
VERIFY(test_assign(Matrix<float,16,16,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION>(),Matrix<float,16,16>()+Matrix<float,16,16>(),
LinearTraversal,NoUnrolling));
VERIFY(test_assign(Matrix<float,2,2,DontAlign|EIGEN_DEFAULT_MATRIX_STORAGE_ORDER_OPTION>(),Matrix<float,2,2>()+Matrix<float,2,2>(),
LinearTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,6,2>(),Matrix<float,6,2>().cwiseQuotient(Matrix<float,6,2>()),
LinearVectorizedTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,17,17>(),Matrix<float,17,17>()+Matrix<float,17,17>(),
LinearTraversal,NoUnrolling));
VERIFY(test_assign(Matrix<float,3,3>(),Matrix<float,3,3>()+Matrix<float,3,3>(),
LinearTraversal,CompleteUnrolling));
VERIFY(test_assign(Matrix<float,4,4>(),Matrix<float,17,17>().block<4,4>(2,3)+Matrix<float,17,17>().block<4,4>(10,4),
DefaultTraversal,CompleteUnrolling));
VERIFY(test_assign(MatrixXf(10,10),MatrixXf(20,20).block(10,10,2,3),
SliceVectorizedTraversal,NoUnrolling));
VERIFY((test_assign<
Map<Matrix<float,4,8>, Aligned, OuterStride<12> >,
Matrix<float,4,8>
>(InnerVectorizedTraversal,CompleteUnrolling)));
VERIFY((test_assign<
Map<Matrix<float,4,8>, Aligned, InnerStride<12> >,
Matrix<float,4,8>
>(DefaultTraversal,CompleteUnrolling)));
VERIFY(test_redux(VectorXf(10),
LinearVectorizedTraversal,NoUnrolling));
VERIFY(test_redux(Matrix<float,5,2>(),
DefaultTraversal,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,6,2>(),
LinearVectorizedTraversal,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,16,16>(),
LinearVectorizedTraversal,NoUnrolling));
VERIFY(test_redux(Matrix<float,16,16>().block<4,4>(1,2),
DefaultTraversal,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,16,16,ColMajor>().block<8,1>(1,2),
LinearVectorizedTraversal,CompleteUnrolling));
VERIFY(test_redux(Matrix<float,16,16,RowMajor>().block<1,8>(2,1),
LinearVectorizedTraversal,CompleteUnrolling));
VERIFY(test_redux(Matrix<double,7,3>(),
DefaultTraversal,CompleteUnrolling));
#endif // EIGEN_VECTORIZE
}
|
#include <iostream>
using namespace std;
int main() {
// 1. Initialize a stack
stack<int> s;
// 2. Push new element
s.push(5);
s.push(13);
s.push(8);
s.push(6);
// 3. Check if stack is empty
if(s.empty()) {
cout << "Stack is empty!" << endl;
return 0;
}
// 4. Pop an element
s.pop();
// 5. Get the top element
cout << "The top element is:" << s.top() << endl;
// 6. Get the size of the stack
cout << "The size is:" << s.size() << endl;
}
|
#include<iostream>
#include<vector>
#include<algorithm>
#include<unordered_map>
using namespace std;
class Solution {
public:
bool isAnagram(string s, string t) {
//基本思想:排序
sort(s.begin(), s.end());
sort(t.begin(), t.end());
return s == t;
}
};
class Solution1 {
public:
bool isAnagram(string s, string t) {
//基本思想:哈希表
unordered_map<char,int> s1, t1;
for (auto v : s)
++s1[v];
for (auto v : t)
++t1[v];
return s1 == t1;
}
};
int main()
{
Solution1 solute;
string s = "anagram", t = "nagaram";
cout << solute.isAnagram(s, t) << endl;
return 0;
}
|
// This file is part of the xxxxxxxxx project.
// This Source Code Form is subject to the terms of the Mozilla Public License,
// v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.
/*
* File: uncertainty.h
* Author: xxxxxxxxx xxxxxxxxx
*
* Created on November 5, 2017, 11:30 AM
*/
#pragma once
#include <vector>
#include <iostream>
#include <memory>
#define _USE_MATH_DEFINES
#include <cmath>
#include "ceres/ceres.h"
namespace cov {
enum EAlgorithm {
eAlgorithmSvdQrIteration = 0,
eAlgorithmSvdDeviceAndconquer = 1,
eAlgorithmTaylorExpansion = 2,
eAlgorithmNullspaceBounding = 3,
eAlgorithmLhuilier = 4
};
inline std::string EAlgorithm_enumToString(EAlgorithm alg) {
switch (alg) {
case eAlgorithmSvdQrIteration: return "SVD_QR_ITERATION";
case eAlgorithmSvdDeviceAndconquer: return "SVD_DEVIDE_AND_CONQUER";
case eAlgorithmLhuilier: return "LHUILLIER";
case eAlgorithmTaylorExpansion: return "TE-INVERSION";
case eAlgorithmNullspaceBounding: return "NBUP";
default: return "not defined";
}
}
//LHUILLIER, TE-INVERSION, NBUP
inline EAlgorithm EAlgorithm_stringToEnum(const std::string& algorithm) {
if (algorithm == "SVD_QR_ITERATION")
return eAlgorithmSvdQrIteration;
if (algorithm == "SVD_DEVIDE_AND_CONQUER")
return eAlgorithmSvdDeviceAndconquer;
if (algorithm == "LHUILLIER")
return eAlgorithmLhuilier;
if (algorithm == "TE-INVERSION")
return eAlgorithmTaylorExpansion;
if (algorithm == "NBUP")
return eAlgorithmNullspaceBounding;
throw std::runtime_error(std::string("Unrecognized algorithm: ") + algorithm);
}
struct Options {
public:
double _epsilon, _lambda;
EAlgorithm _algorithm;
int _numCams, _camParams, _numPoints, _numObs, _svdRemoveN, _maxIterTE;
int *_pts2fix = NULL;
bool _debug = false;
bool _computePtsCov = false;
Options() : _lambda(-1), _svdRemoveN(-1), _maxIterTE(-1) {}
Options(int numCams, int camParams, int numPoints, int numObs) :
_algorithm(eAlgorithmTaylorExpansion), _epsilon(1e-10), _lambda(-1), _numCams( numCams ), _camParams(camParams), _numPoints(numPoints), _numObs(numObs), _svdRemoveN(-1), _maxIterTE(-1) {}
Options(EAlgorithm algorithm, double eps_or_lamb, int numCams, int camParams, int numPoints, int numObs) :
_algorithm(algorithm), _epsilon(eps_or_lamb), _lambda(eps_or_lamb), _numCams( numCams ), _camParams(camParams), _numPoints(numPoints), _numObs(numObs), _svdRemoveN(-1), _maxIterTE(-1) {}
~Options() {
free(_pts2fix);
}
};
struct Statistic {
double timeCreateJ, timeComposeH, timeScaleJH, timeFixJ, timeNormJ, timeMultiplyJJ, timeSplitJJ,
timeInvV, timeComposeZ, timeInvZ, timeTE, timeComposeC, timePtsUnc, timeAll;
double lambda;
int *fixedPts;
std::vector<double> cycle_change;
~Statistic(){
free(fixedPts);
}
};
struct Uncertainty {
std::size_t _camParams = 0;
std::size_t _numCams = 0;
std::size_t _numPoints = 0;
std::size_t _nbCovarianceValuePerCam = 0;
std::vector<double> _camerasUnc;
std::vector<double> _pointsUnc;
void init(const Options& options);
/**
* @return upper triangle of covariance matrix = 1/2*n(n+1) values per camera with n parametes
*/
const std::vector<double> getCamerasUncRaw() const;
/**
* @return matrix of 6x6 values per point
*/
const std::vector<double> getCameraUncMatrix(int id) const;
/**
* @return matrix of 6x6 values per point
*/
const std::vector<double> getCamerasUncMatrices() const;
/**
* @return 6 values per camera
*/
const std::vector<double> getCamerasUncEigenValues() const;
/**
* @return 6 values per point
*/
const std::vector<double> getPointsUncRaw() const;
/**
* @return matrix of 3x3 values per point
*/
const std::vector<double> getPointUncMatrix(int id) const;
/**
* @return matrix of 3x3 values per point
*/
const std::vector<double> getPointsUncMatrices() const;
/**
* @return 3 values per point
*/
const std::vector<double> getPointsUncEigenValues() const;
};
}
/**
* @param[in] options: informations about the reconstruction (numCams, camParams, numPoints, numObs)
* @param[out] statistic: blank object for the output statistics
* @param[in] jacobian: sparse matrix (form Ceres-solver) with jacobian ( you can use the output of the computation of jacobian in Ceres as the input )
* @param[in] points3D: all 3D points (to select the 3 static points)
* @param[out] uncertainties: output covariances for cameras and points
*/
void getCovariances(
cov::Options &options,
cov::Statistic &statistic,
ceres::CRSMatrix &jacobian,
double* points3D,
cov::Uncertainty& uncertainties);
|
#include <iostream>
#include <algorithm>
using namespace std;
template<typename T>
auto reduce(T ar[], int n)
{
T* pt = unique(ar, ar + n);
sort(ar, pt);
return distance(ar, pt);
}
int main()
{
cout << "How many numbers in total?";
int n;
cin >> n;
long* arr = new long[n];
for (int i = 0; i < n; ++i)
{
cout << "Enter the number: ";
cin >> arr[i];
}
int count = reduce(arr, n);
cout << "There are " << count << " numbers that are unique.\n";
for (int i = 0; i < count; ++i)
{
cout << arr[i] << " ";
if (i % 5 == 4)
cout << endl;
}
delete[] arr;
}
|
#pragma once
#include <dynamic_reconfigure/server.h>
#include <ros/forwards.h>
#include <tf2_ros/transform_broadcaster.h>
#include <tf2_ros/transform_listener.h>
#include <nav_msgs/Path.h>
#include <Eigen/Eigen>
#include <Eigen/Dense>
#include "road_map/RoadMap.hpp"
#include <random>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/opencv.hpp>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/Image.h>
#include "path_publisher_ros_tool/PathPublisherInterface.h"
namespace path_publisher_ros_tool {
class PathPublisher {
using Interface = PathPublisherInterface;
using Msg = std_msgs::Header;
public:
PathPublisher(ros::NodeHandle, ros::NodeHandle);
private:
void callbackTimer(const ros::TimerEvent&);
void reconfigureRequest(const Interface::Config&, uint32_t);
void samplePath();
void samplingPath();
bool imageGenerator(Eigen::Affine3d&, const ros::TimerEvent&, cv_bridge::CvImagePtr);
void clipPath(std::vector<Eigen::Vector2d>::iterator& source_start,
std::vector<Eigen::Vector2d>::iterator& source_end,
std::vector<Eigen::Vector2d>& source,
std::vector<Eigen::Vector2d>& dest,
nav_msgs::Path::Ptr& path_ptr);
void setCliper(std::vector<Eigen::Vector2d>::iterator& it, std::vector<Eigen::Vector2d>& source, std::vector<Eigen::Vector2d>::iterator& start, std::vector<Eigen::Vector2d>::iterator& it_end);
void pubnewpath(const ros::Time&);
Interface interface_;
dynamic_reconfigure::Server<Interface::Config> reconfigureServer_;
ros::ServiceClient reset_episode_client_;
tf2_ros::Buffer tfBuffer_;
tf2_ros::TransformListener tfListener_{tfBuffer_};
tf2_ros::TransformBroadcaster tfBroadcaster_;
ros::Timer timer_;
nav_msgs::Path::Ptr path_{new nav_msgs::Path};
nav_msgs::Path::Ptr part_of_path_{new nav_msgs::Path};
std::vector<std::vector<Eigen::Vector3d>> samplePath_{5};
RoadMap map_{49.01439, 8.41722};
Eigen::Vector3d center_;
int switcher{1};
double timerecoder_;
std::vector<Eigen::Vector2d> path_vector_;
std::vector<Eigen::Vector2d> path_vector_whole_;
std::vector<Eigen::Vector2d>::iterator prev_pos_index_;
std::vector<Eigen::Vector2d>::iterator prev_pos_whole_index_;
bool sample_flag_ = false;
bool in_reset_{false};
};
} // namespace path_publisher_ros_tool
|
/*
* MIT License
*
* Copyright (c) 2016, 2017 by S. Yingchareonthawornchai and J. Daly at Michigan State University
*
* 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 <vector>
#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <string>
#include <fstream>
#include <sstream>
#include <iterator>
#include <functional>
#include "InputReader.h"
#include <regex>
using namespace std;
int InputReader::dim = 5;
int InputReader::reps = 1;
unsigned int inline InputReader::atoui(const string& in) {
std::istringstream reader(in);
unsigned int val;
reader >> val;
return val;
}
//CREDITS: http://stackoverflow.com/questions/236129/split-a-string-in-c
std::vector<std::string> & InputReader::split(const std::string &s, char delim, std::vector<std::string> &elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
std::vector<std::string> InputReader::split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, elems);
return elems;
}
vector<Packet> InputReader::ReadPackets(const string& filename) {
vector<Packet> packets;
ifstream input_file(filename);
if (!input_file.is_open())
{
printf("Couldnt open packet set file \n");
exit(1);
} else {
printf("Reading packet file %s\n", filename.c_str());
}
int line_number = 1;
string content;
while (getline(input_file, content) && !content.empty()) {
istringstream iss(content);
vector<string> tokens{ istream_iterator < string > {iss}, istream_iterator < string > {} };
Packet one_packet = new Point[NumDims];
for (int i = 0; i < NumDims; i++) {
one_packet[i] = atoui(tokens[i]);
}
packets.push_back(one_packet);
line_number++;
}
return packets;
}
void InputReader::ReadIPRange(Interval& ipRange, unsigned int& prefix_length, const string& token)
{
//cout << token << endl;
//split slash
vector<string> split_slash = split(token, '/');
vector<string> split_ip = split(split_slash[0], '.');
/*asindmemacces IPv4 prefixes*/
/*temporary variables to store IP range */
unsigned int mask;
int masklit1;
unsigned int masklit2, masklit3;
unsigned int ptrange[4];
for (int i = 0; i < 4; i++)
ptrange[i] = atoui(split_ip[i]);
mask = atoui(split_slash[1]);
prefix_length = mask;
mask = 32 - mask;
masklit1 = mask / 8;
masklit2 = mask % 8;
/*count the start IP */
for (int i = 3; i>3 - masklit1; i--)
ptrange[i] = 0;
if (masklit2 != 0){
masklit3 = 1;
masklit3 <<= masklit2;
masklit3 -= 1;
masklit3 = ~masklit3;
ptrange[3 - masklit1] &= masklit3;
}
/*store start IP */
ipRange.low = ptrange[0];
ipRange.low <<= 8;
ipRange.low += ptrange[1];
ipRange.low <<= 8;
ipRange.low += ptrange[2];
ipRange.low <<= 8;
ipRange.low += ptrange[3];
//key += std::bitset<32>(IPrange[0] >> prefix_length).to_string().substr(32 - prefix_length);
/*count the end IP*/
for (int i = 3; i>3 - masklit1; i--)
ptrange[i] = 255;
if (masklit2 != 0){
masklit3 = 1;
masklit3 <<= masklit2;
masklit3 -= 1;
ptrange[3 - masklit1] |= masklit3;
}
/*store end IP*/
ipRange.high = ptrange[0];
ipRange.high <<= 8;
ipRange.high += ptrange[1];
ipRange.high <<= 8;
ipRange.high += ptrange[2];
ipRange.high <<= 8;
ipRange.high += ptrange[3];
}
void InputReader::ReadPort(Interval& portRange, unsigned int& prefix_length, const string& from, const string& to)
{
portRange.low = atoui(from);
portRange.high = atoui(to);
if (portRange.low == portRange.high) {
prefix_length = 32;
} else {
prefix_length = 16;
}
}
void InputReader::ReadProtocol(Interval& proto, unsigned int& prefix_length, const string& last_token)
{
// Example : 0x06/0xFF
vector<string> split_slash = split(last_token, '/');
if (split_slash[1] != "0xFF") {
proto.low = 0;
proto.high = 255;
prefix_length = 24;
} else {
proto.low = proto.high = std::stoul(split_slash[0], nullptr, 16);
prefix_length = 32;
}
}
int InputReader::ReadFilter(vector<string>& tokens, vector<Rule>& ruleset, unsigned int cost)
{
// 5 fields: sip, dip, sport, dport, proto = 0 (with@), 1, 2 : 4, 5 : 7, 8
/*allocate a few more bytes just to be on the safe side to avoid overflow etc*/
Rule temp_rule;
string key;
if (tokens[0].at(0) != '@') {
/* each rule should begin with an '@' */
printf("ERROR: NOT A VALID RULE FORMAT\n");
exit(1);
}
int index_token = 0;
int i = 0;
for (int rep = 0; rep < reps; rep++)
{
/* reading SIP range */
if (i == 0) {
ReadIPRange(temp_rule.range[i], temp_rule.prefix_length[i], tokens[index_token++].substr(1));
i++;
} else {
ReadIPRange(temp_rule.range[i], temp_rule.prefix_length[i], tokens[index_token++]);
i++;
}
/* reading DIP range */
ReadIPRange(temp_rule.range[i], temp_rule.prefix_length[i], tokens[index_token++]);
i++;
ReadPort(temp_rule.range[i++], temp_rule.prefix_length[i], tokens[index_token], tokens[index_token + 2]);
index_token += 3;
ReadPort(temp_rule.range[i++], temp_rule.prefix_length[i], tokens[index_token], tokens[index_token + 2]);
index_token += 3;
ReadProtocol(temp_rule.range[i++], temp_rule.prefix_length[i], tokens[index_token++]);
}
temp_rule.priority = cost;
ruleset.push_back(temp_rule);
return 0;
}
void InputReader::LoadFilters(ifstream& fp, vector<Rule>& ruleset)
{
int line_number = 0;
string content;
while (getline(fp, content)) {
istringstream iss(content);
vector<string> tokens{ istream_iterator < string > {iss}, istream_iterator < string > {} };
ReadFilter(tokens, ruleset, line_number++);
}
}
vector<Rule> InputReader::ReadFilterFileClassBench(const string& filename)
{
//assume 5*rep fields
vector<Rule> rules;
ifstream column_counter(filename);
ifstream input_file(filename);
if (!input_file.is_open() || !column_counter.is_open())
{
printf("Couldnt open filter set file \n");
exit(1);
}
LoadFilters(input_file, rules);
input_file.close();
column_counter.close();
//need to rearrange the priority
int max_pri = rules.size() - 1;
for (size_t i = 0; i < rules.size(); i++) {
rules[i].priority = max_pri - i;
}
/*for (int i = 0; i < 5; i++) {
set<interval> iv;
for (rule& r : ruleset) {
iv.insert(interval(r.range[i][0], r.range[i][1], 0));
}
cout << "field " << i << " has " << iv.size() << " unique intervals" << endl;
}*/
/*for (auto& r : rules) {
for (auto &p : r.range) {
cout << p[0] << ":" << p[1] << " ";
}
cout << endl;
}
exit(0);*/
return rules;
}
bool IsPower2(unsigned int x) {
return ((x - 1) & x) == 0;
}
bool IsPrefix(unsigned int low, unsigned int high) {
unsigned int diff = high - low;
return ((low & high) == low) && IsPower2(diff + 1);
}
unsigned int PrefixLength(unsigned int low, unsigned int high) {
unsigned int x = high - low;
int lg = 0;
for (; x; x >>= 1) lg++;
return 32 - lg;
}
void InputReader::ParseRange(Interval& range, const string& text) {
vector<string> split_colon = split(text, ':');
// to obtain interval
range.low = atoui(split_colon[LowDim]);
range.high = atoui(split_colon[HighDim]);
if (range.low > range.high) {
printf("Problematic range: %u-%u\n", range.low, range.high);
}
}
vector<Rule> InputReader::ReadFilterFileMSU(const string& filename)
{
vector<Rule> rules;
ifstream input_file(filename);
if (!input_file.is_open())
{
printf("Couldnt open filter set file \n");
exit(1);
}
string content;
getline(input_file, content);
getline(input_file, content);
vector<string> split_comma = split(content, ',');
dim = split_comma.size();
int priority = 0;
getline(input_file, content);
vector<string> parts = split(content, ',');
vector<Interval> bounds(parts.size());
for (size_t i = 0; i < parts.size(); i++) {
ParseRange(bounds[i], parts[i]);
//printf("[%u:%u] %d\n", bounds[i][LOW], bounds[i][HIGH], PrefixLength(bounds[i][LOW], bounds[i][HIGH]));
}
while (getline(input_file, content)) {
// 5 fields: sip, dip, sport, dport, proto = 0 (with@), 1, 2 : 4, 5 : 7, 8
Rule temp_rule;
vector<string> split_comma = split(content, ',');
// ignore priority at the end
for (size_t i = 0; i < split_comma.size() - 1; i++)
{
ParseRange(temp_rule.range[i], split_comma[i]);
if (IsPrefix(temp_rule.range[i].low, temp_rule.range[i].high)) {
temp_rule.prefix_length[i] = PrefixLength(temp_rule.range[i].low, temp_rule.range[i].high);
}
//if ((i == FieldSA || i == FieldDA) & !IsPrefix(temp_rule.range[i][LOW], temp_rule.range[i][HIGH])) {
// printf("Field is not a prefix!\n");
//}
if (temp_rule.range[i].low < bounds[i].low || temp_rule.range[i].high > bounds[i].high) {
printf("rule out of bounds!\n");
}
}
temp_rule.priority = priority++;
//temp_rule.tag = atoi(split_comma[split_comma.size() - 1].c_str());
rules.push_back(temp_rule);
}
for (auto & r : rules) {
r.priority = rules.size() - r.priority;
}
/*for (auto& r : rules) {
for (auto &p : r.range) {
cout << p[0] << ":" << p[1] << " ";
}
cout << endl;
}
exit(0);*/
return rules;
}
vector<Rule> InputReader::ReadFilterFile(const string& filename) {
ifstream in(filename);
if (!in.is_open())
{
printf("Couldnt open filter set file \n");
printf("%s\n", filename.c_str());
exit(1);
} else {
printf("Reading filter file %s\n", filename.c_str());
}
//cout << filename << " ";
string content;
getline(in, content);
istringstream iss(content);
vector<string> tokens{ istream_iterator < string > {iss}, istream_iterator < string > {} };
if (content[0] == '!') {
// MSU FORMAT
vector<string> split_semi = split(tokens.back(), ';');
reps = (atoi(split_semi.back().c_str()) + 1) / 5;
dim = reps * 5;
return ReadFilterFileMSU(filename);
} else if (content[0] == '@') {
// CLassBench Format
/* COUNT COLUMN */
if (tokens.size() % 9 == 0) {
reps = tokens.size() / 9;
}
dim = reps * 5;
return ReadFilterFileClassBench(filename);
} else {
cout << "ERROR: unknown input format please use either MSU format or ClassBench format" << endl;
exit(1);
}
in.close();
}
vector<int> InputReader::ReadResults(const string& filename) {
ifstream in(filename);
if (!in.is_open()) {
printf("Couldn't open result file\n");
printf("%s\n", filename.c_str());
exit(1);
} else {
printf("Reading result file %s\n", filename.c_str());
}
vector<int> results;
while (!in.eof()) {
int r;
in >> r;
results.push_back(r);
}
in.close();
printf("Num Results: %lu\n", results.size());
return results;
}
|
/*
** EPITECH PROJECT, 2019
** tek3
** File description:
** ContactList
*/
#ifndef CONTACTLIST_HPP_
#define CONTACTLIST_HPP_
#include <QtWidgets>
#include <QApplication>
#include <vector>
#include <iostream>
#include "Contact.hpp"
namespace babel {
namespace graphic {
class ContactList : public QWidget {
Q_OBJECT
public:
ContactList(std::vector<babel::DataUser> &data, std::vector<std::string> &friends, QWidget *parent = 0);
ContactList(std::vector<std::string> &friends, std::vector<babel::DataUser> &data, QWidget *parent = 0);
void updateUsers(std::vector<babel::DataUser> &newData, std::vector<std::string> &friends);
void updateFriends(std::vector<DataUser> &newData, std::vector<std::string> &friends);
babel::DataUser getDataSelected(void) const;
void unselectContact(void) const;
void updateSelectedIndex(void);
bool isFriend(std::string name, std::vector<std::string> &friends);
bool isOnline(std::string name, std::vector<babel::DataUser> &users);
std::string getIp(std::string name, std::vector<babel::DataUser> &users);
signals:
void selectedUserChanged();
private:
int _selectedIndex;
QVBoxLayout *_contactListBox;
std::vector<std::unique_ptr<Contact>> _contactList;
};
}
}
#endif /* !CONTACTLIST_HPP_ */
|
#ifndef _ThrowCardProc_H_
#define _ThrowCardProc_H_
#include "BaseProcess.h"
class Table;
class Player;
class ThrowCardProc : public BaseProcess
{
public:
ThrowCardProc();
virtual ~ThrowCardProc();
int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket, Context* pt);
private:
int sendThrowInfoToPlayers(Player* player, Table* table, Player* throwcallplayer, Player* nextplayer, short seq);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef STDLIB_DOUBLE_FORMAT_H
#define STDLIB_DOUBLE_FORMAT_H
class OpDoubleFormat
{
public:
/** The ES Number builtins toFixed(), toPrecision(), and toExponential()
have a away-from-zero bias on rounding ties. C/C++ printf()-style
g/e/f format specifiers uses the bias of the default IEEE-754
rounding mode (round-to-nearest), which biases towards even. */
enum RoundingBias {
ROUND_BIAS_TO_EVEN,
ROUND_BIAS_AWAY_FROM_ZERO
};
/** Format number on mixed decimal-and-exponent format like printf %g,
returning the closest decimal approximation to the given double value.
@param b The result buffer, at least 32 bytes long.
@param d The number to format.
@returns b, or NULL on OOM.
The buffer b is always null-terminated on success.
OOM NOTE: this function may allocate memory for working storage.
If an OOM event occurs, NULL is returned. However, this behavior
is not reliable.
IMPLEMENTATION NOTE: As for op_strtod(), different code is used
depending on whether FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION or
FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION are defined or not.
If FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION is defined, then
Florian Loitsch's double-conversion library is used.
If FEATURE_3P_DTOA_DAVID_M_GAY is defined, then David Gay's code is used.
If either is not defined, then this function will be implemented
using the porting interfaces provided by the StdlibPI class. */
static char *ToString(char *buffer, double d);
static const unsigned MaxPrecision = 20;
/** ECMA-262 15.7.4.6: Format number using the exponential format,
with one digit before the decimal point.
@param b A buffer, at least MAX(precision + 9,10) characters
long if precision >= 0, or at least 32 characters
long otherwise.
@param x The number to format.
@param precision The number of digits after the decimal
point, or -1 to signify "as many as required".
@param bias The rounding bias to use when a tie. The default
is the EcmaScript prescribed mode of away-from-zero.
@returns b, or NULL on OOM.
The buffer b is always null-terminated on success.
OOM NOTE: this function may allocate memory for working storage.
If an OOM event occurs, NULL is returned. However, this behavior
is not reliable.
IMPLEMENTATION NOTE: As for op_strtod(), different code is used
depending on whether FEATURE_3P_DTOA_DAVID_M_GAY or
FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION are defined or not.
If FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION is defined, then
Florian Loitsch's double-conversion library is used.
If FEATURE_3P_DTOA_DAVID_M_GAY is defined, then David Gay's code
is used.
If either is not defined, then this function will be implemented
using the porting interfaces provided by the StdlibPI class. */
static char *ToExponential(register char *b, double x, int precision, RoundingBias bias = ROUND_BIAS_AWAY_FROM_ZERO);
/** ECMA-262 15.7.4.5: Format number using fixed-point format with
precision digits after the decimal point.
@param b The result buffer.
@param x The number to format.
@param precision The number of digits after the decimal point,
or -1 to signify "as many as necessary".
@param bufsiz The size of the buffer.
@param bias The rounding bias to use when a tie. The default
is the EcmaScript prescribed mode of away-from-zero.
@returns b, or NULL on OOM.
The buffer b is always null-terminated on success.
USAGE NOTE: Please do not rely on the default argument value for
"bufsiz". It exists temporarily for backward compatibility and
will be removed.
OOM NOTE: this function may allocate memory for working storage.
If an OOM event occurs, NULL is returned. However, this behavior
is not reliable.
IMPLEMENTATION NOTE: As for op_strtod(), different code is used
depending on whether FEATURE_3P_DTOA_DAVID_M_GAY or
FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION are defined or not.
If FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION is defined, then
Florian Loitsch's double-conversion library is used.
If FEATURE_3P_DTOA_DAVID_M_GAY is defined, then David Gay's code
is used.
If either is not defined, then this function will be implemented
using the porting interfaces provided by the StdlibPI class. */
static char *ToFixed(register char *b, double x, int precision, size_t bufsiz = 32, RoundingBias bias = ROUND_BIAS_AWAY_FROM_ZERO);
/** ECMA-262 15.7.4.5: Format number using the exponential-or-fixed
format, depending on the magnitude of the number.
@param b The result buffer.
@param x The number to format.
@param precision For exponential format, use precision - 1
digits after the decimal point; for fixed-point
format, use precision significant digits.
@param bufsiz The size of the buffer.
@param bias The rounding bias to use when a tie. The default
is the EcmaScript prescribed mode of away-from-zero.
@returns b, or NULL on OOM.
The buffer b is always null-terminated on success.
USAGE NOTE: Please do not rely on the default argument value for
"bufsiz". It exists temporarily for backward compatibility and
will be removed.
OOM NOTE: this function may allocate memory for working storage.
If an OOM event occurs, NULL is returned. However, this behavior
is not reliable.
IMPLEMENTATION NOTE: As for op_strtod(), different code is used
depending on whether FEATURE_3P_DTOA_DAVID_M_GAY or
FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION are defined or not.
If FEATURE_3P_DTOA_FLOITSCH_DOUBLE_CONVERSION is defined, then
Florian Loitsch's double-conversion library is used.
If FEATURE_3P_DTOA_DAVID_M_GAY is defined, then David Gay'scode
is used.
If either is not defined, then this function will be implemented
using the porting interfaces provided by the StdlibPI class. */
static char *ToPrecision(register char *b, double x, int precision, size_t bufsiz = 32, RoundingBias bias = ROUND_BIAS_AWAY_FROM_ZERO);
static char *PrintfFormat(double x, char* b, size_t bufsiz, char fmt, int precision);
};
#endif // STDLIB_DOUBLE_FORMAT_H
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "CSPowerUpBase.h"
#include "CSCharacter.h"
#include "Net/UnrealNetwork.h"
// Sets default values
ACSPowerUpBase::ACSPowerUpBase()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
PeriodicTimer = 0;
TotalNumberOfTicks = 0;
bIsPowerUpActive = false;
SetReplicates(true);
}
void ACSPowerUpBase::OnTick()
{
TicksCounter++;
OnPowerUpTicked();
if (TicksCounter >= TotalNumberOfTicks)
{
OnExpired();
bIsPowerUpActive = false;
OnRep_PowerUpActive();
// Stop the timer
GetWorldTimerManager().ClearTimer(TimerHandle_PowerUpTick);
Target = nullptr;
}
}
void ACSPowerUpBase::Activate(ACSCharacter* TargetPawn)
{
Target = TargetPawn;
OnActivated();
bIsPowerUpActive = true;
OnRep_PowerUpActive();
if (PeriodicTimer)
{
GetWorldTimerManager().SetTimer(TimerHandle_PowerUpTick, this, &ACSPowerUpBase::OnTick, PeriodicTimer, true);
}
else
OnTick();
}
void ACSPowerUpBase::OnRep_PowerUpActive()
{
OnPowerUpStateChanged(bIsPowerUpActive);
}
void ACSPowerUpBase::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ACSPowerUpBase, bIsPowerUpActive);
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2010 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*/
#include "core/pch.h"
#ifdef DOM_JIL_API_SUPPORT
#include "modules/dom/src/domjil/domjilcallrecordtypes.h"
/* static */ OP_STATUS
DOM_JILCallRecordTypes::Make(DOM_JILCallRecordTypes*& new_obj, DOM_Runtime* runtime)
{
new_obj = OP_NEW(DOM_JILCallRecordTypes, ());
RETURN_IF_ERROR(DOM_Object::DOMSetObjectRuntime(new_obj, runtime, runtime->GetPrototype(DOM_Runtime::JIL_CALLRECORDTYPES_PROTOTYPE), "CallRecordTypes"));
RETURN_IF_ERROR(new_obj->PutStringConstant(UNI_L("MISSED"), CALL_RECORD_TYPE_MISSED));
RETURN_IF_ERROR(new_obj->PutStringConstant(UNI_L("OUTGOING"), CALL_RECORD_TYPE_OUTGOING));
RETURN_IF_ERROR(new_obj->PutStringConstant(UNI_L("RECEIVED"), CALL_RECORD_TYPE_RECEIVED));
return OpStatus::OK;
}
/* static */ OpTelephony::CallRecord::Type
DOM_JILCallRecordTypes::FromString(const uni_char* type)
{
if (!type)
return OpTelephony::CallRecord::TypeUnknown;
else if (IsMissed(type))
return OpTelephony::CallRecord::Missed;
else if (IsOutgoing(type))
return OpTelephony::CallRecord::Initiated;
else if (IsReceived(type))
return OpTelephony::CallRecord::Received;
return OpTelephony::CallRecord::TypeUnknown;
}
/* static */ const uni_char*
DOM_JILCallRecordTypes::ToString(OpTelephony::CallRecord::Type type)
{
switch (type)
{
case OpTelephony::CallRecord::Missed: return CALL_RECORD_TYPE_MISSED;
case OpTelephony::CallRecord::Initiated: return CALL_RECORD_TYPE_OUTGOING;
case OpTelephony::CallRecord::Received: return CALL_RECORD_TYPE_RECEIVED;
default: return CALL_RECORD_TYPE_UNKNOWN;
}
}
#endif // DOM_JIL_API_SUPPORT
|
#include <iostream>
#include <string>
#include <sstream>
#include <cstddef> // std::size_t
#include "Contact.class.hpp"
Contact::Contact() : index(0) {
Contact::_count += 1;
return ;
}
Contact::~Contact(){
Contact::_count -= 1;
return ;
}
size_t Contact::getNbInst(){
return Contact::_count;
}
void Contact::setIndex(int i){
if (i < 10)
this->index = i;
}
size_t Contact::numObjs(){
return Contact::_count;
}
size_t Contact::_count = 0;
|
// Created on: 1999-11-26
// Created by: Andrey BETENEV
// Copyright (c) 1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _StepAP203_PersonOrganizationItem_HeaderFile
#define _StepAP203_PersonOrganizationItem_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <StepData_SelectType.hxx>
#include <Standard_Integer.hxx>
class Standard_Transient;
class StepAP203_Change;
class StepAP203_StartWork;
class StepAP203_ChangeRequest;
class StepAP203_StartRequest;
class StepRepr_ConfigurationItem;
class StepBasic_Product;
class StepBasic_ProductDefinitionFormation;
class StepBasic_ProductDefinition;
class StepBasic_Contract;
class StepBasic_SecurityClassification;
//! Representation of STEP SELECT type PersonOrganizationItem
class StepAP203_PersonOrganizationItem : public StepData_SelectType
{
public:
DEFINE_STANDARD_ALLOC
//! Empty constructor
Standard_EXPORT StepAP203_PersonOrganizationItem();
//! Recognizes a kind of PersonOrganizationItem select type
//! 1 -> Change from StepAP203
//! 2 -> StartWork from StepAP203
//! 3 -> ChangeRequest from StepAP203
//! 4 -> StartRequest from StepAP203
//! 5 -> ConfigurationItem from StepRepr
//! 6 -> Product from StepBasic
//! 7 -> ProductDefinitionFormation from StepBasic
//! 8 -> ProductDefinition from StepBasic
//! 9 -> Contract from StepBasic
//! 10 -> SecurityClassification from StepBasic
//! 0 else
Standard_EXPORT Standard_Integer CaseNum (const Handle(Standard_Transient)& ent) const;
//! Returns Value as Change (or Null if another type)
Standard_EXPORT Handle(StepAP203_Change) Change() const;
//! Returns Value as StartWork (or Null if another type)
Standard_EXPORT Handle(StepAP203_StartWork) StartWork() const;
//! Returns Value as ChangeRequest (or Null if another type)
Standard_EXPORT Handle(StepAP203_ChangeRequest) ChangeRequest() const;
//! Returns Value as StartRequest (or Null if another type)
Standard_EXPORT Handle(StepAP203_StartRequest) StartRequest() const;
//! Returns Value as ConfigurationItem (or Null if another type)
Standard_EXPORT Handle(StepRepr_ConfigurationItem) ConfigurationItem() const;
//! Returns Value as Product (or Null if another type)
Standard_EXPORT Handle(StepBasic_Product) Product() const;
//! Returns Value as ProductDefinitionFormation (or Null if another type)
Standard_EXPORT Handle(StepBasic_ProductDefinitionFormation) ProductDefinitionFormation() const;
//! Returns Value as ProductDefinition (or Null if another type)
Standard_EXPORT Handle(StepBasic_ProductDefinition) ProductDefinition() const;
//! Returns Value as Contract (or Null if another type)
Standard_EXPORT Handle(StepBasic_Contract) Contract() const;
//! Returns Value as SecurityClassification (or Null if another type)
Standard_EXPORT Handle(StepBasic_SecurityClassification) SecurityClassification() const;
protected:
private:
};
#endif // _StepAP203_PersonOrganizationItem_HeaderFile
|
#ifndef GAME_GAME_H
#define GAME_GAME_H
#include"basecnst/glpack.h"
class Game
{
public:
Game();
void init_all();
void start();
};
#endif
|
#pragma once
#include "../Entity/Entity.h"
#include <vector>
#include "../Components/BoxCollider.h"
#include "../Core/DFCman.h"
static const int MAX_OBJS_PER_SCENE = 99999;
class dfScene :
public Entity
{
public:
dfScene(void);
virtual ~dfScene(void);
virtual void Init();
virtual void Update();
void (*setupFunc)();
virtual void SetupScene();
std::string name;
int currentNum;
std::vector<int> freeSpots;
Entity* sceneObjects[MAX_OBJS_PER_SCENE];
Entity* GetEntityByIndex(int i);
void RemoveSceneObject(Entity* sceneObj);
void DoCollision();
void RemoveAllSceneObjects();
template<class T> T* CreateSceneObject()
{
int useIndex = -1;
if(freeSpots.size() > 0)
{
useIndex = freeSpots[freeSpots.size() - 1];
freeSpots.pop_back();
}
else if(currentNum < MAX_OBJS_PER_SCENE - 1)
{
useIndex = currentNum;
currentNum++;
}
if(useIndex != -1)
{
T* newObj = new T();
sceneObjects[useIndex] = newObj;
return newObj;
}
dfError("shoot, added too many objects to the scene :c");
dfAssert(false);
return 0;
}
};
|
#include<iostream>
using namespace std;
int main()
{
int t;
cin>>t;
int n;
int a[100000];
while(t)
{
int mod2=0;
int mod4=0;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
for(int i=0;i<n;i++)
{
if(a[i]%4==0)
mod4++;
else if(a[i]%2==0)
mod2++;
}
if(mod4>=(n-mod2-mod4))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
t--;
}
}
|
#include "test_compiler_detection.h"
#define PREFIX TEST
#include "compile_tests.h"
#ifdef TEST_COMPILER_C_STATIC_ASSERT
# error Expect no C features defined
#endif
TEST_STATIC_ASSERT(true);
TEST_STATIC_ASSERT_MSG(true, "msg");
int main()
{
return 0;
}
|
#include "odb/server/cli-client-handler.hh"
#include <cassert>
#include <cstdio>
#include <iostream>
#include <signal.h>
#include <unistd.h>
#include "odb/server/db-client-impl-vmside.hh"
#include "odb/server/server-app.hh"
namespace odb {
namespace {
bool g_sig_stop = false;
bool g_manual_stop = false;
void sigint_handler_fn(int) { g_sig_stop = true; }
} // namespace
CLIClientHandler::CLIClientHandler(Debugger &db, const ServerConfig &conf)
: ClientHandler(db, conf),
_db_client(std::make_unique<DBClientImplVMSide>(db)), _client(_db_client),
_is_tty(isatty(fileno(stdin))), _catch_sigint(false) {}
CLIClientHandler::~CLIClientHandler() { _on_disconnect(); }
void CLIClientHandler::setup_connection() {
_db_client.connect();
_client_connected();
if (get_conf().server_cli_sighandler) {
// Add signal to stop program execution on Ctrl-C
struct sigaction sigint_handler;
sigint_handler.sa_handler = sigint_handler_fn;
sigemptyset(&sigint_handler.sa_mask);
sigint_handler.sa_flags = 0;
sigaction(SIGINT, &sigint_handler, nullptr);
_catch_sigint = true;
}
}
void CLIClientHandler::run_command() {
bool stopped = false;
if (_db_client.state() == DBClient::State::VM_RUNNING) {
_db_client.check_stopped();
stopped = true;
}
if (g_manual_stop) {
stopped = true;
g_manual_stop = false;
}
assert(_db_client.state() == DBClient::State::VM_STOPPED);
if (stopped)
std::cout << _client.exec("state");
if (_is_tty) {
std::cout << "> ";
std::cout.flush();
}
// Disconnect if stdin closed
std::cin.peek();
if (!std::cin.good()) {
_client_disconnected();
if (_is_tty)
std::cout << "Debug session closed, program resumed.\n";
_on_disconnect();
}
// Read and exec one command
std::string cmd;
std::getline(std::cin, cmd);
if (cmd.empty())
return;
std::string out = _client.exec(cmd);
std::cout << out;
if (!out.empty() && out.back() != '\n')
std::cout << std::endl;
}
void CLIClientHandler::check_stopped() {
// @TODO
if (!g_sig_stop)
return;
_db_client.stop();
g_sig_stop = false;
g_manual_stop = true;
}
void CLIClientHandler::_on_disconnect() {
if (_catch_sigint) {
// Remove signal handler
struct sigaction sigint_handler;
sigint_handler.sa_handler = SIG_DFL;
sigemptyset(&sigint_handler.sa_mask);
sigint_handler.sa_flags = 0;
sigaction(SIGINT, &sigint_handler, nullptr);
_catch_sigint = false;
}
}
} // namespace odb
|
#include <bits/stdc++.h>
using namespace std;
string decimal_to_binary(int n)
{
string ans;
while(n>0){
int current_bit = n&1;
ans+=current_bit+'0';
n>>=1;
}
reverse(ans.begin(),ans.end());
return ans;
}
int main()
{
string binary = decimal_to_binary(244);
cout << binary << endl;
return 0;
}
|
#include "bricks/imaging/videocodec.h"
#include "bricks/imaging/bitmap.h"
namespace Bricks { namespace Imaging {
VideoCodec::VideoCodec() :
framesPerSecond(0), frameCount(0), frameWidth(0), frameHeight(0), position(0)
{
}
void VideoCodec::Seek(s64 frame)
{
position = frame;
}
ReturnPointer<BitmapImage> VideoCodec::Read(s64 frame)
{
AutoPointer<Bitmap> bitmap = autonew Bitmap(frameWidth, frameHeight, pixelDescription);
if (!Read(bitmap, frame))
return NULL;
return bitmap;
}
} }
|
#include <iostream>
#include <sstream>
#include <cctype>
#include <set>
#include <algorithm>
#include "util.h"
using namespace std;
std::string convToLower(std::string src)
{
std::transform(src.begin(), src.end(), src.begin(), ::tolower);
return src;
}
void parseHelper(string word, set<std::string>& wordList) {
if (word.length() < 2) {
return;
}
else {
bool punct = false;
for (unsigned int i=0; i<word.length(); i++) {
if (ispunct(word[i])) {
//if there is punctuation, break up the string into 2 new ones
parseHelper(word.substr(0, i), wordList);
parseHelper(word.substr(i+1, word.size()), wordList);
punct = true;
return;
}
}
if (!punct) {
wordList.insert(word);
}
}
}
/** Complete the code to convert a string containing a rawWord
to a set of words based on the criteria given in the assignment **/
std::set<std::string> parseStringToWords(string rawWord)
{
convToLower(rawWord);
stringstream ss(rawWord);
set<std::string> parsedString;
std::string word;
while (!ss.fail()) {
ss >> word;
if (!ss.fail()) {
parseHelper(word, parsedString);
}
}
return parsedString;
}
|
#include "core.h"
#include "engine_platform.h"
#include "asset.h"
#include "math.h"
#include "mesh.h"
static_func void EngineViewCreateGrid(void *buffer, u64 &offset, asset *asset)
{
asset->type = ASSET_TYPE_MESH;
asset->header = buffer;
mesh_header *m = (mesh_header *)asset->header;
m->vertexSize = sizeof(vec3);
m->vertices = (u8 *)m + sizeof(*m);
// Create Grid Vertices
vec3 *v = (vec3 *)m->vertices;
u32 iVert = 0;
i32 gridSize = 500;
i32 halfGridSize = gridSize / 2;
v[iVert++] = { 0.0f, (f32)halfGridSize, 0.0f };
v[iVert++] = { 0.0f, -(f32)halfGridSize, 0.0f };
{
i32 z = halfGridSize;
for (i32 x = -halfGridSize; x < halfGridSize; x++)
{
v[iVert++] = { (f32)x, 0.0f, (f32)z };
v[iVert++] = { (f32)x, 0.0f, -(f32)z };
}
}
{
i32 x = halfGridSize;
for (i32 z = -halfGridSize; z < halfGridSize; z++)
{
v[iVert++] = { (f32)x, 0.0f, (f32)z };
v[iVert++] = { -(f32)x, 0.0f, (f32)z };
}
}
m->nVertices = iVert - 1;
u64 size = MESH_PTR_TOTAL_SIZE(m);
offset += size;
AdvancePointer(buffer, size);
}
static_func bool EngineViewInitialize(engine_platform *engine)
{
// TODO: Remove the vulkan related stuff
void *buffer = VulkanRequestBuffer(RENDERER_BUFFER_TYPE_STAGING, MEGABYTES(64), 0);
u64 offset = 0;
asset assets[10] = {};
EngineViewCreateGrid(buffer, offset, &assets[0]);
// TODO: UI stuff, AABBs, more?
VulkanUpload(assets, 1);
VulkanClearBuffer(vulkanContext->stagingBuffer);
}
|
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <bits/stdc++.h>
#include<string>
using namespace std;
int sum=0;
string temp="";
int a=0;
void addtostring(char c)
{
temp.append(1,c);
}
int main()
{ string s;
cin>>s;
for(int i=0;i<s.length();i++)
{
if(isdigit(s[i]))
{
int n=s[i]-'0';
sum=sum+n;
}
else{
// cout<<typeid(s[i]).name();
addtostring(s[i]);
}
}
cout<<sum<<endl;
cout<<temp;
}
|
#ifndef INSTANCEDMESH_H
#define INSTANCEDMESH_H
#include <list>
#include "core/glmcfg.h"
#include "core/pbutil.h"
#include "geometry.h"
#include "instanceattribsmgr.h"
namespace pb
{
template < typename f32_layout, typename uint32_layout >
class InstancedGeometry : public IInstancedGeometry
{
/*
struct transformBufferState
{
unsigned int idVBO;
unsigned int count;
};
struct transformAttribMgr
{
const unsigned int MAX_TRANSFORMS_PER_ENTRY;
unsigned int mCount;
std::vector<Transforms> mTransforms;
std::vector<transformBufferState> mStates;
transformAttribMgr( unsigned int hintPerInstanceTableSize ) :
MAX_TRANSFORMS_PER_ENTRY( hintPerInstanceTableSize ),
mCount( 0 )
{
mTransforms.emplace_back( MAX_TRANSFORMS_PER_ENTRY, Mat4(1.0f) );
mStates.emplace_back( transformBufferState() );
}
size_t EntryBufferSize()
{
return MAX_TRANSFORMS_PER_ENTRY * sizeof( Mat4 );
}
inline Transforms& EntryBuffer(unsigned int entryId)
{
return mTransforms[ entryId ];
}
inline transformBufferState& EntryState(unsigned int entryId)
{
return mStates[ entryId ];
}
inline unsigned int EntriesCount()
{
return mTransforms.size();
}
unsigned int AddInstance()
{
transformBufferState* pState = &mStates[ EntriesCount()-1 ];
if ( pState->count >= MAX_TRANSFORMS_PER_ENTRY )
{
mTransforms.emplace_back( MAX_TRANSFORMS_PER_ENTRY, Mat4(1.0f) );
mStates.emplace_back( transformBufferState() );
pState = &mStates[ EntriesCount()-1 ];
Transforms& transforms = mTransforms[ EntriesCount()-1 ];
CreateBuffer( *pState, transforms );
}
++pState->count;
return mCount++;
}
void CreateBuffer(transformBufferState& state, Transforms& transforms);
inline Mat4* Transform(unsigned int transformId)
{
unsigned int entryId = transformId / MAX_TRANSFORMS_PER_ENTRY;
unsigned int transformOffset = transformId % MAX_TRANSFORMS_PER_ENTRY;
return &mTransforms[ entryId ][ transformOffset ];
}
inline void UpdateTransform(unsigned int transformId);
};
*/
private:
InstancedGeometry(const InstancedGeometry& rhs);
InstancedGeometry& operator=(const InstancedGeometry& rhs);
public:
InstancedGeometry(unsigned int primitiveType,
Indices* pIndicies,
Positions* pPositions,
ColorsRGBA* pColors,
unsigned int idProgram,
unsigned int hintPerInstanceTableSize);
virtual ~InstancedGeometry();
unsigned int AddInstance();
f32_layout* AttributesF32(unsigned int id);
void UpdateAttributesF32(unsigned int transformId);
uint32_layout* AttributesU32(unsigned int id);
void UpdateAttributesU32(unsigned int transformId);
void UseF32Layout(const attribDesc* attribDescs, int n);
void UseUint32Layout(const attribDesc* attribDescs, int n);
void Render(const glm::mat4& vp);
private:
PBError init();
private:
PBError mStatus;
unsigned int mPrimitiveType;
unsigned int mIdProgram;
// TODO refactor to use packed attributes
unsigned int mIdPositionVBO;
unsigned int mIdColorVBO;
unsigned int mIdIndexArray;
unsigned int mIdVAO;
// backing buffers
Indices* mpBkIndicies;
Positions* mpBkPositions;
ColorsRGBA* mpBkColors;
InstanceAttribsMgr< f32_layout, uint32_layout > mInstancedAttribsMgr;
};
template < typename f32_layout, typename uint32_layout >
InstancedGeometry< f32_layout, uint32_layout >::InstancedGeometry(GLuint primitiveType,
Indices* pIndicies,
Positions* pPositions,
ColorsRGBA* pColors,
unsigned int idProgram,
unsigned int hintPerInstanceTableSize) :
mStatus( PB_ERR_OK ),
mPrimitiveType( primitiveType ),
mIdProgram( idProgram ),
mpBkIndicies( pIndicies ),
mpBkPositions( pPositions ),
mpBkColors( pColors ),
mInstancedAttribsMgr( hintPerInstanceTableSize )
{
GLint attribLocation;
Indices& indicies = *mpBkIndicies;
Positions& positions = *mpBkPositions;
ColorsRGBA& colors = *mpBkColors;
if ( positions.size() != colors.size() )
{
Log::Error( "Buffers are not of the same size" );
mStatus = PB_ERR;
return;
}
Log::Info("length: "+std::to_string(indicies.size()));
/*** VAO ***/
glGenVertexArrays( 1, &mIdVAO );
glBindVertexArray( mIdVAO );
/*** position ***/
// data
glGenBuffers( 1, &mIdPositionVBO );
glBindBuffer( GL_ARRAY_BUFFER, mIdPositionVBO );
glBufferData( GL_ARRAY_BUFFER, positions.size() * sizeof(positions[0]), &positions[0], GL_STATIC_DRAW );
// layout
attribLocation = 0;//glGetAttribLocation( mIdProgram, "attribPosition" );
glEnableVertexAttribArray( attribLocation );
glBindBuffer( GL_ARRAY_BUFFER, mIdPositionVBO );
glVertexAttribPointer( attribLocation, 3, GL_FLOAT, GL_FALSE, 0, (void*)0 );
/*** color ***/
// data
glGenBuffers( 1, &mIdColorVBO );
glBindBuffer( GL_ARRAY_BUFFER, mIdColorVBO );
glBufferData( GL_ARRAY_BUFFER, colors.size() * sizeof(colors[0]), &colors[0], GL_STATIC_DRAW );
// layout
attribLocation = 1;//glGetAttribLocation( mIdProgram, "attribColor" );
glEnableVertexAttribArray( attribLocation );
glBindBuffer( GL_ARRAY_BUFFER, mIdColorVBO );
glVertexAttribPointer( attribLocation, 4, GL_UNSIGNED_BYTE, GL_TRUE, 0, (void*)0 );
/*** indecies ***/
// data
glGenBuffers( 1, &mIdIndexArray );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, mIdIndexArray );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, indicies.size() * sizeof(indicies[0]), &indicies[0], GL_STATIC_DRAW );
// unbind VAO
glBindVertexArray( 0 );
// outside VAO state
//mTransformsMgr.CreateBuffer( transformsState, transforms );
mStatus = PB_ERR;
}
template < typename f32_layout, typename uint32_layout >
InstancedGeometry< f32_layout, uint32_layout >::~InstancedGeometry()
{
PB_DELETE( mpBkIndicies );
PB_DELETE( mpBkPositions );
PB_DELETE( mpBkColors );
glDeleteProgram( mIdProgram );
glDeleteBuffers( 1, &mIdPositionVBO );
glDeleteBuffers( 1, &mIdColorVBO );
glDeleteBuffers( 1, &mIdIndexArray );
glDeleteVertexArrays( 1, &mIdVAO );
}
template < typename f32_layout, typename uint32_layout >
unsigned int InstancedGeometry< f32_layout, uint32_layout >::AddInstance()
{
return mInstancedAttribsMgr.AddInstance();
}
template < typename f32_layout, typename uint32_layout >
f32_layout* InstancedGeometry< f32_layout, uint32_layout >::AttributesF32(unsigned int id)
{
return mInstancedAttribsMgr.AttributesF32( id );
}
template < typename f32_layout, typename uint32_layout >
void InstancedGeometry< f32_layout, uint32_layout >::UpdateAttributesF32(unsigned int id)
{
mInstancedAttribsMgr.UpdateF32( id );
}
template < typename f32_layout, typename uint32_layout >
uint32_layout* InstancedGeometry< f32_layout, uint32_layout >::AttributesU32(unsigned int id)
{
return mInstancedAttribsMgr.AttributesU32( id );
}
template < typename f32_layout, typename uint32_layout >
void InstancedGeometry< f32_layout, uint32_layout >::UpdateAttributesU32(unsigned int id)
{
mInstancedAttribsMgr.UpdateU32( id );
}
template < typename f32_layout, typename uint32_layout >
void InstancedGeometry< f32_layout, uint32_layout >::UseF32Layout(const attribDesc* attribDescs, int n)
{
mInstancedAttribsMgr.UseF32Layout( attribDescs, n );
}
template < typename f32_layout, typename uint32_layout >
void InstancedGeometry< f32_layout, uint32_layout >::UseUint32Layout(const attribDesc* attribDescs, int n)
{
mInstancedAttribsMgr.UseUint32Layout( attribDescs, n );
}
template < typename f32_layout, typename uint32_layout >
void InstancedGeometry< f32_layout, uint32_layout >::Render(const glm::mat4& vp)
{
GLint uniformVpLocation;
glUseProgram( mIdProgram );
glBindVertexArray( mIdVAO );
// set vp matrix
uniformVpLocation = glGetUniformLocation( mIdProgram, "uniformVP" );
glUniformMatrix4fv( uniformVpLocation, 1, GL_FALSE, &vp[0][0] );
GLint attribLocation = 2;
//glDrawElements( mPrimitiveType, mpBkIndicies->size(), GL_UNSIGNED_INT, (void*)0 );
// for ( unsigned int idx = 0; idx < mTransformsMgr.EntriesCount(); ++idx )
// {
// transformBufferState& state = mTransformsMgr.EntryState( idx );
//
// GLint attribLocation = 2;
// glEnableVertexAttribArray( attribLocation );
// glEnableVertexAttribArray( attribLocation+1 );
// glEnableVertexAttribArray( attribLocation+2 );
// glEnableVertexAttribArray( attribLocation+3 );
// glBindBuffer( GL_ARRAY_BUFFER, state.idVBO );
// glVertexAttribPointer( attribLocation+0, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 16, (void*)0 );
// glVertexAttribPointer( attribLocation+1, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 16, (void*)(sizeof(float) * 4) );
// glVertexAttribPointer( attribLocation+2, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 16, (void*)(sizeof(float) * 8) );
// glVertexAttribPointer( attribLocation+3, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 16, (void*)(sizeof(float) * 12) );
// glVertexAttribDivisor( attribLocation+0, 1 );
// glVertexAttribDivisor( attribLocation+1, 1 );
// glVertexAttribDivisor( attribLocation+2, 1 );
// glVertexAttribDivisor( attribLocation+3, 1 );
//
// glDrawElementsInstanced( mPrimitiveType, mpBkIndicies->size(), GL_UNSIGNED_INT, (void*)0, state.count );
//
// glDisableVertexAttribArray( attribLocation );
// glDisableVertexAttribArray( attribLocation+1 );
// glDisableVertexAttribArray( attribLocation+2 );
// glDisableVertexAttribArray( attribLocation+3 );
// }
for ( unsigned int idx = 0; idx < mInstancedAttribsMgr.BuffersCount(); ++idx )
{
mInstancedAttribsMgr.UpdateBufferF32( idx );
mInstancedAttribsMgr.UpdateBufferU32( idx );
mInstancedAttribsMgr.Bind( idx, attribLocation );
glDrawElementsInstanced(
mPrimitiveType,
mpBkIndicies->size(),
GL_UNSIGNED_INT,
(void*)0,
mInstancedAttribsMgr.BufferState( idx )->count );
}
glBindVertexArray( 0 );
}
}
#endif // INSTANCEDMESH_H
|
#ifndef SUBJECT_H
#define SUBJECT_H
#include<list>
#include<string>
class Observer;
class OBSubject {
public:
virtual ~OBSubject();
virtual void Attach(Observer *obv);
virtual void Detach(Observer *obv);
virtual void Notify();
virtual void SetState(const std::string &st) = 0;
virtual std::string GetState() = 0;
protected:
OBSubject();
private:
std::list<Observer*> *_obvs;
};
class SubConcreteSubject :public OBSubject {
public:
SubConcreteSubject();
~SubConcreteSubject();
std::string GetState() override;
void SetState(const std::string &st) override;
private:
std::string _st;
};
#endif
|
#include"konto.h"
#include"person.h"
#include"bank.h"
#include<iostream>
using namespace std;
#include<vector>
#include<memory>
Bank::Bank(){
this->bankname="Bank Austria";
}
Bank::Bank(string bankname){
this->bankname=bankname;
}
vector<shared_ptr<Person>> Bank::getKunden() const{
return kunden;
}
void Bank::kuendigen(){
for(auto& k: kunden)
k=nullptr;
}
ostream& Bank::print(ostream& o) const{
o<<"Kunden:" << endl;
for(const auto& k: kunden){
o<<*k;
}
return o;
}
void Bank::neuerKunde(string name, char art){
auto kunde=make_shared<Person>(name);
kunden.push_back(kunde);
kunde->neues_konto(art);
}
|
#include "Generator.hpp"
#include <assert.h>
#include <iostream>
std::vector<uint8_t> TerrainGen::compress(
const std::vector<uint8_t>& input,
size_t inp_size,
size_t pixels_to_compress,
size_t out_size,
size_t patch_offset_x,
size_t patch_offset_y )
{
assert( pixels_to_compress && "Compression must be larger than 0" );
std::vector<uint8_t> res( out_size * out_size );
// std::cout << inp_size << " " << pixels_to_compress << " " << out_size << " " << patch_offset_x << " " << patch_offset_y << std::endl;
const size_t patch_size = out_size * pixels_to_compress;
for( size_t y = 0; y < out_size; ++y ){
for( size_t x = 0; x < out_size; ++x ){
size_t counter = 0;
const size_t xindex = patch_offset_x * patch_size + pixels_to_compress * x;
const size_t yindex = patch_offset_y * patch_size + pixels_to_compress * y;
for( size_t yi = 0; yi < pixels_to_compress; ++yi ){
for( size_t xi = 0; xi < pixels_to_compress; ++xi ){
counter += input[xindex + xi + (yindex + yi) * inp_size];
}
}
res[x + y * out_size] = counter / ( pixels_to_compress * pixels_to_compress );
// std::cout << "(" << xindex << " " << yindex << " " << counter / (pixels_to_compress * pixels_to_compress) << std::endl;
}
}
// std::cout << std::endl;
return res;
}
|
#pragma once
#include <string>
#include <ionir/construct/type.h>
#include <ionir/construct/inst_yield.h>
#include <ionir/construct/inst.h>
namespace ionir {
class BasicBlock;
struct AllocaInstOpts : InstYieldOpts {
ionshared::Ptr<Type> type;
};
struct AllocaInst : Inst, InstYield {
ionshared::Ptr<Type> type;
// TODO: Missing support for array-type allocas.
explicit AllocaInst(const AllocaInstOpts &opts);
void accept(Pass &visitor) override;
};
}
|
#include "Header/print.cpp"
using namespace std;
class BST
{
private:
node *root;
public:
BST()
{
root=0;
}
void addNode(int info)
{
node *n=root;
node *p=0;
while(n)
{
p=n;
if(n->info<info)
n=n->right;
else n=n->left;
}
node *q = new node();
q->info=info;
if(p==0)
root=q;
else
{
if(p->info<info)
p->right=q;
else p->left=q;
}
}
void delNode(int info)
{
node *n=root;
node *p=0;
while(n && n->info!=info)
{
p=n;
if(n->info<info)
n=n->right;
else if(n->info>info)
n=n->left;
}
if(n)
{
node *s;
if(n->right && n->left)
{
s=n->right;
node *sp=n;
while(s->left)
{
sp=s;
s=s->left;
}
if(sp->right==s)
sp->right=s->right;
else sp->left=s->right;
s->left=n->left;
s->right=n->right;
if(p && p->right==n)
p->right=s;
else if(p && p->left==n)
p->left=s;
}
else if(n->right)
{
s=n->right;
if(n==p->right)
p->right=s;
else p->left=s;
}
else if(n->left)
{
s=n->left;
if(n==p->right)
p->right=s;
else p->left=s;
}
else
{
if(n==root)
root=0;
if(n==p->right)
p->right=0;
else p->left=0;
}
if(n==root)
root=s;
delete(n);
}
else cout<<"Node does not exist!"<<endl;
}
void display()
{
printPretty(root,1,0,cout);
}
};
int main()
{
int choice,no;
BST t;
do
{
system("cls");
cout<<"Enter 1 to Add element"<<endl;
cout<<"Enter 2 to Delete an element"<<endl;
cout<<"Enter 3 to Display"<<endl;
cout<<"Enter 4 to Quit"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
cout<<"Enter an element : ";
cin>>no;
t.addNode(no);
break;
case 2:
cout<<"Enter an element : ";
cin>>no;
t.delNode(no);
break;
case 3:
cout<<endl;
t.display();
cout<<endl;
break;
case 4:
cout<<"GoodBye!"<<endl;
break;
default:
cout<<"Invalid Choice!"<<endl;
break;
}
getch();
}while(choice!=4);
return 0;
}
|
#include "Nodo.h"
#include <iostream>
Nodo::Nodo() {
nhijos = 0;
padre = 0;
}
Nodo* Nodo::agregarHijo() {
this->hijo.push_back(new Nodo);
this->hijo[nhijos]->padre = this;
return this->hijo[nhijos++];
}
void Nodo::setInfo(ListaFichas _fichas) {
fichas.copiaDesde(_fichas);
}
ListaFichas Nodo::getInfo() {
return fichas;
}
Nodo* Nodo::getHijo(int index) {
if (index > nhijos) {
std::cerr << "Fallo interno del nodo. Dimensión excedida" << std::endl;
return hijo[nhijos - 1];
}
if (index < 0) {
return hijo[0];
}
return hijo[index];
}
void Nodo::eliminarNodo() {
/*El siguiente código elimina el nodo en cuestión y todos los nodos inferiores.*/
Nodo* aux, * _padre;
aux = this;
_padre = padre;
if (aux->nhijos != 0) {
do {
while (aux->nhijos != 0) {//Este bucle llega hasta el hijo más lejano
aux = aux->hijo[aux->nhijos - 1];//Salto de nodo en nodo
}
_padre = aux->padre;
delete aux;
aux = _padre;
aux->nhijos--;
aux->hijo.pop_back();
if (aux->nhijos != 0) {
aux = aux->hijo[aux->nhijos - 1];
}
} while (aux != this);
}
if (aux->padre != 0) {
int i = 0;
for (i; i < _padre->nhijos; i++) {
if (_padre->hijo[i] == this) {
break;
}
}
delete _padre->hijo[i];
_padre->hijo.erase(_padre->hijo.begin() + i);
_padre->nhijos--;
}
delete this;
}
void Nodo::setPadre(Nodo* _padre) {
padre = _padre;
}
int Nodo::getNumHijos() {
return nhijos;
}
Nodo* Nodo::getPadre() {
return padre;
}
|
// Copyright (c) 1991-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _gp_Mat2d_HeaderFile
#define _gp_Mat2d_HeaderFile
#include <gp.hxx>
#include <Standard_ConstructionError.hxx>
#include <Standard_OutOfRange.hxx>
class gp_XY;
//! Describes a two column, two row matrix.
//! This sort of object is used in various vectorial or matrix computations.
class gp_Mat2d
{
public:
DEFINE_STANDARD_ALLOC
//! Creates a matrix with null coefficients.
gp_Mat2d()
{
myMat[0][0] = myMat[0][1] = myMat[1][0] = myMat[1][1] = 0.0;
}
//! theCol1, theCol2 are the 2 columns of the matrix.
Standard_EXPORT gp_Mat2d (const gp_XY& theCol1, const gp_XY& theCol2);
//! Assigns the two coordinates of theValue to the column of range
//! theCol of this matrix
//! Raises OutOfRange if theCol < 1 or theCol > 2.
Standard_EXPORT void SetCol (const Standard_Integer theCol, const gp_XY& theValue);
//! Assigns the number pairs theCol1, theCol2 to the two columns of this matrix
Standard_EXPORT void SetCols (const gp_XY& theCol1, const gp_XY& theCol2);
//! Modifies the main diagonal of the matrix.
//! @code
//! <me>.Value (1, 1) = theX1
//! <me>.Value (2, 2) = theX2
//! @endcode
//! The other coefficients of the matrix are not modified.
void SetDiagonal (const Standard_Real theX1, const Standard_Real theX2)
{
myMat[0][0] = theX1;
myMat[1][1] = theX2;
}
//! Modifies this matrix, so that it represents the Identity matrix.
void SetIdentity()
{
myMat[0][0] = myMat[1][1] = 1.0;
myMat[0][1] = myMat[1][0] = 0.0;
}
//! Modifies this matrix, so that it represents a rotation. theAng is the angular
//! value in radian of the rotation.
void SetRotation (const Standard_Real theAng);
//! Assigns the two coordinates of theValue to the row of index theRow of this matrix.
//! Raises OutOfRange if theRow < 1 or theRow > 2.
Standard_EXPORT void SetRow (const Standard_Integer theRow, const gp_XY& theValue);
//! Assigns the number pairs theRow1, theRow2 to the two rows of this matrix.
Standard_EXPORT void SetRows (const gp_XY& theRow1, const gp_XY& theRow2);
//! Modifies the matrix such that it
//! represents a scaling transformation, where theS is the scale factor :
//! @code
//! | theS 0.0 |
//! <me> = | 0.0 theS |
//! @endcode
void SetScale (const Standard_Real theS)
{
myMat[0][0] = myMat[1][1] = theS;
myMat[0][1] = myMat[1][0] = 0.0;
}
//! Assigns <theValue> to the coefficient of row theRow, column theCol of this matrix.
//! Raises OutOfRange if theRow < 1 or theRow > 2 or theCol < 1 or theCol > 2
void SetValue (const Standard_Integer theRow, const Standard_Integer theCol, const Standard_Real theValue)
{
Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 2 || theCol < 1 || theCol > 2, " ");
myMat[theRow - 1][theCol - 1] = theValue;
}
//! Returns the column of theCol index.
//! Raises OutOfRange if theCol < 1 or theCol > 2
Standard_EXPORT gp_XY Column (const Standard_Integer theCol) const;
//! Computes the determinant of the matrix.
Standard_Real Determinant() const
{
return myMat[0][0] * myMat[1][1] - myMat[1][0] * myMat[0][1];
}
//! Returns the main diagonal of the matrix.
Standard_EXPORT gp_XY Diagonal() const;
//! Returns the row of index theRow.
//! Raised if theRow < 1 or theRow > 2
Standard_EXPORT gp_XY Row (const Standard_Integer theRow) const;
//! Returns the coefficient of range (ttheheRow, theCol)
//! Raises OutOfRange
//! if theRow < 1 or theRow > 2 or theCol < 1 or theCol > 2
const Standard_Real& Value (const Standard_Integer theRow, const Standard_Integer theCol) const
{
Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 2 || theCol < 1 || theCol > 2, " ");
return myMat[theRow - 1][theCol - 1];
}
const Standard_Real& operator() (const Standard_Integer theRow, const Standard_Integer theCol) const { return Value (theRow, theCol); }
//! Returns the coefficient of range (theRow, theCol)
//! Raises OutOfRange
//! if theRow < 1 or theRow > 2 or theCol < 1 or theCol > 2
Standard_Real& ChangeValue (const Standard_Integer theRow, const Standard_Integer theCol)
{
Standard_OutOfRange_Raise_if (theRow < 1 || theRow > 2 || theCol < 1 || theCol > 2, " ");
return myMat[theRow - 1][theCol - 1];
}
Standard_Real& operator() (const Standard_Integer theRow, const Standard_Integer theCol) { return ChangeValue (theRow, theCol); }
//! Returns true if this matrix is singular (and therefore, cannot be inverted).
//! The Gauss LU decomposition is used to invert the matrix
//! so the matrix is considered as singular if the largest
//! pivot found is lower or equal to Resolution from gp.
Standard_Boolean IsSingular() const
{
Standard_Real aDet = Determinant();
if (aDet < 0)
{
aDet = -aDet;
}
return aDet <= gp::Resolution();
}
void Add (const gp_Mat2d& Other);
void operator += (const gp_Mat2d& theOther) { Add (theOther); }
//! Computes the sum of this matrix and the matrix
//! theOther.for each coefficient of the matrix :
//! @code
//! <me>.Coef(i,j) + <theOther>.Coef(i,j)
//! @endcode
//! Note:
//! - operator += assigns the result to this matrix, while
//! - operator + creates a new one.
Standard_NODISCARD gp_Mat2d Added (const gp_Mat2d& theOther) const;
Standard_NODISCARD gp_Mat2d operator + (const gp_Mat2d& theOther) const { return Added (theOther); }
void Divide (const Standard_Real theScalar);
void operator /= (const Standard_Real theScalar) { Divide (theScalar); }
//! Divides all the coefficients of the matrix by a scalar.
Standard_NODISCARD gp_Mat2d Divided (const Standard_Real theScalar) const;
Standard_NODISCARD gp_Mat2d operator / (const Standard_Real theScalar) const { return Divided (theScalar); }
Standard_EXPORT void Invert();
//! Inverses the matrix and raises exception if the matrix
//! is singular.
Standard_NODISCARD gp_Mat2d Inverted() const
{
gp_Mat2d aNewMat = *this;
aNewMat.Invert();
return aNewMat;
}
Standard_NODISCARD gp_Mat2d Multiplied (const gp_Mat2d& theOther) const
{
gp_Mat2d aNewMat2d = *this;
aNewMat2d.Multiply (theOther);
return aNewMat2d;
}
Standard_NODISCARD gp_Mat2d operator * (const gp_Mat2d& theOther) const { return Multiplied (theOther); }
//! Computes the product of two matrices <me> * <theOther>
void Multiply (const gp_Mat2d& theOther);
//! Modifies this matrix by premultiplying it by the matrix Other
//! <me> = theOther * <me>.
void PreMultiply (const gp_Mat2d& theOther);
Standard_NODISCARD gp_Mat2d Multiplied (const Standard_Real theScalar) const;
Standard_NODISCARD gp_Mat2d operator * (const Standard_Real theScalar) const { return Multiplied (theScalar); }
//! Multiplies all the coefficients of the matrix by a scalar.
void Multiply (const Standard_Real theScalar);
void operator *= (const Standard_Real theScalar) { Multiply (theScalar); }
Standard_EXPORT void Power (const Standard_Integer theN);
//! computes <me> = <me> * <me> * .......* <me>, theN time.
//! if theN = 0 <me> = Identity
//! if theN < 0 <me> = <me>.Invert() *...........* <me>.Invert().
//! If theN < 0 an exception can be raised if the matrix is not
//! inversible
Standard_NODISCARD gp_Mat2d Powered (const Standard_Integer theN) const
{
gp_Mat2d aMat2dN = *this;
aMat2dN.Power (theN);
return aMat2dN;
}
void Subtract (const gp_Mat2d& theOther);
void operator -= (const gp_Mat2d& theOther) { Subtract (theOther); }
//! Computes for each coefficient of the matrix :
//! @code
//! <me>.Coef(i,j) - <theOther>.Coef(i,j)
//! @endcode
Standard_NODISCARD gp_Mat2d Subtracted (const gp_Mat2d& theOther) const;
Standard_NODISCARD gp_Mat2d operator - (const gp_Mat2d& theOther) const { return Subtracted (theOther); }
void Transpose();
//! Transposes the matrix. A(j, i) -> A (i, j)
Standard_NODISCARD gp_Mat2d Transposed() const;
friend class gp_Trsf2d;
friend class gp_GTrsf2d;
friend class gp_XY;
private:
Standard_Real myMat[2][2];
};
//=======================================================================
//function : SetRotation
// purpose :
//=======================================================================
inline void gp_Mat2d::SetRotation (const Standard_Real theAng)
{
Standard_Real aSinA = sin (theAng);
Standard_Real aCosA = cos (theAng);
myMat[0][0] = myMat[1][1] = aCosA;
myMat[0][1] = -aSinA;
myMat[1][0] = aSinA;
}
//=======================================================================
//function : Add
// purpose :
//=======================================================================
inline void gp_Mat2d::Add (const gp_Mat2d& theOther)
{
myMat[0][0] += theOther.myMat[0][0];
myMat[0][1] += theOther.myMat[0][1];
myMat[1][0] += theOther.myMat[1][0];
myMat[1][1] += theOther.myMat[1][1];
}
//=======================================================================
//function : Added
// purpose :
//=======================================================================
inline gp_Mat2d gp_Mat2d::Added (const gp_Mat2d& theOther) const
{
gp_Mat2d aNewMat2d;
aNewMat2d.myMat[0][0] = myMat[0][0] + theOther.myMat[0][0];
aNewMat2d.myMat[0][1] = myMat[0][1] + theOther.myMat[0][1];
aNewMat2d.myMat[1][0] = myMat[1][0] + theOther.myMat[1][0];
aNewMat2d.myMat[1][1] = myMat[1][1] + theOther.myMat[1][1];
return aNewMat2d;
}
//=======================================================================
//function : Divide
// purpose :
//=======================================================================
inline void gp_Mat2d::Divide (const Standard_Real theScalar)
{
myMat[0][0] /= theScalar;
myMat[0][1] /= theScalar;
myMat[1][0] /= theScalar;
myMat[1][1] /= theScalar;
}
//=======================================================================
//function : Divided
// purpose :
//=======================================================================
inline gp_Mat2d gp_Mat2d::Divided (const Standard_Real theScalar) const
{
gp_Mat2d aNewMat2d;
aNewMat2d.myMat[0][0] = myMat[0][0] / theScalar;
aNewMat2d.myMat[0][1] = myMat[0][1] / theScalar;
aNewMat2d.myMat[1][0] = myMat[1][0] / theScalar;
aNewMat2d.myMat[1][1] = myMat[1][1] / theScalar;
return aNewMat2d;
}
//=======================================================================
//function : Multiply
// purpose :
//=======================================================================
inline void gp_Mat2d::Multiply (const gp_Mat2d& theOther)
{
const Standard_Real aT00 = myMat[0][0] * theOther.myMat[0][0] + myMat[0][1] * theOther.myMat[1][0];
const Standard_Real aT10 = myMat[1][0] * theOther.myMat[0][0] + myMat[1][1] * theOther.myMat[1][0];
myMat[0][1] = myMat[0][0] * theOther.myMat[0][1] + myMat[0][1] * theOther.myMat[1][1];
myMat[1][1] = myMat[1][0] * theOther.myMat[0][1] + myMat[1][1] * theOther.myMat[1][1];
myMat[0][0] = aT00;
myMat[1][0] = aT10;
}
//=======================================================================
//function : PreMultiply
// purpose :
//=======================================================================
inline void gp_Mat2d::PreMultiply (const gp_Mat2d& theOther)
{
const Standard_Real aT00 = theOther.myMat[0][0] * myMat[0][0]
+ theOther.myMat[0][1] * myMat[1][0];
myMat[1][0] = theOther.myMat[1][0] * myMat[0][0]
+ theOther.myMat[1][1] * myMat[1][0];
const Standard_Real aT01 = theOther.myMat[0][0] * myMat[0][1]
+ theOther.myMat[0][1] * myMat[1][1];
myMat[1][1] = theOther.myMat[1][0] * myMat[0][1]
+ theOther.myMat[1][1] * myMat[1][1];
myMat[0][0] = aT00;
myMat[0][1] = aT01;
}
//=======================================================================
//function : Multiplied
// purpose :
//=======================================================================
inline gp_Mat2d gp_Mat2d::Multiplied (const Standard_Real theScalar) const
{
gp_Mat2d aNewMat2d;
aNewMat2d.myMat[0][0] = myMat[0][0] * theScalar;
aNewMat2d.myMat[0][1] = myMat[0][1] * theScalar;
aNewMat2d.myMat[1][0] = myMat[1][0] * theScalar;
aNewMat2d.myMat[1][1] = myMat[1][1] * theScalar;
return aNewMat2d;
}
//=======================================================================
//function : Multiply
// purpose :
//=======================================================================
inline void gp_Mat2d::Multiply (const Standard_Real theScalar)
{
myMat[0][0] *= theScalar;
myMat[0][1] *= theScalar;
myMat[1][0] *= theScalar;
myMat[1][1] *= theScalar;
}
//=======================================================================
//function : Subtract
// purpose :
//=======================================================================
inline void gp_Mat2d::Subtract (const gp_Mat2d& theOther)
{
myMat[0][0] -= theOther.myMat[0][0];
myMat[0][1] -= theOther.myMat[0][1];
myMat[1][0] -= theOther.myMat[1][0];
myMat[1][1] -= theOther.myMat[1][1];
}
//=======================================================================
//function : Subtracted
// purpose :
//=======================================================================
inline gp_Mat2d gp_Mat2d::Subtracted (const gp_Mat2d& theOther) const
{
gp_Mat2d aNewMat2d;
aNewMat2d.myMat[0][0] = myMat[0][0] - theOther.myMat[0][0];
aNewMat2d.myMat[0][1] = myMat[0][1] - theOther.myMat[0][1];
aNewMat2d.myMat[1][0] = myMat[1][0] - theOther.myMat[1][0];
aNewMat2d.myMat[1][1] = myMat[1][1] - theOther.myMat[1][1];
return aNewMat2d;
}
//=======================================================================
//function : Transpose
// purpose :
//=======================================================================
inline void gp_Mat2d::Transpose()
{
const Standard_Real aTemp = myMat[0][1];
myMat[0][1] = myMat[1][0];
myMat[1][0] = aTemp;
}
//=======================================================================
//function : Transposed
// purpose :
//=======================================================================
inline gp_Mat2d gp_Mat2d::Transposed() const
{
gp_Mat2d aNewMat2d;
aNewMat2d.myMat[1][0] = myMat[0][1];
aNewMat2d.myMat[0][1] = myMat[1][0];
aNewMat2d.myMat[0][0] = myMat[0][0];
aNewMat2d.myMat[1][1] = myMat[1][1];
return aNewMat2d;
}
//=======================================================================
//function : operator*
// purpose :
//=======================================================================
inline gp_Mat2d operator* (const Standard_Real theScalar, const gp_Mat2d& theMat2D)
{
return theMat2D.Multiplied (theScalar);
}
#endif // _gp_Mat2d_HeaderFile
|
#include "Button.h"
Button::Button(byte pin) {
this->pin = pin;
this->pin_mode = INPUT; // Assume INPUT if not specified
// Using INPUT_PULLUP, so everything is flipped.
//lastReading = LOW;
lastReading = HIGH;
init();
}
Button::Button(byte pin, byte pin_mode, bool isInterruptButton, long debounceDelay) {
this->pin = pin;
this->pin_mode = pin_mode;
this->isInterruptButton = isInterruptButton;
this->debounceDelay = debounceDelay;
if (pin_mode == INPUT_PULLUP) {
// Using INPUT_PULLUP, so everything is flipped, i.e. HIGH == not pressed
lastReading = HIGH;
}
else {
lastReading = LOW;
}
init();
}
void Button::init() {
pinMode(pin, pin_mode);
update();
}
void Button::update() {
// You can handle the debounce of the button directly
// in the class, so you don't have to think about it
// elsewhere in your code
byte newReading = digitalRead(pin);
if (newReading != lastReading) {
lastDebounceTime = millis();
}
if (millis() - lastDebounceTime > debounceDelay) {
// Update the 'state' attribute only if debounce is checked
state = newReading;
}
lastReading = newReading;
}
byte Button::getState() {
update();
return state;
}
bool Button::isPressed() {
bool result = false;
// The logic for determining a button press differs when the button triggers an interrupt (the if clause)
// vs when we're trying to detect a button press in the loop (the else clause).
// I'm not sure why this is the case, but this code works in those two scenarios.
if (isInterruptButton) {
if ((millis() - lastDebounceTime) >= debounceDelay) {
result = true;
// not sure if this should be current millis() or millis() from the if statement above.
lastDebounceTime = millis();
}
}
else {
if (pin_mode == INPUT_PULLUP) {
// Using INPUT_PULLUP, so everything is flipped.
result = (getState() == LOW);
}
else {
result = (getState() == HIGH);
}
}
return result;
}
void Button::printStatus() {
Serial.print("debounceDelay: ");
Serial.println(debounceDelay);
Serial.print("lastDebounceTime: ");
Serial.println(lastDebounceTime);
}
|
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main(int argc, char** argv){
ifstream input;
input.open("chairs.in", ios::in);
int a, b, c;
input>>a>>b>>c;
input.close();
double ans;
cout<<fixed<<showpoint;
cout<<setprecision(30);
ans = ((double)(a + b+ c)/2)/3;
ofstream output;
output.open("chairs.out", ios::out);
output<<setprecision(30)<<ans;
cout<<ans;
output.close();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.