text
stringlengths 8
6.88M
|
|---|
#include "GameHandler.h"
GameHandler::GameHandler(WindowRef ref) {
setWindow(ref);
Background = new GameLayer(ref);
MainLayer = new GameLayer(ref);
UI = new GameLayer(ref);
}
void GameHandler::setWindow(WindowRef window) {
this->window = window;
}
void GameHandler::drawGame() {
Background->drawLayer();
MainLayer->drawLayer();
UI->drawLayer();
}
GameHandler::~GameHandler() {
}
|
/*
* subckt.h
*
* Created on: Nov 25, 2012
* Author: chjd
*/
#ifndef SUBCKT_H_
#define SUBCKT_H_
class Subckt
{
public:
Subckt(string nm):name(nm){}
void AddNode(int p){node.push_back(p);}
void AddParam(string nm,double v=0){
paramMap.insert(make_pair(nm,new ParamNode(v)));
}
void AddElem(Elem* elem){elemList.push_back(elem);}
~Subckt(){
for(auto it=paramMap.begin(),et=paramMap.end();it!=et;it++)
{
delete (*it);
(*it) = nullptr;
}
}
private:
// subckt name
string name;
public:
ArrayNode node;
list<Elem*> elemList;
unordered_map<string,ParamNode*> paramMap;
};
#endif /* SUBCKT_H_ */
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder 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 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder 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 FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#include "xmlhighlighter.h"
XmlHighlighter::XmlHighlighter(QTextDocument *document)
: QSyntaxHighlighter(document)
{
QTextCharFormat entityFormat;
entityFormat.setForeground(QColor(0, 128, 0));
entityFormat.setFontWeight(QFont::Normal);
setFormatFor(Entity, entityFormat);
QTextCharFormat tagFormat;
tagFormat.setForeground(QColor("#f0e68c"));
tagFormat.setFontWeight(QFont::Normal);
setFormatFor(Tag, tagFormat);
QTextCharFormat commentFormat;
commentFormat.setForeground(QColor("#87ceeb"));
commentFormat.setFontItalic(true);
setFormatFor(Comment, commentFormat);
QTextCharFormat codeFormat;
codeFormat.setForeground(QColor("#ff9e00"));
setFormatFor(Code, codeFormat);
}
void XmlHighlighter::setFormatFor(Construct construct, const QTextCharFormat &format)
{
m_formats[construct] = format;
rehighlight();
}
void XmlHighlighter::highlightBlock(const QString &text)
{
int state = previousBlockState();
int len = text.length();
int start = 0;
int pos = 0;
while (pos < len)
{
switch (state)
{
case NormalState:
default:
while (pos < len)
{
QChar ch = text.at(pos);
if (ch == '<')
{
if (text.mid(pos, 4) == "<!--")
{
state = InComment;
}
else
{
state = InTag;
}
break;
}
else if (ch == '&')
{
start = pos;
while (pos < len && text.at(pos++) != ';')
;
setFormat(start, pos - start, m_formats[Entity]);
}
else if(ch == "{")
{
if(text.mid(pos, 2) == "{{")
{
state = InVar;
break;
}
else if(text.mid(pos, 2) == "{%")
{
state = InLoop;
break;
}
pos++;
break;
}
else
{
pos++;
}
}
break;
case InVar:
start = pos;
while (pos < len)
{
if(text.mid(pos, 2) == "}}")
{
pos += 2;
state = NormalState;
break;
}
else
pos++;
}
setFormat(start, pos - start, m_formats[Code]);
break;
case InLoop:
start = pos;
while (pos < len)
{
if(text.mid(pos, 2) == "%}")
{
pos += 2;
state = NormalState;
break;
}
else
pos++;
}
setFormat(start, pos - start, m_formats[Code]);
break;
case InComment:
start = pos;
while (pos < len)
{
if (text.mid(pos, 3) == "-->")
{
pos += 3;
state = NormalState;
break;
}
else
{
pos++;
}
}
setFormat(start, pos - start, m_formats[Comment]);
break;
case InTag:
QChar quote = QChar::Null;
start = pos;
while (pos < len)
{
QChar ch = text.at(pos);
if (quote.isNull())
{
if (ch == "\"" || ch == '"')
{
quote = ch;
}
else if (ch == '>')
{
pos++;
state = NormalState;
break;
}
}
else if (ch == quote)
{
quote = QChar::Null;
}
pos++;
}
setFormat(start, pos - start, m_formats[Tag]);
break;
}
}
setCurrentBlockState(state);
}
|
class ArmoredSUV_DZE_Base_PMC: Car
{
scope = 0;
brakeDistance = 19;
vehicleClass = "DayZ Epoch Vehicles";
htMin = 60;
htMax = 1800;
afMax = 200;
mfMax = 100;
mFact = 1;
tBody = 200;
expansion = 4;
displayName = "SUV (Armored)";
model = "\Ca\Wheeled_PMC\ArmoredSUV\armoredSUV_PMC.p3d";
icon = "\ca\Wheeled_PMC\data\ui\Icon_suv_minigun_PMC.paa";
picture = "\ca\Wheeled_PMC\data\ui\Picture_suv_minigun_PMC_ca.paa";
mapSize = 7;
maxSpeed = 230;
accuracy = 0.2;
armor = 120;
damageResistance = 0.03099;
transportSoldier = 3;
fuelCapacity = 130;
enableGPS = 0;
supplyRadius = 1.3;
weapons[] = {"MiniCarHorn"};
driverAction = "SUV_Driver_EP1";
cargoAction[] = {"SUV_Cargo_EP1","SUV_Cargo02_EP1","SUV_Cargo01_EP1"};
outsideSoundFilter = 1;
insideSoundCoef = 0.8;
soundGear[] = {"",5.62341e-005,1};
soundGetIn[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_door",0.56234133,1,20};
soundGetOut[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_door",0.562341,1,20};
soundEngineOnInt[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_int_start",0.177828,1};
soundEngineOnExt[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_start",0.177828,1,100};
soundEngineOffInt[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_int_stop",0.177828,1};
soundEngineOffExt[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_stop",0.177828,1,100};
buildCrash0[] = {"Ca\sounds\Vehicles\Crash\crash_building_01",0.707946,1,200};
buildCrash1[] = {"Ca\sounds\Vehicles\Crash\crash_building_02",0.707946,1,200};
buildCrash2[] = {"Ca\sounds\Vehicles\Crash\crash_building_03",0.707946,1,200};
buildCrash3[] = {"Ca\sounds\Vehicles\Crash\crash_building_04",0.707946,1,200};
soundBuildingCrash[] = {"buildCrash0",0.25,"buildCrash1",0.25,"buildCrash2",0.25,"buildCrash3",0.25};
WoodCrash0[] = {"Ca\sounds\Vehicles\Crash\crash_mix_wood_01",0.707946,1,200};
WoodCrash1[] = {"Ca\sounds\Vehicles\Crash\crash_mix_wood_02",0.707946,1,200};
WoodCrash2[] = {"Ca\sounds\Vehicles\Crash\crash_mix_wood_03",0.707946,1,200};
WoodCrash3[] = {"Ca\sounds\Vehicles\Crash\crash_mix_wood_04",0.707946,1,200};
WoodCrash4[] = {"Ca\sounds\Vehicles\Crash\crash_mix_wood_05",0.707946,1,200};
WoodCrash5[] = {"Ca\sounds\Vehicles\Crash\crash_mix_wood_06",0.707946,1,200};
soundWoodCrash[] = {"woodCrash0",0.166,"woodCrash1",0.166,"woodCrash2",0.166,"woodCrash3",0.166,"woodCrash4",0.166,"woodCrash5",0.166};
ArmorCrash0[] = {"Ca\sounds\Vehicles\Crash\crash_vehicle_01",0.707946,1,200};
ArmorCrash1[] = {"Ca\sounds\Vehicles\Crash\crash_vehicle_02",0.707946,1,200};
ArmorCrash2[] = {"Ca\sounds\Vehicles\Crash\crash_vehicle_03",0.707946,1,200};
ArmorCrash3[] = {"Ca\sounds\Vehicles\Crash\crash_vehicle_04",0.707946,1,200};
soundArmorCrash[] = {"ArmorCrash0",0.25,"ArmorCrash1",0.25,"ArmorCrash2",0.25,"ArmorCrash3",0.25};
class SoundEvents
{
class AccelerationIn
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_int_accelerate_3_x",0.562341,1};
limit = "0.4";
expression = "(engineOn*(1-camPos))*gmeterZ";
};
class AccelerationOut
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_accelerate_3",0.562341,1,200};
limit = "0.4";
expression = "(engineOn*camPos)*gmeterZ";
};
};
class Sounds
{
class Engine
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_low",0.177828,1.4,100};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "camPos*engineOn*((rpm factor[0.3, 0.4]) min (rpm factor[0.7, 0.5]))";
};
class EngineHighOut
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_high",1,0.8,300};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "camPos*engineOn*(rpm factor[0.5, 0.8])";
};
class IdleOut
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_ext_idle",0.562341,1,100};
frequency = "1";
volume = "engineOn*camPos*(rpm factor[0.4, 0])";
};
class TiresRockOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-rock2",0.316228,1,30};
frequency = "1";
volume = "camPos*rock*(speed factor[2, 20])";
};
class TiresSandOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-sand2",0.316228,1,30};
frequency = "1";
volume = "camPos*sand*(speed factor[2, 20])";
};
class TiresGrassOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-grass2",0.316228,1,30};
frequency = "1";
volume = "camPos*grass*(speed factor[2, 20])";
};
class TiresMudOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-mud2",0.316228,1,30};
frequency = "1";
volume = "camPos*mud*(speed factor[2, 20])";
};
class TiresGravelOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-gravel2",0.316228,1,30};
frequency = "1";
volume = "camPos*gravel*(speed factor[2, 20])";
};
class TiresAsphaltOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\ext\ext-tires-asphalt3",0.316228,1,30};
frequency = "1";
volume = "camPos*asphalt*(speed factor[2, 20])";
};
class NoiseOut
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Noises\ext\noise2",0.1,1,30};
frequency = "1";
volume = "camPos*(damper0 max 0.03)*(speed factor[0, 8])";
};
class EngineLowIn
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_int_low_x",0.316228,1.4};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "(1-camPos)*engineOn*((rpm factor[0.3, 0.4]) min (rpm factor[0.7, 0.45]))";
};
class EngineHighIn
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_int_high_x",1,0.8};
frequency = "(randomizer*0.05+0.95)*rpm";
volume = "(1-camPos)*engineOn*(rpm factor[0.5, 0.8])";
};
class IdleIn
{
sound[] = {"ca\Sounds_E\Wheeled_E\SUV\SUV_int_idle_x",0.316228,1};
frequency = "1";
volume = "engineOn*(rpm factor[0.4, 0])*(1-camPos)";
};
class TiresRockIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-rock2",0.316228,1};
frequency = "1";
volume = "(1-camPos)*rock*(speed factor[2, 20])";
};
class TiresSandIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-sand2",0.316228,1};
frequency = "1";
volume = "(1-camPos)*sand*(speed factor[2, 20])";
};
class TiresGrassIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-grass2",0.316228,1};
frequency = "1";
volume = "(1-camPos)*grass*(speed factor[2, 20])";
};
class TiresMudIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-mud2",0.316228,1};
frequency = "1";
volume = "(1-camPos)*mud*(speed factor[2, 20])";
};
class TiresGravelIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-gravel2",0.316228,1};
frequency = "1";
volume = "(1-camPos)*gravel*(speed factor[2, 20])";
};
class TiresAsphaltIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Tires\int\int-tires-asphalt3",0.316228,1};
frequency = "1";
volume = "(1-camPos)*asphalt*(speed factor[2, 20])";
};
class NoiseIn
{
sound[] = {"\ca\SOUNDS\Vehicles\Wheeled\Noises\int\noise2",0.177828,1};
frequency = "1";
volume = "(damper0 max 0.03)*(speed factor[0, 8])*(1-camPos)";
};
class Movement
{
sound = "soundEnviron";
frequency = "1";
volume = "0";
};
};
class Turrets: Turrets
{
class MainTurret: MainTurret
{
};
};
class HitPoints: HitPoints
{
class HitLFWheel: HitLFWheel
{
armor = 0.15000001;
};
class HitLBWheel: HitLBWheel
{
armor = 0.15000001;
};
class HitRFWheel: HitRFWheel
{
armor = 0.15000001;
};
class HitRBWheel: HitRBWheel
{
armor = 0.15000001;
};
class HitFuel: HitFuel
{
armor = 1;
passThrough = 1;
};
class HitEngine: HitEngine
{
armor = 1;
passThrough = 1;
};
class HitGlass1: HitGlass1
{
armor = 1;
};
class HitGlass2: HitGlass2
{
armor = 1;
};
class HitGlass3: HitGlass3
{
armor = 1;
};
class HitGlass4: HitGlass4
{
armor = 1;
};
};
class Damage
{
tex[] = {};
mat[] = {"Ca\Wheeled_PMC\ArmoredSUV\data\SUV_body.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_body_damage.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_body_destruct.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_chrom.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_chrom_damage.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_chrom_destruct.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_glass.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_glass_damage.rvmat","Ca\Wheeled_PMC\ArmoredSUV\data\SUV_glass_destruct.rvmat","Ca\Ca_E\data\default.rvmat","Ca\Ca_E\data\default.rvmat","Ca\Ca_E\data\default_destruct.rvmat"};
};
class Library
{
libTextDesc = "An SUV (Sport Utility Vehicle) is a generic marketing term for a vehicle similar to a station wagon, but built on a light-truck chassis. These particular SUVs are up-armored to protect the security operators inside from small-arms fire. This model has been outfitted with a M134 7.62mm Minigun, which can be retracted back into the vehicle.<br /><br /> ""Black Betty"" is a nickname often used for this vehicle by ION Inc. contractors.";
};
class UserActions {
class OpenHatch {
displayName = $STR_AM_OPENGUNNER;
displayNameDefault = $STR_AM_OPENGUNNER;
priority = 0;
position = "zamerny";
showWindow = 0;
radius = 1;
onlyForPlayer = 1;
condition = "this animationPhase 'HideGun_01' == 1";
statement = "this animate ['HideGun_01',0]; this animate ['CloseCover1',0]; this animate ['CloseCover2',0];";
};
class CloseHatch {
displayName = $STR_AM_CLOSEGUNNER;
displayNameDefault = $STR_AM_CLOSEGUNNER;
priority = 0;
position = "zamerny";
showWindow = 0;
radius = 1;
onlyForPlayer = 1;
condition = "isNull (this turretUnit [0]) && (this animationPhase 'HideGun_01' == 0)";
statement = "this animate ['HideGun_01',1]; this spawn {uiSleep 1; _this animate ['CloseCover1',1]; _this animate ['CloseCover2',1];};";
};
};
};
class ArmoredSUV_PMC_DZ: ArmoredSUV_DZE_Base_PMC
{
scope = 2;
side = 2;
faction = "PMC_BAF";
displayName = "$STR_VEH_NAME_SUV_ARMORED";
crew = "";
armor = 80;
typicalCargo[] = {};
class TransportMagazines {};
class TransportWeapons {};
transportMaxWeapons = 20;
transportMaxMagazines = 150;
transportmaxbackpacks = 10;
class Turrets: Turrets
{
class MainTurret: MainTurret
{
body = "mainTurret";
gun = "mainGun";
viewGunnerInExternal = 1;
minElev = -30;
maxElev = 45;
initElev = 0;
soundServo[] = {"\ca\sounds\vehicles\servos\turret-1",0.031622775,1,15};
animationSourceHatch = "";
stabilizedInAxes = "StabilizedInAxesNone";
gunBeg = "muzzle_1";
gunEnd = "chamber_1";
weapons[] = {"M134"};
maxHorizontalRotSpeed = 1.8;
maxVerticalRotSpeed = 1.8;
magazines[] = {"2000Rnd_762x51_M134"};
gunnerAction = "ArmoredSUV_Gunner_PMC";
};
};
class AnimationSources: AnimationSources
{
class Revolving
{
source = "revolving";
weapon = "M134";
};
class HideGun_01
{
source = "user";
initPhase = 0;
animPeriod = 1.2;
};
class HideGun_02: HideGun_01
{
};
class HideGun_03: HideGun_01
{
};
class HideGun_04: HideGun_01
{
};
class CloseCover1
{
source = "user";
initPhase = 0;
animPeriod = 0.7;
};
class CloseCover2: CloseCover1
{
};
};
};
class ArmoredSUV_PMC_DZE: ArmoredSUV_PMC_DZ
{
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {};
};
};
class Upgrades
{
ItemORP[] = {"ArmoredSUV_PMC_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",4},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class ArmoredSUV_PMC_DZE1: ArmoredSUV_PMC_DZE
{
displayName = "$STR_VEH_NAME_SUV_ARMORED+";
original = "ArmoredSUV_PMC_DZE";
maxSpeed = 270; //increased speed slightly since original is 230
brakeDistance = 14;
terrainCoef = 1.5;
class Upgrades
{
ItemAVE[] = {"ArmoredSUV_PMC_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",10},{"ItemScrews",1}}};
};
};
class ArmoredSUV_PMC_DZE2: ArmoredSUV_PMC_DZE1
{
displayName = "$STR_VEH_NAME_SUV_ARMORED++";
armor = 200;
class HitPoints: HitPoints
{
class HitLFWheel: HitLFWheel
{
armor = 0.5;
};
class HitLBWheel: HitLBWheel
{
armor = 0.5;
};
class HitRFWheel: HitRFWheel
{
armor = 0.5;
};
class HitRBWheel: HitRBWheel
{
armor = 0.5;
};
class HitFuel: HitFuel
{
armor = 0.5;
};
class HitEngine: HitEngine
{
armor = 1;
};
class HitGlass1: HitGlass1
{
armor = 2;
};
class HitGlass2: HitGlass2
{
armor = 2;
};
class HitGlass3: HitGlass3
{
armor = 2;
};
class HitGlass4: HitGlass4
{
armor = 2;
};
};
class Upgrades
{
ItemLRK[] = {"ArmoredSUV_PMC_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class ArmoredSUV_PMC_DZE3: ArmoredSUV_PMC_DZE2
{
displayName = "$STR_VEH_NAME_SUV_ARMORED+++";
transportMaxWeapons = 40;
transportMaxMagazines = 400;
transportmaxbackpacks = 15;
class Upgrades
{
ItemTNK[] = {"ArmoredSUV_PMC_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",6},{"PartFueltank",2},{"ItemFuelBarrel",1}}};
};
};
class ArmoredSUV_PMC_DZE4: ArmoredSUV_PMC_DZE3
{
displayName = "$STR_VEH_NAME_SUV_ARMORED++++";
fuelCapacity = 250;
};
class ArmoredSUV_PKT_DZ: ArmoredSUV_PMC_DZ
{
displayName = "$STR_VEH_NAME_SUV_PKT_ARMORED";
class Turrets: Turrets
{
class MainTurret: MainTurret
{
weapons[] = {"PKTBC"};
magazines[] = {"100Rnd_762x54_PK","100Rnd_762x54_PK","100Rnd_762x54_PK"};
};
};
};
class ArmoredSUV_PKT_DZE: ArmoredSUV_PKT_DZ
{
class Turrets: Turrets
{
class MainTurret: MainTurret
{
magazines[] = {};
};
};
class Upgrades
{
ItemORP[] = {"ArmoredSUV_PKT_DZE1",{"ItemToolbox"},{},{{"ItemORP",1},{"PartEngine",4},{"PartWheel",4},{"ItemScrews",2}}};
};
};
class ArmoredSUV_PKT_DZE1: ArmoredSUV_PKT_DZE
{
displayName = "$STR_VEH_NAME_SUV_PKT_ARMORED+";
original = "ArmoredSUV_PKT_DZE";
maxSpeed = 270; //increased speed slightly since original is 230
brakeDistance = 14;
terrainCoef = 1.5;
class Upgrades
{
ItemAVE[] = {"ArmoredSUV_PKT_DZE2",{"ItemToolbox"},{},{{"ItemAVE",1 },{"equip_metal_sheet",10},{"ItemScrews",1}}};
};
};
class ArmoredSUV_PKT_DZE2: ArmoredSUV_PKT_DZE1
{
displayName = "$STR_VEH_NAME_SUV_PKT_ARMORED++";
armor = 200;
class HitPoints: HitPoints
{
class HitLFWheel: HitLFWheel
{
armor = 0.5;
};
class HitLBWheel: HitLBWheel
{
armor = 0.5;
};
class HitRFWheel: HitRFWheel
{
armor = 0.5;
};
class HitRBWheel: HitRBWheel
{
armor = 0.5;
};
class HitFuel: HitFuel
{
armor = 0.5;
};
class HitEngine: HitEngine
{
armor = 1;
};
class HitGlass1: HitGlass1
{
armor = 2;
};
class HitGlass2: HitGlass2
{
armor = 2;
};
class HitGlass3: HitGlass3
{
armor = 2;
};
class HitGlass4: HitGlass4
{
armor = 2;
};
};
class Upgrades
{
ItemLRK[] = {"ArmoredSUV_PKT_DZE3",{"ItemToolbox"},{},{{"ItemLRK",1},{"PartGeneric",4},{"ItemWoodCrateKit",2},{"ItemGunRackKit",2},{"ItemScrews",2}}};
};
};
class ArmoredSUV_PKT_DZE3: ArmoredSUV_PKT_DZE2
{
displayName = "$STR_VEH_NAME_SUV_PKT_ARMORED+++";
transportMaxWeapons = 40;
transportMaxMagazines = 400;
transportmaxbackpacks = 15;
class Upgrades
{
ItemTNK[] = {"ArmoredSUV_PKT_DZE4",{"ItemToolbox"},{},{{"ItemTNK",1},{"PartGeneric",6},{"PartFueltank",2},{"ItemFuelBarrel",1}}};
};
};
class ArmoredSUV_PKT_DZE4: ArmoredSUV_PKT_DZE3
{
displayName = "$STR_VEH_NAME_SUV_PKT_ARMORED++++";
fuelCapacity = 250;
};
|
#ifndef _BASE_VECTOR_4
#define _BASE_VECTOR_4
#ifdef _PSP_VER
#include <libgum.h>
#else
#include <D3dx9math.h>
#endif
class BaseVector4
{
protected:
BaseVector4(void) {}
public:
virtual ~BaseVector4(void) {}
public:
#ifdef _PSP_VER
ScePspFVector4& GetVector(void) { return _vec; }
const ScePspFVector4& GetVector(void) const { return _vec; }
protected:
ScePspFVector4 _vec;
#else
D3DXVECTOR4& GetVector(void) { return _vec; }
const D3DXVECTOR4& GetVector(void) const { return _vec; }
protected:
D3DXVECTOR4 _vec;
#endif
};
#endif
|
//====================================================================================
// @Title: CARTESIAN
//------------------------------------------------------------------------------------
// @Location: /prolix/common/include/cCartesian.cpp
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//====================================================================================
#include "../include/cCartesian.h"
#include "../include/xString.h"
#include "../include/xDraw.h"
//====================================================================================
// cCartesian
//====================================================================================
cCartesian::cCartesian(int rX, int rY):
x(rX),
y(rY)
{
}
cCartesian::cCartesian(float rX, float rY):
x((int)rX),
y((int)rY)
{
}
cCartesian::cCartesian(double rX, double rY):
x((int)rX),
y((int)rY)
{
}
std::string cCartesian::Format()
{
return "(" + toString(x) + "," + toString(y) + ")";
}
//====================================================================================
// Point
//====================================================================================
Point::Point(int rX, int rY):
cCartesian(rX, rY)
{
}
Point::Point(float rX, float rY):
cCartesian((int)rX, (int)rY)
{
}
Point::Point(double rX, double rY):
cCartesian((int)rX, (int)rY)
{
}
void Point::Center(Dimensions dim)
{
x -= dim.w/2;
y -= dim.h/2;
}
Point operator +(Point pos1, Point pos2)
{
return Point(pos1.x + pos2.x, pos1.y + pos2.y);
}
Point operator -(Point pos1, Point pos2)
{
return Point(pos1.x - pos2.x, pos1.y - pos2.y);
}
bool operator ==(Point pos1, Point pos2)
{
return pos1.x == pos2.x && pos1.y == pos2.y;
}
bool operator !=(Point pos1, Point pos2)
{
return pos1.x != pos2.x || pos1.y != pos2.y;
}
//====================================================================================
// Quad
//====================================================================================
Quad::Quad(Point tl, Point tr, Point bl, Point br)
{
top_left = tl;
top_right = tr;
bottom_left = bl;
bottom_right = br;
}
|
#ifndef COMMON_THREAD_THREAD_INSTANCE_H_
#define COMMON_THREAD_THREAD_INSTANCE_H_
#include <cstdint>
#include <set>
#include <memory>
#include "common/thread/lock.h"
#include "common/thread/lock_guard.h"
#include "common/thread/threading.h"
namespace common {
// quite same with singleton
// but each thread owns a unique instance
template <typename T>
class ThreadInstance {
typedef std::set<std::shared_ptr<T> > InstanceSet;
public:
ThreadInstance() { };
virtual ~ThreadInstance() { }
static inline std::shared_ptr<T> instance() {
if (!registered_) {
LockGuard<MutexLock> guard(&lock_);
instances_.insert(instance_);
registered_ = true;
}
return instance_;
}
static inline bool set_instance(const std::shared_ptr<T>& inst) {
if (!registered_) {
instance_ = inst;
LockGuard<MutexLock> guard(&lock_);
instances_.insert(instance_);
registered_ = true;
return true;
}
return false;
}
// return a copy, not a reference
static InstanceSet instances() {
return instances_;
}
private:
static InstanceSet instances_;
static MutexLock lock_;
static thread_local bool registered_;
static thread_local std::shared_ptr<T> instance_;
};
template <typename T>
typename ThreadInstance<T>::InstanceSet ThreadInstance<T>::instances_;
template <typename T>
MutexLock ThreadInstance<T>::lock_;
template <typename T>
thread_local bool ThreadInstance<T>::registered_ = false;
template <typename T>
thread_local std::shared_ptr<T> ThreadInstance<T>::instance_ = std::make_shared<T>();
}
using common::ThreadInstance;
#endif
|
//http://www.codeproject.com/Tips/816934/Min-Binary-Heap-Implementation-in-Cplusplus
#include "vector"
#include "Eigen/Dense"
using namespace std;
class MinHeap
{
private:
void BubbleDown(int index);
void BubbleUp(int index);
void Heapify();
public:
vector<double> _vector;
MinHeap(Eigen::MatrixXd array, int length);
MinHeap(const vector<double>& vector);
MinHeap();
void Insert(double newValue);
double GetMin();
void DeleteMin();
};
|
#pragma once
#include "SDL.h"
#include "TextureManager.h"
#include "LoaderParams.h"
class GameObject {
/* public:
virtual void load(int x, int y, int width, int height, std::string textureID);
virtual void draw(SDL_Renderer* pRenderer);
virtual void update();
virtual void clean() {};
protected:
std::string m_textureID;
int m_x;
int m_y;
int m_width;
int m_height;
int m_currentFrame;
int m_currentRow;
*/
public:
virtual void draw() = 0;
virtual void update() = 0;
virtual void clean() = 0;
virtual ~GameObject() {}
protected:
GameObject(const LoaderParams* pParams) {}
};
|
#include "Function.h"
#include <iostream>
void Parsed::ParseFunc ()
{
int PArg = 0; // parenthesis argument lister
int SArg = 0; // scope argument lister
bool ArgOpened = false;
bool ArgClosed = false;
bool ScopeOpened = false;
bool ScopeClosed = false;
int Pos = 0; // may have to do it -1
for (auto& Statement : this -> Classified)
{
Pos++;
if (Statement.Function)
{
Function Function;
try
{
if (Statement.Args.at (0).compare ("entry") == 0)
{
Function.Name = Statement.Args.at (2);
Function.Entry = true;
}
else
{
Function.Name = Statement.Args.at (1);
Function.Entry = false;
}
Function.ThisScope.Set (Pos, &this -> Classified);
if (Function.Entry == true)
{
try
{
this -> EntryPos = this -> FunctionList.size ();
}
catch (...)
{
}
}
this -> FunctionList.push_back (Function);
Statement.Identifier = this -> FunctionList.size () - 1;
}
catch (...)
{
// error should be written
}
}
}
}
std::string Parsed::CallFunc (Statement* Statement)
{
std::string Data = "call "; // d stands for "data"
try
{
Data.append (Statement -> Args.at (0)).append (" \n");
}
catch (...)
{
return "; error at function call \n";
}
// std::cout << "eh" << std::endl;
return Data;
}
|
#include <iostream>
#include "Image.h"
#define CATCH_CONFIG_MAIN
#include "catch.hpp"
TEST_CASE("Test Load and Save", "[LOAD/SAVE OPERATION]")
{
// buffer for test image
unsigned char* buffer = new unsigned char[16];
for(int i = 0; i < 16; i++) {
buffer[i] = 128 + 4*i;
}
KNGEMI002::Image im_test(4,4, buffer); // test image
im_test.save("Test.pgm");
KNGEMI002::Image im1("Test.pgm");
if (!im1.load()) {
cerr << "Couldn't load Test.pgm" << endl;
}
// saved image identical to loaded image
REQUIRE((im_test == im1));
}
TEST_CASE("Test Addition", "[ADD OPERATION]")
{
// buffer for test image
unsigned char* buffer1 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer1[i] = 100;
}
// buffer for white image
unsigned char* buffer0 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer0[i] = 255;
}
KNGEMI002::Image im_white(2,2, buffer0); // white image
KNGEMI002::Image im_test(2,2, buffer1); // test image
KNGEMI002::Image invert = !im_test; // inverted image
KNGEMI002::Image sum = im_test + invert; // sum of test and inverted image
// sum of test and inverted image should give white image
REQUIRE((sum == im_white));
}
TEST_CASE("Test Invertion", "[INVERT OPERATION]")
{
// buffer for black image
unsigned char* buffer1 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer1[i] = 0;
}
// buffer for white image
unsigned char* buffer0 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer0[i] = 255;
}
KNGEMI002::Image im_white(2,2, buffer0); // white image
KNGEMI002::Image im_black(2,2, buffer1); // test image
KNGEMI002::Image invert = !im_black; // inverted image
// invert of black image should give white image
REQUIRE((invert == im_white));
}
TEST_CASE("Test Subtraction", "[SUBTRACT OPERATION]")
{
// buffer for black image
unsigned char* buffer1 = new unsigned char[4];
for(int i = 0; i < 1; i++) {
buffer1[i] = 0;
}
// buffer for white image
unsigned char* buffer0 = new unsigned char[4];
for(int i = 0; i < 1; i++) {
buffer0[i] = 255;
}
KNGEMI002::Image im_white(1,1, buffer0); // white image
KNGEMI002::Image im_black(1,1, buffer1); // black image
KNGEMI002::Image sub1 = im_white - im_black;
// subtract black image from white image should give white image
REQUIRE((sub1 == im_white));
}
TEST_CASE("Test Mask", "[MASK OPERATION]")
{
// buffer for black image
unsigned char* buffer1 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer1[i] = 0;
}
// buffer for test image
unsigned char* buffer2 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer1[i] = 128;
}
KNGEMI002::Image im_test(2,2, buffer2); // test image
KNGEMI002::Image im_black(2,2, buffer1); // black image
KNGEMI002::Image mask2 = im_test / im_black;
// test image masked by black image should produce the original image
REQUIRE((mask2 == im_test));
}
TEST_CASE("A simple qualitative test", "[QUALITATIVE TEST]")
{
unsigned char* buffer = new unsigned char[169];
int k = 0;
int val = 15;
for(int i = 0; i < 13; i++) {
for(int j = 0; j < 13; j++) {
buffer[k] = val;
}
val += 16;
}
KNGEMI002::Image m(13,13, buffer); // test image m
// create an image mask M1 (via thresholding)
KNGEMI002::Image m1 = m*128;
REQUIRE(m1.get_width() == m.get_width());
REQUIRE(m1.get_height() == m.get_height());
// create an inverted mask of M1 called M2 (by inverting M1)
KNGEMI002::Image m2 = !m1;
REQUIRE(m1.get_width() == m2.get_width());
REQUIRE(m1.get_height() == m2.get_height());
// use M1 and an Image U1 to create a masked image
unsigned char* buffer1 = new unsigned char[169];
int kw = 0;
int valw = 255;
for(int i = 0; i < 13; i++) {
for(int j = 0; j < 13; j++) {
buffer1[k] = val;
}
val -= 16;
}
KNGEMI002::Image u1(13,13, buffer1); // test image u1
KNGEMI002::Image mask1 = m1 / u1;
REQUIRE(mask1.get_width() == u1.get_width());
REQUIRE(mask1.get_height() == u1.get_height());
// use M2 and an Image U2 to create a second masked image
unsigned char* buffer2 = new unsigned char[4];
for(int i = 0; i < 4; i++) {
buffer2[i] = 255;
}
KNGEMI002::Image u2(13,13, buffer2); // test image u2
KNGEMI002::Image mask2 = m2 / u2;
REQUIRE(mask2.get_width() == u2.get_width());
REQUIRE(mask2.get_height() == u2.get_height());
// add the two masked images together to create a new image with pieces of both U1 and U2!
KNGEMI002::Image new_image = mask1 + mask2;
REQUIRE(new_image.get_width() == mask2.get_width());
REQUIRE(new_image.get_height() == mask2.get_height());
}
|
//
// FlowField.h
// yearLong
//
// Created by Surya on 01/04/13.
//
//
#ifndef __yearLong__FlowField__
#define __yearLong__FlowField__
#define ROWS 3
#define COLS 3
#include <iostream>
#include "ofMain.h"
class FlowField{
public:
FlowField();
FlowField(int _resolution, int _w, int _h);
void init();
ofVec2f lookUp(ofVec2f lookup);
int resolution;
int width;
int height;
int cols;
int rows;
// ofVec2f[ROWS][COLS] field;
vector<vector<ofVec2f> > field;
};
#endif /* defined(__yearLong__FlowField__) */
|
#include "stdafx.hpp"
#include "action.hpp"
namespace curses {
// action
action::action(event_handler&& handler) CURSES_NOEXCEPT:
handler_( CURSES_MOVE(event_handler,handler) )
{}
action::~action() CURSES_NOEXCEPT
{}
// signal
signal::signal(const sp_action& action) CURSES_NOEXCEPT:
action_(action)
{}
void signal::emit(const event& e) const
{
action_->emit(e);
}
} // namespace curses
|
//Phoenix_RK
/*
https://leetcode.com/problems/find-the-duplicate-number/
Given an array nums containing n + 1 integers where each integer is between 1 and n (inclusive), prove that at least one duplicate number must exist. Assume that there is only one duplicate number, find the duplicate one.
Example 1:
Input: [1,3,4,2,2]
Output: 2
Example 2:
Input: [3,1,3,4,2]
Output: 3
*/
class Solution {
public:
int findDuplicate(vector<int>& nums) {
int n=nums.size();
for(int i=0;i<n;i++)
{
nums[nums[i]%n]+=n;
if(nums[nums[i]%n]/n==2)
{
return nums[i]%n;
}
}
return -1;
}
};
|
/*
* File: main.cpp
* Author: babang
* Problem: Petya and String
* Created on April 24, 2018, 10:13 PM
*/
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string s, d;
cin >> s >> d;
transform(s.begin(), s.end(), s.begin(), ::tolower);
transform(d.begin(), d.end(), d.begin(), ::tolower);
if (s.compare(d) < 0) cout << -1;
else if (s.compare(d) == 0) cout << 0;
else cout << 1;
return 0;
}
|
// Created on: 1992-04-06
// Created by: Christian CAILLET
// 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 _IGESData_GlobalNodeOfWriterLib_HeaderFile
#define _IGESData_GlobalNodeOfWriterLib_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Transient.hxx>
class IGESData_ReadWriteModule;
class IGESData_Protocol;
class IGESData_IGESEntity;
class IGESData_WriterLib;
class IGESData_NodeOfWriterLib;
class IGESData_GlobalNodeOfWriterLib;
DEFINE_STANDARD_HANDLE(IGESData_GlobalNodeOfWriterLib, Standard_Transient)
class IGESData_GlobalNodeOfWriterLib : public Standard_Transient
{
public:
//! Creates an empty GlobalNode, with no Next
Standard_EXPORT IGESData_GlobalNodeOfWriterLib();
//! Adds a Module bound with a Protocol to the list:
//! does nothing if already in the list,
//! THAT IS, Same Type (exact match) and Same State (that is, IsEqual is not required).
//! Once added, stores its attached Protocol in correspondence
Standard_EXPORT void Add (const Handle(IGESData_ReadWriteModule)& amodule, const Handle(IGESData_Protocol)& aprotocol);
//! Returns the Module stored in a given GlobalNode
Standard_EXPORT const Handle(IGESData_ReadWriteModule)& Module() const;
//! Returns the attached Protocol stored in a given GlobalNode
Standard_EXPORT const Handle(IGESData_Protocol)& Protocol() const;
//! Returns the Next GlobalNode. If none is defined, returned
//! value is a Null Handle
Standard_EXPORT const Handle(IGESData_GlobalNodeOfWriterLib)& Next() const;
DEFINE_STANDARD_RTTI_INLINE(IGESData_GlobalNodeOfWriterLib,Standard_Transient)
private:
Handle(IGESData_ReadWriteModule) themod;
Handle(IGESData_Protocol) theprot;
Handle(IGESData_GlobalNodeOfWriterLib) thenext;
};
#endif // _IGESData_GlobalNodeOfWriterLib_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
**
** Copyright (C) 1995-2012 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"
#ifdef DRAG_SUPPORT
# include "modules/dragdrop/dragdrop_manager.h"
# include "modules/dragdrop/src/private_data.h"
# include "modules/dragdrop/src/events_manager.h"
# include "modules/dom/domeventtypes.h"
# include "modules/doc/frm_doc.h"
# include "modules/doc/html_doc.h"
# include "modules/dochand/win.h"
# include "modules/pi/OpDragObject.h"
OP_STATUS
DragDropEventsManager::RecordAction(HTML_Document* doc, DOM_EventType event, int x, int y, int offset_x, int offset_y, int visual_viewport_x, int visual_viewport_y, BOOL shift_pressed, BOOL control_pressed, BOOL alt_pressed)
{
OP_ASSERT(doc);
if (RecordedDragAction *recorded_drag_action = OP_NEW(RecordedDragAction, (doc, event, x, y, visual_viewport_x, visual_viewport_y, offset_x, offset_y, shift_pressed, control_pressed, alt_pressed)))
recorded_drag_action->Into(&m_recorded_dnd_actions);
else
return OpStatus::ERR_NO_MEMORY;
return OpStatus::OK;
}
void
DragDropEventsManager::ReplayRecordedDragActions()
{
OP_ASSERT(m_replay_next_action);
m_replay_next_action = FALSE;
if ((m_recording_drag_actions == 0 || --m_recording_drag_actions == 0) && !m_replaying_recorded_drag_actions)
{
m_replaying_recorded_drag_actions = TRUE;
while (RecordedDragAction *drag_action = m_recorded_dnd_actions.First())
{
drag_action->Out();
OP_ASSERT(drag_action->GetActionDocument());
HTML_Document* action_doc = drag_action->GetActionDocument();
if (action_doc)
{
DOM_EventType event = drag_action->GetActionType();
if (!action_doc->GetFramesDocument()->IsUndisplaying())
drag_action->Action();
else
{
// If we're going to lose ONDROP/ONDRAGEND we need to make sure the drag gets ended.
if (event == ONDROP || event == ONDRAGEND)
{
DOM_EventType ending_event = (event == ONDROP) ? ONDRAGEND : DOM_EVENT_NONE;
EnsureDragEnds(action_doc, drag_action->GetX(), drag_action->GetY(), drag_action->GetVisualViewportX(), drag_action->GetVisualViewportY(), drag_action->GetOffsetX(), drag_action->GetOffsetY(), drag_action->ShiftPressed(), drag_action->CtrlPressed(), drag_action->AltPressed(), ending_event);
}
}
/* ONDRAGLEAVE action may cause the next one is replayed and the next one might be ONDRAGEND
This is why we need to check if we are still dragging before doing anything more. */
if (event == ONDRAGLEAVE && g_drag_manager->IsDragging())
{
OpDragObject* drag_object = g_drag_manager->GetDragObject();
OP_ASSERT(drag_object);
PrivateDragData* priv_data = static_cast<PrivateDragData*>(drag_object->GetPrivateData());
OP_ASSERT(priv_data);
if (action_doc != priv_data->GetTargetDocument())
{
// The target we'll enter should change this.
action_doc->SetCurrentTargetElement(NULL);
action_doc->SetImmediateSelectionElement(NULL);
action_doc->SetPreviousImmediateSelectionElement(NULL);
action_doc->GetWindow()->UseDefaultCursor();
drag_object->SetVisualDropType(DROP_NONE);
drag_object->SetDropType(DROP_NONE);
}
}
}
OP_DELETE(drag_action);
if (m_recording_drag_actions != 0)
break;
}
m_replaying_recorded_drag_actions = FALSE;
}
}
void
DragDropEventsManager::Reset()
{
m_recording_drag_actions = 0;
m_replaying_recorded_drag_actions = FALSE;
m_replay_next_action = FALSE;
m_recorded_dnd_actions.Clear();
}
void
DragDropEventsManager::CancelPending()
{
m_recorded_dnd_actions.Clear();
}
void
DragDropEventsManager::OnDocumentUnload(HTML_Document* doc)
{
BOOL done;
BOOL check_doc = TRUE;
BOOL ensured_end = FALSE;
BOOL drag_enter_over = FALSE;
do
{
done = TRUE;
RecordedDragAction* iter = m_recorded_dnd_actions.First();
while (iter)
{
DOM_EventType event = iter->GetActionType();
HTML_Document* action_document = iter->GetActionDocument();
RecordedDragAction* next = iter->Suc();
if (action_document == doc || !check_doc)
{
iter->Out();
// If we're going to lose ONDROP/ONDRAGEND we need to make sure the drag gets ended.
if (event == ONDROP || event == ONDRAGEND)
{
DOM_EventType ending_event;
if (action_document == doc)
ending_event = (event == ONDROP) ? ONDRAGEND : DOM_EVENT_NONE;
else
ending_event = event;
EnsureDragEnds(action_document, iter->GetX(), iter->GetY(), iter->GetVisualViewportX(), iter->GetVisualViewportY(), iter->GetOffsetX(), iter->GetOffsetY(), iter->ShiftPressed(), iter->CtrlPressed(), iter->AltPressed(), ending_event);
ensured_end = TRUE;
next = NULL;
}
OP_DELETE(iter);
}
else
{
if (event == ONDRAG || event == ONDRAGENTER || event == ONDRAGOVER)
drag_enter_over = TRUE;
}
iter = next;
}
if (!ensured_end && !drag_enter_over && m_recorded_dnd_actions.First())
{
// There are no ONDRAG/ONDRAGENTER/ONDRAGOVER events which drive
// the whole d'n'd but there are some other ones. Remove them as
// well as there's no point in keeping them and this may even lead
// to the queue never being cleaned up.
done = FALSE;
check_doc = FALSE;
}
} while (!done);
}
void
DragDropEventsManager::OnOOM()
{
RecordedDragAction* iter = m_recorded_dnd_actions.First();
while (iter)
{
DOM_EventType event = iter->GetActionType();
RecordedDragAction* next = iter->Suc();
iter->Out();
// If we're going to lose ONDROP/ONDRAGEND we need to make sure the drag gets ended.
if (event == ONDROP || event == ONDRAGEND)
{
// This will clean the rest of the queue so no need to continue iterating.
g_drag_manager->StopDrag();
return;
}
OP_DELETE(iter);
iter = next;
}
// The queue is empty now. Reset all the flags.
m_recording_drag_actions = 0;
m_replaying_recorded_drag_actions = FALSE;
m_replay_next_action = FALSE;
}
void
DragDropEventsManager::EnsureDragEnds(HTML_Document* doc, int x, int y, int visual_viewport_x, int visual_viewport_y, int offset_x, int offset_y, BOOL shift, BOOL ctrl, BOOL alt, DOM_EventType ending_event)
{
OP_ASSERT(ending_event == ONDRAGEND || ending_event == ONDROP || ending_event == DOM_EVENT_NONE);
CancelPending();
if (ending_event == ONDRAGEND)
{
OpDragObject* drag_object = g_drag_manager->GetDragObject();
OP_ASSERT(drag_object);
drag_object->SetDropType(DROP_NONE);
PrivateDragData* priv_data = static_cast<PrivateDragData*>(drag_object->GetPrivateData());
OP_ASSERT(priv_data);
HTML_Element* dnd_source_element = priv_data->GetSourceHtmlElement();
HTML_Document* src_doc = priv_data->GetElementsDocument(dnd_source_element);
if (src_doc)
g_drag_manager->DragAction(src_doc, ONDRAGEND, x, y, visual_viewport_x, visual_viewport_y, offset_x, offset_y, shift, ctrl, alt);
else // We couldn't send ONDRAGEND event which would end and clean up d'n'd so we have to do it here.
g_drag_manager->StopDrag();
}
else if (ending_event == ONDROP)
g_drag_manager->DragAction(doc, ONDROP, x, y, visual_viewport_x, visual_viewport_y, offset_x, offset_y, shift, ctrl, alt);
else // We couldn't send any d'n'd event which would end and clean up d'n'd so we have to do it here.
g_drag_manager->StopDrag();
doc->GetWindow()->UseDefaultCursor();
}
BOOL
DragDropEventsManager::RecordedDragAction::Action()
{
return g_drag_manager->DragAction(document, event, x, y, visual_viewport_x, visual_viewport_y, offset_x, offset_y, shift_pressed, control_pressed, alt_pressed);
}
#endif // DRAG_SUPPORT
|
#include "database.h"
#include <fcntl.h>
#include <stdio.h>
#include <iostream>
#include <glog/logging.h>
#include <glog/stl_logging.h>
#include <google/protobuf/text_format.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include "machine_study_config.pb.h"
#include "machine_study.pb.h"
using namespace mstudy;
MySqlDatabase::MySqlDatabase() {
is_connected_ = initDatabase();
}
MySqlDatabase::~MySqlDatabase() {
}
bool MySqlDatabase::initDatabase() {
// ้
็ฝฎๆไปถไธญ่ฏปๅๆฐๆฎๅบ้
็ฝฎ
std::string file_name = "config.prototxt";
// ่ฏปๅๆไปถ
int fd = open(file_name.c_str(), O_RDONLY);
if (fd == -1) {
LOG(ERROR) << "open " << file_name << " error";
return false;
}
google::protobuf::io::FileInputStream* input = new google::protobuf::io::FileInputStream(fd);
mstudy::MStudyConfig config;
if (!google::protobuf::TextFormat::Parse(input, &config)){
LOG(ERROR) << "textformat::parse error ";
}
delete input;
close(fd);
if (conn_ == NULL){
conn_ = std::shared_ptr<mysqlpp::Connection>(new mysqlpp::Connection(config.db_name().c_str(),
config.db_server().c_str(),
config.db_username().c_str(),
config.db_password().c_str(),
config.db_port()));
}
// conn_->set_option(new mysqlpp::SetCharsetDirOption("utf-8"));
bool result = conn_->connected();
LOG(INFO) << "connect " << config.db_server() << " "
<< config.db_name() << " "
<< config.db_username() << " "
<< config.db_password() << " "
<< config.db_port() << " "
<< result;
return result;
}
bool MySqlDatabase::insert2(const std::string& bytes){
if (!is_connected_){
LOG(ERROR) << "had not connect database." ;
return false;
}
bool result = true;
try {
Query query = conn_->query();
query << "insert into features(image_feature) values('"
<< mysqlpp::escape << bytes << "');";
query.execute();
}catch(const BadQuery& er){
LOG(ERROR) << er.what();
result = false;
}catch(const Exception& er){
LOG(ERROR) << er.what();
result = false;
}
return result;
}
bool MySqlDatabase::insert(int64_t st_id, int64_t picture_bin_id, const std::string & dbcode,
int32_t tonality1, int32_t tonality2, int32_t tonality3,
const std::string & feature_data){
if (!is_connected_){
LOG(ERROR) << "had not connect database." ;
return false;
}
bool result = true;
LOG(INFO) << "insert data picture_bin_id :" << picture_bin_id;
try {
Query query = conn_->query();
query << "insert into features(st_id, picture_bin_id, dbcode, tonality1, tonality2, tonality3, feature_data) values("
<< st_id << ","
<< picture_bin_id << ","
<< "'" << mysqlpp::escape << dbcode << "',"
<< tonality1 << ","
<< tonality2 << ","
<< tonality3 << ","
<< "'" << mysqlpp::escape << feature_data << "');";
query.execute();
}catch(const BadQuery& er){
LOG(ERROR) << er.what();
result = false;
}catch(const Exception& er){
LOG(ERROR) << er.what();
result = false;
}
return result;
}
bool MySqlDatabase::read(int64_t index, int64_t max, vector<shared_ptr<mstudy::FeatureData>>& datas){
if (!is_connected_){
LOG(ERROR) << "had not connect database." ;
}
bool result = true;
try {
Query query = conn_->query();
query << "select id, st_id, picture_bin_id, dbcode, tonality1, tonality2, tonality3, feature_data from features limit " << index <<"," << max;
StoreQueryResult query_result = query.store();
if (!query_result){
LOG(ERROR) << query.error();
return false;
}
int num_rows = query_result.num_rows();
for (int i=0; i<num_rows; i++){
shared_ptr<mstudy::FeatureData> item = shared_ptr<mstudy::FeatureData>(new mstudy::FeatureData);
int64_t id = query_result[i][0];
item->set_st_id(query_result[i][1]);
item->set_picture_bin_id(query_result[i][2]);
mysqlpp::sql_blob_null dbcode_blob = query_result[i][3];
int count = dbcode_blob.data.length() / sizeof(float);
float * dbcode = (float*)dbcode_blob.data.data();
for(int i=0; i<count; i++){
item->add_dbcode(dbcode[i]);
}
item->set_tonality1(query_result[i][4]);
item->set_tonality2(query_result[i][5]);
item->set_tonality3(query_result[i][6]);
mysqlpp::sql_blob_null blob = query_result[i][7];
if (blob.is_null){
continue;
}
count = blob.data.length() / sizeof(float);
float * array = (float*)blob.data.data();
for (int i=0; i<count; i++){
item->add_feature_data(array[i]);
}
datas.push_back(item);
LOG(INFO) << item->DebugString();
}
}catch(const BadQuery& er){
LOG(ERROR) << er.what();
result = false;
}catch(const Exception& er){
LOG(ERROR) << er.what();
result = false;
}
return result;
}
|
//*************************************************************************************************************
//
// 2DUI่จญๅฎใใๆง้ ไฝใฎๅฆ็[UISetingTypes.h]
// Author : Sekine Ikuto
//
//*************************************************************************************************************
#ifndef _UISETINGTYPES_H_
#define _UISETINGTYPES_H_
//-------------------------------------------------------------------------------------------------------------
// ใคใณใฏใซใผใใใกใคใซ
//-------------------------------------------------------------------------------------------------------------
#include "Mylibrary.h"
#include "TextfileController.h"
#include <unordered_map>
//-------------------------------------------------------------------------------------------------------------
// ใใฏใญๅฎ็พฉ
//-------------------------------------------------------------------------------------------------------------
#define UISETING_ABILITY_DEFAULT "default"
#define UISETING_ABILITY_NUMBER "number"
#define UISETING_ABILITY_FLASHING "flashing"
#define UISETING_ABILITY_FADE "fade"
//-------------------------------------------------------------------------------------------------------------
// ๅๅ็ฉบ้ๅฎ็พฉ
//-------------------------------------------------------------------------------------------------------------
namespace ui2d
{
//-------------------------------------------------------------------------------------------------------------
// ใจใคใชใขในๅฎฃ่จ
//-------------------------------------------------------------------------------------------------------------
using Map_for_load = std::unordered_map<std::string, int>;
//-------------------------------------------------------------------------------------------------------------
// ๅๆๅๅฎ็พฉ
//-------------------------------------------------------------------------------------------------------------
// ใในใฏใฎ่จญๅฎๅค
enum
{
MASK_NONE = 0b00000000,
MASK_NUMBER = 0b00000001,
MASK_FLASHING = 0b00000010,
MASK_FADE = 0b00000100,
MASK_MAX = 0b00000111,
};
// ใใฉใฐใฎ่จญๅฎๅค
enum
{
FLAG_NONE = -1,
FLAG_NUMBER,
FLAG_FLASHING,
FLAG_FADE,
FLAG_MAX
};
//-------------------------------------------------------------------------------------------------------------
// ๆง้ ไฝๅฎ็พฉ
//-------------------------------------------------------------------------------------------------------------
// 2DUIใฎ่จญๅฎ็จใฎๆง้ ไฝ
typedef struct SETING
{
/* ใกใณใ้ขๆฐ */
SETING() {}
SETING(int nTextureID, bool bDisp, D3DXVECTOR3& pos, D3DXVECTOR2& size, float fRotation, int nOriginType, D3DXCOLOR& col) :
nTextureID(nTextureID), bDisp(bDisp), pos(pos), size(size), fRotation(fRotation), nOriginType(nOriginType), col(col)
{}
// ใณใใผใณใณในใใฉใฏใฟ
SETING(SETING &CopySource)
{
this->nTextureID = CopySource.nOriginType; // ใใฏในใใฃID
this->bDisp = CopySource.bDisp; // ๆ็ปใใฉใฐ
this->pos = CopySource.pos; // ไฝ็ฝฎ
this->size = CopySource.size; // ใตใคใบ
this->fRotation = CopySource.fRotation; // ๅ่ปข้
this->nOriginType = CopySource.nOriginType; // ๅ็นใฟใคใ
this->col = CopySource.col; // ่ฒ
}
// ใณใใผ
SETING &operator = (SETING &CopySource)
{
this->nTextureID = CopySource.nOriginType; // ใใฏในใใฃID
this->bDisp = CopySource.bDisp; // ๆ็ปใใฉใฐ
this->pos = CopySource.pos; // ไฝ็ฝฎ
this->size = CopySource.size; // ใตใคใบ
this->fRotation = CopySource.fRotation; // ๅ่ปข้
this->nOriginType = CopySource.nOriginType; // ๅ็นใฟใคใ
this->col = CopySource.col; // ่ฒ
}
/* ใกใณใๅคๆฐ */
int nTextureID; // ใใฏในใใฃID
bool bDisp; // ๆ็ปใใฉใฐ
D3DXVECTOR3 pos; // ไฝ็ฝฎ
D3DXVECTOR2 size; // ใตใคใบ
float fRotation; // ๅ่ปข้
int nOriginType; // ๅ็นใฟใคใ
D3DXCOLOR col; // ่ฒ
} SETING;
//-------------------------------------------------------------------------------------------------------------
// ใฏใฉในๅฎ็พฉ
//-------------------------------------------------------------------------------------------------------------
class CLoadinfo
{
public:
/* ใกใณใ้ขๆฐ */
// ่จญๅฎๆ
ๅ ฑใใญใผใใใ
inline static void LoadSetingInfo(const char *pFileName, std::vector<SETING> *output)
{
}
// ใใใใฎ่จญๅฎ
static void SetMap(void);
// ใใใใฎๅ้ค
static void UnsetMap(void);
private:
/* ใกใณใ้ขๆฐ */
// ไธ่กใใๆ
ๅ ฑใ่ชญใฟๅใ
inline static void ReadFromLine(const char * info, CLoadinfo* load)
{
}
// ่ชญใฟๅใฃใ่กใใใใฉใกใผใฟใ่จญๅฎใใ
inline static void ReadFromLineSetParam(const char * line, CLoadinfo* load)
{
// ๅคๆฐๅฎฃ่จ
char aData[MYLIB_STRINGSIZE] = {};
int nData = 0;
D3DXCOLOR float4 = D3DXCOLOR(0.0f, 0.0f, 0.0f, 0.0f);
// ็ตไบใใคใณใฟใๆฅใๆ
// UIใฟใคใ
if (sscanf(line, "UI_TYPE = %s", aData) == 1)
{
}
// ๅ็นID
else if (sscanf(line, "ORIGINTYPEID = %d", &nData) == 1)
{
}
// ไฝ็ฝฎ
else if (sscanf(line, "POS = %f %f %f", &float4.r, &float4.g, &float4.b) == 3)
{
}
// ใตใคใบ
else if (sscanf(line, "SIZE = %f %f", &float4.r, &float4.g) == 2)
{
}
// ๅ่ปข
else if (sscanf(line, "ROTATION = %f", &float4.r) == 1)
{
}
// ่ฒ
else if (sscanf(line, "COL = %f %f %f %f", &float4.r, &float4.g, &float4.b, &float4.a) == 4)
{
}
// ใใฏในใใฃใฟใคใใฎ่จญๅฎ
else if (sscanf(line, "TEXTURETYPE = %d", &nData) == 1)
{
}
// ในใฏใชใใใใกใคใซ
else if (sscanf(line, "SCRIPTFILE = %s", aData) == 1)
{
}
}
/* ใกใณใๅคๆฐ */
static Map_for_load *m_pMap; // ใญใผใ็จใฎใใใ
};
}
#endif
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
int n;
while(scanf("%d",&n)){
if(n==-1)
break;
ll male=0,female=1;
for(int i=0;i<n;i++){
ll t=female;
female=male+1;
male+=t;
// cout<<male<<" "<<female<<"\n";
}
cout<<male<<" "<<female+male<<"\n";
}
return 0;
}
|
#pragma once
#include "common.h"
#include "streams/streams.h"
NAMESPACE_BEGIN(NAMESPACE_BINTABLE)
class MemoryInputStream : public InputStream {
public:
MemoryInputStream(char* input_data, std::streamsize input_data_size);
void read(char *data, const std::streamsize size) override;
void skip(const std::streamsize size) override;
private:
char* input_data;
const std::streamsize input_data_size;
std::streamsize current_position;
};
class MemoryOutputStream : public OutputStream {
public:
MemoryOutputStream(char* output_data, std::streamsize output_data_max_size);
void write(const char *data, const std::streamsize size) override;
void write(InputStream& stream, const std::streamsize size) override;
private:
char* output_data;
const std::streamsize output_data_max_size;
std::streamsize current_position;
};
NAMESPACE_END(NAMESPACE_BINTABLE)
|
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<bits/stdc++.h>
#include<queue>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j,k) for(i=j;i>=k;i--)
#define pb push_back
inline long long MAX2(long long a, long long int b){return (a)>(b)?(a):(b);}
inline long long MAX3(long long a, long long b,long long c){return (a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c));}
inline long long MIN2(long long a, long long b){return (a)<(b)?(a):(b);}
inline long long MIN3(long long a, long long b,long long c){return (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c));}
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector< pair<int,int> > vii;
typedef long long ll;
int n,m;
vector< vi > graph(100005);
int visited[100005]={},num[100005],low[100005];
int indegree[100005];
int counter;
vi roots,s;
void dfs(int i)
{
visited[i]=1;
s.pb(i);
num[i]=low[i]=++counter;
int j;
FOR0(j,graph[i].size())
{
if(num[graph[i][j]]==-1)
dfs(graph[i][j]);
if(visited[graph[i][j]])
low[i]=MIN2(low[i],low[graph[i][j]]);
}
if(num[i]==low[i])
{
roots.pb(num[i]);
while(1)
{
int v=s.back();
visited[v]=0;
low[v]=num[i];
s.pop_back();
if(v==i)break;
}
}
}
void check_indegree(int i)
{
int j;
FOR0(j,graph[i].size())
{
if(low[graph[i][j]]!=low[i])
{
indegree[low[graph[i][j]]]++;
}
}
}
int main()
{
int t,i,j;
cin>>t;
while(t--)
{
cin>>n>>m;
FOR0(i,n)
{
graph[i].clear();
indegree[i+1]=0;
visited[i]=0;
num[i]=-1;
low[i]=-1;
roots.clear();
}
int x,y;
FOR0(i,m)
{
cin>>x>>y;
graph[x-1].pb(y-1);
}
counter =0;
int ans=0;
FOR0(i,n)
{
if(num[i]==-1)
dfs(i);
}
FOR0(i,n)
{
check_indegree(i);
}
FOR0(i,roots.size())
{
if(indegree[roots[i]]==0)
ans++;
}
cout<<ans<<endl;
}
}
|
#ifndef CONNEXION
#define CONNEXION
#include <winsock2.h>
#include <iostream>
int connexion(u_short port, SOCKET &sock, SOCKADDR_IN &sin);
#endif
|
/*
* @author : dhruv-gupta14
* @date : 25/12/2018
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
int count = 0;
string str;
cin >> str;
transform(str.begin(), str.end(), str.begin(), ::tolower);
for (int i = 0; i < str.length(); i++)
{
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u')
{
count++;
}
}
cout<<count;
return 0;
}
|
/******************************************************************************
* This file is part of the Geometric harmonization project *
* *
* (C) 2014 Azamat Shakhimardanov *
* Herman Bruyninckx *
* azamat.shakhimardanov@mech.kuleuven.be *
* Department of Mechanical Engineering, *
* Katholieke Universiteit Leuven, Belgium. *
* *
* You may redistribute this software and/or modify it under either the *
* terms of the GNU Lesser General Public License version 2.1 (LGPLv2.1 *
* <http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html>) or (at your *
* discretion) of the Modified BSD License: *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions *
* are met: *
* 1. Redistributions of source code must retain the above copyright *
* notice, this list of conditions and the following disclaimer. *
* 2. Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* 3. The name of the author may not be used to endorse or promote *
* products derived from this software without specific prior written *
* permission. *
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR *
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED *
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,*
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS *
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) *
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, *
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING *
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
*******************************************************************************/
#include <kdl_extensions/computationalstate_kdl.hpp>
namespace kdle
{
//Link computational state
//TODO: These has to be deprecated in the favor of Global and Local
//Link computational state
SegmentState::SegmentState()
{
X.Identity();
Xtotal.Identity();
Xdot.Zero();
Xdotdot.Zero();
F.Zero();
// Fext.Zero();
Z.Zero();
Vj.Zero();
jointIndex = 0;
jointName = " ";
segmentName = " ";
}
SegmentState::SegmentState(const SegmentState& copy)
{
X = copy.X;
Xtotal = copy.Xtotal;
Xdot = copy.Xdot;
Xdotdot = copy.Xdotdot;
F = copy.F;
// Fext = copy.Fext;
Z = copy.Z;
Vj = copy.Vj;
jointIndex = copy.jointIndex;
jointName = copy.jointName;
segmentName = copy.segmentName;
}
SegmentState& SegmentState::operator=(const SegmentState& copy)
{
if (this != ©)
{
X = copy.X;
Xtotal = copy.Xtotal;
Xdot = copy.Xdot;
Xdotdot = copy.Xdotdot;
F = copy.F;
// Fext = copy.Fext;
Z = copy.Z;
Vj = copy.Vj;
jointIndex = copy.jointIndex;
jointName = copy.jointName;
segmentName = copy.segmentName;
}
return *this;
}
bool SegmentState::operator==(const SegmentState& instance)
{
return
((this->X == instance.X) &&
(this->Xdot == instance.Xdot) &&
(this->Xdotdot == instance.Xdotdot) &&
(this->F == instance.F));
};
bool SegmentState::operator!=(const SegmentState& instance)
{
return !(operator==(instance));
};
SegmentState::~SegmentState()
{
}
//Joint computational state
JointState::JointState()
{
q = 0.0;
qdot = 0.0;
qdotdot = 0.0;
torque = 0.0;
jointIndex = 0;
Fext.Zero();
jointName = " ";
}
JointState::JointState(const JointState& copy)
{
q = copy.q;
qdot = copy.qdot;
qdotdot = copy.qdotdot;
torque = copy.torque;
Fext = copy.Fext;
jointIndex = copy.jointIndex;
jointName = copy.jointName;
}
JointState& JointState::operator=(const JointState& copy)
{
if (this != ©)
{
q = copy.q;
qdot = copy.qdot;
qdotdot = copy.qdotdot;
torque = copy.torque;
Fext = copy.Fext;
jointIndex = copy.jointIndex;
jointName = copy.jointName;
}
return *this;
}
JointState::~JointState()
{
}
};
|
// -----------------------------------------------------------------------------
// AnalysisManager.h
//
// Class definition of the analysis manager
// * Author: Everybody is an author!
// * Creation date: 4 August 2020
// -----------------------------------------------------------------------------
#ifndef AnalysisManager_h
#define AnalysisManager_h 1
// Q-Pix includes
#include "GeneratorParticle.h"
#include "MCParticle.h"
// GEANT4 includes
#include "globals.hh"
// ROOT includes
#include "TROOT.h"
#include "TFile.h"
#include "TTree.h"
#include "TBranch.h"
// C++ includes
#include <map>
#include <set>
class AnalysisManager {
public:
AnalysisManager();
~AnalysisManager();
void Book(std::string const);
void Save();
void EventFill();
void EventReset();
void SetRun(int const);
void SetEvent(int const);
void FillMetadata(double const &, double const &, double const &);
void AddInitialGeneratorParticle(GeneratorParticle const *);
void AddFinalGeneratorParticle(GeneratorParticle const *);
void AddMCParticle(MCParticle const *);
int ProcessToKey(std::string const &);
inline void AddProcess(std::string const & process) { process_names_.insert(process); }
inline std::set< std::string > GetProcessNames() const { return process_names_; }
static AnalysisManager* Instance();
private:
static AnalysisManager * instance_;
std::set< std::string > process_names_;
// ROOT objects
TFile * tfile_;
TTree * metadata_;
TTree * event_tree_;
// variables that will go into the metadata tree
double detector_length_x_;
double detector_length_y_;
double detector_length_z_;
// variables that will go into the event trees
int run_;
int event_;
int number_particles_;
int number_hits_;
double energy_deposit_;
std::vector< int > particle_track_id_;
std::vector< int > particle_parent_track_id_;
std::vector< int > particle_pdg_code_;
std::vector< double > particle_mass_;
std::vector< double > particle_charge_;
std::vector< int > particle_process_key_;
std::vector< int > particle_total_occupancy_;
std::vector< double > particle_initial_x_;
std::vector< double > particle_initial_y_;
std::vector< double > particle_initial_z_;
std::vector< double > particle_initial_t_;
std::vector< double > particle_initial_px_;
std::vector< double > particle_initial_py_;
std::vector< double > particle_initial_pz_;
std::vector< double > particle_initial_energy_;
std::vector< int > hit_track_id_;
std::vector< double > hit_start_x_;
std::vector< double > hit_start_y_;
std::vector< double > hit_start_z_;
std::vector< double > hit_start_t_;
std::vector< double > hit_end_x_;
std::vector< double > hit_end_y_;
std::vector< double > hit_end_z_;
std::vector< double > hit_end_t_;
std::vector< double > hit_length_;
std::vector< double > hit_energy_deposit_;
std::vector< int > hit_process_key_;
std::vector< double > phit_start_x_;
std::vector< double > phit_start_y_;
std::vector< double > phit_start_z_;
std::vector< double > phit_start_t_;
std::vector< double > phit_end_x_;
std::vector< double > phit_end_y_;
std::vector< double > phit_end_z_;
std::vector< double > phit_end_t_;
// number of generator particles
int generator_initial_number_particles_;
int generator_final_number_particles_;
// vectors for initial generator particles
std::vector< double > generator_initial_particle_x_;
std::vector< double > generator_initial_particle_y_;
std::vector< double > generator_initial_particle_z_;
std::vector< double > generator_initial_particle_t_;
std::vector< double > generator_initial_particle_px_;
std::vector< double > generator_initial_particle_py_;
std::vector< double > generator_initial_particle_pz_;
std::vector< double > generator_initial_particle_energy_;
std::vector< int > generator_initial_particle_pdg_code_;
std::vector< double > generator_initial_particle_mass_;
std::vector< double > generator_initial_particle_charge_;
// vectors for final generator particles
std::vector< double > generator_final_particle_x_;
std::vector< double > generator_final_particle_y_;
std::vector< double > generator_final_particle_z_;
std::vector< double > generator_final_particle_t_;
std::vector< double > generator_final_particle_px_;
std::vector< double > generator_final_particle_py_;
std::vector< double > generator_final_particle_pz_;
std::vector< double > generator_final_particle_energy_;
std::vector< int > generator_final_particle_pdg_code_;
std::vector< double > generator_final_particle_mass_;
std::vector< double > generator_final_particle_charge_;
};
#endif
|
#include "C:\Users\Andrey\Desktop\Linearization\Linerization\Working Test\version 1.1\include\Signal.h"
#include "C:\Users\Andrey\Desktop\Linearization\Linerization\Working Test\version 1.1\include\Sinus.h"
#include "C:\Users\Andrey\Desktop\Linearization\Linerization\Working Test\version 1.1\include\Rectangle.h"
#include "C:\Users\Andrey\Desktop\Linearization\Linerization\Working Test\version 1.1\include\Triangle.h"
Signal::Signal(void)
{
}
Signal::~Signal(void)
{
}
//--------------------------------------------------------
void Signal::setOffsetY(float _setY) {
offsetY = _setY;
}
void Signal::setOffsetX(float _setX) {
if (_setX < 0.0) _setX = 0.0;
if (_setX > 360.0) _setX = 360.0;
offsetX = (diskret / 360.0)*_setX; // ะฟะตัะตะฒะพะดะธะผ ะธะท ะณัะฐะดััะพะฒ ะฒ ะดะธัะบัะตัั
}
void Signal::setCycles(uint16_t _cycles)
{
if (_cycles < 0) _cycles = 0;
cycles = _cycles;
}
void Signal::setPeriod(uint16_t _per)
{
if (_per < 0) _per = 0;
if (_per > 10000) _per = 10000;
period = _per;
}
void Signal::setSymmetry(uint16_t _sym)
{
if (_sym < 0) _sym = 0;
if (_sym > 100) _sym = 100;
symmetry = _sym;
}
void Signal::setAmplitude(float _ampl) {
amplitude = _ampl;
}
void Signal::setMode(byte _mode) {
mode = _mode;
}
float Signal::getAmplitude(void) const {
return float(amplitude);
}
float Signal::getOffsetY(void) const {
return float(offsetY);
}
uint16_t Signal::getOffsetX(void) const {
return uint16_t(offsetX);
}
uint16_t Signal::getCycles(void) const
{
return uint16_t(cycles);
}
uint16_t Signal::getPeriod(void) const
{
return uint16_t(period);
}
uint16_t Signal::getSymmetry(void) const
{
return (uint16_t)symmetry;
}
uint16_t Signal::getVal(int _number) const {
return uint16_t(val[_number]);
}
byte Signal::getMode(void) const {
return byte(mode);
}
Signal* Signal::createSignal(Signal_ID id)
{
Signal* ptr;
switch (id) {
case Sinus_ID:
ptr = new Sinus();
break;
case Triangle_ID:
ptr = new Triangle();
break;
case Rectangle_ID:
ptr = new Rectangle();
break;
default:
assert(false);
}
return ptr;
}
//------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------
// ัะฐัััะธััะฒะฐะตั ะฐะผะฟะปะธััะดั ะธ ัะผะตัะตะฝะธะต ะพัะฝะพั. ะพัะธ OY
// minVal ะธ maxVal ะทะฐะดะฐัั "ัะฐะทะผะฐั
" ัะธะณะฝะฐะปะฐ ะฒ ะฒะพะปััะฐั
void Signal::setParam(float _minVal, float _maxVal, float _setX, uint16_t _freq, uint16_t _cycles, int _symmetry) {
if (_minVal < -10.79967041015625) _minVal = -10.79967041015625;
if (_maxVal > 10.79967041015625) _maxVal = 10.79967041015625;
double diapason; // 1: 0-5V, 2: 0-10V, 3: 0-10.8V, 4: +-5V, 5: +-10V, 6: +-10.8V
if (_minVal >= 0.0)
{
setMode(3);
diapason = 10.8;
if (_maxVal <= 9.999847412109375)
{
setMode(2);
diapason = 10.0;
if (_maxVal <= 4.999923706054688)
{
setMode(1);
diapason = 5.0;
}
}
double setY;
setY = _minVal;
setOffsetY(setY);
}
else
{
setMode(6);
diapason = 21.6;
if (_minVal >= -9.999847412109375)
{
setMode(5);
diapason = 20.0;
if (_minVal >= -4.999923706054688)
{
setMode(4);
diapason = 10.0;
}
}
double setY;
setY = diapason / 2 - Abs(_minVal);
setOffsetY(setY);
}
double ampl;
ampl = Abs(_maxVal - _minVal) / 2;
setAmplitude(ampl);
setOffsetX(_setX); // ะฒัััะฐะฒะปัะตั ะฝะฐัะฐะปัะฝัั ัะฐะทั (ะฒ ะณัะฐะดััะฐั
)
setPeriod(_freq); // ะฒัััะฐะฒะปัะตั ัะฐััะพัั ัะธะณะฝะฐะปะฐ
setCycles(_cycles); // ะฒัััะฐะฒะปัะตั ัะธัะปะพ ะณะตะฝะตัะธััะตะผัั
ะฟะตัะธะพะดะพะฒ ( 0 - continium mode )
setSymmetry(_symmetry); // ะฒัััะฐะฒะปัะตั ัะธะผะผะตััะธั ัะธะณะฝะฐะปะฐ (ะดะปั ัะธะฝััะฐ 100% const)
setVal(diapason);
}
|
/*
Crapenstein:
- Bruno Caceiro
- David Cardouzo
*/
#include "OpenGLIncludes.h"
#include <iostream>
#include <cmath>
#include <vector>
#include <cstring>
#include "Camera.h"
#include "Room.h"
#include "Wall.h"
#include "Robot.h"
#include "DoorWall.h"
#include "Map.h"
#include "Ball.h"
#include "RgbImage.h"
#include "collidingObject.h"
#include "torch.h"
#include "Cube.h"
using namespace std;
void Keyboard(unsigned char key, int x, int y);
void KeyboardUp(unsigned char key, int x, int y);
void specialkeypressed(int key, int x, int y);
void specialkeyUp(int key, int x, int y);
void MouseMotion(int x, int y);
void Mouse(int button, int state, int x, int y);
void desenhaRobot();
void createMap();
void Display();
void Reshape (int w, int h);
void Timer(int value);
void Idle();
void initFog();
void desenhaTexto(char *string, GLfloat x, GLfloat y, GLfloat z);
Camera* camera;
vector<CollidingObject*> collidableObjects;
vector<CollidingObject*>::iterator collidableObjectsIterator;
GLuint texture[5];
bool enableFog = false;
GLint wScreen=800, hScreen=600;
bool keyStates[256] = {false};
bool specialKeyStates[256] = {false};
bool g_fps_mode = false;
//bool g_mouse_left_down = false;
// Movement settings
const float g_translation_speed = 0.5;
const float g_rotation_speed = M_PI/180*0.2;
int g_viewport_width = 0;
int g_viewport_height = 0;
Map* map;
DoorWall* testeDoor;
Robot* robotFofinho;
Cube* cuboTeste;
Cube* cuboTeste2;
Cube* cuboTeste3;
Cube* teste123;
Ball * bola1;
Ball * bola2;
Torch* huehuehue;
char texto[30];
char paused[30];
bool openDoor = false;
GLuint skyTexture[1];
const float BOX_SIZE = 3.0f; //The length of each side of the cube
const float BOX_HEIGHT = BOX_SIZE; //The height of the box off of the ground
const float FLOOR_SIZE = 10.0f; //The length of each side of the floor
float angle;
bool isPaused = false;
//Draws the cube
void drawCube(float angle) {
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glRotatef(-angle, 1.0f, 1.0f, 0.0f);
glBegin(GL_QUADS);
//Top face
glColor3f(1.0f, 1.0f, 0.0f);
glNormal3f(0.0, 1.0f, 0.0f);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
//Bottom face
glColor3f(1.0f, 0.0f, 1.0f);
glNormal3f(0.0, -1.0f, 0.0f);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
//Left face
glNormal3f(-1.0, 0.0f, 0.0f);
glColor3f(0.0f, 1.0f, 1.0f);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glColor3f(0.0f, 0.0f, 1.0f);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
//Right face
glNormal3f(1.0, 0.0f, 0.0f);
glColor3f(1.0f, 0.0f, 0.0f);
glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glColor3f(0.0f, 1.0f, 0.0f);
glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glEnd();
glColor3f(1.0f, 1.0f, 1.0f);
glBegin(GL_QUADS);
//Front face
glNormal3f(0.0, 0.0f, 1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, BOX_SIZE / 2);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, BOX_SIZE / 2);
//Back face
glNormal3f(0.0, 0.0f, -1.0f);
glTexCoord2f(0.0f, 0.0f);
glVertex3f(-BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glTexCoord2f(1.0f, 0.0f);
glVertex3f(-BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glTexCoord2f(1.0f, 1.0f);
glVertex3f(BOX_SIZE / 2, BOX_SIZE / 2, -BOX_SIZE / 2);
glTexCoord2f(0.0f, 1.0f);
glVertex3f(BOX_SIZE / 2, -BOX_SIZE / 2, -BOX_SIZE / 2);
glEnd();
glPopMatrix();
}
//Draws the floor
void drawFloor() {
glPushMatrix();
glTranslatef(20,5,10);
glBegin(GL_QUADS);
glNormal3f(0, 1, 0);
glTexCoord2f(0, 0);
glVertex3f(-FLOOR_SIZE / 2, 0, FLOOR_SIZE / 2);
glTexCoord2f(0, 1);
glVertex3f(-FLOOR_SIZE / 2, 0, -FLOOR_SIZE / 2);
glTexCoord2f(1, 1);
glVertex3f(FLOOR_SIZE / 2, 0, -FLOOR_SIZE / 2);
glTexCoord2f(1, 0);
glVertex3f(FLOOR_SIZE / 2, 0, FLOOR_SIZE / 2);
glEnd();
glPopMatrix();
}
void drawScene() {
/*LUZESSSS*/
//luz vermelha situada perto da origem
GLfloat ambientLight[4] = {0.4,0.4,0.4,1.0};
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, ambientLight);
glEnable(GL_LIGHT0);
GLfloat lightPos[4] = {1, 1, 1, 1.0};
glLightfv(GL_LIGHT0,GL_POSITION, lightPos);
GLfloat lightColor[4] = {255,0,0,1};
glLightfv(GL_LIGHT0,GL_DIFFUSE, lightColor);
glLightfv(GL_LIGHT0,GL_SPECULAR, lightColor);
glLightf(GL_LIGHT0,GL_CONSTANT_ATTENUATION, 1);
glLightf(GL_LIGHT0,GL_LINEAR_ATTENUATION, 0.5);
glLightf(GL_LIGHT0,GL_QUADRATIC_ATTENUATION, 0.5);
//draw Skybox
//glDisable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,skyTexture[0]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
glPushMatrix();
glColor4f(1.0,1.0,1.0,1.0);
glNormal3f(0.0f, 1.0f, 0.0f);
glBegin(GL_QUADS);
glTexCoord2f(0.0f,0.0f); glVertex3f( -5000, 51, -5000);
glTexCoord2f(1000.0f,0.0f); glVertex3f( 5000, 51, -5000);
glTexCoord2f(1000.0f,1000.0f); glVertex3f( 5000, 51, 5000);
glTexCoord2f(0.0f,1000.0f); glVertex3f( -5000, 51, 5000);
glColor4f(1.0,1.0,1.0,1.0);
glEnd();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
//huehuehue->draw();
map->update();
/* Update Robot */
robotFofinho->drawRobot();
bola1->update();
bola2->update();
if(camera->m_x>400)
glEnable(GL_FOG);
else
glDisable(GL_FOG);
cuboTeste->draw();
huehuehue->draw();
}
void criaDefineTexturas()
{
RgbImage imag;
glGenTextures(1, &texture[0]);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
imag.LoadBmpFile("assets/doorFofa.bmp");
glTexImage2D(GL_TEXTURE_2D, 0, 3,
imag.GetNumCols(),
imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,
imag.ImageData());
glGenTextures(1, &texture[1]);
glBindTexture(GL_TEXTURE_2D, texture[1]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
imag.LoadBmpFile("assets/chaoFofinho.bmp");
glTexImage2D(GL_TEXTURE_2D, 0, 3,
imag.GetNumCols(),
imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,
imag.ImageData());
glGenTextures(1, &texture[2]);
glBindTexture(GL_TEXTURE_2D, texture[2]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
imag.LoadBmpFile("assets/parede3.bmp");
glTexImage2D(GL_TEXTURE_2D, 0, 3,
imag.GetNumCols(),
imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,
imag.ImageData());
glGenTextures(1, &texture[3]);
glBindTexture(GL_TEXTURE_2D, texture[3]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
imag.LoadBmpFile("assets/wolf.bmp");
glTexImage2D(GL_TEXTURE_2D, 0, 3,
imag.GetNumCols(),
imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,
imag.ImageData());
glGenTextures(1, &skyTexture[0]);
glBindTexture(GL_TEXTURE_2D, skyTexture[0]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
imag.LoadBmpFile("assets/chaleira.bmp");
glTexImage2D(GL_TEXTURE_2D, 0, 3,
imag.GetNumCols(),
imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,
imag.ImageData());
}
void initializeObjects() {
initFog();
camera = new Camera();
huehuehue = new Torch(GL_LIGHT1,1,1,50);
map = new Map();
bola1 = new Ball(15,5,3,3,8,1);
bola2 = new Ball(25,5,10,0.5,9,-1);
robotFofinho = new Robot(8,5,3,1.3,camera);
cuboTeste = new Cube(30,2,25,2,0.25, 1.0f,0.0f,0.0f);
/*cuboTeste2 = new Cube(40,2,25,2,0.25, 0.0f,1.0f,0.0f);
cuboTeste3 = new Cube(50,2,25,2,0.25, 0.0f,0.0f,1.0f);
teste123 = new Cube(0,0,0,2,0.25, 0.0f,0.0f,1.0f);
*/
//set Robot Bounds FIXME move inside the robot class
robotFofinho->setBounds(8,5,3,1.3,1.3,5);
//set the camera to have the bounds of the robot
camera->setObject(robotFofinho);
}
void initFog(void){
GLfloat nevoeiroCor[] = {0.7, 0.7, 0.7, 1.0};
glFogfv(GL_FOG_COLOR,nevoeiroCor);
glFogi(GL_FOG_MODE, GL_LINEAR); //Equao do nevoeiro - linear
glFogf(GL_FOG_START, 10); // Distncia a que ter incio o nevoeiro
glFogf(GL_FOG_END, 30); // Distncia a que o nevoeiro terminar
glFogf (GL_FOG_DENSITY, 0.3);
}
void desenhaTexto(char *string, GLfloat x, GLfloat y, GLfloat z) {
glRasterPos3f(x,y,z);
while(*string)
glutBitmapCharacter(GLUT_BITMAP_HELVETICA_10, *string++);
}
int main (int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH | GLUT_STENCIL);
glutInitWindowSize(wScreen, hScreen);
glutCreateWindow("CGenstein");
srand(time(NULL));
// Initialize the container of the collidableObjects
collidableObjects.clear();
glClearColor(BLACK);
glShadeModel(GL_SMOOTH);
glEnable(GL_TEXTURE_2D);
glEnable(GL_DEPTH_TEST);
criaDefineTexturas( );
initializeObjects();
initFog();
sprintf(texto, "Bruno Caceiro | David Cardoso");
sprintf(paused, "Paused");
/* LIGHTS */
glEnable(GL_LIGHTING);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glutIgnoreKeyRepeat(1);
glutDisplayFunc(Display);
glutIdleFunc(Display);
glutReshapeFunc(Reshape);
glutMouseFunc(Mouse);
glutMotionFunc(MouseMotion);
glutPassiveMotionFunc(MouseMotion);
glutKeyboardFunc(Keyboard);
glutKeyboardUpFunc(KeyboardUp);
glutSpecialFunc(specialkeypressed);
glutSpecialUpFunc(specialkeyUp);
glutIdleFunc(Idle);
glutTimerFunc(1, Timer, 0);
glutMainLoop();
return 0;
}
void Display (void) {
glClearColor (0.0,0.0,0.0,1.0); //clear the screen to black
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear the color buffer and the depth buffer
//glLoadIdentity();
//draw the minimap
if(!isPaused) {
glEnable(GL_LIGHTING);
glViewport(g_viewport_width/2 + g_viewport_width/6 ,0,g_viewport_width/2 , g_viewport_height/5);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-20,20,-20,20,-20,20);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(1, 1, 1, 0, 0, 0, 0, 1, 0);
glPushMatrix();
glClear( GL_COLOR_BUFFER_BIT);
glPopMatrix();
desenhaTexto(texto, -15, -15, 0);
glViewport (0, 0, g_viewport_width/4, g_viewport_height/4);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-50,50,-50,50,-50,50);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
float a,b,c;
camera->GetPos(a,b,c);
float q,w,e;
camera->GetDirectionVector(q,w,e);
gluLookAt(a, 0, c, a, -5, c, q, 0, e);
glPushMatrix();
glClear( GL_COLOR_BUFFER_BIT);
glColor3f(0.1, 0.0, 0.0);
glBegin(GL_POLYGON);
glVertex3f(a-100, -0.1, c-100);
glVertex3f(a+100, -0.1, c-100);
glVertex3f(a+100, -0.1, c+100);
glVertex3f(a-100, -0.1, c+100);
glEnd();
glPopMatrix();
drawScene();
glViewport (0, 0, (GLsizei)g_viewport_width , (GLsizei)g_viewport_height); //set the viewport to the current window specifications
glMatrixMode (GL_PROJECTION); //set the matrix to projection
glLoadIdentity();
gluPerspective (60, (GLfloat)g_viewport_width / (GLfloat)g_viewport_height, 0.1 , 1000.0); //set the perspective (angle of sight, width, height, ,depth)
camera->Refresh();
drawScene();
}
else {
glDisable(GL_LIGHTING);
glViewport(0,0,g_viewport_width, g_viewport_height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-20,20,-20,20,-20,20);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(5, 5, 5, 0, 0, 0, 0 , 1, 0);
glPushMatrix();
glPopMatrix();
glColor4f(1.0, 1.0, 1.0,1.0);
desenhaTexto(paused, 1, 1, 1);
}
glutSwapBuffers(); //swap the buffers
}
void Reshape (int w, int h) {
//printf("reshape!!!!\n");
g_viewport_width = w;
g_viewport_height = h;
glViewport (0, 0, (GLsizei)w, (GLsizei)h); //set the viewport to the current window specifications
glMatrixMode (GL_PROJECTION); //set the matrix to projection
glLoadIdentity ();
gluPerspective (60, (GLfloat)w / (GLfloat)h, 0.1 , 1000.0); //set the perspective (angle of sight, width, height, ,depth)
glMatrixMode (GL_MODELVIEW); //set the matrix back to model
}
void Timer(int value)
{
if(g_fps_mode && !isPaused){
if(keyStates['w'] || specialKeyStates[GLUT_KEY_UP]) {
robotFofinho->Move(g_translation_speed);
}
if(keyStates['s'] || specialKeyStates[GLUT_KEY_DOWN]) {
robotFofinho->Move(-g_translation_speed);
}
if(keyStates['a'] || specialKeyStates[GLUT_KEY_LEFT]) {
robotFofinho->Strafe(g_translation_speed);
}
if(keyStates['d'] || specialKeyStates[GLUT_KEY_RIGHT]) {
robotFofinho->Strafe(-g_translation_speed);
}
}
robotFofinho->updateLasers();
glutTimerFunc(1, Timer, 0);
}
void Idle()
{
Display();
}
//========================================================
//Input
void Keyboard(unsigned char key, int x, int y)
{
if(key == 27) {
g_fps_mode = !g_fps_mode;
if(g_fps_mode) {
glutSetCursor(GLUT_CURSOR_NONE);
glutWarpPointer(g_viewport_width/2, g_viewport_height/2);
}
else {
glutSetCursor(GLUT_CURSOR_LEFT_ARROW);
}
}
keyStates[tolower(key)] = true;
}
void KeyboardUp(unsigned char key, int x, int y)
{
if(key == 'p') {
//printf("sdhjcfhsdnfvjhdbfk hjsdnrgtsdhj\n");
map->checkOpenDoors();
}
if(key == 'f')
initFog();
if(key == 'b')
isPaused = !isPaused;
keyStates[tolower(key)] = false;
}
void specialkeypressed(int key, int x, int y)
{
specialKeyStates[key] = true; // Set the state of the current key to pressed
}
void specialkeyUp(int key, int x, int y)
{
specialKeyStates[key] = false; // Set the state of the current key to pressed
}
void Mouse(int button, int state, int x, int y)
{
if(state == GLUT_DOWN) {
if(button == GLUT_LEFT_BUTTON) {
robotFofinho->fireLaser();
}
}
/*else if(state == GLUT_UP) {
if(button == GLUT_LEFT_BUTTON) {
g_mouse_left_down = false;
}
}*/
}
void MouseMotion(int x, int y)
{
// This variable is hack to stop glutWarpPointer from triggering an event callback to Mouse(...)
// This avoids it being called recursively and hanging up the event loop
static bool just_warped = false;
if(just_warped) {
just_warped = false;
return;
}
if(g_fps_mode) {
int dx = x - g_viewport_width/2;
int dy = y - g_viewport_height/2;
if(dx) {
camera->RotateYaw(g_rotation_speed*dx);
}
if(dy) {
camera->RotatePitch(g_rotation_speed*dy);
}
//glutSetCursor(GLUT_CURSOR_FULL_CROSSHAIR);
glutWarpPointer(g_viewport_width/2, g_viewport_height/2);
just_warped = true;
}
}
|
#include <iostream>
using namespace std;
int main() {
/*int count = 255;
cout<<count;*/
/*int count;
cin>>count;
cout<<count;*/
int count, age;
cout<<"Enter your number "<<" ";
cin>>count;
cout<<"Enter your age ";
cin>>age;
return 0;
}
|
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
#include <numeric>
#include <sstream>
#include <cmath>
#include <ctime>
std::vector<int> GenerateRandVec(int numOfNums, int min, int max);
void BubbleSort(std::vector<int>& theVec);
int Factorial(int number);
void PrintHorizontalVector(std::vector<int>& theVec);
int Fib(int number);
double Area(double radius);
double Area(double height, double width);
int main() {
// Bubble Sort
std::vector<int> testVec = GenerateRandVec(10, 5, 50);
BubbleSort(testVec);
for(auto x: testVec)
std::cout << x << "\n";
// Factorial
std::cout << "Factorial 6 = " << Factorial(6) << "\n";
// To print an array horizontally on the screen
/*
------------------
| 0 | 1 | 2 |
--------------
| 10 | 8 | 2 |
--------------
*/
std::vector<int> theVec = {10,8,2,5,9,11,6,14};
PrintHorizontalVector(theVec);
// Fibonnaci
int index;
std::cout << "Get Fibonacci Index: ";
std::cin >> index;
printf("Fib(%d) = %d\n", index, Fib(index));
// Overloaded Functions: same name function but different params
std::cout << "Area Circle (c) or Rectangle (r) : ";
char areaType;
std::cin >> areaType;
switch(areaType){
case 'c':
std::cout << "Enter Radius : ";
double radius;
std::cin >> radius;
std::cout << "Area = " << Area(radius) << "\n";
break;
case 'r':
std::cout << "Enter Height : ";
double height, width;
std::cin >> height;
std::cout << "Enter Width : ";
std::cin >> width;
std::cout << "Area = " << Area(height, width) << "\n";
break;
default : std::cout << "Please Enter c or r \n";
}
return 0;
}
std::vector<int> GenerateRandVec(int numOfNums, int min, int max){
std::vector<int> vecValues;
srand(time(NULL));
int i = 0, randVal = 0;
while(i < numOfNums){
randVal = min + std::rand() % ((max + 1) - min); // the modulus can never be greater than the divider
vecValues.push_back((randVal));
i++;
}
return vecValues;
}
void BubbleSort(std::vector<int>& theVec){
int i = theVec.size() - 1;
while(i >= 1){
int j = 0;
while(j < i){
printf("\nIs %d > %d\n", theVec[j], theVec[j+1]);
if(theVec[j] > theVec[j+1]){
std::cout << "Switch\n";
int temp = theVec[j];
theVec[j] = theVec[j+1];
theVec[j+1] = temp;
} else {
std::cout << "Don't Switch\n";
}
j += 1;
for(auto k: theVec){
std::cout << k << ", ";
}
}
std::cout << "\nEnd of Round\n";
i -= 1;
}
}
int Factorial(int number){
if(number==1){
return 1;
} else {
int result = number * Factorial(number - 1);
return result;
}
}
void PrintHorizontalVector(std::vector<int>& theVec){
int dashes = std::ceil(theVec.size() * 5);
for(int n = 0; n < dashes; n++)
std::cout << "-";
std::cout << "\n";
for(int n = 0; n < theVec.size(); n++)
printf("| %2d ", n);
std::cout << "|\n";
for(int n = 0; n < dashes; n++)
std::cout << "-";
std::cout << "\n";
for(int n = 0; n < theVec.size(); n++)
printf("| %2d ", theVec[n]);
std::cout << "|\n";
}
int Fib(int number){
/*0,1,1,2,3,5*/
if(number < 2) return number;
return Fib(number-1) + Fib(number-2);
}
double Area(double radius){
return M_PI*std::pow(radius, 2);
}
double Area(double height, double width){
return height*width;
}
|
#include <bits/stdc++.h>
#define CASE(t) printf("Case %d: ",++t) // t initialized 0
using namespace std;
#define INF 1e9
#define EPS 1e-9
#define PI acos(-1.0)
double sqr(double x)
{
return (x*x);
}
double DEG_to_RAD(double d)
{
return d * PI / 180.0;
}
double RAD_to_DEG(double r)
{
return r * 180.0 / PI;
}
struct point_i
{
int x, y; // whenever possible, work with point_i
point_i()
{
x = y = 0; // default constructor
}
point_i(int _x, int _y) : x(_x), y(_y) {}
}; // constructor
struct point
{
double x, y; // only used if more precision is needed
point()
{
x = y = 0.0; // default constructor
}
point(double _x, double _y) : x(_x), y(_y) {}
}; // constructor
struct vec
{
double x, y; // name: `vec' is different from STL vector
vec(double _x, double _y) : x(_x), y(_y) {}
};
vec toVec(point a, point b) // convert 2 points to vector a->b
{
return vec(b.x - a.x, b.y - a.y);
}
double dot(vec a, vec b)
{
return (a.x * b.x + a.y * b.y);
}
double norm_sq(vec v)
{
return v.x * v.x + v.y * v.y;
}
point translate(point p, vec v) // translate p according to v
{
return point(p.x + v.x, p.y + v.y);
}
// returns the distance from p to the line defined by
// two points a and b (a and b must be different)
// the closest point is stored in the 4th parameter (byref)
double dist(point p1, point p2) // Euclidean distance
{
// hypot(dx, dy) returns sqrt(dx * dx + dy * dy)
return hypot(p1.x - p2.x, p1.y - p2.y);
}
vec scale(vec v, double s) // nonnegative s = [<1 .. 1 .. >1]
{
return vec(v.x * s, v.y * s);
} // shorter.same.longer
double distToLine(point p, point a, point b, point &c)
{
// formula: c = a + u * ab
vec ap = toVec(a, p), ab = toVec(a, b);
double u = dot(ap, ab) / norm_sq(ab);
c = translate(a, scale(ab, u)); // translate a to c
return dist(p, c);
} // Euclidean distance between p and c
// returns the distance from p to the line segment ab defined by
// two points a and b (still OK if a == b)
// the closest point is stored in the 4th parameter (byref)
double distToLineSegment(point p, point a, point b, point &c)
{
vec ap = toVec(a, p), ab = toVec(a, b);
double u = dot(ap, ab) / norm_sq(ab);
if (u < 0.0)
{
c = point(a.x, a.y); // closer to a
return dist(p, a);
} // Euclidean distance between p and a
if (u > 1.0)
{
c = point(b.x, b.y); // closer to b
return dist(p, b);
} // Euclidean distance between p and b
return distToLine(p, a, b, c);
} // run distToLine as above
double angle(point a, point o, point b) // returns angle aob in rad
{
vec oa = toVec(o, a), ob = toVec(o, b);
return acos(dot(oa, ob) / sqrt(norm_sq(oa) * norm_sq(ob)));
}
int insideCircle(point_i p, point_i c, int r) // all integer version
{
int dx = p.x - c.x, dy = p.y - c.y;
int Euc = dx * dx + dy * dy, rSq = r * r; // all integer
return Euc < rSq ? 0 : Euc == rSq ? 1 : 2;
} //inside/border/outside
bool circle2PtsRad(point p1, point p2, double r, point &c)
{
double d2 = (p1.x - p2.x) * (p1.x - p2.x) +
(p1.y - p2.y) * (p1.y - p2.y);
double det = r * r / d2 - 0.25;
if (det < 0.0) return false;
double h = sqrt(det);
c.x = (p1.x + p2.x) * 0.5 + (p1.y - p2.y) * h;
c.y = (p1.y + p2.y) * 0.5 + (p2.x - p1.x) * h;
return true;
} // to get the other center, reverse p1 and p2
struct intersected_points
{
bool no_intersection;
pair<point,point>i_pts;
};
//intersection points of circle
//Reference :http://www.ambrsoft.com/TrigoCalc/Circles2/circle2intersection/CircleCircleIntersection.htm
intersected_points intersectPts(point c1,point c2, double r1,double r2)
{
intersected_points ret;
double x1 = c1.x;
double y1 = c1.y;
double x2 = c2.x;
double y2 = c2.y;
double sqx = sqr(x1-x2);
double sqy = sqr(y1-y2);
double dis = sqrt(sqx+sqy);
if(r1+r2>dis && dis>fabs(r1-r2))
{
ret.no_intersection = false;
double delta = (dis+r1+r2)*(dis+r1-r2)
*(dis-r1+r2)*(-dis+r1+r2);
delta = 1.00*(sqrt(delta))/4.00;
double x_i_1,y_i_1,x_i_2,y_i_2;
x_i_1 = (x1+x2)/2.00;
x_i_1 += ((x2-x1)*(sqr(r1)-sqr(r2)))/(2.000*sqr(dis));
x_i_1 += (2.00*(y1-y2)*delta)/(sqr(dis));
x_i_2 = (x1+x2)/2.00;
x_i_2 += ((x2-x1)*(sqr(r1)-sqr(r2)))/(2.000*sqr(dis));
x_i_2 -= (2.00*(y1-y2)*delta)/(sqr(dis));
y_i_1 = (y1+y2)/2.00;
y_i_1 += ((y2-y1)*(sqr(r1)-sqr(r2)))/(2.000*sqr(dis));
y_i_1 += (2.00*(x1-x2)*delta)/(sqr(dis));
y_i_2 = (y1+y2)/2.00;
y_i_2 += ((y2-y1)*(sqr(r1)-sqr(r2)))/(2.000*sqr(dis));
y_i_2 -= (2.00*(x1-x2)*delta)/(sqr(dis));
point i_p1(x_i_1,y_i_1);
point i_p2(x_i_2,y_i_2);
ret.i_pts.first = i_p1;
ret.i_pts.second = i_p2;
}
else
{
ret.no_intersection = true;
}
return ret;
}
int main()
{
int tc,cas=0;
cin>>tc;
while(tc--)
{
double x1,y1,r1,x2,y2,r2;
cin>>x1>>y1>>r1>>x2>>y2>>r2;
point c1(x1,y1);
point c2(x2,y2);
intersected_points ip =
intersectPts(c1,c2,r1,r2);
if(ip.no_intersection)
{
CASE(cas);
printf("%lf\n",0.00);
}
else
{
point ip1 = ip.i_pts.first;
point ip2 = ip.i_pts.second;
double ang1 = angle(c1,ip1,c2);
if(ang1>(PI))
{
ang1 = 2*PI - ang1;
}
double area_sector1
= (PI*sqr(r1)*ang1)/(2.00*PI);
double t_a = sqrt(sqr(c1.x-ip1.x)
+ sqr(c1.y-ip1.y));
double t_b = sqrt(sqr(c1.x-ip2.x)
+ sqr(c1.y-ip2.y));
double t_c = sqrt(sqr(ip1.x-ip2.x)
+ sqr(ip1.y-ip2.y));
double t_s = (t_a+t_b+t_c)/2;
double t_area = sqrt(t_s*(t_s-t_a)
*(t_s-t_b)
*(t_s-t_c));
area_sector1 -= t_area;
double ang2 = angle(c1,ip2,c2);
if(ang2>PI)
{
ang2 = 2*PI - ang2;
}
double area_sector2
= (PI*sqr(r1)*ang2)/(2.00*PI);
t_a = sqrt(sqr(c2.x-ip1.x)
+ sqr(c2.y-ip1.y));
t_b = sqrt(sqr(c2.x-ip2.x)
+ sqr(c2.y-ip2.y));
t_c = sqrt(sqr(ip1.x-ip2.x)
+ sqr(ip1.y-ip2.y));
t_s = (t_a+t_b+t_c)/2;
t_area = sqrt(t_s*(t_s-t_a)
*(t_s-t_b)
*(t_s-t_c));
area_sector2 -= t_area;
double fin_area
= area_sector1 + area_sector2;
CASE(cas);
printf("%f\n",fin_area);
}
}
return 0;
}
|
#include <stdio.h>
#include <algorithm>
#include <memory.h>
#include <vector>
#include <queue>
#include <functional>
using namespace std;
#define ll long long
struct edge {
ll ax, ay, bx, by;
};
struct dot {
ll x, y;
};
ll ccw(dot A, dot B, dot C) {
return (A.x*B.y + B.x*C.y + C.x*A.y) - (A.y*B.x + B.y*C.x + C.y*A.x);
}
bool isintersect(edge A, edge B) {
dot a = { A.ax,A.ay }, b = { A.bx,A.by }, c = { B.ax,B.ay }, d = { B.bx,B.by };
if (ccw(a, b, c) * ccw(a, b, d) <= 0 && ccw(c,d,a) * ccw(c,d,b) <= 0)return true;
else return false;
}
int main()
{
int n, m, k;
ll ax, ay, bx, by, q, sx, sy, ex, ey;
scanf("%d %d", &n, &m);
scanf("%d", &k);
vector <edge> A;
for (int i = 0; i < k; i++) {
scanf("%lld %lld %lld %lld %lld", &q, &ax, &ay, &bx, &by);
if (ax > bx)swap(ax, bx);
if (ay > by)swap(ay, by);
A.push_back({ ax,ay,bx,by });
}
scanf("%lld %lld %lld %lld", &sx, &sy, &ex, &ey);
vector <vector <int> >vec(A.size() + 1);
vector <bool> chk(A.size() + 1, false);
for (int i = 0; i < A.size()-1; i++) {
for (int j = i + 1; j < A.size(); j++) {
if (A[i].ax == A[i].bx && A[j].ax == A[j].bx) {
if (A[i].by < A[j].ay || A[j].by < A[i].ay)continue;
if (A[i].ay <= A[j].ay && A[j].by <= A[i].by)continue;
if (A[j].ay <= A[i].ay && A[i].by <= A[j].by)continue;
}
if (A[i].ay == A[i].by && A[j].ay == A[j].by) {
if (A[i].bx < A[j].ax || A[j].bx < A[i].ax)continue;
if (A[i].ax <= A[j].ax && A[j].bx <= A[i].bx)continue;
if (A[j].ax <= A[i].ax && A[i].bx <= A[j].bx)continue;
}
if (isintersect(A[i], A[j])) {
vec[i].push_back(j);
vec[j].push_back(i);
}
}
}
queue <dot> que;
vector <bool> ter(A.size()+1, false);
vector <int> dist(A.size() + 1, -1);
for (int i = 0; i < A.size(); i++) {
if (A[i].ax <= sx && sx <= A[i].bx && A[i].ay <= sy && sy <= A[i].by) {
dist[i] = 0;
que.push({ i,0 });
chk[i] = true;
}
if (A[i].ax <= ex && ex <= A[i].bx && A[i].ay <= ey && ey <= A[i].by)ter[i] = true;
}
while (!que.empty()) {
dot a = que.front(); que.pop();
for (int i = 0; i < vec[a.x].size(); i++) {
int b = vec[a.x][i];
if (chk[b])continue;
if (dist[b] == -1 || dist[b] > dist[a.x] + 1) {
dist[b] = dist[a.x] + 1;
que.push({ b,dist[b] });
chk[b] = true;
}
}
}
int answer = 5001;
for (int i = 0; i < ter.size(); i++) {
if (ter[i])answer = min(answer, dist[i]);
}
printf("%d\n", answer + 1);
}
|
#include "DrawGraphics.h"
namespace P_RVD
{
/*
set the initial attributes
*/
void GraphicsDrawer::Init()
{
cameraPosition = { 0.0f, 0.0f, 0.0f };
centerPosition = { 0.0f, 0.0f, 3.0f };
upDirection = { 0.0f, 1.0f, 0.0f };
// set the position of light
lightPosition[0] = 0.0f;
lightPosition[1] = 0.0f;
lightPosition[2] = 3.0f;
lightPosition[3] = 0.0f;
//set the ambient, diffuse, specular light attributes
ambient[0] = 0.2f;
ambient[1] = 0.2f;
ambient[2] = 0.2f;
ambient[3] = 1.0f;
diffuse[0] = 1.0f;
diffuse[1] = 1.0f;
diffuse[2] = 0.0f;
diffuse[3] = 1.0f;
specular[0] = 0.0f;
specular[1] = 0.0f;
specular[2] = 0.0f;
specular[3] = 1.0f;
shininess = 40.0f;
glClearColor(0.1f, 0.2f, 0.1f, 1.0f);
glEnable(GL_DEPTH_TEST);
//glDepthFunc(GL_LEQUAL);
GLfloat white_light[] = { 1.0, 1.0, 1.0, 1.0 };
GLfloat spot_direction[] = { 0.0, 0.0, -3.0};
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 60.f);
GLfloat light_model_amb[] = { 0.2, 0.2, 0.2, 1.0 };
glLightModelfv(GL_LIGHT_MODEL_AMBIENT, light_model_amb);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white_light);
glLightfv(GL_LIGHT0, GL_SPECULAR, white_light);
glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, spot_direction);
glLightfv(GL_LIGHT0, GL_POSITION, lightPosition);
glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 2.0);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
// glShadeModel(GL_SMOOTH);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
glMaterialfv(GL_FLOAT, GL_AMBIENT, ambient);
glMaterialfv(GL_FLOAT, GL_DIFFUSE, diffuse);
glMaterialfv(GL_FLOAT, GL_SPECULAR, specular);
glMaterialf(GL_FLOAT, GL_SHININESS, shininess);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluLookAt(cameraPosition.x, cameraPosition.y, cameraPosition.z,
centerPosition.x, centerPosition.y, centerPosition.z,
upDirection.x, upDirection.y, upDirection.z);
glMatrixMode(GL_MODELVIEW);
}
void GraphicsDrawer::Run()
{
glFrontFace(GL_CW);
glCullFace(GL_BACK);
glEnable(GL_CULL_FACE);
}
void GraphicsDrawer::DrawPoints(Points _points)
{
t_index number = (t_index)_points.getPointsNumber();
for (t_index i = 0; i < number; ++i)
{
glPushMatrix();
glPointSize(1.0f);
glBegin(GL_POINTS);
glVertex3d(_points.getPoint(i).x, _points.getPoint(i).y, _points.getPoint(i).z);
glEnd();
glPopMatrix();
}
}
void GraphicsDrawer::DrawMesh(const Mesh& _m)
{
t_index facet_nb = _m.meshFacets.getFacetsNumber();
//test
glPushMatrix();
glPointSize(10.0f);
glBegin(GL_POINTS);
glVertex3d(0.0f, 0.0f, 0.0f);
glEnd();
glPopMatrix();
for (t_index i = 0; i < facet_nb; ++i)
{
Facet temp_facet = _m.meshFacets.getFacet(i);
Vector3d pos1 = _m.meshVertices.getPoint(temp_facet.m_v1);
Vector3d pos2 = _m.meshVertices.getPoint(temp_facet.m_v2);
Vector3d pos3 = _m.meshVertices.getPoint(temp_facet.m_v3);
DrawTriangle(pos1, pos2, pos3);
}
}
void GraphicsDrawer::DrawTriangle(Vector3d _v1, Vector3d _v2, Vector3d _v3)
{
Vector3d normal = Math::computeNormal(_v1, _v2, _v3);
glPushMatrix();
glBegin(GL_TRIANGLES);
glNormal3d(normal.x, normal.y, normal.z);
glVertex3d(_v1.x, _v1.y, _v1.z);
glNormal3d(normal.x, normal.y, normal.z);
glVertex3d(_v2.x, _v2.y, _v2.z);
glNormal3d(normal.x, normal.y, normal.z);
glVertex3d(_v3.x, _v3.y, _v3.z);
glEnd();
glPopMatrix();
}
}
|
#include <iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int value[1005];
int vol[1005];
int just[1005][1005];
int N,V;
void d(int x)
{
if(x==N+1)
{
return;
}
else
{
for(int i=0; i<=V; i++) //่่ๆปไฝ็งฏไธบ0๏ผ็ฉๅไฝ็งฏไธบ0ๆ
ๅต
{
if(i>=vol[x])
{
just[x][i] = max(just[x-1][i-vol[x]]+value[x],just[x-1][i]);
}
else
{
just[x][i] = just[x-1][i];
}
}
d(++x);
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>N>>V;
for(int i=1; i<=N; i++)
{
cin>>value[i];
}
for(int i=1; i<=N; i++)
{
cin>>vol[i];
}
memset(just,0,sizeof(just)); //ไธๅ ๅๅงๅไน้่ฟ๏ผๅ ๅๆถ้ดๅ้ฟ
d(1);
// for(int i=0;i<=N;i++)
// {
// for(int j=0;j<=V;j++)
// {
// cout<<just[i][j]<<" ";
// }
// cout<<endl;
// }
cout<<just[N][V]<<endl;
}
return 0;
}
|
#include <SDL.h>
#include <iostream>
#include "Room.h"
#include "SDLobsluga.h"
#include <SDL_image.h>
using namespace std;
int main(int argc, char* args[])
{
int x, y;
Room room;
Ekwipunek* equipment=new Ekwipunek;
room.WeNeedToBuildAWall();
room.AddNewPuzzle('N', 359, 210, 70, 45, 0, 0,1);//sejf
room.AddNewPuzzle('N', 140, 290, 135, 130, 1, 1, 2);//szafka
room.AddNewPuzzle('S', 420, 275, 90, 50, 2, 2, 2);//szuflada
room.AddNewPuzzle('S', 125, 300, 250, 100, 3, 3, 2);//skrzynia
room.AddNewPuzzle('N', 490, 150, 200, 230, 4, 4, 2);//drzwi
room.AddNewPuzzle('E', 420, 360, 90, 50, 6, 6, 2);//szafa
room.AddNewPuzzle('W', 420, 360, 90, 50, 7, 7, 2);//krzeslo
//Start up SDL and create window
try {
init();
}
catch (int) {
cout << "Error, inicjhalizacja not working" << endl;
return 0;
}
//Load media
if (!loadMedia())
{
printf("Failed to load media!\n");
}
else
{
bool quit = false;
bool paused = false;
//Obsluga zdarzen
SDL_Event e;
ObecnyObraz = ObrazSciany[North];
Prepare();
while (!quit)
{
//Kolejka zdarzen
while (SDL_PollEvent(&e) != 0)
{
if(e.type==SDL_MOUSEBUTTONDOWN){
SDL_GetMouseState(&x, &y);
paused=room.CheckClick(x, y,room.walls->direction, equipment);
}
//Sprawdza czy zamykany
if (e.type == SDL_QUIT)
{
quit = true;
}
//Sprawdza ktory przycisk
if (e.type == SDL_KEYDOWN&&paused!=true)
{
//Lewo czy prawo
switch (e.key.keysym.sym)
{
case SDLK_LEFT:
room.walls=room.walls->previous;
break;
case SDLK_RIGHT:
room.walls = room.walls->next;
break;
default:
break;
}
//Jaka sciana
switch (room.walls->direction) {
case 'N':
ObecnyObraz = ObrazSciany[North];
break;
case 'E':
ObecnyObraz = ObrazSciany[East];
break;
case 'S':
ObecnyObraz = ObrazSciany[South];
break;
case 'W':
ObecnyObraz = ObrazSciany[West];
break;
}
}
SDL_RenderCopy(Obraz, ObecnyObraz, NULL, NULL);
SDL_RenderPresent(Obraz);
}
}
}
close();
return 0;
}
|
// Created on: 1994-06-16
// Created by: EXPRESS->CDL V0.2 Translator
// Copyright (c) 1994-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 _RWHeaderSection_ReadWriteModule_HeaderFile
#define _RWHeaderSection_ReadWriteModule_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepData_ReadWriteModule.hxx>
#include <Standard_Integer.hxx>
#include <TColStd_SequenceOfAsciiString.hxx>
class TCollection_AsciiString;
class StepData_StepReaderData;
class Interface_Check;
class Standard_Transient;
class StepData_StepWriter;
class RWHeaderSection_ReadWriteModule;
DEFINE_STANDARD_HANDLE(RWHeaderSection_ReadWriteModule, StepData_ReadWriteModule)
//! General module to read and write HeaderSection entities
class RWHeaderSection_ReadWriteModule : public StepData_ReadWriteModule
{
public:
Standard_EXPORT RWHeaderSection_ReadWriteModule();
//! associates a positive Case Number to each type of HeaderSection entity,
//! given as a String defined in the EXPRESS form
Standard_EXPORT Standard_Integer CaseStep (const TCollection_AsciiString& atype) const Standard_OVERRIDE;
//! associates a positive Case Number to each type of HeaderSection Complex entity,
//! given as a String defined in the EXPRESS form
Standard_EXPORT virtual Standard_Integer CaseStep (const TColStd_SequenceOfAsciiString& types) const Standard_OVERRIDE;
//! returns True if the Case Number corresponds to a Complex Type
Standard_EXPORT virtual Standard_Boolean IsComplex (const Standard_Integer CN) const Standard_OVERRIDE;
//! returns a StepType (defined in EXPRESS form which belongs to a
//! Type of Entity, identified by its CaseNumber determined by Protocol
Standard_EXPORT const TCollection_AsciiString& StepType (const Standard_Integer CN) const Standard_OVERRIDE;
Standard_EXPORT void ReadStep (const Standard_Integer CN, const Handle(StepData_StepReaderData)& data, const Standard_Integer num, Handle(Interface_Check)& ach, const Handle(Standard_Transient)& ent) const Standard_OVERRIDE;
Standard_EXPORT void WriteStep (const Standard_Integer CN, StepData_StepWriter& SW, const Handle(Standard_Transient)& ent) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(RWHeaderSection_ReadWriteModule,StepData_ReadWriteModule)
protected:
private:
};
#endif // _RWHeaderSection_ReadWriteModule_HeaderFile
|
/**
* Unidad 4: Servo con joystick
*/
#include <Servo.h>
Servo servo; // Crear un objeto tipo Servo llamado servo
int angulo = 0;
int pinX = A1;
int pinY = A2;
void setup() {
servo.attach(6);
}
void loop() {
int ejeX = analogRead(pinX);
angulo = ejeX - 512; // Con esta operaciรณn conseguimos tener valores entre -512 y 511
if (abs(angulo) < 50) angulo = 0; // Filtramos movimientos pequeรฑos del joystick
angulo = map(angulo, -512, 511, 0, 180); // Mapeamos los valores a grados
servo.write(angulo);
}
|
#ifndef _GLIBCXX_MACHINE_H
#define _GLIBCXX_MACHINE_H
#include <list>
#include "Item.h"
#include "Being.h"
#include "Platform.h"
using namespace std;
class Machine{
list<Item*> items;
list<Item*>::iterator it = items.end();
bool paid;
public:
Machine(bool mpaid);
bool addItem(Item& i);
void removeItem(int item);
Item& getNextItem();
int itemCount();
bool isPaid();
};
enum MACHINE_TEXTURES{BG=0, FRAME, FRAME_SEL};
class MachineResources {
public:
static int bg, frame, frame_sel;
};
class MachineManager {
map<pair<int, int>, Machine*> machines;
Renderer& rend;
Game& game;
Hitbox box;
int font;
Machine* curr_machine;
bool over_machine, render_machine;
int curr_x, curr_y;
double deltax, deltay;
bool pressed, cangetpress;
double ystart = 0.01;
double xstart = 0.01;
double itemx = 0.145;
double itemy = 0.145;
double framesp = 0.01;
int itemsel = -1, itemseli = -1;
int itemover = -1;
bool mouseOverTile(double dx, double dy, int tx, int ty);
public:
MachineManager(Game& mgame, Renderer& mrend, Hitbox& mbox, int mfont);
void add(pair<int, int> mach, bool paid);
void check(double dx, double dy, int x, int y);
void set(pair<int, int> mach);
void unset();
void render();
void control(Being* player);
bool addItem(pair<int, int> mach, Item& it);
void updateVars(double deltax, double deltay, bool pressed, bool cangetpress);
bool exists(pair<int, int> mach);
bool isRendering();
bool currentIsPaid();
pair<int, int> getCurrentCoords();
void clear();
};
#endif
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* 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.
*/
#ifndef SKLAND_GUI_INTERNAL_ABSTRACT_EVENT_HANDLER_PRIVATE_HPP_
#define SKLAND_GUI_INTERNAL_ABSTRACT_EVENT_HANDLER_PRIVATE_HPP_
#include <skland/gui/abstract-event-handler.hpp>
#include <skland/core/rect.hpp>
#include "abstract-event-handler-event-task.hpp"
#include "abstract-event-handler-redraw-task.hpp"
namespace skland {
struct AbstractEventHandler::Private {
Private(AbstractEventHandler *event_handler)
: mouse_task(event_handler),
mouse_motion_task(event_handler),
redraw_task(event_handler),
is_damaged_(false) {}
~Private() {}
EventTask mouse_task;
EventTask mouse_motion_task;
RedrawTask redraw_task;
// Damage area
bool is_damaged_;
RectI damaged_region_;
};
}
#endif // SKLAND_GUI_INTERNAL_ABSTRACT_EVENT_HANDLER_PRIVATE_HPP_
|
/*****************************************************************************************************************
* File Name : sortElementsByFrequency.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\sites\geeksforgeeks\arrays\page07\sortElementsByFrequency.h
* Created on : Jan 5, 2014 :: 8:08:17 PM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef SORTELEMENTSBYFREQUENCY_H_
#define SORTELEMENTSBYFREQUENCY_H_
bool sortFunc(pair<int,unsigned> it1,pair<int,unsigned int> it2){
if(it1.second != it2.second){
return it1.second > it2.second?true:false;
}else{
return it1.first > it2.first?true:false;
}
}
void sortElementsByFrequencyHashmap(vector<int> userInput){
if(userInput.size() == 0 || userInput.size() == 1){
return;
}
hash_map<int,unsigned int> frequencyMap;
hash_map<int,unsigned int>::iterator itToFrequencyMap;
vector<pair<int,unsigned int> > sortedFrequencyMap;
pair<int,unsigned int> itToSortedPair;
unsigned int count;
for(unsigned int counter = 0;counter < userInput.size();counter++){
if((itToFrequencyMap = frequencyMap.find(userInput[counter])) != frequencyMap.end()){
frequencyMap[itToFrequencyMap->first] += 1;
}else{
frequencyMap.insert(pair<int,unsigned int>(userInput[counter],1));
}
}
copy(frequencyMap.begin(),frequencyMap.end(),back_inserter(sortedFrequencyMap));
sort(sortedFrequencyMap.begin(),sortedFrequencyMap.end(),sortFunc);
userInput.clear();
for(unsigned int counter = 0;counter < sortedFrequencyMap.size();counter++){
itToSortedPair = sortedFrequencyMap[counter];
count = itToSortedPair.second;
while(count--){
userInput.push_back(itToSortedPair.first);
}
}
}
void sortElementsByFrequencySort(vector<int> userInput){
if(userInput.size() == 0 || userInput.size() == 1){
return;
}
sort(userInput.begin(),userInput.end());
vector<pair<int,unsigned int> > frequencyMap;
unsigned int frequency = 0;
for(unsigned int counter=0;counter < userInput.size();){
frequency = 1;
while(counter + 1 < userInput.size() && userInput[counter] == userInput[counter+1]){
frequency += 1;
}
frequencyMap.push_back(pair<int,unsigned int>(userInput[counter],frequency));
counter += frequency;
}
sort(frequencyMap.begin(),frequencyMap.end(),sortFunc);
userInput.clear();
pair<int,unsigned int> itToSortedPair;
for(unsigned int counter = 0;counter < frequencyMap.size();counter++){
itToSortedPair = frequencyMap[counter];
frequency = itToSortedPair.second;
while(frequency--){
userInput.push_back(itToSortedPair.first);
}
}
}
#endif /* SORTELEMENTSBYFREQUENCY_H_ */
/************************************************* End code *******************************************************/
|
/*
===========================================================================
Copyright (C) 2017 waYne (CAM)
===========================================================================
*/
#pragma once
#ifndef ELYSIUM_CORE_OBJECT
#define ELYSIUM_CORE_OBJECT
#ifndef ELYSIUM_CORE_EXPORT
#include "Export.hpp"
#endif
namespace Elysium
{
namespace Core
{
/// <summary>
/// Object serves as base for any class of this framework, comparable to.NET
/// </summary>
class EXPORT Object
{
public:
// constructors & destructor
Object();
virtual ~Object();
// methods
//virtual Object* Clone(); // https://www.agiledeveloper.com/articles/cloning072002.htm
//virtual String ToString();
protected:
// copy constructor
Object(const Object& Source);
};
}
}
#endif
|
// WAP to create an array where index is the multiple of all the elements
//expect that
#include<stdio.h>
#include<conio.h>
void Multiply(int*, int*, int);
void main(){
int size;
int a[100];
int b[100];
scanf_s("%d", &size);
for (int i = 0; i < size; i++) scanf_s("%d", &a[i]);
Multiply(a, b, size);
for (int i = 0; i < size; i++)
printf("%d\t", b[i]);
_getch();
}
void Multiply(int *ap, int *bp, int size){
ap[-1] = 1;
bp[size] = 1;
for (int i = 0; i < size; i++){
bp[i] = ap[i];
ap[i] = ap[i] * ap[i - 1];
}
for (int i = size-1; i >= 0; i--){
bp[i] = bp[i] * bp[i + 1];
}
int i = -1;
int j = 1;
while (1){
if (j > size) break;
bp[j - 1] = bp[j] * ap[i];
j++;
i++;
}
}
|
#include "particle.h"
void V_scalar::update_v(double eta, double torque, Ran &myran) {
double tmp = std::sqrt(vx_next * vx_next + vy_next * vy_next);
double c1 = vx_next / tmp;
double s1 = vy_next / tmp;
double noise;
if (eta > 0) {
noise = (myran.doub() - 0.5) * eta * 2 * PI + torque;
} else {
noise = torque;
}
double c2 = std::cos(noise);
double s2 = std::sin(noise);
vx = vx_next = c1 * c2 - s1 * s2;
vy = vy_next = c1 * s2 + c2 * s1;
}
void V_scalar::update_x(double & _x, double & _y, double v0, double Lx, double Ly) {
_x += v0 * vx;
_y += v0 * vy;
if (_x < 0) {
_x += Lx;
} else if (_x >= Lx) {
_x -= Lx;
}
if (_y < 0) {
_y += Ly;
} else if (_y >= Ly) {
_y -= Ly;
}
}
void V_vectorial::update_v(double eta, double torque, Ran &myran) {
double noise_x, noise_y;
myran.circle_point_picking(noise_x, noise_y);
double tmp = eta * n_neighbor;
vx_next += noise_x * tmp;
vy_next += noise_y * tmp;
tmp = 1 / std::sqrt(vx_next * vx_next + vy_next * vy_next);
vx_next *= tmp;
vy_next *= tmp;
if (torque != 0) {
double c1 = std::cos(torque);
double s1 = std::sin(torque);
vx = c1 * vx_next - s1 * vy_next;
vy = c1 * vy_next - s1 * vx_next;
vy_next = vx;
vy_next = vy;
} else {
vx = vx_next;
vy = vy_next;
}
n_neighbor = 1;
}
double V_conti::h;
double V_conti::sqrt_24_Dr_h;
void V_conti::update_x(double & _x, double & _y, double v0, double Lx, double Ly) {
double vx = v0 * std::cos(theta);
double vy = v0 * std::sin(theta);
_x += vx * h;
_y += vy * h;
if (_x < 0) {
_x += Lx;
} else if (_x >= Lx) {
_x -= Lx;
}
if (_y < 0) {
_y += Ly;
} else if (_y >= Ly) {
_y -= Ly;
}
}
|
/*
* MidiMessage.h
*
* Created on: Feb 4, 2019
* Author: juniper
*/
#ifndef TOUCHKEYS_MIDIMESSAGE_H_
#define TOUCHKEYS_MIDIMESSAGE_H_
// MIDI standard messages
enum {
kMidiMessageNoteOff = 0x80,
kMidiMessageNoteOn = 0x90,
kMidiMessageAftertouchPoly = 0xA0,
kMidiMessageControlChange = 0xB0,
kMidiMessageProgramChange = 0xC0,
kMidiMessageAftertouchChannel = 0xD0,
kMidiMessagePitchWheel = 0xE0,
kMidiMessageSysex = 0xF0,
kMidiMessageSysexEnd = 0xF7,
kMidiMessageActiveSense = 0xFE,
kMidiMessageReset = 0xFF
};
enum {
kMidiControlAllSoundOff = 120,
kMidiControlAllControllersOff = 121,
kMidiControlLocalControl = 122,
kMidiControlAllNotesOff = 123
};
class MidiMessage {
public:
MidiMessage(int channel, int type, int note, int velocity);
MidiMessage();
~MidiMessage();
int getChannel() const;
void setChannel(int channel);
int getNote() const;
int getNoteNumber() const;
void setNote(int note);
int getType() const;
void setType(int type);
int getVelocity() const;
void setVelocity(int velocity);
bool isNoteOff() const;
bool isNoteOn() const;
bool isAftertouch() const;
bool isAllNotesOff() const;
bool isAllSoundOff() const;
bool isController() const;
int getControllerNumber() const;
int getControllerValue() const;
bool isChannelPressure() const;
int getChannelPressureValue() const;
bool isPitchWheel() const;
int getPitchWheelValue() const;
static MidiMessage noteOn(int channel, int note, int velocity);
static MidiMessage noteOff(int channel, int note);
static MidiMessage noteOff(int channel, int note, int);
static MidiMessage aftertouchChange(int channel, int note, int value);
int getAfterTouchValue() const;
int getRawDataSize() const;
const unsigned char* getRawData() const;
private:
int channel_;
int type_;
int note_;
int velocity_;
int controller_;
int controllerValue_;
int pitchWheelValue_;
};
#endif /* TOUCHKEYS_MIDIMESSAGE_H_ */
|
#include <iostream>
using namespace std;
typedef struct LIST_NODE
{
int Data;
LIST_NODE *Next_Ptr;
} LIST_NODE;
class Linked_LIST
{
private:
int Global_Position;
LIST_NODE* Head_NODE;
public:
Linked_LIST();
int Create();
int Get_ITEM(int n);
bool IsEmpty();
int Length();
int Insert(int Position, int Data);
int Retrieve(int Data);
int Delete(int Position);
int Destroy();
};
extern Linked_LIST LIST;
|
#include "Acceptor.h"
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/socket.h>
#include "InetAddress.h"
#include "Logger.h"
namespace chatty {
namespace net {
Acceptor::setConnectionCallback() {
// channel_.setReadCallBack();
channel_.setReadCallBack(std::bind(&Acceptor::startAccept, this));
}
Acceptor::Acceptor(EventLoop *loop, int fd)
: loop_(loop), acceptSock_(fd), channel_(loop, fd) {
channel_.setReadCallBack(Acceptor::startAccept);
}
int Acceptor::startListen() {
struct sockaddr_in address;
::memset(&address, 0, sizeof address);
address.sin_family = AF_INET;
address.sin_addr.sin_addr = ::htonl(INADDR_ANY);
address.sin_port = htons();
if (::bind(fd_, (struct sockaddr *)&address, (socklen_t)sizeof address) !=
0) {
LOGERROR << "bind()" << std::endl;
exit(-1);
}
if (::listen(fd_, SOMAXCONN) != 0) {
LOGERROR << "listen()" << std::endl;
exit(-1);
}
}
void Acceptor::startAccept() {
InetAddress addr;
int fd = acceptSock_.accept(&addr);
assert(fd > 0);
auto conn = std::make_shared<TcpConnection>(loop_, fd, addr);
connCallback_(conn);
}
} // namespace net
} // namespace chatty
|
#ifndef __HSAREA__
#define __HSAREA__
#define HSAREA_PROPERTY(GetFunc , SetFunc , Type , Name) __declspec(property(get = GetFunc , put = SetFunc)) Type Name
#define HSAREA_PROPERTY_R(GetFunc , Type , Name) __declspec(property(get = GetFunc)) Type Name
enum EHSAreaType {
EHSAreaType_Rectangle = 0,
EHSAreaType_Circle
};
template <typename T> struct THSPoint {
T x;
T y;
};
template <typename T> struct THSize {
T Width;
T Height;
};
template <typename T> struct THSArea {
T left;
T right;
T top;
T bottom;
};
template <typename T> class CHSArea : public THSArea<T>{
private:
EHSAreaType _InnnerAreaType;
public:
CHSArea () {
_InnnerAreaType = EHSAreaType_Rectangle;
left = right = top = bottom = 0;
}
void Set ( T left , T top , T right , T bottom ) {
this->left = left;
this->top = top;
this->right = right;
this->bottom = bottom;
}
void Set ( THSArea<T> tArea ) {
this->left = tArea.left;
this->top = tArea.top;
this->right = tArea.right;
this->bottom = tArea.bottom;
}
EHSAreaType SetAreaType ( EHSAreaType Type ) {
_InnnerAreaType = Type;
return Type;
}
EHSAreaType GetAreaType ( void ) {
return _InnnerAreaType;
}
//__declspec ( property( get = GetAreaType , put = SetAreaType ) ) EHSAreaType AreaType;
HSAREA_PROPERTY ( GetAreaType , SetAreaType , EHSAreaType , AreaType );
THSPoint<T> GetCenter ( void ) {
THSPoint<T> pt;
pt.x = ( left + right ) / 2;
pt.y = ( top + bottom ) / 2;
return pt;
}
void SetCenter ( T x , T y ) {
THSPoint<T> c = this->GetCenter ();
this->MoveOffset ( x - c.x , y - c.y );
}
void SetCenter ( THSPoint<T> ptCenter ) {
THSPoint<T> c = this->GetCenter ();
this->MoveOffset ( ptCenter.x - c.x , ptCenter.y - c.y );
}
THSize<T> GetSize (void) {
THSize<T> s;
s.Width = right - left;
s.Height = bottom - top;
return s;
}
void SetSize ( T Width , T Height ) {
this->right = this->left + Width;
this->bottom = this->top + Height;
}
void SetSize ( THSize<T> size ) {
this->SetSize ( size.Width , size.Height );
}
THSize<T> GetPixelSize ( void ) {
THSize<T> s = this->GetSize ();
s.Width++;
s.Height++;
return s;
}
void SetPixelSize ( T Width , T Height ) {
this->SetSize ( Width - 1, Height - 1);
}
void SetPixelSize ( THSize<T> size ) {
this->SetPixelSize ( size.Width , size.Height );
}
T GetCircleRadius () {
THSize<T> s = this->GetSize ();
T m = ( s.Width < s.Height ) ? s.Width : s.Height;
return m / 2;
}
void SetCircleRadius ( T radius ) {
THSPoint<T> pt = this->GetCenter ();
this->left = pt.x - radius;
this->top = pt.y - radius;
this->right = pt.x + radius;
this->bottom = pt.y + radius;
}
void MoveTo ( T left , T top ){
T offsetX = left - this->left;
T offsetY = top - this->top;
this->right += offsetX;
this->bottom += offsetY;
this->left = left;
this->top = top;
}
void MoveOffset ( T OffsetX , T OffsetY ) {
this->left += OffsetX;
this->right += OffsetX;
this->top += OffsetY;
this->bottom += OffsetY;
}
bool HitTest ( T x , T y ) {
THSize<T> size;
T r2;
switch ( _InnnerAreaType ) {
case EHSAreaType_Rectangle:
if ( ( x >= left ) && ( x <= right ) ) {
if ( ( y >= top ) && ( y <= bottom ) ) {
return true;
}
}
break;
case EHSAreaType_Circle:
size = this->GetSize ();
if ( size.Width < size.Height ) r2 = size.Width * size.Width;
else r2 = size.Height * size.Height;
T xside = this->left + this->right - 2 * x;
T yside = this->top + this->bottom - 2 * y;
if ( r2 >= ( xside * xside + yside * yside ) ) {
return true;
}
break;
}
return false;
}
bool HitTest ( THSPoint<T> pt ) {
return this->HitTest ( pt.x , pt.y );
}
bool HitTest ( CHSArea<T> Area ) {
THSize<T> size;
if ( Area.AreaType == _InnnerAreaType ) {
switch ( _InnnerAreaType ) {
case EHSAreaType_Rectangle:
if ( ( this->right >= Area.left ) && ( this->left <= Area.right ) ) {
if ( ( this->bottom >= Area.top ) && ( this->top <= Area.bottom ) ) {
return true;
}
}
break;
case EHSAreaType_Circle:
T r1 , r2;
THSPoint<T> pt1 , pt2;
size = this->GetSize ();
r1 = ( size.Width < size.Height ) ? size.Width : size.Height;
size = Area.GetSize ();
r2 = ( size.Width < size.Height ) ? size.Width : size.Height;
pt1 = this->GetCenter ();
pt2 = Area.GetCenter ();
T lhs = ( r1 + r2 ) * ( r1 + r2 ) / 4;
T rhs1 = ( pt2.x - pt1.x ) * ( pt2.x - pt1.x );
T rhs2 = ( pt2.y - pt1.y ) * ( pt2.y - pt1.y );
if ( lhs >= ( rhs1 + rhs2 ) ) {
return true;
}
break;
}
} else {
CHSArea *pCircleSide , *pRectangleSide;
if ( this->_InnnerAreaType == EHSAreaType_Rectangle ) {
pRectangleSide = this;
pCircleSide = &Area;
} else {
pRectangleSide = &Area;
pCircleSide = this;
}
THSPoint<T> CircleCenter = pCircleSide->GetCenter ();
THSize<T> CircleSize = pCircleSide->GetSize ();
T Radius = ( CircleSize.Width < CircleSize.Height ) ? CircleSize.Width / 2: CircleSize.Height / 2;
//้ทๆนๅฝขใฎ้ ็นใๅใซๆฅ่งฆใใฆใใชใใใ็ขบ่ช
//ๅทฆไธ
if ( pCircleSide->HitTest ( pRectangleSide->left , pRectangleSide->top ) ) return true;
//ๅณไธ
if ( pCircleSide->HitTest ( pRectangleSide->right , pRectangleSide->top ) ) return true;
//ๅณไธ
if ( pCircleSide->HitTest ( pRectangleSide->right , pRectangleSide->bottom ) ) return true;
//ๅทฆไธ
if ( pCircleSide->HitTest ( pRectangleSide->left , pRectangleSide->bottom ) ) return true;
//ๅใ้ทๆนๅฝขใฎๅ
้จใซใใใ
if ( pRectangleSide->HitTest ( CircleCenter ) ) return true;
//่พบใจๅใๆฅ่งฆใใฆใชใใ(ๅพๆฅๅฎ่ฃ
)
}
return false;
}
bool HitTest ( THSArea<T> Area , EHSAreaType Type ) {
CHSArea<T> ca;
ca.Set ( Area );
ca.AreaType = Type;
return this->HitTest(ca);
}
/*
//ๅพๆฅๅฎ่ฃ
ไบๅฎ
bool HitTestLine ( T x1 , T y1 , T x2 , T y2 ) {
switch ( _InnnerAreaType ) {
case EHSAreaType_Rectangle:
break;
case EHSAreaType_Circle:
break;
}
return false;
}
*/
};
#endif
|
#include <conio.h>
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <math.h>
#include <locale.h>
#include <ctype.h>
float valor = 1;
int main()
{
ret:
printf("\nInsira um valor\n");
scanf("%f",&valor);
while(valor>=0)
{
printf("\nInsira um valor\n");
scanf("%f",&valor);
}
printf("\nInsira somente valores positivos\n");
goto ret;
}
|
/*
#include <stdio.h>
#include <string.h>
#include "pico/stdlib.h"
//#include "hardware/spi.h"
#include "hardware/gpio.h"
*/
#include "pico/time.h"
#include "blinkt.h"
#define dataPin 17
#define clockPin 18
int main()
{
//stdio_init_all();
blinkt_init(dataPin, clockPin);
for(;;) {
static int red = 0;
red = 10 - red; // switch between on and off
for (int i = 0; i < 8; ++i) {
blinkt_show();
sleep_ms(100);
blinkt_set_pixel_colour(i, red, 0, 0);
}
}
return 0;
}
|
#include <iostream>
#include <stdlib.h>
using namespace std;
class Vector{
private:
int length, capacity;
double *v;
public:
Vector(){
length= 0;
cout<<"Enter starting capacity of the array\n";
cin>>capacity;
v = new double[2];
}
~Vector(){
cout<<"Array deleted\n";
}
int getLength();
int getCapacity();
void grow(int);
void append(double);
void removeLast();
void print();
void insert(int, double);
};
int Vector::getLength(){
return length;
}
int Vector::getCapacity(){
return capacity;
}
//increases the capacity of the array by the given amount
void Vector::grow(int amount){
capacity += amount;
double *vNew = new double[capacity];
for (int i = 0; i<length; i++){
*(vNew + i) = *(v+i);
}
v = vNew;
delete [] vNew;
}
//adds the given element to the end of the array
void Vector::append(double num){
if (length == capacity){
grow(1);
}
length++;
*(v+ length-1) = num;
}
//removes last element of the array
void Vector::removeLast(){
if (length == 0){
cout<< "Error: No elements in vector\n";
}
else{
*(v+length-1) = 0;
length--;
}
}
//prints all elements of the array
void Vector::print(){
if (length == 0){
cout<<"Array Empty";
}
else{
for (int i = 0; i<length; i++){
cout<<v[i]<<endl;
}
}
}
//inserts an element at the given index
void Vector::insert(int index, double num){
if (index<0 || index>=length){
cout<<"Error: Index out of range";
}
else{
if(length==capacity){
grow(1);
}
//shift all elements after index to the right
else{
for (int i = length-1; i>=index; i--){
v[i+1] = v[i];
}
v[index] = num;
length++;
}
}
}
int main() {
Vector vec1;
int choice, s = 0;
while(s ==0){
std::cout<<"Main menu:\n\n1. Print the array\n2. Append element at the end\n3. Remove last element\n";
std::cout<<"4. Insert one element\n5. Exit\n\nSelect an option:\n";
std::cin>>choice;
switch(choice){
case 1: cout<<"You selected 'Print the array'"<<endl;
vec1.print();
break;
case 2: cout<<"You selected 'Append element at the end'"<<endl;
double entry;
cout<<"Enter value to add\n";
cin>>entry;
vec1.append(entry);
break;
case 3: cout<<"You selected 'Remove last element'"<<endl;
vec1.removeLast();
break;
case 4: cout<<"You selected 'Insert one element'"<<endl;
int i;
double val;
cout<<"Enter index\n";
cin>>i;
cout<<"Enter value to append\n";
cin>>val;
vec1.insert(i, val);
break;
case 5: cout<<"You selected 'Exit'"<<endl;
s = 1;
break;
default: cout<<"Error: Invalid entry"<<endl;
}
}
}
|
๏ปฟ#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
using namespace std;
int N;
int nMap[101][101];
int nAns[101][101];
int nChecked[101][101];
queue<int> q;
void BFS(int y)
{
q.push(y);
while (!q.empty())
{
int cy = q.front();
q.pop();
for (int i = 1; i <= N; i++)
{
if (nMap[cy][i] == 1 && nChecked[cy][i] == 0)
{
nAns[y][i] = 1;
nChecked[cy][i] = 1;
q.push(i);
}
}
}
}
int main(void)
{
cin >> N;
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
cin >> nMap[i][j];
}
}
for (int y = 1; y <= N; y++)
{
BFS(y);
memset(nChecked, 0, sizeof(nChecked));
}
for (int i = 1; i <= N; i++)
{
for (int j = 1; j <= N; j++)
{
cout << nAns[i][j] << " ";
}
cout << endl;
}
return 0;
}
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "CSPowerUpSpawner.h"
#include "CSPowerUpBase.h"
#include "CSCharacter.h"
#include "Components/DecalComponent.h"
#include "Components/SphereComponent.h"
#include "TimerManager.h"
// Sets default values
ACSPowerUpSpawner::ACSPowerUpSpawner()
{
// 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;
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
SphereComp->SetSphereRadius(75.0f);
RootComponent = SphereComp;
DecalComp = CreateDefaultSubobject<UDecalComponent>(TEXT("DecalComp"));
DecalComp->SetRelativeRotation(FRotator(0.0f, -90.0f, 0.0f));
DecalComp->DecalSize = FVector(64, 75, 75);
DecalComp->SetupAttachment(RootComponent);
SetReplicates(true);
}
// Called when the game starts or when spawned
void ACSPowerUpSpawner::BeginPlay()
{
Super::BeginPlay();
Respawn();
}
void ACSPowerUpSpawner::NotifyActorBeginOverlap(AActor* OtherActor)
{
Super::NotifyActorBeginOverlap(OtherActor);
if (Role < ENetRole::ROLE_Authority)
return;
ACSCharacter * PlayerPawn = Cast<ACSCharacter>(OtherActor);
if (PlayerPawn == nullptr)
return;
// This is running only on the server PowerUpInstance will be nullptr here on the clients
if (PowerUpInstance)
{
PowerUpInstance->Activate(PlayerPawn);
PowerUpInstance = nullptr;
GetWorldTimerManager().SetTimer(TimerHandle_RespawnTimer, this, &ACSPowerUpSpawner::Respawn, RespawnTimer, false);
}
}
void ACSPowerUpSpawner::Respawn()
{
if (Role < ENetRole::ROLE_Authority)
return;
if (PowerUpClass == nullptr)
{
UE_LOG(LogTemp, Warning, TEXT("PowerUpClass is nullptr in %s. Please update your blueprint"), *GetName());
return;
}
FActorSpawnParameters SpawnParams;
SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn;
PowerUpInstance = GetWorld()->SpawnActor<ACSPowerUpBase>(PowerUpClass, GetTransform(), SpawnParams);
}
|
#include <iostream>
using namespace std;
int main(){
int tests{};
int cols{};
int diff{};
int top{};
int bottom{};
bool possible{};
cin >> tests;
while(tests--){
diff = -1;
possible = true;
cin >> cols;
while(cols--){
cin >> top >> bottom;
if(diff == -1){
diff = top - bottom;
}else{
if(diff != top - bottom){
possible = false;
}
}
}
if(possible){
cout << "yes" << endl;
}else{
cout << "no" << endl;
}
if(tests){
cout << endl;
}
}
}
|
#ifndef __RTSP_SVR_HH__
#define __RTSP_SVR_HH__
#include <pthread.h>
#include "LiveStreamMediaSource.hh"
#include "BasicUsageEnvironment.hh"
//#include "service/Service.h"
#include "RTSPServer.hh"
class CRtspServer //: public CService
{
public:
CRtspServer();
virtual ~CRtspServer();
virtual int PrepareStream(const char *pStreamName);
virtual int ReleaseStream();
virtual int Start(int port);
virtual int Stop();
virtual bool PushVideo(unsigned char* data, unsigned int length, uint64_t pts);
virtual bool PushAudio(unsigned char* data, unsigned int length, uint64_t pts);
virtual int SetParamConfig(const char *key, const char *val);
//virtual int Java_fireNotify(JNIEnv *env, int type, int arg1, int arg2, void* obj);
void ParserUrl(const char* streamName, char* fileName, int maxLen);
char* LiveUrl();
bool IsAudioEnable();
static CRtspServer * pThis; //ฮยฒฮยฌฮฮคฮฯฮฆฮฮฅฮป
static void DemandIDR(void* arg, int streamId);
protected:
static void* ThreadRtspServerProcImpl(void* arg);
void ThreadRtspServer();
private:
int m_port;
char m_StreamName[128];
bool m_Stop;
LiveStreamMediaSource* m_Input;
char m_watchVariable;
TaskScheduler* m_scheduler;
UsageEnvironment* m_env;
RTSPServer* m_rtspServer;
pthread_t m_pThread;
int m_pushVCnt;
int m_pushACnt;
bool m_EnableAudio;
FILE* m_264;
//
};
#define LOGI_print(n, t, ...) fprintf(stderr, n" "t"\n", ##__VA_ARGS__)
#define LOGD_print(n, t, ...) fprintf(stderr, n" "t"\n", ##__VA_ARGS__)
#define LOGW_print(n, t, ...) fprintf(stderr, n" "t"\n", ##__VA_ARGS__)
#define LOGE_print(n, t, ...) fprintf(stderr, n" "t"\n", ##__VA_ARGS__)
#endif
|
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
// ะัะธะผะตั ะฑะฐะทะพะฒัั
ะพะฟะตัะฐัะธะน ั ัะธะบัะธัะพะฒะฐะฝะฝัะผะธ ะพะดะฝะพะผะตัะฝัะผะธ ะผะฐััะธะฒะฐะผะธ
// V 1.0
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
#include <iostream>
using namespace std;
int main() {
cout << "ะฆะตะปะพัะธัะปะตะฝะฝัะน ะผะฐััะธะฒ\n";
int arr[5];
// int arr[5] = {23, 1, 12, 70, 3}; // ะัะพััะฐั ะธะฝะธัะธะฐะปะธะทะฐัะธั ัะธะบัะธัะพะฒะฐะฝะฝะพะณะพ ะผะฐััะธะฒะฐ
// ะะฝะธัะธะฐะปะธะทะธััะตะผ ะฒัะต ัะปะตะผะตะฝัั ะผะฐััะธะฒะฐ ะทะฝะฐัะตะฝะธะตะผ 0
// int array[5] = {};
// int array[5] { 4, 5, 8, 9, 12 }; // ะะปะธ ัะฐะบ (uniform-ะธะฝะธัะธะฐะปะธะทะฐัะธั)
// int array[] = {0, 1, 2, 3, 4}; // ัะฟะธัะพะบ ะธะฝะธัะธะฐะปะธะทะฐัะพัะพะฒ ะฐะฒัะพะผะฐัะธัะตัะบะธ ะพะฟัะตะดะตะปะธั ะดะปะธะฝั ะผะฐััะธะฒะฐ
cout << "ะ ะฐะทะผะตั ะผะฐััะธะฒะฐ: " << sizeof(arr) / sizeof(arr[5]) << endl;
arr[0] = {1}; // ะะพะผะตัะฐะตะผ ะฒ ะธะฝะดะตะบั 0 ะผะฐััะธะฒะฐ ัะธัะปะพ 1
cout << "ะกะพะดะตัะถะธะผะพะต ะผะฐััะธะฒะฐ: " << arr[0] << endl;
arr[1] = {14}; // ะะพะผะตัะฐะตะผ ะฒ ะธะฝะดะตะบั 1 ะผะฐััะธะฒะฐ ัะธัะปะพ 14
cout << "ะกะพะดะตัะถะธะผะพะต 2-ะณะพ ะธะฝะดะตะบัะฐ ะผะฐััะธะฒะฐ: " << arr[1] << endl;
cout << "ะะฐะฟะพะปะฝัะตะผ ะธะฝะดะตะบัั ะผะฐััะธะฒะฐ ะฟัะธ ะฟะพะผะพัะธ ัััััะธะบะฐ" << endl;
int a = 0;
for (int i = 0; i <= 4; ++i) {
cout << (arr[i] = {++a}) << " ";
}
cout << "ะกะธะผะฒะพะปัะฝัะน ะผะฐััะธะฒ\n";
char ch[13] = {'H', 'e', 'l', 'l', 'o', ',', ' ',
'W', 'o', 'r', 'l', 'd', '!'};
cout << ch << endl;
cout << "ะะฐััะธะฒ ะฒะตัะตััะฒะตะฝะฝัั
ัะธัะตะป\n";
float fl[4] = {0};
float ff = 0.0;
for (int f = 0; f <= 4; ++f) {
cout << (fl[f] = {ff += 0.1}) << " ";
}
cout << "\n";
cout << "ะะฐะฟะพะปะฝะตะฝะธะต ะผะฐััะธะฒะฐ ะฒัััะฝัั\n";
int man[3];
cout << "ะะฒะตะดะธัะต ะฟะพ ะพัะตัะตะดะธ ััะธ ัะตะปัั
ัะธัะปะฐ\n";
int b, c, d;
cin >> b >> c >> d; // ะะฒะพะด ะดะฐะฝะฝัั
ะฟะพะปัะทะพะฒะฐัะตะปะตะผ
man[0] = {b};
man[1] = {c};
man[2] = {d};
cout << "ะกะพะดะตัะถะธะผะพะต ะฟะพะปัะทะพะฒะฐัะตะปััะบะพะณะพ ะผะฐััะธะฒะฐ: " << man[0] << " " << man[1] << " " << man[2] << endl;
// ะัะฟะพะปัะทัะตะผ ะฟะตัะตัะธัะปะตะฝะธะต (ะบะพะฝััะฐะฝัั) ะฒ ะบะฐัะตััะฒะต ะธะฝะดะตะบัะฐ
cout << " \n";
enum {
INDEX = 0
};
arr[INDEX] = {5};
cout << arr[0] << endl;
// ะัะฟะพะปัะทัะตะผ ะฟะตัะตะผะตะฝะฝัั (ะฝะต ะบะพะฝััะฐะฝัั) ะฒ ะบะฐัะตััะฒะต ะธะฝะดะตะบัะฐ
short index = 4;
arr[index] = {50};
cout << arr[index] << endl;
cout << endl;
// ะคะธะบัะธัะพะฒะฐะฝะฝัะต ะผะฐััะธะฒั ะฝะต ะผะพะณัั ะฑััั runtime!
int array[5]; // ะผะฐััะธะฒ ัะพะดะตัะถะธั 5 ะฟัะพัััั
ัะธัะตะป
array[0] = 4;
array[1] = 5;
array[2] = 8;
array[3] = 9;
array[4] = 12;
for (int i = 0; i <= 4; ++i) {
cout << array[i] << endl;
}
// ะัั ะพะดะธะฝ ัะฟะพัะพะฑ ะฟะพะปััะธัั ัะพะดะตัะถะธะผะพะต ัะธะบัะธัะพะฒะฐะฝะฝะพะณะพ ะผะฐััะธะฒะฐ
cout << endl;
for (auto t : array) {
cout << t << " ";
}
return 0;
}
// Output
/*
ัะตะปะพัะธัะปะตะฝะฝัะน ะผะฐััะธะฒ
ะ ะฐะทะผะตั ะผะฐััะธะฒะฐ: 5
ะกะพะดะตัะถะธะผะพะต ะผะฐััะธะฒะฐ: 1
ะกะพะดะตัะถะธะผะพะต 2-ะณะพ ะธะฝะดะตะบัะฐ ะผะฐััะธะฒะฐ: 14
ะะฐะฟะพะปะฝัะตะผ ะธะฝะดะตะบัั ะผะฐััะธะฒะฐ ะฟัะธ ะฟะพะผะพัะธ ัััััะธะบะฐ
1 2 3 4 5 ะกะธะผะฒะพะปัะฝัะน ะผะฐััะธะฒ
Hello, World!
ะะฐััะธะฒ ะฒะตัะตััะฒะตะฝะฝัั
ัะธัะตะป
0.1 0.2 0.3 0.4 0.5
ะะฐะฟะพะปะฝะตะฝะธะต ะผะฐััะธะฒะฐ ะฒัััะฝัั
ะะฒะตะถะธัะต ะฟะพ ะพัะตัะตะดะธ ััะธ ัะตะปัั
ัะธัะปะฐ
45
32
69
ะกะพะดะตัะถะธะผะพะต ัััะฝะพะณะพ ะผะฐัััะธะฒะฐ: 45 32 69
*/
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
// END FILE
// -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- //
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2005 Opera Software AS. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
#ifndef BTConfigDialog_H
#define BTConfigDialog_H
#include "SimpleDialog.h"
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/m2/src/util/buffer.h"
#include "adjunct/m2/src/engine/engine.h"
#include "adjunct/bittorrent/bt-util.h"
#include "adjunct/bittorrent/connection.h"
#include "modules/windowcommander/OpTransferManager.h"
#include "modules/xmlutils/xmlparser.h"
#include "modules/xmlutils/xmltoken.h"
#include "modules/xmlutils/xmltokenhandler.h"
class BTConfigDialog : public Dialog,
public OpTransferListener,
public XMLTokenHandler,
public XMLParser::Listener,
public OpSocketListener
{
public:
BTConfigDialog();
virtual ~BTConfigDialog();
Type GetType() {return DIALOG_TYPE_BITTORRENT_CONFIGURATION;}
DialogType GetDialogType() {return TYPE_OK_CANCEL;}
const char* GetWindowName() {return "BitTorrent Configuration Dialog";}
const char* GetHelpAnchor() {return "bittorrent.html#prefs";}
BOOL GetModality() {return TRUE;}
BOOL GetIsBlocking() {return TRUE;}
void OnInit();
void OnCancel();
UINT32 OnOk();
BOOL OnInputAction(OpInputAction *action);
void OnClick(OpWidget *widget, UINT32 id);
private:
// MpSocketObserver.
virtual void OnSocketInstanceNumber(int instance_number) { }
virtual void OnSocketConnected(OpSocket* socket) { }
virtual void OnSocketDataReady(OpSocket* socket) { }
virtual void OnSocketClosed(OpSocket* socket) { }
virtual void OnSocketConnectionRequest(OpSocket* socket) {};
virtual void OnSocketConnectError(OpSocket* socket, OpSocket::Error socket_error) { }
virtual void OnSocketListenError(OpSocket* socket, OpSocket::Error error) {}
virtual void OnSocketReceiveError(OpSocket* socket, OpSocket::Error socket_error) { }
virtual void OnSocketSendError(OpSocket* socket, OpSocket::Error socket_error) { }
virtual void OnSocketCloseError(OpSocket* socket, OpSocket::Error socket_error) { }
virtual void OnSocketDataSendProgressUpdate(OpSocket* socket, unsigned int bytes_sent) { }
virtual void OnSocketDataSent(OpSocket* socket, unsigned int bytes_sent) { }
// OpTransferListener
void OnProgress(OpTransferItem* transferItem, TransferStatus status);
void OnReset(OpTransferItem* transferItem) { }
void OnRedirect(OpTransferItem* transferItem, URL* redirect_from, URL* redirect_to) {};
// XML Parsing callbacks.
void StartElementHandler(const XMLToken &token);
void EndElementHandler(const XMLToken &token);
void CharacterDataHandler(const uni_char *s, int len);
// Implementation of the XMLTokenHandler API
virtual XMLTokenHandler::Result HandleToken(XMLToken &token);
// Implementation of the XMLParser::Listener API
virtual void Continue(XMLParser *parser);
virtual void Stopped(XMLParser *parser);
private:
P2PSocket m_listensocket;
OpString m_content_string;
OpString m_return_status;
OpString m_source_ip_address;
INT32 m_feed_id;
OpEdit *m_port;
OpTransferItem* m_transfer_item;
};
#endif // BTConfigDialog_H
|
#ifndef DATEWINDOW_H
#define DATEWINDOW_H
#include <QDialog>
#include <QPushButton>
namespace Ui {
class dateWindow;
}
class dateWindow : public QDialog
{
Q_OBJECT
public:
explicit dateWindow(QWidget *parent = 0);
~dateWindow();
private:
Ui::dateWindow *ui;
QPushButton *doneButton;
};
#endif // DATEWINDOW_H
|
// Created on: 1993-02-26
// Created by: Remi LEQUETTE
// Copyright (c) 1993-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 _TopLoc_SListNodeOfItemLocation_HeaderFile
#define _TopLoc_SListNodeOfItemLocation_HeaderFile
#include <Standard.hxx>
#include <TopLoc_SListOfItemLocation.hxx>
#include <TopLoc_ItemLocation.hxx>
#include <Standard_Transient.hxx>
class TopLoc_SListNodeOfItemLocation;
DEFINE_STANDARD_HANDLE(TopLoc_SListNodeOfItemLocation, Standard_Transient)
class TopLoc_SListNodeOfItemLocation : public Standard_Transient
{
public:
TopLoc_SListNodeOfItemLocation(const TopLoc_ItemLocation& I, const TopLoc_SListOfItemLocation& aTail);
TopLoc_SListOfItemLocation& Tail() const;
TopLoc_ItemLocation& Value() const;
DEFINE_STANDARD_RTTIEXT(TopLoc_SListNodeOfItemLocation,Standard_Transient)
protected:
private:
TopLoc_SListOfItemLocation myTail;
TopLoc_ItemLocation myValue;
};
#include <TopLoc_SListNodeOfItemLocation.lxx>
#endif // _TopLoc_SListNodeOfItemLocation_HeaderFile
|
//==========================LDR and LEDS===================================================
#define analogpin 0
#define led_r 10
#define led_g 11
#include <LiquidCrystal.h>
LiquidCrystal lcd(2,3,4,5,6,7);
int val;
void setup() {
Serial.begin(9600);
lcd.begin(16,2);
pinMode(analogpin,INPUT);
pinMode(led_r ,OUTPUT);
pinMode(led_g ,OUTPUT);
pinMode(8, OUTPUT);}
void loop(){
lcd.clear();
val = analogRead (analogpin);
Serial.println (val);
if(val<470){
lcd.println("*DOOR IS CLOSED*");
delay(100);
lcd.clear();
digitalWrite(led_r ,1);
digitalWrite(led_g ,0);
}
else{
lcd.print("**DOOR IS OPEN**");
delay(100);
digitalWrite(led_g ,1);
digitalWrite(led_r ,0);
}}
|
#include <string>
#include <iostream>
#include <vector>
#include <cctype>
using namespace std;
int fun(string A){
int i = A.length()-1;
int ans = 0;
int flag = 1;
if(int(A[i])==32){
// cout<<"yes";
while(i>=0&&int(A[i])==32){
i--;
}
}
cout<<A;
while(i>=0&&int(A[i])!=32){
i--;
// flag = 0;
ans++;
}
return ans;
}
int main(){
string s;
getline(cin,s);
// cout<<s;
cout<<fun(s);
}
|
#ifndef MATH_PRIME_FACTOR_HPP
#define MATH_PRIME_FACTOR_HPP
#include <vector>
namespace Math
{
std::vector<int> primeFactors(int num)
{
std::vector<int> v;
int f = 2;
while (num > 1)
{
if (num % f == 0)
{
v.push_back(f);
num /= f;
}
else
++f;
}
return v;
}
} // namespace Math
#endif /* end of include guard : MATH_PRIME_FACTOR_HPP */
|
#include "string.h"
#include "input_params.h"
// Print usage.
void display_usage()
{
cout << "--help\n";
cout << "--lattice-size [32, 64, 128] {##} (default 32x32)\n";
cout << "--operator [laplace, laplace2, staggered\n";
cout << " g5_staggered, normal_staggered, index] (default staggered)\n";
cout << "--outer-solver [gcr, bicgstab, cg] (default gcr)\n";
cout << "--outer-precision [outer prec] (default 5e-7)\n";
cout << "--outer-max-iter [outer maximum iterations] (default 100000)\n";
cout << "--outer-restart [yes, no] (default yes)\n";
cout << "--outer-restart-freq [#] (default 64)\n";
cout << "--null-operator [laplace, laplace2, staggered\n";
cout << " g5_staggered, normal_staggered, index] (default staggered)\n";
cout << "--null-precond [none, eo, normal] (default none, only applies to staggered)\n";
cout << "--null-solver [gcr, bicgstab, cg, cr, minres,\n";
cout << " arpack, bicgstab-l, richardson] (default bicgstab)\n";
cout << "--null-precision [null prec] {#, #...} (default 5e-5)\n";
cout << "--null-max-iter [null nax iter] {#, #...} (default 500)\n";
cout << "--null-restart [yes, no] (default no)\n";
cout << "--null-restart-freq [#] (default 8 if restarting is enabled)\n";
cout << "--null-bicgstab-l [#] (default 4 if using bicgstab-l)\n";
cout << "--null-relax-param [#] (default 1, needs to be set for convergence)\n";
//cout << "--null-mass [mass] {#, #...} (default 1e-4)\n";
cout << "--null-mass [mass] (default 1e-2)\n";
cout << "--null-eo [corner, yes, no, topo] (default yes)\n";
cout << "--null-global-ortho-conj [yes, no] (default no, it only helps in some weird fluke cases)\n";
cout << "--null-ortho-eo [yes, no] (default no)\n";
cout << "--mass [mass] (default 1e-2)\n";
cout << "--blocksize [blocksize] {#, #...} (default 4, same for all levels)\n";
cout << "--nvec [nvec] {#, #...} (default 4, same for all levels)\n";
cout << "--nrefine [number coarse] (default 1)\n";
cout << "--cycle-type [v, k] (default v)\n";
cout << "--mg-type [self, normal_eqn] (default self)\n";
cout << "--smoother-solver [gcr, bicgstab, cg, minres,\n";
cout << " cr, bicgstab-l, none] (default gcr)\n";
cout << "--smoother-type [self, normal_eqn] (default self)\n";
cout << "--npre-smooth [presmooth steps] {#, #, ...} (default 6, same for all levels)\n";
cout << "--npost-smooth [postsmooth steps] {#, #, ...} (default 6, same for all levels)\n";
cout << "--coarse-solver [gcr, bicgstab, cg, minres,\n";
cout << " cr, none] (default gcr)\n";
cout << "--coarse-precision [coarse precision] {#, #, ...} (default 1e-2, same for all levels)\n";
cout << "--coarse-max-iter [coarse maximum iterations] (default 1024)\n";
cout << "--coarse-restart-freq [#] (default 64)\n";
cout << "--gauge [unit, load, random] (default load)\n";
cout << "--gauge-transform [yes, no] (default no)\n";
cout << "--beta [3.0, 6.0, 10.0, 10000.0] (default 6.0)\n";
cout << "--load-cfg [path] (default do not load, overrides beta)\n";
cout << "--do-freetest [yes, no] (default no)\n";
cout << "--do-eigentest [yes, no] (default no)\n";
cout << "--n-ev [all, # smallest] (default all)\n";
cout << "--n-cv [#] (default min(all, 2.5*n-ev))\n";
}
// Parse inputs, put into mg_input_params.
int parse_inputs(int argc, char** argv, mg_input_params *params)
{
for (int i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0)
{
display_usage();
return 0;
}
if (i+1 != argc)
{
if (strcmp(argv[i], "--mass") == 0)
{
params->mass = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--operator") == 0)
{
if (strcmp(argv[i+1], "laplace") == 0)
{
params->opt = LAPLACE;
}
else if (strcmp(argv[i+1], "laplace2") == 0)
{
params->opt = LAPLACE_NC2;
}
else if (strcmp(argv[i+1], "staggered") == 0)
{
params->opt = STAGGERED;
}
else if (strcmp(argv[i+1], "g5_staggered") == 0)
{
params->opt = G5_STAGGERED;
}
else if (strcmp(argv[i+1], "normal_staggered") == 0)
{
params->opt = STAGGERED_NORMAL;
}
else if (strcmp(argv[i+1], "index") == 0)
{
params->opt = STAGGERED_INDEX;
}
i++;
}
else if (strcmp(argv[i], "--outer-solver") == 0)
{
if (strcmp(argv[i+1], "gcr") == 0)
{
params->out_solve = OUTER_GCR;
}
else if (strcmp(argv[i+1], "bicgstab") == 0)
{
params->out_solve = OUTER_BICGSTAB;
}
else if (strcmp(argv[i+1], "cg") == 0)
{
params->out_solve = OUTER_CG;
}
i++;
}
else if (strcmp(argv[i], "--outer-precision") == 0)
{
params->outer_precision = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--outer-max-iter") == 0)
{
params->outer_max_iter = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--outer-restart") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->outer_restart = true;
}
else if (strcmp(argv[i+1], "no") == 0)
{
params->outer_restart = false;
}
i++;
}
else if (strcmp(argv[i], "--outer-restart-freq") == 0)
{
params->outer_restart_freq = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-operator") == 0)
{
if (strcmp(argv[i+1], "laplace") == 0)
{
params->nvec_params.opt_null = LAPLACE;
}
else if (strcmp(argv[i+1], "laplace2") == 0)
{
params->nvec_params.opt_null = LAPLACE_NC2;
}
else if (strcmp(argv[i+1], "staggered") == 0)
{
params->nvec_params.opt_null = STAGGERED;
}
else if (strcmp(argv[i+1], "g5_staggered") == 0)
{
params->nvec_params.opt_null = G5_STAGGERED;
}
else if (strcmp(argv[i+1], "normal_staggered") == 0)
{
params->nvec_params.opt_null = STAGGERED_NORMAL;
}
else if (strcmp(argv[i+1], "index") == 0)
{
params->nvec_params.opt_null = STAGGERED_INDEX;
}
i++;
}
else if (strcmp(argv[i], "--blocksize") == 0)
{
params->blocksizes[0] = atoi(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->blocksizes.push_back(atoi(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--nvec") == 0)
{
params->nvec_params.n_null_vectors[0] = atoi(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->nvec_params.n_null_vectors.push_back(atoi(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--null-precond") == 0)
{
if (strcmp(argv[i+1], "none") == 0)
{
params->nvec_params.null_prec = NULL_PRECOND_NONE;
}
else if (strcmp(argv[i+1], "eo") == 0)
{
params->nvec_params.null_prec = NULL_PRECOND_EO;
}
else if (strcmp(argv[i+1], "normal") == 0)
{
params->nvec_params.null_prec = NULL_PRECOND_NORMAL;
}
i++;
}
else if (strcmp(argv[i], "--null-precision") == 0)
{
params->nvec_params.null_precisions[0] = atof(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->nvec_params.null_precisions.push_back(atof(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--null-max-iter") == 0)
{
params->nvec_params.null_max_iters[0] = atoi(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->nvec_params.null_max_iters.push_back(atoi(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--null-restart") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->nvec_params.null_restart = true;
}
else if (strcmp(argv[i+1], "no") == 0)
{
params->nvec_params.null_restart = false;
}
i++;
}
else if (strcmp(argv[i], "--null-restart-freq") == 0)
{
params->nvec_params.null_restart_freq = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-bicgstab-l") == 0)
{
params->nvec_params.null_bicgstab_l = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-relax-param") == 0)
{
params->nvec_params.null_relaxation = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-mass") == 0)
{
params->nvec_params.null_mass = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--null-solver") == 0)
{
if (strcmp(argv[i+1], "gcr") == 0)
{
params->nvec_params.null_gen = MINV_GCR;
}
else if (strcmp(argv[i+1], "bicgstab") == 0)
{
params->nvec_params.null_gen = MINV_BICGSTAB;
}
else if (strcmp(argv[i+1], "cg") == 0)
{
params->nvec_params.null_gen = MINV_CG;
}
else if (strcmp(argv[i+1], "cr") == 0)
{
params->nvec_params.null_gen = MINV_CR;
}
else if (strcmp(argv[i+1], "minres") == 0)
{
params->nvec_params.null_gen = MINV_MINRES;
}
else if (strcmp(argv[i+1], "richardson") == 0)
{
params->nvec_params.null_gen = MINV_SOR;
}
else if (strcmp(argv[i+1], "arpack") == 0)
{
params->nvec_params.null_gen = MINV_INVALID;
params->nvec_use_eigen = true;
}
else if (strcmp(argv[i+1], "bicgstab-l") == 0)
{
params->nvec_params.null_gen = MINV_BICGSTAB_L;
}
i++;
}
else if (strcmp(argv[i], "--null-eo") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->nvec_params.bstrat = BLOCK_EO; // even/odd
}
else if (strcmp(argv[i+1], "corner") == 0)
{
params->nvec_params.bstrat = BLOCK_CORNER; // corners
}
else if (strcmp(argv[i+1], "topo") == 0)
{
params->nvec_params.bstrat = BLOCK_TOPO; // chirality as defined by taste singlet.
}
else // none.
{
params->nvec_params.bstrat = BLOCK_NONE; // fully reduce.
}
i++;
}
else if (strcmp(argv[i], "--null-global-ortho-conj") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->nvec_params.do_global_ortho_conj = true; // yes, globally orthogonalize null vectors against previous and conj.
}
else if (strcmp(argv[i+1], "no") == 0)
{
params->nvec_params.do_global_ortho_conj = false;
}
i++;
}
else if (strcmp(argv[i], "--null-ortho-eo") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->nvec_params.do_ortho_eo = true; // yes, split null vectors into eo before orthogonalizing.
}
else if (strcmp(argv[i+1], "no") == 0)
{
params->nvec_params.do_ortho_eo = false;
}
i++;
}
else if (strcmp(argv[i], "--nrefine") == 0)
{
params->n_refine = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--multi-strategy") == 0)
{
if (strcmp(argv[i+1], "smooth") == 0)
{
params->mlevel_type = MLEVEL_SMOOTH;
}
else if (strcmp(argv[i+1], "recursive") == 0)
{
params->mlevel_type = MLEVEL_RECURSIVE;
}
i++;
}
else if (strcmp(argv[i], "--cycle-type") == 0) // aliased to multi-strategy
{
if (strcmp(argv[i+1], "v") == 0)
{
params->mlevel_type = MLEVEL_SMOOTH;
}
else if (strcmp(argv[i+1], "k") == 0)
{
params->mlevel_type = MLEVEL_RECURSIVE;
}
i++;
}
else if (strcmp(argv[i], "--coarse-solver") == 0)
{
if (strcmp(argv[i+1], "cr") == 0)
{
params->in_solve = CR;
}
else if (strcmp(argv[i+1], "bicgstab") == 0)
{
params->in_solve = BICGSTAB;
}
else if (strcmp(argv[i+1], "cg") == 0)
{
params->in_solve = CG;
}
else if (strcmp(argv[i+1], "gcr") == 0)
{
params->in_solve = GCR;
}
else if (strcmp(argv[i+1], "minres") == 0)
{
params->in_solve = MINRES;
}
else if (strcmp(argv[i+1], "none") == 0)
{
params->in_solve = NONE;
}
i++;
}
else if (strcmp(argv[i], "--coarse-precision") == 0)
{
params->inner_precisions[0] = atof(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->inner_precisions.push_back(atof(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--coarse-max-iter") == 0)
{
params->inner_max = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--coarse-restart-freq") == 0)
{
params->inner_restart = atoi(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--gauge") == 0)
{
if (strcmp(argv[i+1], "unit") == 0)
{
params->gauge_load = GAUGE_UNIT;
}
else if (strcmp(argv[i+1], "random") == 0)
{
params->gauge_load = GAUGE_RANDOM;
}
else
{
params->gauge_load = GAUGE_LOAD;
}
i++;
}
else if (strcmp(argv[i], "--gauge-transform") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->do_gauge_transform = true;
}
else
{
params->do_gauge_transform = false;
}
i++;
}
else if (strcmp(argv[i], "--beta") == 0)
{
params->beta = atof(argv[i+1]);
i++;
}
else if (strcmp(argv[i], "--lattice-size") == 0)
{
params->lattice_size_x = atoi(argv[i+1]);
if (i+2 != argc)
{
if (argv[i+2][0] == '-' && argv[i+2][1] == '-') // look for --
{
params->lattice_size_y = params->lattice_size_x;
}
else // assume number
{
params->lattice_size_y = atoi(argv[i+2]);
i++;
}
}
else
{
params->lattice_size_y = params->lattice_size_x; // At the end, don't try to grab the next element!
}
i++;
}
else if (strcmp(argv[i], "--mg-type") == 0)
{
if (strcmp(argv[i+1], "self") == 0)
{
params->normal_eqn_mg = false;
}
else if (strcmp(argv[i+1], "normal_eqn") == 0)
{
params->normal_eqn_mg = true;
}
i++;
}
else if (strcmp(argv[i], "--smoother-solver") == 0)
{
if (strcmp(argv[i+1], "gcr") == 0)
{
params->in_smooth = MINV_GCR;
}
else if (strcmp(argv[i+1], "bicgstab") == 0)
{
params->in_smooth = MINV_BICGSTAB;
}
else if (strcmp(argv[i+1], "cg") == 0)
{
params->in_smooth = MINV_CG;
}
else if (strcmp(argv[i+1], "cr") == 0)
{
params->in_smooth = MINV_CR;
}
else if (strcmp(argv[i+1], "minres") == 0)
{
params->in_smooth = MINV_MINRES;
}
else if (strcmp(argv[i+1], "bicgstab-l") == 0)
{
params->in_smooth = MINV_BICGSTAB_L;
}
else if (strcmp(argv[i+1], "none") == 0)
{
params->in_smooth = MINV_INVALID;
}
i++;
}
else if (strcmp(argv[i], "--smoother-type") == 0)
{
if (strcmp(argv[i+1], "self") == 0)
{
params->normal_eqn_smooth = false;
}
else if (strcmp(argv[i+1], "normal_eqn") == 0)
{
params->normal_eqn_smooth = true;
}
i++;
}
else if (strcmp(argv[i], "--npre-smooth") == 0)
{
params->pre_smooths[0] = atoi(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->pre_smooths.push_back(atoi(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--npost-smooth") == 0)
{
params->post_smooths[0] = atoi(argv[i+1]);
i++;
while (i+1 != argc && argv[i+1][0] != '-')
{
params->post_smooths.push_back(atoi(argv[i+1]));
i++;
}
}
else if (strcmp(argv[i], "--load-cfg") == 0)
{
params->load_cfg = argv[i+1];
params->do_load = true;
i++;
}
else if (strcmp(argv[i], "--do-freetest") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->do_free = true;
}
else
{
params->do_free = false;
}
i++;
}
//#ifdef EIGEN_TEST
else if (strcmp(argv[i], "--do-eigentest") == 0)
{
if (strcmp(argv[i+1], "yes") == 0)
{
params->do_eigentest = true;
}
else
{
params->do_eigentest = false;
}
i++;
}
else if (strcmp(argv[i], "--n-ev") == 0)
{
if (strcmp(argv[i+1], "all") == 0)
{
params->set_eigen = -1;
params->set_cv = -1;
}
else
{
params->set_eigen = atoi(argv[i+1]);
}
i++;
}
else if (strcmp(argv[i], "--n-cv") == 0)
{
params->set_cv = atoi(argv[i+1]);
i++;
}
//#endif // EIGENTEST
else
{
display_usage();
return 0;
}
}
}
return 1;
}
// Set defaults.
mg_input_params::mg_input_params()
{
////// TOP LEVEL PROPERTIES ////////
// Describe the staggered fermions
// double
mass = 0.01; // Can be overridden on command line with --mass
// What operator are we using for the solve? (Laplace is free only.) Can set on command line.
// op_type
opt = STAGGERED; // STAGGERED, LAPLACE, LAPLACE_NC2, G5_STAGGERED
// L_x = L_y = Dimension for a lattice.
// int
lattice_size_x = 32; // Can be set on command line with --lattice-size.
lattice_size_y = 32;
/////// OUTER SOLVER ////////
// Solver algorithm to use.
//outer_solver
out_solve = OUTER_GCR;
// Target relative residual for outer solver.
//double
outer_precision = 5e-7;
// Are we using restarts for the otuer solver?
//bool
outer_restart = true;
// How frequently are we restarting, if we are?
//int
outer_restart_freq = 64;
// What's the maximum number of outer iterations before we give up?
//int
outer_max_iter = 100000;
/////// NULL VECTOR GENERATION ///////////////
// What operator are we using for null vector generation? Can set on command line.
//op_type
nvec_params.opt_null = STAGGERED;
// Null vector generation
// If GEN_NULL_VECTOR isn't defined:
// 1 for just const vector, 2 for const + even/odd vector, 4 for each corner
// of the hypercube.
// If GEN_NULL_VECTOR is defined and eo = 0:
// Generate "n_null_vector" null vectors which are block orthogonalized.
// IF GEN_NULL_VECTOR is defined and eo = 1:
// Generate "n_null_vector" null vectors, partition into even and odd.
// Total number of null vectors is 2*VECTOR_COUNT.
// IF GEN_NULL_VECTOR is defined and eo = 3:
// Generate "n_null_vector" null vectors, partition into four corners.
// Total number of null vectors is 4*VECTOR_COUNT.
//int
nvec_params.n_null_vectors.push_back(4); // Note: Gets multiplied by 2 for LAPLACE_NC2 test.
// Can be overriden on command line with --nvec
// How are we generating null vectors?
//mg_null_gen_type
nvec_params.null_gen = MINV_BICGSTAB; // MINV_GCR, MINV_CG, MINV_MINRES, MINV_BICGSTAB_L
// How are we preconditioning our solve?
//null_precond_strategy
nvec_params.null_prec = NULL_PRECOND_NONE; // NULL_PRECOND_EO, NULL_PRECOND_NORMAL
// Relative precision we solve the residual equation to, per level.
//vector<double>
nvec_params.null_precisions.push_back(5e-5); // Can be overriden on command line with --null-precision
// Maximum number of iterations for null vector generation, per level.
//vector<int>
nvec_params.null_max_iters.push_back(500); // Can be overriden on command line with --null-max-iter
// Do we restart our null space solver?
//bool
nvec_params.null_restart = false;
// if we are restarting, what's the frequency?
//int
nvec_params.null_restart_freq = 8;
// What l to use if we're using BiCGStab-l for null vector generation.
//int
nvec_params.null_bicgstab_l = 4;
// What relaxation parameter are we using for MinRes or Richardson?
//double
nvec_params.null_relaxation = 1.0;
// What mass do we use for null vector generation?
//double
nvec_params.null_mass = 1e-2;
// How many ways do we split the null vectors up?
//int
nvec_params.null_partitions = 2;
// blocking strategy
//blocking_strategy
nvec_params.bstrat = BLOCK_EO; // BLOCK_NONE, BLOCK_EO, BLOCK_CORNER
// Do we globally orthogonalize null vectors both against previous null vectors and their conjugate?
//bool
nvec_params.do_global_ortho_conj = false;
// Do we split null vectors into even/odd, then orthogonalize, or do we orthogonalize first?
//bool
nvec_params.do_ortho_eo = false;
// Do we just generate null vectors with arpack instead?
nvec_use_eigen = false;
//////// MG PROPERTIES ////////////
// vector of block sizes.
//vector<int>
blocksizes.push_back(4);
// Multigrid information.
//int
n_refine = 1; // 1 = two level V cycle, 2 = three level V cycle, etc.
// Can be set on command line with --nrefine
// Inner solver.
//mg_multilevel_type
mlevel_type = MLEVEL_SMOOTH; // V cycle = MLEVEL_SMOOTH, K cycle = MLEVEL_RECURSIVE
// MG type---do I use D_coarse everywhere, or D^\dag_coarse D_coarse?
//bool
normal_eqn_mg = false;
//////////// MG SMOOTHER //////////
// What solver do we use to smooth?
//inner_solver
in_smooth = MINV_GCR; // MINV_BICGSTAB, MINV_BICGSTAB_L, MINV_CG, MINV_CR, MINV_MINRES, MINV_INVALID for none.
// What relaxation parameter do we use (for MINRES)
//double
omega_smooth = 0.67; // for MINRES only.
// How many pre-smoothing iterations do we perform?
//vector<int>
pre_smooths.push_back(6);
// How many post-smoothing iterations do we perform?
//vector<int>
post_smooths.push_back(6);
// Do we smooth with the normal equations?
//bool
normal_eqn_smooth = false; // do we smooth with the normal equations?
////////// COARSE SOLVE ///////////
// What solver do we use for coarse solvers?
//inner_solver
in_solve = GCR; //CR; //GCR;
// What inner precision do we solve to?
//vector<double>
inner_precisions.push_back(1e-2);
// What is the restart frequency of our inner solve?
//int
inner_restart = 64;
// What is te maximum number of iterations for our inner solve?
//int
inner_max = 1024;
/////////// GAUGE FIELD /////////////
// How are we creating the gauge field? Load it, random, unit? Can set on command line.
//gauge_create_type
gauge_load = GAUGE_LOAD; // GAUGE_LOAD, GAUGE_UNIT, GAUGE_RANDOM
// Should we do a random gauge rotation? Can set on command line.
//bool
do_gauge_transform = false;
// Gauge field information.
//double
beta = 6.0; // For random gauge field, phase angles have std.dev. 1/sqrt(beta).
// For heatbath gauge field, corresponds to non-compact beta.
// Can be set on command line with --beta.
// Load an external cfg?
//char*
load_cfg = NULL;
//bool
do_load = false;
///////////// TEST TYPES //////////////
// Do the free field test? Overrides # null vectors, partitioning scheme, etc.
//bool
do_free = false;
//#ifdef EIGEN_TEST
//bool
do_eigentest = false;
//int
set_eigen = -1; // default for generating all eigenvalues.
//int
set_cv = -1; // default for generating all eigenvalues, or
//#endif // EIGEN_TEST
}
|
#include<cstdio>
#include<string>
#include<vector>
#include<set>
#include<cctype>
#include<iostream>
#include<sstream>
using namespace std;
set<string> ss;
set<string>::iterator it;
string s,t;
vector<string> ans;
int n,m;
int cnt;
inline void tol()
{
for(int i=0;i<s.length();++i)
if(isalpha(s[i])) s[i]=tolower(s[i]);
else s[i]=' ';
}
int main()
{
cnt=1;
while(scanf("%d%d",&n,&m)!=EOF){
ss.clear();
ans.clear();
while(n--){
cin>>s;
tol();
ss.insert(s);
}
getchar();
for(int i=0;i<m;++i){
getline(cin,t);
s=t;
tol();
int c=0;
istringstream is(s);
for(string a;is>>a;)
if(ss.count(a))
++c;
if(n<=c){
if(n<c) ans.clear();
n=c;
ans.push_back(t);
}
}
printf("Excuse Set #%d\n",cnt++);
for(int i=0;i<ans.size();++i)
cout<<ans[i]<<endl;
putchar('\n');
}
return 0;
}
/*
#include <iostream>
#include <sstream>
#include <vector>
#include <set>
#include <cctype>
#include <iterator>
#include <algorithm>
using namespace std;
char downcase(char c) { return tolower(c); }
char cleanup(char c) { return isalpha(c) ? tolower(c) : ' '; }
int main()
{
ios::sync_with_stdio(false);
for (int K, E, Ti = 1; cin >> K >> E; Ti++) {
set<string> keywords;
for (int i = 0; i < K; i++) {
string s;
cin >> s;
transform(s.begin(), s.end(), s.begin(), downcase);
keywords.insert(s);
}
cin.ignore();
vector<string> ans;
int m = 0;
for (int i = 0; i < E; i++) {
string line;
getline(cin, line);
const string orig_line = line;
transform(line.begin(), line.end(), line.begin(), cleanup);
istringstream iss(line);
cout<<line<<endl;
int c = 0;
for (string s; iss >> s;) {
if (keywords.count(s)) {
++c;
}
}
if (c > m) {
m = c;
ans.clear();
ans.push_back(orig_line);
} else if (c == m) {
ans.push_back(orig_line);
}
}
cout << "Excuse Set #" << Ti << endl;
copy(ans.begin(), ans.end(), ostream_iterator<string>(cout, "\n"));
cout << endl;
}
return 0;
}
*/
|
#ifndef USER_H_
#define USER_H_
#include <iostream>
#include <fstream>
#include <string.h>
#include <vector>
#include "parser.h"
#include "helper_funcs.h"
using namespace std;
int addUser(Json::Value requestBody){
// Check arguments inside requestBody
string checkStr[2] = {"username", "password"};
bool foundAll = jsonContains(requestBody, checkStr, 2);
if(!foundAll){ // should have username and password
return 400;
} else{
// Create user with username
string username = requestBody["username"].asString();
string folder_name = root_dir + "/users/" + username;
if(mkdir(folder_name.c_str(), 0777) != -1){
// Overwrite total users
if(!inc_total_users()){
return 500;
} else {
cout<<"Successfully created user " + username<<endl;
ofstream w_file;
w_file.open((root_dir + "/users/" + username + "/info.txt").c_str());
Json::StyledWriter styledWriter;
w_file<<styledWriter.write(requestBody);
w_file.close();
return 201; // Created
}
} else{
cout<<"Cant created user " + username<<endl;
return 400; // Bad Request
}
}
// Code should never go down and return over here
return 500;
}
int removeUser(Json::Value requestBody){
int status_code = user_check_Del_Update_Permission(requestBody);
if(status_code != 0){
return status_code;
} else{ // Allow delete & update on user now!!
string username = requestBody["username"].asString();
string user_folder = root_dir + "/users/" + username;
int status = removeDir(user_folder);
if(status < 0){
cout<<"removeUser: cant remove user "<<username<<endl;
return 500; // Server Internal Error
} else {
// Overwrite total users
if(!dec_total_users()){
return 500;
} else {
cout<<"removeUser: successfully remove user "<<username<<endl;
return 204; // Deleted
}
}
}
// Code should never go down and return over here
return 500;
}
int updateUser(Json::Value requestBody){
int status_code = user_check_Del_Update_Permission(requestBody);
if(status_code != 0){
cout<<"not allowed to update\n";
return status_code;
} else{ // Allow delete & update on user now!!
string username = requestBody["username"].asString();
Json::Value value;
int status = getUserContent(username, value);
if(status != 200){
return status;
} else{
// Insert updated value:
Json::Value new_value;
Json::StyledWriter styledWriter;
bool has_new_password = false;
for(auto const& key : requestBody.getMemberNames()){
if(key == "password" && has_new_password)
continue;
else if(key == "new_password"){
new_value["password"] = requestBody["new_password"];
has_new_password = true;
} else{
new_value[key] = requestBody[key];
}
}
update(requestBody, new_value);
// Writeback to info.txt
string user_folder = root_dir + "/users/" + username;
ofstream w_file;
w_file.open((user_folder + "/info.txt").c_str(), ios::trunc);
w_file<<styledWriter.write(new_value);
w_file.close();
return 200;
}
}
// Code should never go down and return over here
return 500;
}
int getUser(Json::Value requestBody, Json::Value& result){
// Check arguments inside requestBody
string checkStr1[2] = {"username", "password"};
bool foundAll = jsonContains(requestBody, checkStr1, 2);
if(!foundAll){ // Does not have specific key for this METHOD
return 400;
} else{
// Update the user from the database
string username = requestBody["username"].asString();
string password = requestBody["password"].asString();
string user_folder = root_dir + "/users/" + username;
// Check if username EXISTS and info.txt EXISTS or not
if(!isDirExist(user_folder)) // username does not EXIST
return 400; // Bad Request
if(!isFileExist(user_folder + "/info.txt")) // somehow info.txt got deleted
return 500; // Server Internal Error
// Check if the username and password given matches before removing user
ifstream input_file((user_folder + "/info.txt").c_str());
// Read info.txt
input_file.seekg(0, ios::end);
streampos length = input_file.tellg();
input_file.seekg(0, ios::beg);
char buf[1024];
input_file.read(buf, length);
string temp(buf);
// Parse username and password from info.txt
Json::Reader reader;
Json::Value value;
if(reader.parse(temp, value)){
// Check arguments inside requestBody
string checkStr2[2] = {"username", "password"};
foundAll = jsonContains(value, checkStr2, 2);
if(foundAll){
string user_username = value["username"].asString();
string user_password = value["password"].asString();
if(username != user_username){ // username DIFFERENT username in info.txt
return 500; // Server Internal Error
} else{
if(password == user_password){
// Only allow getting user if given password
// the same as the password stored in the database
result = value;
return 200;
} else{ // password is DIFFERENT => cant delete
cout<<"Password is DIFFERENT\n";
return 400; // Bad Request
}
}
} else{ // cant find either username or password in info.txt
return 500;
}
} else{ // cant parse Json Object from info.txt
return 500; // Server Internal Error
}
}
// Code should never go down and return over here
return 500;
}
#endif // USER_H_
|
#include<iostream>
#include<algorithm>
#include<ctime>
#include<vector>
using namespace std;
int main()
{
int n=10000000;
vector<int> data;
data.resize(n);
srand(time(NULL));
for(int i=0;i<n;i++)
{
data[i]=(rand()%10);
}
clock_t t=clock();
sort(data.begin(),data.begin()+n);
t=clock()-t;
cout<<t<<endl;
cout<<t/(double)CLOCKS_PER_SEC<<endl;
return 0;
}
|
#ifndef RDDLPARSER_PSTREAM_H
#define RDDLPARSER_PSTREAM_H
#include<fstream>
class PStream{
public:
PStream(const char* name);
PStream& operator<<(bool val);
PStream& operator<<(short val);
PStream& operator<<(unsigned short val);
PStream& operator<<(int val);
PStream& operator<<(unsigned int val);
PStream& operator<<(long val);
PStream& operator<<(unsigned long val);
PStream& operator<<(float val);
PStream& operator<<(double val);
PStream& operator<<(long double val);
PStream& operator<<(void* val);
private:
std::ofstream stream;
};
#endif
|
#include "harmdataview.h"
#include "module_base_def.h"
#include "qcustomplot.h"
#include "statdatatool.h"
#include <QComboBox>
CHarmDataView::CHarmDataView(QWidget *parent)
: CStatViewBase(parent)
{
/*
for (int i = 0; i != HARM_MAX; i++) {
QString chn, key;
key.sprintf("%dharm_rms_vol.dat", i + 1);
chn.sprintf("%dๆฌก็ตๅ่ฐๆณขๅน
ๅผ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "V");
key.sprintf("%dharm_rms_cur.dat", i + 1);
chn.sprintf("%dๆฌก็ตๆต่ฐๆณขๅน
ๅผ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "A");
key.sprintf("%dharm_ang_vol.dat", i + 1);
chn.sprintf("%dๆฌก็ตๅ่ฐๆณข็ธไฝ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "ยฐ");
key.sprintf("%dharm_ang_cur.dat", i + 1);
chn.sprintf("%dๆฌก็ตๆต่ฐๆณข็ธไฝ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "ยฐ");
key.sprintf("%dharm_per_vol.dat", i + 1);
chn.sprintf("%dๆฌก็ตๅ่ฐๆณขๅซๆ็", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "%");
key.sprintf("%dharm_per_cur.dat", i + 1);
chn.sprintf("%dๆฌก็ตๆต่ฐๆณขๅซๆ็", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "%");
key = "harm_thd_per_vol.dat";
chn = "็ตๅๆป่ฐๆณข็ธๅ็";
m_mapFileName[key] = StatItemInfo(chn, "%");
key = "harm_thd_per_cur.dat";
chn = "็ตๆตๆป่ฐๆณข็ธๅ็";
m_mapFileName[key] = StatItemInfo(chn, "%");
}
QMap<QString, StatItemInfo>::iterator ite = m_mapFileName.begin();
for (; ite != m_mapFileName.end(); ++ite) {
m_pCombDataSel->addItem(ite.value().chinese);
}
m_pCombDataSel->setCurrentIndex(0);
*/
//ไฟฎๆน๏ผไฝฟไธๆๆกๆๅบ
QString chn, key;
for (int i = 0; i != HARM_MAX; i++)
{
key.sprintf("%dharm_rms_vol.dat", i + 1);
chn.sprintf("%dๆฌก็ตๅ่ฐๆณขๅน
ๅผ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "V");
m_vecBoxName.append(chn);
key.sprintf("%dharm_rms_cur.dat", i + 1);
chn.sprintf("%dๆฌก็ตๆต่ฐๆณขๅน
ๅผ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "A");
m_vecBoxName.append(chn);
key.sprintf("%dharm_ang_vol.dat", i + 1);
chn.sprintf("%dๆฌก็ตๅ่ฐๆณข็ธไฝ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "ยฐ");
m_vecBoxName.append(chn);
key.sprintf("%dharm_ang_cur.dat", i + 1);
chn.sprintf("%dๆฌก็ตๆต่ฐๆณข็ธไฝ", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "ยฐ");
m_vecBoxName.append(chn);
key.sprintf("%dharm_per_vol.dat", i + 1);
chn.sprintf("%dๆฌก็ตๅ่ฐๆณขๅซๆ็", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "%");
m_vecBoxName.append(chn);
key.sprintf("%dharm_per_cur.dat", i + 1);
chn.sprintf("%dๆฌก็ตๆต่ฐๆณขๅซๆ็", i + 1);
m_mapFileName[key] = StatItemInfo(chn, "%");
m_vecBoxName.append(chn);
}
key = "harm_thd_per_vol.dat";
chn = "็ตๅๆป่ฐๆณข็ธๅ็";
m_mapFileName[key] = StatItemInfo(chn, "%");
m_vecBoxName.append(chn);
key = "harm_thd_per_cur.dat";
chn = "็ตๆตๆป่ฐๆณข็ธๅ็";
m_mapFileName[key] = StatItemInfo(chn, "%");
m_vecBoxName.append(chn);
for(int i=0;i<m_vecBoxName.size();i++)
{
m_pCombDataSel->addItem(m_vecBoxName.at(i));
}
m_pCombDataSel->setCurrentIndex(0);
}
CHarmDataView::~CHarmDataView()
{
}
//bool CHarmDataView::_getStatDataFromFile(QString statFilePath, StatDataPoints *points)
//{
// // ไป็ป่ฎกๆไปถไธญ่ฏปๅๆๆ็ป่ฎกๆฐๆฎ
// CStatDataTool tool;
// StatRecordInfo info;
// int idx = statFilePath.lastIndexOf('/');
// QString infoFilePath = statFilePath.left(idx + 1) + "stat.info";
// for (int i = 0; i != 4; i++)
// points[i].clear();
// // ๅ
่ฏปๅ็ป่ฎก้
็ฝฎไฟกๆฏ,่ทๅ่ตทๅงๆถ้ดไปฅๅ็ป่ฎกๆฐๆฎๆฐ้
// if (!tool.ReadInfoFromFile(infoFilePath.toStdString(), info))
// return false;
// if (!tool.InitReadFile(statFilePath.toStdString(), _getStatPhaseCount(statFilePath)))
// return false;
// // ่ฝฌๅไธบๆพ็คบ็็ป่ฎกๆฐๆฎ็ผๅญ่ตทๆฅ
// StatDatas dats;
// if (!tool.ReadDataFromFile(0, info.statTotalCnt - 1, dats))
// return false;
// float params = 1;
// if (statFilePath.contains("harm_rms_cur"))
// params = info.meaCfg.ct;
// for (int i = 0; i != (int)dats.size(); i++) {
// UtcTime curTime = info.firstTime.toUtcTime();
// curTime.tv_sec += i * info.statCycle;
// DateTime curDate = curTime.toDateTime();
// QDateTime tmp(QDate(curDate.year, curDate.month, curDate.day),
// QTime(curDate.hour, curDate.minute, curDate.second, curDate.ms));
// StatOnePoint point[4];
// for (int j = 0; j != (int)dats.at(i).max_val.size(); j++)
// point[0].y.push_back(dats.at(i).max_val.at(j) * params);
// for (int j = 0; j != (int)dats.at(i).min_val.size(); j++)
// point[1].y.push_back(dats.at(i).min_val.at(j) * params);
// for (int j = 0; j != (int)dats.at(i).avg_val.size(); j++)
// point[2].y.push_back(dats.at(i).avg_val.at(j) * params);
// for (int j = 0; j != (int)dats.at(i).cp95_val.size(); j++)
// point[3].y.push_back(dats.at(i).cp95_val.at(j) * params);
// for (int j = 0; j != 4; j++) {
// point[j].x = tmp.toTime_t();
// points[j].push_back(point[j]);
// }
// }
// return true;
//}
|
/*********************************************************\
* Copyright (c) 2012-2018 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "RendererRuntime/Core/GetUninitialized.h"
#include <cassert>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
inline MaterialBlueprintResourceListener::MaterialBlueprintResourceListener() :
mIdentityColorCorrectionLookupTable3D(getUninitialized<TextureResourceId>()),
mSsaoSampleKernelTextureResourceId(getUninitialized<TextureResourceId>()),
mSsaoNoiseTexture4x4ResourceId(getUninitialized<TextureResourceId>()),
mRendererRuntime(nullptr),
mPassData(nullptr),
mCompositorContextData(nullptr),
mRenderTargetWidth(1),
mRenderTargetHeight(1),
mNearZ(0.0f),
mFarZ(0.0f),
mPreviousJitter(0.0f, 0.0f),
mPreviousNumberOfRenderedFrames(getUninitialized<uint64_t>()),
mHosekWilkieSky(nullptr),
mObjectSpaceToWorldSpaceTransform(nullptr),
mMaterialTechnique(nullptr)
{
// Nothing here
}
inline MaterialBlueprintResourceListener::~MaterialBlueprintResourceListener()
{
clear();
}
//[-------------------------------------------------------]
//[ Protected methods ]
//[-------------------------------------------------------]
inline const PassBufferManager::PassData& MaterialBlueprintResourceListener::getPassData() const
{
assert(nullptr != mPassData);
return *mPassData;
}
//[-------------------------------------------------------]
//[ Protected virtual RendererRuntime::IMaterialBlueprintResourceListener methods ]
//[-------------------------------------------------------]
inline void MaterialBlueprintResourceListener::beginFillUnknown()
{
// Nothing here
}
inline bool MaterialBlueprintResourceListener::fillUnknownValue(uint32_t, uint8_t*, uint32_t)
{
// Nothing here
// Value not filled
return false;
}
inline void MaterialBlueprintResourceListener::beginFillMaterial()
{
// Nothing here
}
inline bool MaterialBlueprintResourceListener::fillMaterialValue(uint32_t, uint8_t*, uint32_t)
{
// Nothing here
// Value not filled
return false;
}
inline void MaterialBlueprintResourceListener::beginFillInstance(const PassBufferManager::PassData& passData, const Transform& objectSpaceToWorldSpaceTransform, MaterialTechnique& materialTechnique)
{
// Remember the pass data memory address of the current scope
// TODO(co) Rethink the evil const-cast on here
mPassData = &const_cast<PassBufferManager::PassData&>(passData);
// Remember the instance data of the current scope
mObjectSpaceToWorldSpaceTransform = &objectSpaceToWorldSpaceTransform;
mMaterialTechnique = &materialTechnique;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // RendererRuntime
|
#pragma once
#include "Object.h"
#include <string>
#include <DxLib.h>
using namespace std;
class TitleObject : public Object {
private:
Vector2 accel;
public:
TitleObject(Vector2 vec);
~TitleObject() = default;
Vector2 GetAccel() const;
void Init() override;
void Fin() override;
void Update() override;
void Draw() const override;
void DrawOverlay() const;
void DrawBackground() const;
void Pop();
void Back();
};
|
#ifndef LISTAST_H
#define LISTAST_H
#include "NodoT.h"
#include <iostream>
using namespace std;
template <typename T>
class ListaST
{
private:
NodoT<T>* inicio;
NodoT<T>* fin;
public:
ListaST(){
inicio = fin = NULL;
}
void muestraTusDatos(void){
NodoT<T>* aux;
aux = inicio;
if(laListaEstaVacia())
cout << "La lista esta vacia" << endl;
while(aux!= NULL){
cout << aux->dameTuValor();
aux = aux->dameTuSiguiente();
}
}
bool laListaEstaVacia(void){
return inicio==NULL;
}
void inserta(T v){
if(!laListaEstaVacia()){
if(v <= inicio->dameTuValor()){ //Inserta un dato al INICIO de la lista
inicio = new NodoT<T>(v, inicio);
}
else{
if(v > fin->dameTuValor()){ //Inserta un dato al FINAL de la lista
fin->modificaTuSiguiente(new NodoT<T>(v));
fin = fin->dameTuSiguiente();
}
else{
NodoT<T>* aux2;
NodoT<T>* aux1 = inicio;
while(v > aux1->dameTuValor()){
aux2 = aux1;
aux1 = aux1->dameTuSiguiente();
}
aux2->modificaTuSiguiente(new NodoT<T>(v,aux1));
}
}
}
else{
inicio = new NodoT<T>(v); //Inserta un dato SI LA LISTA ESTA VACIA
fin = inicio;
}
}
void borra(T v){
NodoT<T>* aux;
if(v <= fin->dameTuValor()){
if(v == inicio->dameTuValor()){ //Elimina un dato de la lista si estรก al INICIO
inicio = inicio->dameTuSiguiente();
delete(aux);
}
else{
NodoT<T>* aux1;
NodoT<T>* aux2;
aux1 = inicio;
while(aux1 != NULL && aux1->dameTuValor()<v){
aux2 = aux1;
aux1 = aux1->dameTuSiguiente();
}
if(aux1->dameTuValor() == v){
aux2->modificaTuSiguiente(aux1->dameTuSiguiente());
if(aux1 == fin){
fin = aux2;
}
delete(aux1);
}
else{
cout << "El valor no esta en la lista: " << v << endl;
}
}
}
else{
cout << "El valor no esta en la lista: " << v << endl;
}
}
void compara(T v, ListaST<T>& LR){ // Compara la una lista con un valor dado por el usuario
NodoT<T>* aux1; // los valores que cumplan la condiciรณn son guardados en
aux1 = inicio; // una la lista que se pasa como referencia.
while(aux1 != fin){
if(aux1->dameTuValor() < v){
LR.inserta(aux1->dameTuValor());
}
aux1 = aux1->dameTuSiguiente();
}
if(aux1 == fin){
if(aux1->dameTuValor() < v){
LR.inserta(aux1->dameTuValor());
}
}
}
float promedio(void){
NodoT<int>* aux;
int i = 0;
float suma = 0;
aux = inicio;
while(aux != NULL){
suma = suma + aux->dameTuValor();
i++;
aux = aux->dameTuSiguiente();
}
return suma/i;
}
};
#endif // LISTAST_H
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; 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 Manuela Hutter (manuelah)
*/
#ifdef AUTO_UPDATE_SUPPORT
#ifndef UPDATE_AVAILABLE_DIALOG_H
#define UPDATE_AVAILABLE_DIALOG_H
#include "adjunct/quick_toolkit/widgets/Dialog.h"
#include "adjunct/quick/managers/AutoUpdateManager.h"
/***********************************************************************************
*
* @class UpdateAvailableDialog
*
* @brief Dialog that informs about an available browser update.
* @author Manuela Hutter
*
*
***********************************************************************************/
class UpdateAvailableDialog : public Dialog, OpPageListener
{
public:
UpdateAvailableDialog(AvailableUpdateContext* context);
~UpdateAvailableDialog();
///--------------------- Dialog ---------------------///
Dialog::DialogType GetDialogType();
Type GetType() {return DIALOG_TYPE_AUTOUPDATE_AVAILABLE;}
const char* GetWindowName() {return "Auto Update Available Dialog";}
DialogImage GetDialogImageByEnum() {return IMAGE_NONE;}
const char* GetHelpAnchor() {return "autoupdate.html";}
virtual BOOL GetIsResizingButtons() {return TRUE;}
OpInputAction* GetOkAction();
OpInputAction* GetCancelAction();
const uni_char* GetOkText() {return m_ok_text.CStr();}
const uni_char* GetCancelText() {return m_cancel_text.CStr();}
void OnInit();
BOOL OnInputAction(OpInputAction* action);
UINT32 OnOk();
void OnCancel();
///----------- OpPageListener -----------------///
BOOL OnPagePopupMenu(OpWindowCommander* commander, OpDocumentContext& context);
void OnPageLoadingFinished(OpWindowCommander* commander, OpLoadingListener::LoadingFinishStatus status, BOOL stopped_by_user);
private:
void ShowBrowserView();
void ShowBrowserViewError();
private:
OpFileLength m_update_size;
OpString m_update_info_url;
OpString m_ok_text;
OpString m_cancel_text;
};
#endif //UPDATE_AVAILABLE_DIALOG_H
#endif // AUTO_UPDATE_SUPPORT
|
#include <catch2/catch_test_macros.hpp>
#include <iostream>
#include <fstream>
#include <random>
#include <oineus/oineus.h>
using dim_type = size_t;
template<class Int, class Real, size_t D>
typename oineus::Grid<Int, Real, D>
get_grid(Real* pdata, typename oineus::Grid<Int, Real, D>::GridPoint dims, bool wrap)
{
return oineus::Grid<Int, Real, D>(dims, wrap, pdata);
}
template<class Int, class Real, size_t D>
typename oineus::VRUDecomposition<Int>::MatrixData
get_boundary_matrix(const typename oineus::Grid<Int, Real, D>& grid, bool negate, bool wrap, dim_type top_d, int n_threads)
{
auto fil = grid.freudenthal_filtration(top_d, negate, n_threads);
auto bm = fil.boundary_matrix_full();
return bm.data;
}
template<class Int, class Real, size_t D>
decltype(auto) compute_diagrams_and_v_ls_freudenthal(const typename oineus::Grid<Int, Real, D>& grid, bool negate, bool wrap, dim_type top_d, int n_threads)
{
auto fil = grid.freudenthal_filtration(top_d + 1, negate, n_threads);
auto decmp = oineus::VRUDecomposition<Int>(fil, false);
oineus::Params params;
params.sort_dgms = false;
params.clearing_opt = false;
params.n_threads = n_threads;
if (n_threads == 1)
params.compute_u = true;
decmp.reduce(params);
auto dgms = decmp.diagram(fil, true);
return std::make_pair(dgms, decmp);
}
TEST_CASE("Basic reduction")
{
using Int = int;
std::vector<std::vector<Int>> d_cols;
d_cols.emplace_back(std::vector<Int>({0, 1}));
d_cols.emplace_back(std::vector<Int>({1}));
oineus::VRUDecomposition<Int> decmp(d_cols);
oineus::Params params;
params.sort_dgms = false;
params.clearing_opt = false;
params.compute_v = true;
params.compute_u = true;
params.n_threads = 1;
decmp.reduce(params);
REQUIRE(decmp.sanity_check());
}
TEST_CASE("Simple reduction")
{
using Real = double;
using Int = int;
std::vector<Real> xs;
std::ifstream f {"./a_6.txt"};
REQUIRE(f.good());
Real x;
while(f >> x)
xs.push_back(x);
REQUIRE(xs.size() == 216);
using Grid = oineus::Grid<int, Real, 3>;
using GridPoint = typename Grid::GridPoint;
bool wrap = false;
bool negate = true;
int n_threads = 1;
dim_type top_d = 2;
GridPoint dims {6, 6, 6};
Grid grid = get_grid<Int, Real, 3>(xs.data(), dims, wrap);
auto dv = compute_diagrams_and_v_ls_freudenthal<Int, Real, 3>(grid, negate, wrap, top_d, n_threads);
auto dgms = dv.first;
auto decmp = dv.second;
REQUIRE(dgms.n_dims() == top_d + 1);
REQUIRE(decmp.sanity_check());
}
TEST_CASE("Simple reduction parallel")
{
using Real = double;
using Int = int;
std::vector<Real> xs;
std::ifstream f {"./a_6.txt"};
REQUIRE(f.good());
Real x;
while(f >> x)
xs.push_back(x);
REQUIRE(xs.size() == 216);
using Grid = oineus::Grid<int, Real, 3>;
using GridPoint = typename Grid::GridPoint;
bool wrap = false;
bool negate = true;
int n_threads = 4;
dim_type top_d = 2;
GridPoint dims {6, 6, 6};
Grid grid = get_grid<Int, Real, 3>(xs.data(), dims, wrap);
auto dv = compute_diagrams_and_v_ls_freudenthal<Int, Real, 3>(grid, negate, wrap, top_d, n_threads);
auto dgms = dv.first;
auto decmp = dv.second;
REQUIRE(dgms.n_dims() == top_d + 1);
REQUIRE(decmp.sanity_check());
}
TEST_CASE("Vietoris--Rips")
{
using Real = double;
using Int = int;
using oineus::dim_type;
using Point = oineus::Point<Real, 2>;
std::vector<Point> points;
int n_points = 6;
std::mt19937_64 gen(1);
std::uniform_real_distribution<Real> dis(0, 1);
for(int i = 0; i < n_points; ++i) {
Point p;
for(int coord = 0; coord < 2; ++coord)
p[coord] = dis(gen);
points.push_back(p);
// points.emplace_back({dis(gen), dis(gen)});
}
dim_type max_dim = 3;
Real max_radius = 0.4;
auto fil_1 = oineus::get_vr_filtration<Int, Real, 2>(points, max_dim, max_radius);
auto fil_2 = oineus::get_vr_filtration_naive<Int, Real, 2>(points, max_dim, max_radius);
REQUIRE(fil_1.cells() == fil_2.cells());
}
|
#include "TestFramework.h"
#include "treeface/math/Mat2.h"
void TestFramework::content()
{
{
treeface::Mat2f mat_fwd(123.456f, 789.123f, 654.321f, 234.578f);
treeface::Mat2f mat_inv = mat_fwd;
float det = mat_inv.inverse();
IS_EPSILON(det, -487379.7);
IS_EPSILON(mat_inv.data.get<0>(), -0.0004813044f);
IS_EPSILON(mat_inv.data.get<1>(), 0.001619113f);
IS_EPSILON(mat_inv.data.get<2>(), 0.001342528f);
IS_EPSILON(mat_inv.data.get<3>(), -0.0002533056f);
{
treeface::Mat2f mat_fwd_inv = mat_fwd * mat_inv;
IS_EPSILON(mat_fwd_inv.data.get<0>(), 1.0f);
LE(std::abs(mat_fwd_inv.data.get<1>()), 0.00001f);
LE(std::abs(mat_fwd_inv.data.get<2>()), 0.00001f);
IS_EPSILON(mat_fwd_inv.data.get<3>(), 1.0f);
}
{
treeface::Mat2f mat_inv_fwd = mat_inv * mat_fwd;
IS_EPSILON(mat_inv_fwd.data.get<0>(), 1.0f);
LE(std::abs(mat_inv_fwd.data.get<1>()), 0.00001f);
LE(std::abs(mat_inv_fwd.data.get<2>()), 0.00001f);
IS_EPSILON(mat_inv_fwd.data.get<3>(), 1.0f);
}
{
treeface::Vec2f vec_fwd_inv = mat_inv * (mat_fwd * treeface::Vec2f(444.333f, 222.111f));
IS_EPSILON(vec_fwd_inv.x, 444.333f);
IS_EPSILON(vec_fwd_inv.y, 222.111f);
}
{
treeface::Vec2f vec_inv_fwd = mat_fwd * (mat_inv * treeface::Vec2f(444.333f, 222.111f));
IS_EPSILON(vec_inv_fwd.x, 444.333f);
IS_EPSILON(vec_inv_fwd.y, 222.111f);
}
}
{
treeface::Mat2f mat_rot;
mat_rot.set_rotate(3.1415927f/6);
{
treeface::Vec2f rot_unit_x = mat_rot * treeface::Vec2f(1.0f, 0.0f);
IS_EPSILON(rot_unit_x.x, 1.732051f/2);
IS_EPSILON(rot_unit_x.y, 0.5f);
}
{
treeface::Vec2f rot_rot_unit_x = mat_rot * (mat_rot * treeface::Vec2f(1.0f, 0.0f));
IS_EPSILON(rot_rot_unit_x.x, 0.5f);
IS_EPSILON(rot_rot_unit_x.y, 1.732051f/2);
}
{
treeface::Vec2f rot_result = mat_rot * treeface::Vec2f(1.0f, 1.732051f);
LE(std::abs(rot_result.x), 0.00001f);
IS_EPSILON(rot_result.y, 2.0f);
}
mat_rot.set_rotate(-3.1415927f/3);
{
{
treeface::Vec2f rot_unit_y = mat_rot * treeface::Vec2f(0.0f, 2.0f);
IS_EPSILON(rot_unit_y.x, 1.732051f);
IS_EPSILON(rot_unit_y.y, 1.0f);
}
}
}
}
|
/*
* @lc app=leetcode.cn id=1000 lang=cpp
*
* [1000] ๅๅนถ็ณๅคด็ๆไฝๆๆฌ
*/
// @lc code=start
class Solution {
public:
int dp[31][31][31];
int sum[31];
int mergeStones(vector<int>& stones, int K) {
int n = stones.size();
if((n-1)%(K-1))return -1;
if(n < 2)return 0;
memset(dp, 0x3f, sizeof(dp));
for(int i=1;i<=n;i++)
{
sum[i] = sum[i-1] + stones[i-1];
dp[i][i][1] = 0;
}
for(int len = 2; len <= n; len++)
{
for(int i=1;i<=n-len+1;i++)
{
int j = i + len - 1;
for(int k=2;k<=K;k++)
{
for(int p = i;p<j;p++)
{
dp[i][j][k] = min(dp[i][j][k], dp[i][p][k-1] + dp[p+1][j][1]);
}
}
dp[i][j][1] = min(dp[i][j][1], dp[i][j][K] + sum[j] - sum[i-1]);
}
}
return dp[1][n][1];
}
};
// @lc code=end
|
#include <functional>
#include <reactor/base/SimpleLogger.h>
#include <reactor/net/EventLoop.h>
#include <reactor/net/InetAddress.h>
#include <reactor/net/TcpConnection.h>
#include <reactor/net/TcpServer.h>
using namespace reactor::net;
class DiscardServer {
public:
DiscardServer(EventLoop *loop, const InetAddress &addr):
loop_(loop),
server_(loop, addr) {
using namespace std::placeholders;
server_.set_connection_callback(std::bind(&DiscardServer::on_connection, this, _1));
server_.set_message_callback(std::bind(&DiscardServer::on_message, this, _1));
}
void start() {
server_.start();
}
private:
void on_connection(const TcpConnectionPtr &conn) {
LOG(Debug) << conn->peer_address().to_string()
<< (conn->connected() ? "connected" : "disconnected");
LOG(Debug) << conn->get_tcp_info_string();
}
void on_message(const TcpConnectionPtr &conn) {
LOG(Debug) << "receive " << static_cast<long>(conn->buffer()->readable_bytes()) << " bytes";
conn->buffer()->retrieve_all();
}
EventLoop *loop_;
TcpServer server_;
};
int main() {
EventLoop loop;
DiscardServer server(&loop, InetAddress("0.0.0.0", 9090));
server.start();
loop.loop();
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2012 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"
#include "modules/media/mediatimeranges.h"
MediaTimeRanges::MediaTimeRanges()
: m_ranges(NULL)
, m_allocated(0)
, m_used(0)
{
}
/* virtual */
MediaTimeRanges::~MediaTimeRanges()
{
op_free(m_ranges);
}
/* virtual */ OP_STATUS
MediaTimeRanges::SetRanges(const OpMediaTimeRanges* ranges)
{
OP_ASSERT(ranges);
UINT32 length = ranges->Length();
// Resize the array if required.
if (m_allocated < length)
{
void* mem = op_realloc(m_ranges, sizeof(Range) * length);
RETURN_OOM_IF_NULL(mem);
m_ranges = static_cast<Range*>(mem);
m_allocated = length;
}
for (UINT32 i = 0; i < length; i++)
{
m_ranges[i].start = ranges->Start(i);
m_ranges[i].end = ranges->End(i);
}
m_used = length;
return OpStatus::OK;
}
void MediaTimeRanges::Merge()
{
for (UINT32 i = 0; i + 1 < m_used; i++)
{
Range& cur = m_ranges[i];
Range& next = m_ranges[i + 1];
if (cur.end >= next.start)
{
if (cur.end < next.end)
cur.end = next.end;
op_memmove(&m_ranges[i + 1], &m_ranges[i + 2], (m_used - i - 2) * sizeof(Range));
i--;
m_used--;
}
}
}
bool MediaTimeRanges::IsNormalized()
{
for (UINT32 i = 0; i < m_used; i++)
{
if (m_ranges[i].start >= m_ranges[i].end)
return false;
if (i + 1 < m_used && m_ranges[i].end >= m_ranges[i + 1].start)
return false;
}
return true;
}
void MediaTimeRanges::Normalize()
{
// Throw out empty ranges.
UINT32 in = 0, out = 0;
while (in < m_used)
{
if (!m_ranges[in].IsEmpty())
m_ranges[out++] = m_ranges[in];
in++;
}
m_used = out;
// Insertion sort on range start times.
for (UINT32 i = 1; i < m_used; i++)
{
UINT32 j;
Range cur = m_ranges[i];
for (j = i; j > 0 && cur.start < m_ranges[j - 1].start; j--)
m_ranges[j] = m_ranges[j - 1];
m_ranges[j] = cur;
}
Merge();
}
OP_STATUS MediaTimeRanges::AddRange(double start, double end)
{
if (start >= end)
return OpStatus::OK;
if (!IsNormalized())
Normalize();
if (m_used >= m_allocated)
{
// Allocate more than one at a time?
void* mem = op_realloc(m_ranges, sizeof(Range) * (m_used + 1));
RETURN_OOM_IF_NULL(mem);
m_ranges = static_cast<Range*>(mem);
m_allocated++;
}
// Insert into an already normalized list.
UINT32 idx;
for (idx = 0; idx < m_used; idx++)
if (start < m_ranges[idx].start)
break;
op_memmove(&m_ranges[idx + 1], &m_ranges[idx], (m_used - idx) * sizeof(Range));
m_ranges[idx].start = start;
m_ranges[idx].end = end;
m_used++;
Merge();
return OpStatus::OK;
}
/* virtual */ UINT32
MediaTimeRanges::Length() const
{
return m_used;
}
/* virtual */ double
MediaTimeRanges::Start(UINT32 idx) const
{
OP_ASSERT(idx < m_used);
return m_ranges[idx].start;
}
/* virtual */ double
MediaTimeRanges::End(UINT32 idx) const
{
OP_ASSERT(idx < m_used);
return m_ranges[idx].end;
}
|
#include <modul/kas/kas.h>
#include "ui_kas.h"
#include <QStandardItemModel>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QDate>
#include <QSqlError>
#include <QDebug>
#include <QLocale>
#include <QMessageBox>
Kas::Kas(QWidget *parent) :
QDialog(parent),
ui(new Ui::Kas)
{
ui->setupUi(this);
this->tataLayout();
this->tataTabel();
this->refreshData();
}
Kas::~Kas()
{
delete ui;
}
void Kas::on_pSimpan_clicked()
{
QSqlQuery query;
QString ket,keluar,masuk,tgl,saldo;
tgl = QDate().currentDate().toString("yyyy-MM-dd");
ket = ui->lKet->text();
if(ui->comboJenis->currentIndex() == 0){
keluar = "0";
masuk = ui->lUang->text();
}else if(ui->comboJenis->currentIndex() == 1){
masuk = "0";
keluar = ui->lUang->text();
}else{
masuk = "0";
keluar = "0";
}
query.exec("SELECT saldo FROM tbl_kas ORDER BY id DESC");
query.next();
saldo = QString::number(query.value(0).toInt() + masuk.toInt() - keluar.toInt());
if(!ui->lUang->text().isEmpty()){
if(query.exec("INSERT INTO tbl_kas SET ket=\""+ket+"\", tgl=\""+tgl+"\", keluar=\""+keluar+"\", masuk=\""+masuk+"\", saldo=\""+saldo+"\"")){
modelKas->clear();
this->refreshData();
this->tataTabel();
ui->lUang->clear();
ui->lKet->clear();
ui->lUang->setFocus();
}else{
qDebug()<<query.lastError().text();
}
}else{
QMessageBox::warning(this,"Masukkan Uang","Masukkan sejumlah uang terlebih dahulu");
}
}
void Kas::tataLayout(){
//Combo jenis
ui->comboJenis->addItems(QStringList()<<"Masuk"<<"Keluar");
//Combo Bulan
ui->comboBulan->addItems(QStringList()<<"Januari"<<"Pebruari"<<"Maret"<<"April"<<"Mei"<<"Juni"<<"Juli"<<"Agustus"<<"September"<<"Oktober"<<"November"<<"Desember");
ui->comboBulan->setCurrentIndex(QDate().currentDate().toString("M").toInt()-1);
//Combo Tahun
this->initComboTahun();
//Atur Layout Tabel Peminjaman
modelKas = new QStandardItemModel(0,4,this);
ui->tblKas->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tblKas->setSortingEnabled(true);
ui->tblKas->resizeColumnsToContents();
ui->tblKas->setEditTriggers(QAbstractItemView::NoEditTriggers);
ui->tblKas->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tblKas->horizontalHeader()->setStretchLastSection(true);
ui->tblKas->setModel(modelKas);
}
void Kas::tataTabel(){
modelKas->setHorizontalHeaderItem(0, new QStandardItem(QString("Uraian")));
modelKas->setHorizontalHeaderItem(1, new QStandardItem(QString("Tanggal")));
modelKas->setHorizontalHeaderItem(2, new QStandardItem(QString("Masuk")));
modelKas->setHorizontalHeaderItem(3, new QStandardItem(QString("Keluar")));
modelKas->setHorizontalHeaderItem(4, new QStandardItem(QString("Saldo")));
ui->tblKas->setColumnWidth(0, 400);//Uraian
ui->tblKas->setColumnWidth(1, 200);//Tanggal
ui->tblKas->setColumnWidth(2, 200);//Masuk
ui->tblKas->setColumnWidth(3, 200);//Keluar
ui->tblKas->setColumnWidth(4, 200);//Saldo
}
void Kas::refreshData(){
QSqlQuery query;
QString keluar, masuk, saldo;
QString bulan = QString::number(ui->comboBulan->currentIndex()+1);
QString tahun = ui->comboTahun->currentText();
if(query.exec(" SELECT * FROM tbl_kas WHERE MONTH(tgl) = '"+bulan+"' AND YEAR(tgl) = '"+tahun+"' ")){
int counter=0;
// index column
int ket = query.record().indexOf("ket");
int tgl_ = query.record().indexOf("tgl");
int masuk_ = query.record().indexOf("masuk");
int keluar_ = query.record().indexOf("keluar");
int saldo_ = query.record().indexOf("saldo");
while(query.next()){
modelKas->setItem(counter,0,new QStandardItem(QString(query.value(ket).toString())));
modelKas->setItem(counter,1,new QStandardItem(QString(query.value(tgl_).toString())));
modelKas->setItem(counter,2,new QStandardItem(QString(query.value(masuk_).toString())));
modelKas->setItem(counter,3,new QStandardItem(QString(query.value(keluar_).toString())));
modelKas->setItem(counter,4,new QStandardItem(QString(query.value(saldo_).toString())));
counter++;
}
}
query.exec("SELECT SUM(masuk) FROM tbl_kas");
query.next();
masuk = QLocale::system().toString(query.value(0).toInt());
query.exec("SELECT SUM(keluar) FROM tbl_kas");
query.next();
keluar = QLocale::system().toString(query.value(0).toInt());
query.exec("SELECT saldo FROM tbl_kas ORDER BY id DESC");
query.next();
saldo = QLocale::system().toString(query.value(0).toInt());
ui->lTotalPemasukan->setText("Rp. "+masuk);
ui->lTotalKeluar->setText("Rp. "+keluar);
ui->lSaldoAkhir->setText("Rp. "+saldo);
}
void Kas::on_comboBulan_currentIndexChanged(int index)
{
QString::number(index);
//this->on_bRefresh_clicked();
}
void Kas::on_bRefresh_clicked()
{
modelKas->clear();
this->refreshData();
this->tataTabel();
}
void Kas::initComboTahun(){
QSqlQuery querytahun;
QString sql = "SELECT DISTINCT YEAR(tgl) FROM tbl_kas WHERE YEAR(tgl) != YEAR(NOW())";
if( querytahun.exec(sql) ){
while(querytahun.next()){
ui->comboTahun->addItem(querytahun.value(0).toString());
}
}else{
qDebug()<<"Sql Query Error "<<__FILE__<<__LINE__;
}
QString curYear = QDate().currentDate().toString("yyyy");
ui->comboTahun->addItem(curYear);
ui->comboTahun->setCurrentIndex(ui->comboTahun->count()-1);
}
|
#include <bits/stdc++.h>
using namespace std;
#define MOD 1000000007
#define INF 10e13
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
typedef long long ll;
int main()
{
ll n;
cin >> n;
ll ans = INF;
for (ll i = 1; i*i <= n; i++)
{
if (n % i == 0){
ans = min(ans, i + (n/i) - 2);
}
}
cout << ans << endl;
}
|
#pragma once
#include "torch/networks.hpp"
#include <memory>
#include <mutex>
#include <string>
#include <thread>
#include <torch/torch.h>
namespace OptimExplorer
{
struct Hparams
{
size_t batch_size = 256;
size_t epochs = 5;
};
class TorchSystem
{
public:
TorchSystem();
private:
void train();
void set_model();
void do_epoch(torch::optim::Optimizer& optim);
void do_test();
void attempt_to_use_cuda()
{
if (torch::cuda::is_available())
{
printf("CUDA DEVICE COUNT: %zu\n", torch::cuda::device_count());
m_device = torch::Device(torch::kCUDA);
}
}
void use_cpu() { m_device = torch::Device(torch::kCPU); }
void set_hparams(const Hparams& hp) { m_hparams = hp; }
void save_model(const std::string& name) const
{
torch::save(m_model.ptr(), m_model_path + name + ".pt");
}
std::string m_data_path = "./data/mnist";
std::string m_model_path = "./models/";
torch::Device m_device = torch::Device(torch::kCPU);
torch::nn::AnyModule m_model;
Hparams m_hparams;
size_t m_epochs_trained = 0;
// TODO: change to abstract DataSet
torch::data::datasets::MNIST m_train_dataset =
torch::data::datasets::MNIST(m_data_path, torch::data::datasets::MNIST::Mode::kTrain);
torch::data::datasets::MNIST m_test_dataset =
torch::data::datasets::MNIST(m_data_path, torch::data::datasets::MNIST::Mode::kTest);
// Mutexes
// We might be able to use shared mutexes & diff mutex for model/hparam/dataset
// but lets keep it simple for now.
// TODO: not using recursive mutex will allow other funcs to run in between each epoch of train
std::recursive_mutex m_mutex;
};
} // namespace OptimExplorer
|
//
// Created by Nowidh on 2020/7/8.
//
#include"TargetCodeGenerator.h"
#include<iostream>
#include<algorithm>
using std::ios;
using std::cout;
using std::endl;
extern FunSheet xTable;
//ๆต่ฏ็จ๏ผๅฎ้
ๅบ่ฏฅไฝฟ็จ็ฌฆๅท่กจ็ๅฝๆฐ
bool isTemporary(string nowString)
{
if (nowString[0] == '_' && nowString.size()>1)
return true;
return false;
}
//ๆฅ็็ปๆไฝๅๅ็ๅ็งป้๏ผๆต่ฏ็จ
int findSonOffset(string sonName)
{
return 0;
}
//ไปๆไปถไธญ่ฏปๅๅๅ
ๅผ
void TargetCodeGenerator::read(string filename)
{
ifstream infile;
infile.open(filename, ios::in);
if (!infile.is_open())
{
cout << "Open Failed!!!" << endl;
exit(0);
}
string line, th[4];
while (!infile.eof())
{
std::getline(infile, line);
if(line == "")
break;
//bookไธบๅผๅงๅคๅถ็ไฝ็ฝฎ๏ผturnไธบๅฐไบๅชไธชๆไฝๆฐ๏ผ0๏ผ1๏ผ2๏ผ3๏ผ
int book = 1, turn = 0;
for (int i = 1; i < line.size() - 1; i++)
{
if (line[i] == ',')
{
th[turn] = "";
for (int j = book + 1; j < i - 1; j++)
{
th[turn] += line[j];
}
turn++;
book = i + 1;
}
if(turn == 3)
break;
}
//ๅ ไธบๅฐไบๆๅไธไธช้ๅทๅฐฑๅไธไบ๏ผๆไปฅ่ฆๆๆๅ็็ฎๆ ๆไฝๆฐๅๅค็ไธไธ
if(line!="")
{
th[turn] = "";
for (int i = book + 1; i < line.size() - 2; i++)
{
th[turn] += line[i];
}
}
//ๅญๅ
ฅๆๆๅๅ
ๅผ้ไธญ
quar tq;
tq.oper = th[0], tq.o1 = th[1], tq.o2 = th[2], tq.target = th[3];
AllQuarColl.push_back(tq);
}
int a = 1;
}
//ๆฏๅฆๆฏ่ทณ่ฝฌ็ฌฆ๏ผ็ฎๅๆif๏ผelse๏ผwhile๏ผwe
//ๆฏๅ่ฟๅtrue๏ผๅฆๅ่ฟๅfalse
bool TargetCodeGenerator::isSpilt(quar nowQuar)
{
for (int i = 0; i < SpiltQuarSize; i++)
{
if (nowQuar.oper == SpiltQuar[i])
{
return true;
}
}
return false;
}
//ๅๅฒๅๅ
ๅผไธบๅบๆฌๅ๏ผๅญๅ
ฅๅบๆฌๅ้ไธญ
void TargetCodeGenerator::spiltMidCode()
{
quar nowQuar;
set<int> BeginQuarColl; //ๅบๆฌๅๅ
ฅๅฃๆไปค็ผๅท้๏ผไป0ๅผๅง
BeginQuarColl.insert(0); //็ฌฌไธไธชๅๅ
ๅผๅ ๅ
ฅ
//้ๅๆๆๅๅ
ๅผ
for (int i = 1; i < AllQuarColl.size(); i++)
{
//ๅฆๆไธไธๆกๆฏ่ทณ่ฝฌ่ฏญๅฅ๏ผๅๅฐๆญคๆกๅ ๅ
ฅ
if (isSpilt(AllQuarColl[i - 1]))
{
BeginQuarColl.insert(i);
}
//็นๅค๏ผwhileๅผๅงๅๅ
ๅผไนๆฏๅผๅงๅๅ
ๅผ
if (AllQuarColl[i].oper == quatName::beginWhile)
{
BeginQuarColl.insert(i);
}
}
//ๅฝๅๅบๆฌๅ
BaseBlock nowBlock;
//้ๅๆฏไธไธช็ผๅท๏ผไปฅๅฝๅๅ
ฅๅฃ่ฏญๅฅๅผๅง๏ผไธไธไธชๅ
ฅๅฃ่ฏญๅฅ็ปๆ๏ผไธๅ
ๅซ๏ผ๏ผๅผๅงๅคๅถ
for (auto g = BeginQuarColl.begin(); g != prev(BeginQuarColl.end()); g++)
{
nowBlock.BaseBlockQuar.clear();
auto next = g;
int nowBegin = *g; //ๅผๅง
int nowEnd = *(++next); //็ปๆ
//ๅบๆฌๅๅผๅงๅ็ปๆ็ไฝ็ฝฎ็ผๅท
nowBlock.BaseBlockStart = nowBegin;
nowBlock.BaseBlockEnd = nowEnd - 1;
//ๅผๅงๅคๅถ
for (int i = nowBegin; i < nowEnd; i++)
{
nowBlock.BaseBlockQuar.push_back(AllQuarColl[i]);
}
//ๅ ๅ
ฅๅบๆฌๅ้
BaseBlockColl.push_back(nowBlock);
}
//ๅฉไธๆๅไธไธชๅผๅง่ฏญๅฅ็ดๅฐๆๆๅๅ
ๅผ็ปๆ๏ผๆไปฅ่กฅไธ
nowBlock.BaseBlockQuar.clear();
int nowBegin = *prev(BeginQuarColl.end());
int nowEnd = AllQuarColl.size();
nowBlock.BaseBlockStart = nowBegin;
nowBlock.BaseBlockEnd = nowEnd - 1;
for (int i = nowBegin; i < nowEnd; i++)
{
nowBlock.BaseBlockQuar.push_back(AllQuarColl[i]);
}
BaseBlockColl.push_back(nowBlock);
int a = 1;
}
//ๅคๆญๆไฝ็ฌฆๆฏๅฆๆฏๅฝๆฐ่ฐ็จ๏ผๅฝๆฐๅฃฐๆ๏ผไธป็จๅบๅฃฐๆ๏ผ่ฟ็จๅฃฐๆ๏ผๅฝๆฐ็ปๆ๏ผไธป็จๅบ็ปๆ๏ผ่ฟ็จ็ปๆ
int BaseBlock::isHaveActivity(string nowOp)
{
for (int i = 0; i < notAcitvityCount; i++)
{
if (nowOp == notAcitvity[i])
return 1;
}
return 0;
}
//ๅคๆญๆไฝๆฐๆฏๅฆๆฏ็ฉบๆ ผ
int BaseBlock::isBlankOper(string nowOper)
{
if (nowOper == "_" && nowOper.size()==1)
return 1;
return 0;
}
//ๅๅงๅๅบๆฌๅๆดป่ทไฟกๆฏ๏ผๆ็
งๅบๆฌๅไธญๅๅ
ๅผๆฐ้็ๆๅฏนๅบๆฐ้็ๆดป่ทไฟกๆฏ็ปๆไฝ
//ไธดๆถๅ้ๅๅงๅไธบno๏ผๅ
ถไปๅๅงๅไธบyes
void BaseBlock::initBlockActive()
{
for (int i = 0; i < BaseBlockQuar.size(); i++)
{
//ๅฝๅๅๅ
ๅผ็ๆดป่ทไฟกๆฏ๏ผ็ฎ็ฌฆๆฒกๅฅๅฝฑๅ๏ผๆไปฅ็ดๆฅๅคๅถ
active nowActivity;
nowActivity.oper = BaseBlockQuar[i].oper;
//ๆฅ็ๆฏๅฆๆฏไธดๆถๅ้
string checkTemp = "";
//ๆฅ็ๆฏๅฆๆฏ็ฉบ็
if (!isBlankOper(BaseBlockQuar[i].o1)) //้็ฉบ๏ผ็ปง็ปญ
{
checkTemp = BaseBlockQuar[i].o1;
if (isTemporary(checkTemp)) //ๆฅ็ๆฏๅฆๆฏไธดๆถๅ้
{
nowActivity.o1 = "no"; //ไธดๆถๅ้ไธบno
tempVariable[checkTemp] = "no";
}
else
{
nowActivity.o1 = "yes"; //ๅฆๅไธบyes
notTempVariable[checkTemp] = "yes";
}
}
//็ฌฌไบไธชๆไฝๆฐ๏ผๅไธ
if (!isBlankOper(BaseBlockQuar[i].o2))
{
checkTemp = BaseBlockQuar[i].o2;
if (isTemporary(checkTemp))
{
nowActivity.o2 = "no";
tempVariable[checkTemp] = "no";
}
else
{
nowActivity.o2 = "yes";
notTempVariable[checkTemp] = "yes";
}
}
//็ฎๆ ๆไฝๆฐ๏ผๅไธ
if (!isBlankOper(BaseBlockQuar[i].target))
{
checkTemp = BaseBlockQuar[i].target;
if (isTemporary(checkTemp))
{
nowActivity.target = "no";
tempVariable[checkTemp] = "no";
}
else
{
nowActivity.target = "yes";
notTempVariable[checkTemp] = "yes";
}
}
BaseBlockActivity.push_back(nowActivity); //ๅญๅจ
int a = 1;
}
}
//่ฎก็ฎๆดป่ทไฟกๆฏ๏ผ็จ็ไธ่ฏพppt็ๆนๆณ
void BaseBlock::checkBlockActive()
{
//้ฆๅ
ๅๅงๅๅฝๅๅบๆฌๅ็ๆดป่ทไฟกๆฏ
initBlockActive();
int a = 1;
//ๅผๅงๅกซๆดป่ทไฟกๆฏ่กจ๏ผๅ็ๆฅ
for (int i = BaseBlockActivity.size() - 1; i >= 0; i--)
{
if (isHaveActivity(BaseBlockQuar[i].oper))
continue;
string nowVariable = "";
string changeMessage = "";
if (!isBlankOper(BaseBlockQuar[i].target))
{
nowVariable = BaseBlockQuar[i].target; //ๅฝๅๆไฝๆฐ
if (isTemporary(nowVariable)) //ๅฆๆๆฏไธดๆถๅ้็ๆไฝ
{
changeMessage = tempVariable[nowVariable];
BaseBlockActivity[i].target = changeMessage; //ไป่กจไธญๆพๅฐๅผ๏ผ่ต็ปๆดป่ทไฟกๆฏ่กจ
tempVariable[nowVariable] = "no"; //็ฎๆ ๆไฝๆฐๅไธบno
}
else //ๅฆๆไธๆฏไธดๆถๅ้็ๆไฝ
{
changeMessage = notTempVariable[nowVariable];
BaseBlockActivity[i].target = changeMessage;
notTempVariable[nowVariable] = "no";
}
}
if (!isBlankOper(BaseBlockQuar[i].o2))
{
nowVariable = BaseBlockQuar[i].o2;
if (isTemporary(nowVariable))
{
changeMessage = tempVariable[nowVariable];
BaseBlockActivity[i].o2 = changeMessage; //ไป่กจไธญๆพๅฐๅผ๏ผ่ต็ปๆดป่ทไฟกๆฏ่กจ
tempVariable[nowVariable] = "yes"; //ๆไฝๆฐ2ๅไธบyes
}
else
{
changeMessage = notTempVariable[nowVariable];
BaseBlockActivity[i].o2 = changeMessage;
notTempVariable[nowVariable] = "yes";
}
}
if (!isBlankOper(BaseBlockQuar[i].o1))
{
nowVariable = BaseBlockQuar[i].o1;
if (isTemporary(nowVariable))
{
changeMessage = tempVariable[nowVariable];
BaseBlockActivity[i].o1 = changeMessage; //ไป่กจไธญๆพๅฐๅผ๏ผ่ต็ปๆดป่ทไฟกๆฏ่กจ
tempVariable[nowVariable] = "yes"; //ๆไฝๆฐ1ๅไธบyes
}
else
{
changeMessage = notTempVariable[nowVariable];
BaseBlockActivity[i].o1 = changeMessage;
notTempVariable[nowVariable] = "yes";
}
}
int a = 1;
}
}
//่ฎก็ฎๅ้ๅญๅจๅผๅงๅๅ
็ธๅฏนไบold spๅญๅจไฝ็ฝฎ(ไฝฟ็จoldspไฝไฝ็ไฝ็ฝฎ)็ๅ็งป้๏ผ่ฟไธชๅฝๆฐๆฏๆๅบ่ฏฅๅฎ็ฐ็
int TargetCodeGenerator::findBpOffset(string tempName)
{
//ๆฅ็ๅฑๆฌก๏ผๆๆถไฝฟ็จๆต่ฏๅฝๆฐ
int tempLevel = itStack.back().getLevel(tempName);
//่ฟๅๅผ(2)+display((ๅฑๆฌก+1)*2)
//็ฑไบๅ้ๅ็งปไฝ็ฝฎ็ปๅบๆถไนๆฏไป้ถๅผๅง๏ผๆไปฅไธๅผๅงๅฏไปฅ็ดๆฅๅ 2
//ๅบ่ฏฅๅ 1๏ผๅ ไธบ่ฎก็ฎๅๆๅdisplay่กจ็ๆๅ็ไฝไฝ๏ผๅๅ 1ๆๆฏๅญๅจๅผๅงไฝ็ฝฎ
int spOffset = 2 + 2 * (tempLevel + 1) + 1;
return spOffset;
}
//่ฎก็ฎๆๆฑๅ้็ธๅฏนไบๆๅจๅฑsp็ๅ็งป้๏ผ่ฟไธชๅฝๆฐๆฏๆๅบ่ฏฅๅฎ็ฐ็
int TargetCodeGenerator::findTrueOffset(string tempName)
{
//ๅจ่ฟๆถๆๅฐไผๆๅ็งป้่ฝฌๅไธบๆๅไฝไฝ็
ElemSheet::iterator tmpIter = itStack.back().getElemIterator(tempName);
int trueOffset = findBpOffset(tempName) + tmpIter.offSet() + 1;
return trueOffset;
}
//็ๆๆฐๆฎๆฎตๅๅ ๆ ๆฎต,ๅๅงๅ,ๅจๅๅค็ๆไปฃ็ ๆถ่ฐ็จ
void TargetCodeGenerator::initAsm()
{
code nowCode;
//็ๆๆฐๆฎๆฎตๅ ไธบๆๆๆฐๆฎ้ฝๅญๅจๅ ๆ ๆฎต๏ผๆไปฅๆฐๆฎๆฎตไธบ็ฉบ
nowCode.name = "sseg", nowCode.oper = "segment", nowCode.dest = "stack";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "Temp", nowCode.dest = "db", nowCode.source = "'0000H','$'";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "N", nowCode.dest = "dw", nowCode.source = "0";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "dw", nowCode.dest = "512", nowCode.source = "dup(?)";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = "sseg", nowCode.oper = "ends";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
//ๅผๅง็จๅบๆฎต๏ผๅๅงๅๆฐๆฎๆฎต๏ผๅ ๆ ๆฎต๏ผ็จๅบๆฎต
nowCode.name = "cseg", nowCode.oper = "segment";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "assume",nowCode.dest="cs:cseg,",nowCode.source="ds:sseg";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = " assume", nowCode.oper = "ss:sseg";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
/* nowCode.name = "PrintAx", nowCode.oper = "proc", nowCode.dest = "", nowCode.source = "";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "push", nowCode.dest = "si", nowCode.source = "";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "push", nowCode.dest = "cx", nowCode.source = "";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "push", nowCode.dest = "dx", nowCode.source = "";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "mov", nowCode.dest = "si,", nowCode.source = "offset Temp+3";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "xor", nowCode.dest = "cx,", nowCode.source = "cx";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "mov", nowCode.dest = "cl,", nowCode.source = "4";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = "MainPart:", nowCode.oper = "mov", nowCode.dest = "dh,", nowCode.source = "al";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "shr", nowCode.dest = "ax,", nowCode.source = "1";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "shr", nowCode.dest = "ax,", nowCode.source = "1";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "shr", nowCode.dest = "ax,", nowCode.source = "1";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "shr", nowCode.dest = "ax,", nowCode.source = "1";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";*/
}
//ๅค็็จๅบๅผๅงๅๅ
ๅผ
void TargetCodeGenerator::programBegin(quar nowQuar)
{
//start
code nowCode;
nowCode.name = "start:", nowCode.oper = "mov",nowCode.dest="ax,",nowCode.source="sseg";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "mov", nowCode.dest = "ds,", nowCode.source = "ax";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "mov", nowCode.dest = "ax,", nowCode.source = "sseg";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "mov", nowCode.dest = "ss,", nowCode.source = "ax";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
//ๅผๅงๅ้
็จๅบ็ๅ ๆ ็ฉบ้ด
//้ฆๅ
ๅฐbpๅญๅ
ฅ๏ผไธบold sp
stackManager.push(targetCodeArea, blank, "bp");
//mov bp๏ผsp
stackManager.movp(targetCodeArea, blank, "bp,", "sp");
//็กฎๅฎ้่ฆ็ๅญๅจๅๅ
๏ผๆฅ่กจ็กฎๅฎๆฐๆฎๅญๅจๅบ็้ฟๅบฆๅ่ฎก็ฎ๏ผold spๅทฒ็ปๅ ๅ
ฅไบ๏ผๅฐฑไธ็จ็ฎไบ
//็ฐๅจbpๆๅold sp็ไฝไฝ๏ผ้่ฟ[bp]ๅฏไปฅๅๅบold sp
//(่ฟๅๅผ(2)+display((ๅฝๅๅฝๆฐๅฑๆฌกๆฐ+1)*2)+ๆฐๆฎๅญๅจๅบ้ฟๅบฆ๏ผไธ็จไน๏ผๅฏไปฅ็ดๆฅๅพๅฐๅญๅจๅๅ
ๆฐ))
FunSheet::iterator nowIt = itStack[itStack.size()-1];
int dataLenth = nowIt.len();
int nowLevel = nowIt.level();
int storeLenth = 2 + (nowLevel + 1) * 2 + dataLenth;
//้่ฟๅๅฐspๆฅๅผ่พๅญๅจ็ฉบ้ด
stackManager.subSp(targetCodeArea, blank, to_string(storeLenth));
//่ฎก็ฎdisplay่กจ๏ผไนๅๅทฒ็ป่ทๅ่ฟๅฝๅๅฑๆฌกไบ๏ผ็ดๆฅ็จๅฐฑ่กไบ
//ๅ ไธบๆฏ็จๅบๅผๅง๏ผๆไปฅ็ดๆฅ2ไธชๅญๅจๅๅ
่ตๅผๅฐฑ่กไบ
MOV(targetCodeArea, blank, "word ptr [bp-4],", "bp");
}
//ๅจdisplay่กจไธญๆฅๆพไฝ็ฝฎ๏ผ่พๅ
ฅๅ้ๅฑๆฌก๏ผ่ฟๅๆๅไฝไฝ็ๅ็งป้
int TargetCodeGenerator::findInDisplay(int Level)
{
//่ฟๅๅผ(2)+(Level+1)*2
int place = 2 + (Level + 1) * 2;
return place;
}
//ๅค็่ตๅผ
void TargetCodeGenerator::assignCalculation(quar nowQuar, string name)
{
string o1 = nowQuar.o1;
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//ๅผๅง่ฟ่กLD่ฟ็จ
string o1Code = "";
o1Code = findXxx(o1, blank);
string nowRe = "";
//็ๆmovๆไปค
MOV(targetCodeArea, blank, "ax,", o1Code);
nowRe = "ax";
//ๅผๅง่ฟ่กST่ฟ็จ,targetไธๅฎไธๆฏๆฐๅญ
nowRdlTemp = nowQuar.target;
//ๅผๅงๅฏปๅ
string target = nowQuar.target;
string tarCode = "";
tarCode = findXxx(target, blank);
MOV(targetCodeArea, blank, tarCode + ",", "ax");
//ๆดๆนnowRdlTemp็ๅผ
nowRdlTemp = "0"; //ๆธ
็ฉบ
}
//ๅค็ๅ ๅ
void TargetCodeGenerator::addCalculation(quar nowQuar, string name)
{
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//้ฆๅ
่ฟ่กLD่ฟ็จ
//ๅคๆญๆไฝๆฐ1ๆฏๅฆๆฏๆฐๅญ
string o1 = nowQuar.o1;
string o1Code = "";
o1Code = findXxx(o1, blank);
nowRdlTemp = o1;
string nowRe = "";
MOV(targetCodeArea, blank, "ax,", o1Code);
nowRe = "ax";
//ไนๅๅผๅงadd/sub่ฟ็จ
string o2 = nowQuar.o2;
string o2Code = "";
o2Code = findXxx(o2, blank);
nowRdlTemp = nowQuar.target;
if (nowQuar.oper == quatName::ADD)
{
ADD(targetCodeArea, blank, nowRe + ",", o2Code);
}
else
{
SUB(targetCodeArea, blank, nowRe + ",", o2Code);
}
//ไนๅๅผๅงST่ฟ็จ
string target = nowQuar.target;
string tarCode = "";
//targetๅฟ
ๅฎไธบๅ้๏ผไธ็จๅคๆญ๏ผ่ฝ็ถๅคๆญไนไธ้บป็ฆ๏ผ
tarCode = findXxx(target, blank);
nowRdlTemp = target;
MOV(targetCodeArea, blank, tarCode + ",", nowRe);
}
//ๅค็ไน
void TargetCodeGenerator::mulCalculation(quar nowQuar, string name)
{
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//่ฟ่กLD่ฟ็จ
string o1 = nowQuar.o1;
string o1Code = "";
string nowRe = "";
o1Code = findXxx(o1, blank);
nowRdlTemp = o1; //axๅฏๅญๅจๅ
็ไธ่ฅฟ
//่ฟ้ๆไผๅ็็ฉบ้ด๏ผๅฏไปฅ็จppt็ๆนๆณ
XOR(targetCodeArea, blank, "ax,", "ax"); //ๆธ
็ฉบax
XOR(targetCodeArea, blank, "dx,", "dx"); //ๆธ
็ฉบdx๏ผdxๆๆถๅชไผๅจไน้ค็จๅฐ
MOV(targetCodeArea, blank, "ax,", o1Code);
nowRe = "ax";
//ๅผๅงmul่ฟ็จ
string o2 = nowQuar.o2;
string o2Code = "";
o2Code = findXxx(o2, blank);
MOV(targetCodeArea, blank,"cx,",o2Code);
nowRdlTemp = nowQuar.target;
IMUL(targetCodeArea, blank, "cx");
//ๅผๅงST่ฟ็จ
string target = nowQuar.target;
string tarCode = "";
tarCode = findXxx(target, blank);
MOV(targetCodeArea, blank, tarCode + ",", "ax");
}
//ๅค็้ค
void TargetCodeGenerator::divCalculation(quar nowQuar, string name)
{
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//่ฟ่กLD่ฟ็จ
string o1 = nowQuar.o1;
string o1Code = "";
string nowRe = "";
o1Code = findXxx(o1, blank);
nowRdlTemp = o1; //axๅฏๅญๅจๅ
็ไธ่ฅฟ
//่ฟ้ๆไผๅ็็ฉบ้ด๏ผๅฏไปฅ็จppt็ๆนๆณ
XOR(targetCodeArea, blank, "ax,", "ax"); //ๆธ
็ฉบax
XOR(targetCodeArea, blank, "dx,", "dx"); //ๆธ
็ฉบdx๏ผdxๆๆถๅชไผๅจไน้ค็จๅฐ
MOV(targetCodeArea, blank, "ax,", o1Code);
nowRe = "ax";
//ๅผๅงdiv่ฟ็จ
string o2 = nowQuar.o2;
string o2Code = "";
o2Code = findXxx(o2, blank);
MOV(targetCodeArea, blank,"cx,",o2Code);
nowRdlTemp = nowQuar.target;
IDIV(targetCodeArea, blank, "cx");
//ๅผๅงST่ฟ็จ
string target = nowQuar.target;
string tarCode = "";
tarCode = findXxx(target, blank);
MOV(targetCodeArea, blank, tarCode + ",", "ax");
}
//ๅค็ๅ
ณ็ณป่ฟ็ฎ
void TargetCodeGenerator::relCalculation(quar nowQuar, string name)
{
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//้ฆๅ
่ฟ่กcmp o1๏ผo2็ฏ่
//ๅ
LD
string o1 = nowQuar.o1;
string o1Code = "";
string nowRe = "";
o1Code = findXxx(o1, blank);
nowRdlTemp = o1; //axๅฏๅญๅจๅ
็ไธ่ฅฟ
MOV(targetCodeArea, blank, "ax,", o1Code);
nowRe = "ax";
//LDไนๅๅฐฑๆฏๅฏปๅcmpไบ
string o2 = nowQuar.o2;
string o2Code = "";
o2Code = findXxx(o2, blank);
//ๅฏๅญๅจไธๅ๏ผๅฐฑไธๅญไบ
//่ฏฅcmpไบ
CMP(targetCodeArea, blank, nowRe + ",", o2Code);
//็ฐๅจ่ฏฅ็้ธกๅฟ่ทณ่ฝฌไบ๏ผๆๅจ็ๆๆ ๅท็ๆถๅๆณจๆ็น
//ๆกไปถ่ทณ่ฝฌๆไปค
string relJmpCode = getRelAsm(nowQuar.oper);
relJmp(targetCodeArea, blank, relJmpCode, "");
//ๆ ๅทๅ
ฅๆ
ifSEM.push_back(targetCodeArea.size() - 1);
//ไธบๅๆถmov ax,0
MOV(targetCodeArea, blank, "ax,", "0");
//ๆ ๆกไปถ่ทณ่ฝฌๅฐๅผๅง็ปt่ตๅผ
relJmp(targetCodeArea, blank, "jmp", "");
//ๅ
ฅๆ
elSEM.push_back(targetCodeArea.size() - 1);
//็ฐๅจ็ๆๅ่ทณ็็ฎๆ ไฝ็ฝฎ
string nowLabel = "x" + to_string(labelId++);
MOV(targetCodeArea, nowLabel, "ax,", "1");
//ๅผนๅฏนๅบ็ๆ
int nowJmp = ifSEM[ifSEM.size() - 1];
ifSEM.pop_back();
targetCodeArea[nowJmp].source = nowLabel;
//ๅผๅงๆax็ๅผ่ต็ปๅฏนๅบ็ๅ้
nowLabel = "x" + to_string(labelId++);
string target = nowQuar.target;
string tarCode = "";
tarCode = findXxx(target, nowLabel);
//ๅๅกซ
nowJmp = elSEM[elSEM.size() - 1];
elSEM.pop_back();
targetCodeArea[nowJmp].source = nowLabel;
MOV(targetCodeArea, blank, tarCode + ",", "ax");
nowRdlTemp = target;
}
//ๅค็if่ทณ่ฝฌ(ๅ่ทณ)
void TargetCodeGenerator::ifCalculation(quar nowQuar, string name)
{
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//ๅผๅงๅฏปๅ
string o1 = nowQuar.o1;
string o1Code = "";
o1Code = findXxx(o1, blank);
//่ฏฅcmpไบ
MOV(targetCodeArea, blank, "ax,", "0");
CMP(targetCodeArea, blank, "ax,", o1Code);
//่ฏฅ่ทณ่ฝฌไบ
relJmp(targetCodeArea, blank, "je", "");
//ๅ
ฅifๆ
ifSEM.push_back(targetCodeArea.size() - 1);
nowRdlTemp = "const";
}
//ๅค็else่ทณ่ฝฌ(ๆ ๆกไปถ)
void TargetCodeGenerator::elCalculation(quar nowQuar, string name)
{
returnLabel(name);
//็ดๆฅ่ทณ่ฝฌๅฐฑ่ก๏ผไนๅๅๅกซ
relJmp(targetCodeArea, blank, "jmp", "");
ifJmpName = "x"+ to_string(labelId++);
//ๅ
ฅelseๆ
ifSEM.push_back(targetCodeArea.size() - 1);
}
//ๅค็endIf(ๆ ๅจไฝ๏ผNOP,ไธบไบๅตๅฅๆๆไบ่ฟไธช)
void TargetCodeGenerator::endIfCalculation(quar nowQuar, string name)
{
returnLabel(name);
ifJmpName = "x"+ to_string(labelId++);
}
//ๅค็wh่ฏญๅฅ
void TargetCodeGenerator::whCalculation(quar nowQuar, string name)
{
NOP(targetCodeArea, name);
whSEM.push_back(targetCodeArea.size() - 1);
}
//ๅค็do่ทณ่ฝฌ(ๅ่ทณ)
void TargetCodeGenerator::doCalculation(quar nowQuar, string name)
{
//้ฆๅ
ๅฆๆๆๆ ๅท๏ผ็ๆๆ ๅท
returnLabel(name);
//ๅผๅงๅฏปๅ
string o1 = nowQuar.o1;
string o1Code = "";
o1Code = findXxx(o1, blank);
//่ฏฅcmpไบ
MOV(targetCodeArea, blank, "ax,", "0");
CMP(targetCodeArea, blank, "ax,", o1Code);
//่ฏฅ่ทณ่ฝฌไบ
relJmp(targetCodeArea, blank, "je", "");
//ๅ
ฅdoๆ
doSEM.push_back(targetCodeArea.size() - 1);
nowRdlTemp = "const";
}
//ๅค็we่ทณ่ฝฌ(ๆ ๆกไปถ)
void TargetCodeGenerator::weCalculation(quar nowQuar, string name)
{
returnLabel(name);
//ๆๅจๅๅบๆ ๅท
int nowReturn = whSEM[whSEM.size() - 1];
string label = targetCodeArea[nowReturn].name;
whSEM.pop_back();
relJmp(targetCodeArea, blank, "jmp", label);
}
//ๅค็ๆฐ็ปๅๅผgetAddress(address,a,b,t)
void TargetCodeGenerator::getAdrCalculation(quar nowQuar, string name)
{
returnLabel(name);
//่ฎก็ฎ็ๅฎๅ็งป้,ๅๅ ๆฅ็ๆต่ฏifwhileๆๆกฃ
int trueOffset = findTrueOffset(nowQuar.o1);
//ๆฅdisplay่กจ็กฎๅฎ่ฟไธชๅ้ๆๅจ็ๆดปๅจ่ฎฐๅฝๅผๅงไฝ็ฝฎ
//่กจ็ๅ็ผๅฏไปฅ่ฎก็ฎๅพๅบ๏ผๆๆ็ไธ่ฅฟ่ฎก็ฎๅๅไธบๆฑ็ผไปฃ็ ๅณๅฏ
//ๆฅ็็ฎๆ ๆไฝๆฐ็ๅฑๆฌก
int o1Level = itStack.back().getLevel(nowQuar.o1);
//ๅจdisplay่กจไธญๆฅๆพ็ฎๆ ไฝ็ฝฎ
int o1Dis = findInDisplay(o1Level);
//ๅฐๅฐๅ่ฃ
ๅฐbxไธญ๏ผ้่ฟ[bp-xxx]ๆพๅฐ
string strDis = to_string(o1Dis);
//ๅ ไธบๅฐๅไธบ2ไธชๅญๅจๅๅ
๏ผๆไปฅไธบword ptr
strDis = "word ptr [bp-" + strDis + "]";
//่ฃ
ๅ
ฅsiไธญ
MOV(targetCodeArea, blank, "si,", strDis);
//siๅ
ๅๅป็ๅฎๅ็งป้
string strTrueOffset = to_string(trueOffset);
SUB(targetCodeArea, blank, "si,", strTrueOffset);
//ๅๅๅปๆฐ็ปๅ็งป้
string arrOffset = findXxx(nowQuar.o2, blank);
SUB(targetCodeArea, blank, "si,", arrOffset);
SUB(targetCodeArea, blank, "si,", arrOffset);
MOV(targetCodeArea, blank, "ax,", "si");
//ไนๅๅฏปๅtarget
string tarCode = findBpxxx(nowQuar.target, blank);
MOV(targetCodeArea, blank, tarCode + ",", "ax");
}
//ๅค็ๅฝๆฐๅฃฐๆๅผๅงbeginFunction
void TargetCodeGenerator::beginFunCalculation(quar nowQuar)
{
//ไปๅฝๆฐๆ ่ทๅพๅฝๅๅฝๆฐ็name
string nowFunName = itStack.back().name();
PROC(targetCodeArea, nowFunName);
//ๅผๅงๅ้
ๅฝๆฐ็ๅ ๆ ็ฉบ้ด
//้ฆๅ
ๅฐbpๅญๅ
ฅ๏ผไธบold sp
stackManager.push(targetCodeArea, blank, "bp");
//mov bp๏ผsp
stackManager.movp(targetCodeArea, blank, "bp,", "sp");
//็กฎๅฎ้่ฆ็ๅญๅจๅๅ
๏ผๆฅ่กจ็กฎๅฎๆฐๆฎๅญๅจๅบ็้ฟๅบฆๅ่ฎก็ฎ๏ผold spๅทฒ็ปๅ ๅ
ฅไบ๏ผๅฐฑไธ็จ็ฎไบ
//็ฐๅจbpๆๅold sp็ไฝไฝ๏ผ้่ฟ[bp]ๅฏไปฅๅๅบold sp
//(่ฟๅๅผ(2)+display((ๅฝๅๅฝๆฐๅฑๆฌกๆฐ+1)*2)+ๆฐๆฎๅญๅจๅบ้ฟๅบฆ๏ผไธ็จไน๏ผๅฏไปฅ็ดๆฅๅพๅฐๅญๅจๅๅ
ๆฐ))
int dataLenth = itStack.back().len();
int nowLevel = itStack.back().level();
int storeLenth = 2 + (nowLevel + 1) * 2 + dataLenth;
//้่ฟๅๅฐspๆฅๅผ่พๅญๅจ็ฉบ้ด
stackManager.subSp(targetCodeArea, blank, to_string(storeLenth));
//ๅฐold sp่ต็ปbx,ไนๅ่ฎฉbxๆๅdisplayๅผๅง็ไฝไฝ
MOV(targetCodeArea, blank, "bx,", "word ptr [bp]");
SUB(targetCodeArea, blank, "bx,", "4");
//ๅฐ่ขซ่ฐๅฝๆฐdisplayๅผๅง็ไฝไฝ่ต็ปsi
MOV(targetCodeArea, blank, "si,", "bp");
SUB(targetCodeArea, blank, "si,", "4");
//ๅผๅงๅคๅถLๆกdisplay่ฎฐๅฝ
for (int i = 0; i < nowLevel - 1; i++)
{
MOV(targetCodeArea, blank, "ax,", "word ptr [bx]");
MOV(targetCodeArea, blank, "word ptr [si],", "ax");
//่ฎฉbxๅsi็งปๅไธไธๆก่ฎฐๅฝ
SUB(targetCodeArea, blank, "bx,", "2");
SUB(targetCodeArea, blank, "si,", "2");
}
//ๅคๅถไบL-1ๆก๏ผๅฉไธๆก่กฅไธ
MOV(targetCodeArea, blank, "ax,", "word ptr [bx]");
MOV(targetCodeArea, blank, "word ptr [si],", "ax");
SUB(targetCodeArea, blank, "si,", "2");
//ๅฐ่ขซ่ฐๅฝๆฐ็bpไฝ็ฝฎๅ ๅ
ฅdisplay
MOV(targetCodeArea, blank, "word ptr [si],", "bp");
}
//ๅค็่ฟๅๅผgetResult
void TargetCodeGenerator::resultCalculation(quar nowQuar, string name)
{
returnLabel(name);
//ๅฏปๅ
string target = nowQuar.target;
string tarCode = "";
tarCode = findXxx(target, blank);
//ๆaxไธญ็่ฟๅๅผ่ต็ปtarget
//MOV(targetCodeArea, blank, tarCode + ",", "ax");
MOV(targetCodeArea, blank, "si,","sp");
MOV(targetCodeArea, blank, "ax,", "word ptr [si-6]");
MOV(targetCodeArea, blank, tarCode + ",", "ax");
}
//ๅค็่ฟๅๅผassignResult ๏ผ
void TargetCodeGenerator::assResultCalculation(quar nowQuar, string name)
{
returnLabel(name);
//ๅฏปๅ
string o1 = nowQuar.o1;
string o1Code="";
o1Code = findXxx(o1, blank);
//ๆ่ฟๅๅผ่ต็ปax
MOV(targetCodeArea, blank, "ax,", o1Code);
//ๆ่ฟๅๅผๅญๅฐๆดปๅจ่ฎฐๅฝไธญ
MOV(targetCodeArea, blank, "word ptr [bp-2],","ax");
}
//ๅค็ๅฝๆฐๅฃฐๆ็ปๆendFunction
void TargetCodeGenerator::endFunCalculation(quar nowQuar, string name)
{
returnLabel(name);
stackManager.movp(targetCodeArea, blank, "sp,", "bp");
stackManager.pop(targetCodeArea, blank, "bp");
//่ทๅพๅฝๅๅฝๆฐname๏ผไนๅๅผนๆ
string nowFunName = itStack.back().name();
itStack.pop_back();
//็ๆretๆไปค
RET(targetCodeArea, blank);
//ๅฝๆฐ็ปๆ่ฏญๅฅ
ENDP(targetCodeArea, nowFunName);
}
//ๅค็ไผ ๅๆฐๅๅ
ๅผmoveTureParๆmoveFalsePar
void TargetCodeGenerator::parCalculation(quar nowQuar, string name, int index, int level)
{
returnLabel(name);
string o1 = nowQuar.o1;
string o1Code = "";
ElemSheet::iterator nowIter = itStack.back().getElemIterator(o1);
if(isNum(o1))
{
for(int i=1;i<o1.size();i++)
{
o1Code+=o1[i];
}
}
else
{
if (nowIter.cat() == catPoint)
{
//่ฎก็ฎ็ๅฎๅ็งป้,ๅๅ ๆฅ็ๆต่ฏifwhileๆๆกฃ
int trueOffset = findTrueOffset(o1);
//ๆฅdisplay่กจ็กฎๅฎ่ฟไธชๅ้ๆๅจ็ๆดปๅจ่ฎฐๅฝๅผๅงไฝ็ฝฎ
//่กจ็ๅ็ผๅฏไปฅ่ฎก็ฎๅพๅบ๏ผๆๆ็ไธ่ฅฟ่ฎก็ฎๅๅไธบๆฑ็ผไปฃ็ ๅณๅฏ
//ๆฅ็็ฎๆ ๆไฝๆฐ็ๅฑๆฌก
int o1Level = itStack.back().getLevel(o1);
//ๅจdisplay่กจไธญๆฅๆพ็ฎๆ ไฝ็ฝฎ
int o1Dis = findInDisplay(o1Level);
//ๅฐๅฐๅ่ฃ
ๅฐbxไธญ๏ผ้่ฟ[bp-xxx]ๆพๅฐ
string strDis = to_string(o1Dis);
//ๅ ไธบๅฐๅไธบ2ไธชๅญๅจๅๅ
๏ผๆไปฅไธบword ptr
strDis = "word ptr [bp-" + strDis + "]";
//่ฃ
ๅ
ฅbxไธญ
MOV(targetCodeArea, blank, "bx,", strDis);
//็ฐๅจbx้้ขๆๅฏนๅบ็ๅผๅงไฝ็ฝฎ็ๅฐๅ
//้่ฟๅ็งป้ๅฏไปฅ็กฎๅฎไฝ็ฝฎ
//ๆๆถๆฒก่่ไผๅ๏ผๆฒก็ๅปpptไธญstๆไปค๏ผๅ็ปญๅฏ่ฝไผๅ
string strTrueOffset = to_string(trueOffset);
SUB(targetCodeArea, blank, "bx,", strTrueOffset);
o1Code = "[bx]";
}
else
{
if (nowQuar.oper == quatName::moveTurePar)
{
o1Code = findXxx(o1, blank);
}
else
{
//่ฎก็ฎ็ๅฎๅ็งป้,ๅๅ ๆฅ็ๆต่ฏifwhileๆๆกฃ
int trueOffset = findTrueOffset(o1);
//ๆฅdisplay่กจ็กฎๅฎ่ฟไธชๅ้ๆๅจ็ๆดปๅจ่ฎฐๅฝๅผๅงไฝ็ฝฎ
//่กจ็ๅ็ผๅฏไปฅ่ฎก็ฎๅพๅบ๏ผๆๆ็ไธ่ฅฟ่ฎก็ฎๅๅไธบๆฑ็ผไปฃ็ ๅณๅฏ
//ๆฅ็็ฎๆ ๆไฝๆฐ็ๅฑๆฌก
int o1Level = itStack.back().getLevel(o1);
//ๅจdisplay่กจไธญๆฅๆพ็ฎๆ ไฝ็ฝฎ
int o1Dis = findInDisplay(o1Level);
//ๅฐๅฐๅ่ฃ
ๅฐbxไธญ๏ผ้่ฟ[bp-xxx]ๆพๅฐ
string strDis = to_string(o1Dis);
//ๅ ไธบๅฐๅไธบ2ไธชๅญๅจๅๅ
๏ผๆไปฅไธบword ptr
strDis = "word ptr [bp-" + strDis + "]";
//่ฃ
ๅ
ฅbxไธญ
MOV(targetCodeArea, blank, "bx,", strDis);
//็ฐๅจbx้้ขๆๅฏนๅบ็ๅผๅงไฝ็ฝฎ็ๅฐๅ
//้่ฟๅ็งป้ๅฏไปฅ็กฎๅฎไฝ็ฝฎ
//ๆๆถๆฒก่่ไผๅ๏ผๆฒก็ๅปpptไธญstๆไปค๏ผๅ็ปญๅฏ่ฝไผๅ
string strTrueOffset = to_string(trueOffset);
SUB(targetCodeArea, blank, "bx,", strTrueOffset);
o1Code = "bx";
}
}
}
//ๅญๅฐaxไธญ
MOV(targetCodeArea, blank, "ax,", o1Code);
//่ทๅพ่ขซ่ฐๅฝๆฐๅฑๆฌกๅท
int nowOffset = 2 + 2 + 2 + (level + 1) * 2 + 2 * (index+1);
MOV(targetCodeArea, blank, "si,", "sp");
string strNow = "word ptr [si-" + to_string(nowOffset) + "]";
MOV(targetCodeArea, blank, strNow + ",", "ax");
}
//ๅค็ๅฝๆฐ่ฐ็จCall
void TargetCodeGenerator::callCalculation(quar nowQuar, string name)
{
returnLabel(name);
//่ฟ้ๅบ่ฏฅ่ฐ็จๅฝๆฐ่ฟญไปฃๅจ๏ผ็จๆฅ่ทๅๅฝๆฐๅฑๆฌก
FunSheet::iterator callIter = itStack.back().getFunIterator(nowQuar.o1);
//่ทๅพ่ขซ่ฐๅฝๆฐ็ๅฑๆฌก๏ผ่ฎก็ฎdisplay้ฟๅบฆ
int callLevel = callIter.level();
//ๅฐๅ
ฅๆ ็ๅๅ
ๅผ็ๆไปฃ็
for (int i = 0; i < paraColl.size(); i++)
{
parCalculation(paraColl[i], blank, i, callLevel);
}
paraColl.clear();
//็ๆcallๆไปค
CALLP(targetCodeArea, blank, nowQuar.o1);
}
//ๅค็็ปๆไฝๅๅฐๅgetSonAddres
void TargetCodeGenerator::getSonCalculation(quar nowQuar, string name)
{
returnLabel(name);
//่ฎก็ฎ็ๅฎๅ็งป้,ๅๅ ๆฅ็ๆต่ฏifwhileๆๆกฃ
int trueOffset = findTrueOffset(nowQuar.o1);
//ๆฅdisplay่กจ็กฎๅฎ่ฟไธชๅ้ๆๅจ็ๆดปๅจ่ฎฐๅฝๅผๅงไฝ็ฝฎ
//่กจ็ๅ็ผๅฏไปฅ่ฎก็ฎๅพๅบ๏ผๆๆ็ไธ่ฅฟ่ฎก็ฎๅๅไธบๆฑ็ผไปฃ็ ๅณๅฏ
//ๆฅ็็ฎๆ ๆไฝๆฐ็ๅฑๆฌก
int o1Level = itStack.back().getLevel(nowQuar.o1);
//ๅจdisplay่กจไธญๆฅๆพ็ฎๆ ไฝ็ฝฎ
int o1Dis = findInDisplay(o1Level);
//ๅฐๅฐๅ่ฃ
ๅฐbxไธญ๏ผ้่ฟ[bp-xxx]ๆพๅฐ
string strDis = to_string(o1Dis);
//ๅ ไธบๅฐๅไธบ2ไธชๅญๅจๅๅ
๏ผๆไปฅไธบword ptr
strDis = "word ptr [bp-" + strDis + "]";
//่ฃ
ๅ
ฅsiไธญ
MOV(targetCodeArea, blank, "si,", strDis);
//siๅ
ๅๅป็ๅฎๅ็งป้
string strTrueOffset = to_string(trueOffset);
SUB(targetCodeArea, blank, "si,", strTrueOffset);
//่ทๅ็ๆฏ้ๅฏน็ปๆไฝ็ฌฌไธไธช็ๅ็งป้๏ผ็ฌฌไธไธชๆฏ0๏ผ็ฌฌไบไธชๆฏ2
//ไนๅไธ่ฝๅ 1๏ผๅ ไธบๅทฒ็ปๆๅไบไฝไฝ
int sonOffset = itStack.back().getElemIterator(nowQuar.o1).type().sonOffSet(nowQuar.o2);
//ๅๅๅปๅๅๅ็งป้
string strSon = to_string(sonOffset);
SUB(targetCodeArea, blank, "si,", strSon);
MOV(targetCodeArea, blank, "ax,", "si");
//ไนๅๅฏปๅtarget
string tarCode = findBpxxx(nowQuar.target, blank);
//string tarCode = findXxx(nowQuar.target, blank);
MOV(targetCodeArea, blank, tarCode + ",", "ax");
}
//ๅค็่พๅ
ฅ
void TargetCodeGenerator::inCalculation(quar nowQuar, string name)
{
returnLabel(name);
//ๆธ
็ฉบ
MOV(targetCodeArea, blank, "ax,", "0");
MOV(targetCodeArea, blank, "N,", "ax");
//ๅฐๅญๅจๅๅ
็ๅฐๅ่ต็ปsi
LEA(targetCodeArea, blank, "si,", "N");
CALLP(targetCodeArea, blank, "READ10");
MOV(targetCodeArea, blank, "ax,", "N");
//ๅฐax็ๅผ่ต็ปๆไฝๆฐ
string target = nowQuar.target;
string tarCode = findXxx(target, blank);
//่ตๅผ
MOV(targetCodeArea, blank, tarCode+",", "ax");
}
//ๅค็่พๅบ
void TargetCodeGenerator::outCalculation(quar nowQuar, string name)
{
returnLabel(name);
//ๅฏปๅ
string o1 = nowQuar.o1;
string o1Code = findXxx(o1, blank);
MOV(targetCodeArea, blank, "ax,", o1Code);
//call
CALLP(targetCodeArea, blank, "PrintAx");
}
//ๅค็็ปๆ็จๅบ
void TargetCodeGenerator::programEnd(quar nowQuar, string name)
{
returnLabel(name);
//็ๆ็ปๆไธญๆญ่ฏญๅฅ็ญ็ญ้ด้ดไธ่ฅฟ
//ๅฝๆฐๆ ๅผนๆ
itStack.pop_back();
code nowCode;
//็ปๆไธญๆญ
nowCode.name = blank, nowCode.oper = "mov", nowCode.dest = "ah,", nowCode.source = "4ch";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = blank, nowCode.dest = "int", nowCode.source = "21h";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = "cseg", nowCode.oper = "ends", nowCode.dest = "", nowCode.source = "";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
nowCode.name = blank, nowCode.oper = "end", nowCode.dest = "start", nowCode.source = "";
targetCodeArea.push_back(nowCode);
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
}
//็ๆ็ฎๆ ไปฃ็
void TargetCodeGenerator::generateCode()
{
for (int i = 0; i < BaseBlockColl.size(); i++)
{
BaseBlockColl[i].checkBlockActive();
}
//ๆๅผ็ฎๆ ๆไปถ
asmout.open("../Files/target.asm", ios::out);
if (!asmout.is_open())
{
cout << "Open Failed!!!" << endl;
exit(0);
}
//ๅๅงๅๆฐๆฎๆฎต๏ผๅ ๆ ๆฎต
initAsm();
//้ๅๆๆๅบๆฌๅ
for (int i = 0; i < BaseBlockColl.size(); i++)
{
//้ๅๅบๆฌๅไธญๅๅ
ๅผ
for (int j = 0; j < BaseBlockColl[i].BaseBlockQuar.size(); j++)
{
//ๅๅพๅฝๅๅๅ
ๅผๆไฝๆฐ
quar nowQuar = BaseBlockColl[i].BaseBlockQuar[j];
//ๅฏนๅบprogram xxx
if (nowQuar.oper == quatName::beginProgram)
{
if(!itStack.size())
{
itStack.push_back(xTable.getMain());
} else
{
FunSheet::iterator nowIt;
nowIt = itStack[itStack.size()-1];
itStack.push_back(nowIt.getFunIterator(nowQuar.o1));
}
itStack.back().setOffSet(0);
//ๅๅ
ๅผๅบๅท++
}
//ๆไฝ็ฌฆไธบ็จๅบๅผๅงๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็,ๅฏนๅบ
if (nowQuar.oper == quatName::beginFunction)
{
if (itStack.size() == 1)
{
programBegin(nowQuar);
}
else
{
string nowName = "";
nowName = getName(prevQuarNum);
beginFunCalculation(nowQuar);
}
}
//ๆไฝ็ฌฆไธบ่ตๅผๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::Assign)
{
string nowName = "";
nowName = getName(prevQuarNum);
assignCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบๅ ๅๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::ADD ||nowQuar.oper == quatName::SUB)
{
string nowName = "";
nowName = getName(prevQuarNum);
addCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบไนๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็,ไนๅ้คๅฏไปฅๆพๅจไธ่ตท๏ผๅฐฑๆนๅ ่กๅฐฑ่ก
if (nowQuar.oper == quatName::MUL)
{
string nowName = "";
nowName = getName(prevQuarNum);
mulCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบ้คๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::DIV)
{
string nowName = "";
nowName = getName(prevQuarNum);
divCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบๅ
ณ็ณป่ฟ็ฎๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::GT || nowQuar.oper == quatName::GE ||
nowQuar.oper == quatName::LT || nowQuar.oper == quatName::LE ||
nowQuar.oper == quatName::EQ || nowQuar.oper == quatName::NEQ)
{
string nowName = "";
nowName = getName(prevQuarNum);
relCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบifๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::beginIf)
{
string nowName = "";
nowName = getName(prevQuarNum);
ifCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบelseๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::Else)
{
string nowName = "";
nowName = getName(prevQuarNum);
elCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบendifๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::endIf)
{
string nowName = "";
nowName = getName(prevQuarNum);
endIfCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบbeginWhileๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::beginWhile)
{
string nowName = "";
nowName = getName(prevQuarNum);
whCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบDoๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::Do)
{
string nowName = "";
nowName = getName(prevQuarNum);
doCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบendWhileๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::endWhile)
{
string nowName = "";
nowName = getName(prevQuarNum);
weCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบgetAddressๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::getAddress)
{
string nowName = "";
nowName = getName(prevQuarNum);
getAdrCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบgetResultๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::getResult)
{
string nowName = "";
nowName = getName(prevQuarNum);
resultCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบassignResultๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::assignResult)
{
string nowName = "";
nowName = getName(prevQuarNum);
assResultCalculation(nowQuar, nowName);
}
//ๅค็ไผ ๅๅๅ
ๅผ๏ผ็ดๆฅๅๆ
if (nowQuar.oper == quatName::moveTurePar || nowQuar.oper == quatName::moveFalsePar)
{
string nowName = "";
nowName = getName(prevQuarNum);
if(nowName!=blank&&nowName!="")
{
NOP(targetCodeArea, nowName);
}
paraColl.push_back(nowQuar);
}
//ๅค็callๅๅ
ๅผ
if (nowQuar.oper == quatName::Call)
{
string nowName = "";
nowName = getName(prevQuarNum);
callCalculation(nowQuar, nowName);
}
//ๅค็็ปๆไฝๅฏปๅ
if (nowQuar.oper == quatName::getSonAddres)
{
string nowName = "";
nowName = getName(prevQuarNum);
getSonCalculation(nowQuar, nowName);
}
//ๆไฝ็ฌฆไธบ็จๅบ็ปๆๆถ่ฐ็จๅฏนๅบๅฝๆฐๅค็
if (nowQuar.oper == quatName::endFunction)
{
if (itStack.size() == 1)
{
string nowName = "";
nowName = getName(prevQuarNum);
programEnd(nowQuar, nowName);
}
else
{
string nowName = "";
nowName = getName(prevQuarNum);
endFunCalculation(nowQuar, nowName);
}
}
//ๅค็่พๅ
ฅ
if(nowQuar.oper == quatName::Input)
{
string nowName = "";
nowName = getName(prevQuarNum);
inCalculation(nowQuar, nowName);
}
//ๅค็่พๅบ
if(nowQuar.oper == quatName::Output)
{
string nowName = "";
nowName = getName(prevQuarNum);
outCalculation(nowQuar, nowName);
}
code nowCode;
nowCode.name = nowCode.oper = nowCode.dest = nowCode.source = "";
targetCodeArea.push_back(nowCode);
prevQuarNum++;
}
//ๆธ
็ฉบๆดป่ท่กจ
isActive.clear();
}
int a = 1;
for (int i = 0; i < targetCodeArea.size(); i++)
{
if(i==8)
{
asmout<<endl<<"PrintAX proc\n"
" push si\n"
" push cx\n"
" push dx \n"
" mov si,offset Temp+3;ไฟๅญๅญๅจ็ปๆ็ๅญ็ฌฆไธฒ็ๆๅไธไธชๅญ็ฌฆๅ็งปๅฐๅ\n"
" xor cx,cx ;ๅฏนcXๆธ
้ถ\n"
" mov cl,4 ;่ฎพ็ฝฎๅพช็ฏๆฌกๆฐไธบ4ๆฌก\n"
" MainPart: mov DH,AL ;ๅฐAl็ๅ
ๅฎนไผ ้็ปDH\n"
" shr AX,1\n"
" shr AX,1\n"
" shr AX,1\n"
" shr AX,1\n"
" and dh,0FH\n"
" add dh,30H\n"
" cmp dh,':' \n"
" ja isLetter \n"
" jb No \n"
" isLetter: add dh,7H \n"
" No: mov [si],dh \n"
" dec si\n"
" loop MainPart\n"
"print: mov dx,offset Temp \n"
" mov ah,09\n"
" int 21H\n"
" pop dx\n"
" pop cx\n"
" pop si\n"
" ret\n"
" PrintAX endp"<<endl<<endl;
asmout<<"READ10 PROC NEAR\n"
" XOR DX,DX\n"
" MOV BX,10\n"
"RD0:\n"
" MOV AH,1\n"
" INT 21H\n"
" CMP AL,13 ;่พๅ
ฅๅ่ฝฆ็ปๆ\n"
" JZ RT0\n"
" AND AX,0FH ;ๅฐAHๆธ
้ถ\n"
" XCHG AX,[SI]\n"
" MUL BX ;ๅฐๅไธไฝๆฐๅญไนๅๅไธไธไฝๆฐๅญ็ธๅ \n"
" ADD AX,[SI]\n"
" XCHG AX,[SI]\n"
" JMP RD0 \n"
"\n"
"RT0: RET\n"
"READ10 ENDP"<<endl;
}
if( targetCodeArea[i].name==""&&targetCodeArea[i].name==""&&
targetCodeArea[i].name==""&&targetCodeArea[i].name=="")
{
asmout<<endl;
continue;
}
if (targetCodeArea[i].name.size() > 0)
{
asmout << targetCodeArea[i].name;
if (targetCodeArea[i].name[0] == 'x')
asmout << ":" + blank;
}
if (targetCodeArea[i].oper.size() > 0)
asmout << " " << targetCodeArea[i].oper;
if (targetCodeArea[i].dest.size() > 0)
asmout << " " << targetCodeArea[i].dest;
if (targetCodeArea[i].source.size() > 0)
asmout << " " << targetCodeArea[i].source;
asmout << endl;
}
asmout.close();
cout<<"generate succeed!"<<endl;
}
//ๅคๆญไธไธชๅญ็ฌฆไธฒๆฏๅฆๆฏๆฐๅญ
int TargetCodeGenerator::isNum(string nowStr)
{
int isnum = 1;
if(nowStr[0]!='0')
isnum = 0;
return isnum;
}
//่ฟ่กๅฏปๅๆไฝ
string TargetCodeGenerator::findBpxxx(string nowOper, string name)
{
//่ฎก็ฎ็ๅฎๅ็งป้,ๅๅ ๆฅ็ๆต่ฏifwhileๆๆกฃ
int trueOffset = findTrueOffset(nowOper);
//ๆฅdisplay่กจ็กฎๅฎ่ฟไธชๅ้ๆๅจ็ๆดปๅจ่ฎฐๅฝๅผๅงไฝ็ฝฎ
//่กจ็ๅ็ผๅฏไปฅ่ฎก็ฎๅพๅบ๏ผๆๆ็ไธ่ฅฟ่ฎก็ฎๅๅไธบๆฑ็ผไปฃ็ ๅณๅฏ
//ๆฅ็็ฎๆ ๆไฝๆฐ็ๅฑๆฌก
int o1Level = itStack.back().getLevel(nowOper);
//ๅจdisplay่กจไธญๆฅๆพ็ฎๆ ไฝ็ฝฎ
int o1Dis = findInDisplay(o1Level);
//ๅฐๅฐๅ่ฃ
ๅฐbxไธญ๏ผ้่ฟ[bp-xxx]ๆพๅฐ
string strDis = to_string(o1Dis);
//ๅ ไธบๅฐๅไธบ2ไธชๅญๅจๅๅ
๏ผๆไปฅไธบword ptr
strDis = "word ptr [bp-" + strDis + "]";
//่ฃ
ๅ
ฅbxไธญ
MOV(targetCodeArea, name, "bx,", strDis);
//็ฐๅจbx้้ขๆๅฏนๅบ็ๅผๅงไฝ็ฝฎ็ๅฐๅ
//้่ฟๅ็งป้ๅฏไปฅ็กฎๅฎไฝ็ฝฎ
//ๆๆถๆฒก่่ไผๅ๏ผๆฒก็ๅปpptไธญstๆไปค๏ผๅ็ปญๅฏ่ฝไผๅ
string strTrueOffset = to_string(trueOffset);
//็ๆๅญ็ฌฆไธฒ
strTrueOffset = "word ptr [bx-" + strTrueOffset + "]";
return strTrueOffset;
}
//็ๆๆ้ๅฏนๅบ็ๆไฝๆฐไปฃ็
string TargetCodeGenerator::findPointxxx(string nowOper, string name)
{
//่ฎก็ฎ็ๅฎๅ็งป้,ๅๅ ๆฅ็ๆต่ฏifwhileๆๆกฃ
int trueOffset = findTrueOffset(nowOper);
string strOffset = to_string(trueOffset);
//ๅฐๅฝๅๅๅ
็ๅผๅญๅ
ฅbx,ๆฏไธไธช็ๅฎๅฐๅ
strOffset = "word ptr [bp-" + strOffset + "]";
MOV(targetCodeArea, name, "bx,", strOffset);
//ไนๅ้่ฟbx็ๅผ้ดๆฅๅฏปๅ
string strPointOffset = "word ptr [bx]";
return strPointOffset;
}
//ๅฐ่ฃ
ไธ็งๅฏปๅๅฝขๅผ
string TargetCodeGenerator::findXxx(string nowOper, string name)
{
string nowCode = "";
if (isNum(nowOper)) //ๅฆๆๆฏๆฐๅญ,ๅๅช้ๅฐๅ
ถๆพๅฐๅฏๅญๅจไธญ
{
//่ฎก็ฎๆบๆไฝๆฐๅฝขๅผ
for(int i=1; i < nowOper.size(); i++)
nowCode += nowOper[i];
//ๆดๆนnowRdlTemp็ๅผ
nowRdlTemp = "const"; //constไปฃ่กจๅธธๅผ
}
else
{
ElemSheet::iterator nowIter = itStack.back().getElemIterator(nowOper);
CAT nowCat = nowIter.cat();
if(nowIter.cat() == catVn || nowIter.cat() == catPoint)
{
nowCode = findPointxxx(nowOper, name);
nowRdlTemp = nowOper;
}
else
{
//ๅคๆญๆฏๅฆๆฏๅๆฐ๏ผ้ๅๅฏนๅบ็ๆไฝ
//็ฐๅจไธ็จไบ๏ผ็ดๆฅๅฏปๅๅฐฑ่ก
nowCode = findBpxxx(nowOper, name);
//ๆดๆนnowRdlTemp็ๅผ
nowRdlTemp = nowOper; //ๅ้ๅ
}
}
return nowCode;
}
//ๅฐๅ
ณ็ณป่ฝฌๆขๆๆฑ็ผๆไฝ็ฌฆ๏ผๅฆLTๅฏนๅบJL
string TargetCodeGenerator::getRelAsm(string relOper)
{
const int relNum = 6;
string rel[6] = { "LT","LE","GT","GE","EQ","NEQ" };
string asmRel[6] = { "JL","JLE","JG","JGE","JE","JNE" };
for (int i = 0; i < relNum; i++)
{
if (relOper == rel[i])
return asmRel[i];
}
return "take it boy";
}
//็จไบๅคๆญไนๅๆฏๅฆๆฏ้่ฆ็ๆๆ ๅท๏ผif็จ่ฟไธช
string TargetCodeGenerator::getName(int prevQuarName)
{
string nowName = "";
/*if (AllQuarColl[prevQuarNum].oper == quatName::Else)
{
nowName = "x" + to_string(labelId);
labelId++;
}
else if (AllQuarColl[prevQuarNum].oper == quatName::endIf)
{
nowName = "x" + to_string(labelId);
labelId++;
}*/
if(ifJmpName!="" &&ifJmpName!=blank)
{
nowName = ifJmpName;
ifJmpName="";
}
else if (AllQuarColl[prevQuarNum].oper == quatName::endWhile)
{
nowName = "x" + to_string(labelId);
labelId++;
}
else if (AllQuarColl[prevQuarNum + 1].oper == quatName::beginWhile)
{
nowName = "x" + to_string(labelId);
labelId++;
}
else
{
nowName = blank;
}
return nowName;
}
//ๅฆๆ้่ฆ็่ฏ็ๆๆ ๅท๏ผไนๅๅๅกซ,ifไฝฟ็จ
void TargetCodeGenerator::returnLabel(string name)
{
if (name != blank && name != "")
{
//ๅ่ทณ็็ฎๆ
NOP(targetCodeArea, name);
//ๅผนๅฏนๅบ็ๆ
int nowJmp = 0;
if (AllQuarColl[prevQuarNum].oper == quatName::Else)
{
nowJmp = ifSEM[ifSEM.size() - 1];
ifSEM.pop_back();
}
else if (AllQuarColl[prevQuarNum].oper == quatName::endIf)
{
nowJmp = ifSEM[ifSEM.size() - 1];
ifSEM.pop_back();
}
else if (AllQuarColl[prevQuarNum].oper == quatName::endWhile)
{
nowJmp = doSEM[doSEM.size() - 1];
doSEM.pop_back();
}
targetCodeArea[nowJmp].source = name;
}
}
|
/** Underscore
@file /.../Source/Kabuki_SDK-Impl/_App/RealTimeKeyboard.h
@author Cale McCollough
@copyright Copyright 2016 Cale McCollough ยฉ
@license http://www.apache.org/licenses/LICENSE-2.0
@brief This file contains the _ class.
*/
using System.Diagnostics;
namespace _IO
{
delegate void Event ();
/** A computer keyboard.
Keyboard events are stored as delegates.
*/
class RealTimeKeyboard
{
const int DefaultBufferSize = 256, //< The default buffer size.
MinBufferSize = 64, //< Min buffer size.
MaxBufferSize = 1024 * 10; //< Max buffer size.
/** Default constructor. **/
RealTimeKeyboard (int a = DefaultBufferSize)
{
if (a < MinBufferSize) bufferSize = MinBufferSize;
else if (a > MaxBufferSize) bufferSize = MaxBufferSize;
else bufferSize = a;
start = stop = begin;
}
/** Resets the event buffer. */
void Clear ()
{
start = stop = begin;
}
/** Inserts an event into the buffer. */
void Insert (Event a)
{
if (stop + 1 > end)
{
Debug.Assert (start != begin, "Insert (byte): Buffer overflow.");
stop = begin;
buffer[stop] = a;
}
Debug.Assert (stop + 1 == start, "Insert (byte): Buffer overflow.");
buffer[++stop] = a;
}
/** */
void Update ()
{
if (start > stop)
{
for (int i = start; i <= end; ++i) buffer[i] ();
for (int i = begin; i <= stop; ++i) buffer[i] ();
start = stop = begin;
return;
}
for (int i = start; i <= end; ++i) buffer[i] ();
start = stop = begin;
}
// Returns a string representation of this object.
string ToString ()
{
return "begin: " + begin + " end: " + end + " start: " + start + " stop: " + stop + "\n";
}
private:
int begin,
end,
start,
stop,
bufferSize;
Event buffer[];
}
}
|
#pragma once
#include <string>
#include "../include/definitions.h"
namespace ACJudge2
{
class Sandbox
{
public:
Result Run(Tstring cmd, Time time, Memory memory, bool restricted, Tstring fin = T(""), Tstring fout = T(""), Tstring ferr = T(""));
private:
#if defined _WIN32
// Set limits
// Tags will be saved in
JOBOBJECT_EXTENDED_LIMIT_INFORMATION SetLimits(Time time, Memory memory, bool restricted);
// Set UI restrictions
JOBOBJECT_BASIC_UI_RESTRICTIONS SetRulesUI(bool restricted);
// Redirect file input/output/error target
STARTUPINFO Redirection(Tstring in, Tstring out, Tstring err);
#elif defined _NIX
// Set time limit
// Both with setitimer and setrlimit
// Here time is CPU time, and stime is actual time
Return set_time_limit(Time time);
// Set memory limit
// With setrlimit
Return set_space_limit(Memory memory);
// Redirect I/O flow <file> to file with name <name>
Return set_file(FILE *fp, Tstring file, Tstring mode);
// Starter
// This is what the starter have to do before execve
void start(Tstring file, Tchar *args[], Time time, Memory memory, bool restricted, Tstring fin, Tstring fout, Tstring ferr);
// Set time and memory limits for current process
// Always called immediately after forking
Return set_limits(Time time, Memory memory);
// Set rules (security) for current process
// Called when <restricted> is true
// [Thanks] QingDaoU Judger
// link: https://github.com/QingdaoU/Judger
Return set_rules(Tstring s);
// Set group of current process to guest for safety
Return set_gid();
// Redirect file input/output/error target
Return redirection(Tstring in, Tstring out, Tstring err);
#endif
};
}
|
// OLED
#include <Multi_BitBang.h>
#include <Multi_OLED.h>
#define OLED_w 128
#define OLED_h 64
#define NUM_DISPLAYS 2
#define NUM_BUSES 2
#define BASE_CONTRAST 1000
// I2C bus info
uint8_t scl_list[NUM_BUSES] = {D1, D1}; //{9,9,9,9};
uint8_t sda_list[NUM_BUSES] = {D2, D0}; //{5,6,7,8};
int32_t speed_list[NUM_BUSES] = {4000000L, 4000000L}; // OLED display info
uint8_t bus_list[NUM_DISPLAYS] = {0, 1}; // can be multiple displays per bus
uint8_t addr_list[NUM_DISPLAYS] = {0x3c, 0x3c};
uint8_t type_list[NUM_DISPLAYS] = {OLED_128x64, OLED_128x64};
uint8_t flip_list[NUM_DISPLAYS] = {0, 1};
uint8_t invert_list[NUM_DISPLAYS] = {0, 0};
unsigned char bmp[OLED_w * OLED_h / 8];
int Kp_delta = 0;
int Ti_delta = 0;
int Td_delta = 0;
int part = 0;
void setup()
{
Serial.begin(500000);
Serial.println();
pinMode(D3, INPUT_PULLUP);
pinMode(D4, INPUT_PULLUP);
pinMode(D5, INPUT_PULLUP);
pinMode(D6, INPUT_PULLUP);
pinMode(D7, INPUT);
pinMode(D8, INPUT);
Multi_I2CInit(sda_list, scl_list, speed_list, NUM_BUSES);
Multi_OLEDInit(bus_list, addr_list, type_list, flip_list, invert_list, NUM_DISPLAYS);
for (uint8_t i = 0; i < NUM_DISPLAYS; i++)
{
Multi_OLEDFill(i, 0);
Multi_OLEDSetContrast(i, BASE_CONTRAST);
}
}
char flt[16] = {' '};
float result = 0;
void loop()
{
get_sequ();
Multi_OLEDWriteString(0, 0, 0, "", FONT_NORMAL, 0);
Multi_OLEDLoadBMP(0, bmp);
if (digitalRead(D5) == 0) {
Kp_delta--;
} else if (digitalRead(D6) == 0) {
Kp_delta++;
}
Serial.write(Kp_delta);
if (digitalRead(D3) == 0) {
Ti_delta--;
} else if (digitalRead(D4) == 0) {
Ti_delta++;
}
Serial.write(Ti_delta);
if (digitalRead(D7) == 1) {
Td_delta--;
} else if (digitalRead(D8) == 1) {
Td_delta++;
}
Serial.write(Td_delta);
result = 1.7433 + 0.5 * Kp_delta;
String buf;
buf += F("Kp: ");
buf += String(result, 6);
buf.toCharArray(flt, 16);
Multi_OLEDWriteString(1, 0, 0, flt, FONT_NORMAL, 0);
result = 0.1755 + 0.5 * Ti_delta;
buf = "";
buf += F("Ti: ");
buf += String(result, 6);
buf.toCharArray(flt, 16);
Multi_OLEDWriteString(1, 0, 2, flt, FONT_NORMAL, 0);
result = 0.0439 + 0.1 * Td_delta;
buf = "";
buf += F("Td: ");
buf += String(result, 6);
buf.toCharArray(flt, 16);
Multi_OLEDWriteString(1, 0, 4, flt, FONT_NORMAL, 0);
}
void wait_for_serial() {
while (Serial.available() <= 0) {
}
}
unsigned char temp;
void get_sequ() {
get_init_sequ();
for (int i = 0; i < OLED_w * OLED_h / 8; ++i) {
wait_for_serial();
temp = Serial.read();
bmp[i] = temp ;
}
// int i = 0;
// while (i < OLED_w * OLED_h / 8) {
// if (Serial.available()) {
// bmp[i] = Serial.read();
// ++i;
// }
// }
}
void get_init_sequ() {
uint8_t init_i = 0;
while (init_i < 2) {
wait_for_serial();
if (Serial.read() == 69) {
init_i++;
}
}
}
|
#include "cleanuptools.hpp"
#include "scene.hpp"
// #include <SFML/Graphics.hpp>
#include "SFML-2.5.1-macos-clang/include/SFML/Graphics.hpp"
#include "SFML-2.5.1-macos-clang/include/SFML/Window.hpp"
#include "whereami/whereami.h"
#include <csignal> // kill
// #include <string> - don't think it is needed
#include <thread> // for sleep operations after buttons are pressed
#include <chrono> // not sure if needed or not
/*****************************************************************************
*
*
*****************************************************************************/
namespace fs = std::filesystem;
int main() {
// FLAGS
int pid;
TabMode mode = MANUAL;
int MANUALCLEAN = 0;
int REVERT = 0;
int AUTOCLEAN = 0; // activate everytime button pressed
int EVENTPROCESSED = 1; // start off by drawing the base
int MODECHANGED = 0;
int isAutoActive= 0;
// desktop-vacuum/src/main.cpp
// monitor directory that contains desktop-vacuum
int length = wai_getExecutablePath(NULL, 0, NULL);
char *path = new char[length + 1];
wai_getExecutablePath(path, length, NULL);
path[length] = '\0';
fs::path buildPath = fs::path(path).parent_path(); // desktop-vacuum/build
fs::path dirPath = buildPath.parent_path(); // desktop-vacuum
fs::path resPath = fs::path(dirPath.string() + "/res");
fs::path monitorPath = dirPath.parent_path();
Scene interface;
interface.loadConfig(monitorPath, resPath);
/* Loading window-related values */
int width = interface.getWidth();
int height = interface.getHeight();
sf::Color bgColour = interface.getBgColour();
int width2 = interface.getWidth2();
int height2 = interface.getHeight2();
/* Window initialisation */
sf::RenderWindow window(sf::VideoMode(width, height), "Desktop-vacuum",
sf::Style::Titlebar | sf::Style::Close);
window.setVerticalSyncEnabled(true);
sf::View view1(sf::FloatRect(0.f, 0.f, width, height));
sf::View view2(sf::FloatRect(0.f, 0.f, width2, height2));
sf::Vector2i pos;
// [>* Cleaner *<]
CleanupTools cleaner(monitorPath, resPath);
delete[] path;
// [> Event-based rendering <]
while (window.isOpen()) {
sf::Event event;
/* Separate loop for performing the cleans */
if (MANUALCLEAN && !isAutoActive) {
interface.writeChanges();
cleaner.manualCleanup();
// to make sure it doesn't finish too quickly
std::this_thread::sleep_for(std::chrono::milliseconds(200));
interface.finishManualC(MANUALCLEAN);
EVENTPROCESSED = 1;
} else if (REVERT && !isAutoActive) {
cleaner.revert();
// to make sure it doesn't finish too quickly
std::this_thread::sleep_for(std::chrono::milliseconds(200));
interface.finishRevert(REVERT);
EVENTPROCESSED = 1;
} else if (AUTOCLEAN) {
// needs more AUTOCLEAN checks...this case is different
// std::this_thread::sleep_for(std::chrono::milliseconds(400));
if (isAutoActive) {
// killing running process
// "toggle"
kill(pid, SIGKILL);
interface.finishAutoC(isAutoActive);
} else {
// start autoclean process
interface.writeChanges();
pid = fork();
if (pid == 0) {
cleaner.autoCleanup();
exit(0);
}
isAutoActive = 1;
}
AUTOCLEAN = 0;
EVENTPROCESSED = 1;
}
while (window.pollEvent(event)) {
EVENTPROCESSED = 1;
float x = sf::Mouse::getPosition(window).x;
float y = sf::Mouse::getPosition(window).y;
switch(event.type) {
case sf::Event::Closed:
window.close();
if (isAutoActive) kill(pid, SIGKILL);
interface.writeChanges();
break;
case sf::Event::MouseButtonPressed:
// passing in x, y coord and flags
interface.updateAll(x, y, MANUALCLEAN, REVERT, AUTOCLEAN,
isAutoActive, MODECHANGED);
break;
default:
break;
}
}
if (EVENTPROCESSED) {
interface.getMode(mode);
window.clear(bgColour);
interface.redrawAll(window);
// new tab has been selected
if (MODECHANGED) {
pos = window.getPosition();
if (mode == GROUPINGS ||mode == IGNORELST) {
window.setSize(sf::Vector2u(width2, height2));
window.setView(view2);
window.setPosition(pos);
} else {
window.setSize(sf::Vector2u(width, height));
window.setView(view1);
window.setPosition(pos);
}
MODECHANGED = 0;
}
window.display();
EVENTPROCESSED = 0;
}
}
return 0;
}
|
#ifndef CONTACTSPANEL_H
#define CONTACTSPANEL_H
#include "adjunct/quick_toolkit/windows/DesktopWindow.h"
#include "adjunct/desktop_util/treemodel/optreemodel.h"
#include "adjunct/desktop_util/treemodel/optreemodelitem.h"
#include "modules/util/adt/opvector.h"
#include "adjunct/quick/panels/HotlistPanel.h"
#include "modules/widgets/OpWidget.h"
#ifdef MSWIN
#include "platforms/windows/windows_ui/oui.h"
#endif
class OpToolbar;
class OpLabel;
class OpHotlistView;
/***********************************************************************************
**
** ContactsPanel
**
***********************************************************************************/
class ContactsPanel : public HotlistPanel
{
public:
ContactsPanel();
virtual ~ContactsPanel();
OpHotlistView* GetHotlistView() const {return m_hotlist_view;}
virtual OP_STATUS Init();
virtual void GetPanelText(OpString& text, Hotlist::PanelTextType text_type);
virtual const char* GetPanelImage() {return "Panel Contacts";}
virtual void OnLayoutPanel(OpRect& rect);
virtual void OnLayoutToolbar(OpToolbar* toolbar, OpRect& rect);
virtual void OnFullModeChanged(BOOL full_mode);
virtual void OnFocus(BOOL focus,FOCUS_REASON reason);
virtual Type GetType() {return PANEL_TYPE_CONTACTS;}
// == OpInputContext ======================
INT32 GetSelectedFolderID();
void SetSelectedItemByID(INT32 id,
BOOL changed_by_mouse = FALSE,
BOOL send_onchange = TRUE,
BOOL allow_parent_fallback = FALSE)
{
m_hotlist_view->SetSelectedItemByID(id, changed_by_mouse, send_onchange, allow_parent_fallback);
}
virtual BOOL OnInputAction(OpInputAction* action);
virtual const char* GetInputContextName() {return "Contacts Panel";}
virtual void OnAdded();
virtual void OnRemoving();
virtual void OnShow(BOOL show);
private:
OpHotlistView* m_hotlist_view;
};
#endif // CONTACTSPANEL_H
|
#include <stdio.h>
#include <stdlib.h>
//ํธ๋ฆฌ๋
ธ๋ ๊ตฌ์กฐ์ฒด
typedef struct TreeNode {
int data; //๋ฐ์ดํฐ
struct TreeNode *left, *right; //์ผ์ชฝ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ, ์ค๋ฅธ์ชฝ ๋
ธ๋๋ฅผ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ
} TreeNode;
//ํจ์ ์ ์ธ
void inorder(TreeNode *);
void preorder(TreeNode *);
void postorder(TreeNode *);
void triple_order(TreeNode *);
int main()
{
//์ด์งํธ๋ฆฌ ์1
/*
TreeNode n1 = { 'a', NULL, NULL };
TreeNode n2 = { 'b', NULL, NULL };
TreeNode n3 = { '*', &n1, &n2 };
TreeNode n4 = { 'c', NULL, NULL };
TreeNode n5 = { 'd', NULL, NULL };
TreeNode n6 = { '/', &n4, &n5 };
TreeNode n7 = { '+', &n3, &n6 };
TreeNode *root1 = &n7; //๋ฃจํธ ๋
ธ๋ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ
//๊ฒฐ๊ณผ ์ถ๋ ฅ
printf("inorder of ์1 = ");
inorder(root1); //์ค์์ ์ดํ
printf("\npreorder of ์1 = ");
preorder(root1); //์ ์์ ์ดํ
printf("\npostorder of ์1 = ");
postorder(root1); //ํ์์ ์ดํ
printf("\ntriple order of ์1 = ");
triple_order(root1); //triple order ์ดํ
*/
//์ด์งํธ๋ฆฌ ์2
TreeNode n1 = { '3', NULL, NULL };
TreeNode n2 = { '2', NULL, NULL };
TreeNode n3 = { '*', &n1, &n2 };
TreeNode n4 = { '4', NULL, NULL };
TreeNode n5 = { '2', NULL, NULL };
TreeNode n6 = { '/', &n4, &n5 };
TreeNode n7 = { '+', &n3, &n6 };
TreeNode n8 = { '2', NULL, NULL };
TreeNode n9 = { '3', NULL, NULL };
TreeNode n10 = { '5', NULL, NULL };
TreeNode n11 = { '*', &n9, &n10 };
TreeNode n12 = { '2', NULL, NULL };
TreeNode n13 = { '+', &n11, &n12 };
TreeNode n14 = { '+', &n8, &n13 };
TreeNode n15 = { '*', &n7, &n14 };
TreeNode *root2 = &n15; //๋ฃจํธ ๋
ธ๋ ๊ฐ๋ฆฌํค๋ ํฌ์ธํฐ
printf("inorder of ์2 = ");
inorder(root2); //์ค์์ ์ดํ
printf("\npreorder of ์2 = ");
preorder(root2); //์ ์์ ์ดํ
printf("\npostorder of ์2 = ");
postorder(root2); //ํ์์ ์ดํ
printf("\ntriple order of ์2 = ");
triple_order(root2); //triple_order ์ดํ
}
//์ค์์ ์ดํ
void inorder(TreeNode *root)
{
if (root) { //root ๋
ธ๋ ํฌ์ธํฐ๊ฐ NULL ์๋ ๋ ๊น์ง
inorder(root->left); //์ผ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ ์ค์์ ์ดํ
printf("%c ", root->data); //root ๋ฐ์ดํฐ๊ฐ ์ถ๋ ฅ
inorder(root->right); //์ค๋ฅธ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ ์ค์์ ์ดํ
}
}
//์ ์์ ์ดํ
void preorder(TreeNode *root)
{
if (root) { //root๋
ธ๋ ํฌ์ธํฐ๊ฐ NULL์ด ์๋ ๋ ๊น์ง
printf("%c ", root->data); //root ๋ฐ์ดํฐ๊ฐ ์ถ๋ ฅ
preorder(root->left); //์ผ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ ์ ์์ ์ดํ
preorder(root->right); //์ค๋ฅธ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ ์ ์์ ์ดํ
}
}
//ํ์์ ์ดํ
void postorder(TreeNode *root)
{
if (root) { //root ๋
ธ๋ ํฌ์ธํฐ๊ฐ NULL์ด ์๋ ๋ ๊น์ง
postorder(root->left); //์ผ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ ํ์์ ์ดํ
postorder(root->right); //์ค๋ฅธ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ ํ์์ ์ดํ
printf("%c ", root->data); //root ๋ฐ์ดํฐ๊ฐ ์ถ๋ ฅ
}
}
void triple_order(TreeNode *root)
{
if (root != NULL) { //root ๋
ธ๋ ํฌ์ธํฐ๊ฐ NULL์ด ์๋ ๋ ๊น์ง
printf("%c ", root->data); //root ๋ฐ์ดํฐ๊ฐ ์ถ๋ ฅ
triple_order(root->left); //์ผ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ triple order ์ดํ
printf("%c ", root->data); //๋ค์ root ๋ฐ์ดํฐ๊ฐ ์ถ๋ ฅ
triple_order(root->right); //์ค๋ฅธ์ชฝ ๋ถ๋ถ ํธ๋ฆฌ triple order ์ดํ
printf("%c ", root->data); //๋ค์ root ๋ฐ์ดํฐ๊ฐ ์ถ๋ ฅ
}
}
|
int momBut = 2;
int led1 = 3;
int led2 = 4;
int led3 = 5;
int counter = 0;
int lastButtonState = 0;
int buttonVal;
void setup() {
pinMode(2, INPUT);
pinMode(led1, OUTPUT);
pinMode(led2, OUTPUT);
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
buttonVal = digitalRead(momBut);
if(buttonVal != lastButtonState){
if (buttonVal == HIGH)
{
counter = counter + 1;
}
delay(50);
}
lastButtonState = buttonVal;
if(counter == 1 )
{
digitalWrite(led1, HIGH);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
}
else if(counter == 2)
{
digitalWrite(led1, LOW);
digitalWrite(led2, HIGH);
digitalWrite(led3, LOW);
}
else if(counter == 3)
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, HIGH);
}
else if(counter == 4)
{
digitalWrite(led1, LOW);
digitalWrite(led2, LOW);
digitalWrite(led3, LOW);
counter = 0;
}
}
|
#include <SDL.h>
#define GLEW_STATIC
#include <GL/glew.h>
#include "treeface/base/PackageManager.h"
#include "treeface/graphics/ShapeGenerator.h"
#include "treeface/math/Constants.h"
#include "treeface/misc/UniversalValue.h"
#include "treeface/scene/Geometry.h"
#include "treeface/scene/MaterialManager.h"
#include "treeface/scene/Scene.h"
#include "treeface/scene/SceneGraphMaterial.h"
#include "treeface/scene/SceneNode.h"
#include "treeface/scene/SceneRenderer.h"
#include "treeface/scene/VisualObject.h"
#include <set>
#include <treecore/File.h>
#include <treecore/StringRef.h>
using namespace treeface;
using namespace treecore;
using namespace std;
const int window_w = 1024;
const int window_h = 768;
const float handle_sz = 15;
SDL_Window* window = nullptr;
SDL_GLContext context = nullptr;
RefCountHolder<Geometry> curve_stroke_geom;
RefCountHolder<VisualObject> curve_stroke_visual;
RefCountHolder<Geometry> curve_fill_geom;
RefCountHolder<VisualObject> curve_fill_visual;
RefCountHolder<VisualObject> handle_visual;
RefCountHolder<Scene> scene;
StrokeStyle style_thick{ LINE_CAP_BUTT, LINE_JOIN_BEVEL, treeface::PI * 0.75f, 5.0f };
struct MouseHandleRect: public RefCountObject
{
MouseHandleRect( const Vec2f& pos )
: node( new SceneNode() )
, position( pos )
{
node->add_item( handle_visual );
_update_node_trans_();
scene->get_root_node()->add_child( node );
}
virtual ~MouseHandleRect()
{
scene->get_root_node()->remove_child( node );
}
bool is_inside( Vec2f& value )
{
float r = handle_sz / 2;
if (position.x - r <= value.x && value.x <= position.x + r &&
position.y - r <= value.y && value.y <= position.y + r)
return true;
else
return false;
}
void move( const Vec2f& delta )
{
position.x += delta.x;
position.y += delta.y;
_update_node_trans_();
}
void _update_node_trans_()
{
Mat4f trans;
trans.set_translate( position.x, position.y, 1 );
node->set_transform( trans );
}
bool active = false;
bool pressed = false;
Vec2f position;
RefCountHolder<SceneNode> node;
};
Array<RefCountHolder<MouseHandleRect> > mouse_handles;
void setup_sdl()
{
SDL_Init( SDL_INIT_VIDEO & SDL_INIT_TIMER & SDL_INIT_EVENTS );
printf( "create window\n" );
window = SDL_CreateWindow( "sdl_setup test", 50, 50, window_w, window_h, SDL_WINDOW_OPENGL );
if (!window)
{
fprintf( stderr, "error: failed to create window: %s\n", SDL_GetError() );
exit( 1 );
}
printf( "create opengl context\n" );
context = SDL_GL_CreateContext( window );
if (!context)
{
fprintf( stderr, "error: failed to create GL context: %s\n", SDL_GetError() );
exit( 1 );
}
SDL_GL_MakeCurrent( window, context );
printf( "init glew\n" );
{
GLenum glew_err = glewInit();
if (glew_err != GLEW_OK)
{
fprintf( stderr, "error: failed to init glew: %s\n", glewGetErrorString( glew_err ) );
exit( 1 );
}
}
}
void setup_scene()
{
PackageManager::getInstance()->add_package( File::getCurrentWorkingDirectory().getParentDirectory().getChildFile( "examples/resource.zip" ), PackageManager::OVERWRITE );
ShapeGenerator* gen = ShapeGenerator::getInstance();
// create scene
scene = new Scene();
// create visual object for mouse handles
float r = handle_sz / 2;
gen->move_to( Vec2f( -r, -r ) );
gen->line_to( Vec2f( r, -r ) );
gen->line_to( Vec2f( r, r ) );
gen->line_to( Vec2f( -r, r ) );
gen->close_path();
Geometry* geom = ShapeGenerator::create_fill_geometry();
geom->host_draw_begin();
gen->fill_simple( geom );
geom->host_draw_end();
Material* mat_stroke = scene->get_material_manager()->get_material( "material_stroke_rainbow.json" );
if (mat_stroke == nullptr)
die( "no stroke material" );
Material* mat_fill = scene->get_material_manager()->get_material( "material_uni_color.json" );
if (mat_fill == nullptr)
die( "no fill material" );
SceneGraphMaterial* mat_stroke_sg = dynamic_cast<SceneGraphMaterial*>(mat_stroke);
SceneGraphMaterial* mat_fill_sg = dynamic_cast<SceneGraphMaterial*>(mat_fill);
handle_visual = new VisualObject( geom, mat_stroke_sg );
// create curve
curve_stroke_geom = ShapeGenerator::create_complicated_stroke_geometry();
curve_fill_geom = ShapeGenerator::create_fill_geometry();
curve_stroke_visual = new VisualObject( curve_stroke_geom, mat_stroke_sg );
curve_fill_visual = new VisualObject( curve_fill_geom, mat_fill_sg );
scene->get_root_node()->add_item( curve_stroke_visual );
scene->get_root_node()->add_item( curve_fill_visual );
curve_fill_geom->set_uniform_value( "color", Vec4f( 1.0f, 0.0f, 1.0f, 0.5f ) );
}
struct MouseHandleSorter
{
int compareElements( const MouseHandleRect* a, const MouseHandleRect* b )
{
if (a->position.x < b->position.x)
return -1;
else if (a->position.x > b->position.x)
return 1;
else return 0;
}
};
void update_curve()
{
Logger::writeToLog( "update curve" );
curve_stroke_geom->host_draw_begin();
curve_fill_geom->host_draw_begin();
curve_stroke_geom->get_host_vertex_cache().clear_quick();
curve_stroke_geom->get_host_index_cache().clearQuick();
curve_fill_geom->get_host_vertex_cache().clear_quick();
curve_fill_geom->get_host_index_cache().clearQuick();
if (mouse_handles.size() > 0)
{
Array<MouseHandleRect*> handles_sort;
for (int i = 0; i < mouse_handles.size(); i++)
handles_sort.add( mouse_handles[i] );
MouseHandleSorter sorter;
handles_sort.sort( sorter );
ShapeGenerator* gen = ShapeGenerator::getInstance();
gen->clear();
Vec2f p_prev( 0.0f, handles_sort[0]->position.y );
gen->move_to( p_prev );
// printf( " move to %f %f\n", p_prev.x, p_prev.y );
for (const MouseHandleRect* curr_handle : handles_sort)
{
float x_avg = (p_prev.x + curr_handle->position.x) / 2;
Vec2f ctrl1( x_avg, p_prev.y );
Vec2f ctrl2( x_avg, curr_handle->position.y );
gen->curve_to( ctrl1, ctrl2, curr_handle->position );
// printf( " bessel4 %f %f %f %f %f %f\n", ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, curr_handle->position.x, curr_handle->position.y );
p_prev = curr_handle->position;
}
gen->line_to( Vec2f( float(window_w), handles_sort.getLast()->position.y ) );
// printf( " line %f %f\n", float(window_w), handles_sort.getLast()->position.y );
gen->stroke_complicated_preserve( style_thick, curve_stroke_geom );
gen->line_to( Vec2f( float(window_w), float(window_h) ) );
gen->line_to( Vec2f( 0.0f, float(window_h) ) );
gen->fill_simple( curve_fill_geom );
}
curve_stroke_geom->host_draw_end();
curve_fill_geom->host_draw_end();
}
void on_mouse_motion( SDL_MouseMotionEvent& e )
{
Vec2f mouse_pos( float(e.x), float(e.y) );
Vec2f mouse_delta( float(e.xrel), float(e.yrel) );
bool handle_moved = false;
for (int i = 0; i < mouse_handles.size(); i++)
{
MouseHandleRect* curr = mouse_handles[i];
if ( curr->is_inside( mouse_pos ) )
curr->active = true;
if (curr->pressed)
{
handle_moved = true;
curr->move( mouse_delta );
}
}
if (handle_moved) update_curve();
}
void on_mouse_down( SDL_MouseButtonEvent& e )
{
Vec2f mouse_pos( float(e.x), float(e.y) );
if (e.button == SDL_BUTTON_LEFT)
{
Logger::writeToLog( "left pressed at " + String( e.x ) + ", " + String( e.y ) );
int num_select = 0;
for (int i = 0; i < mouse_handles.size(); i++)
{
MouseHandleRect* curr = mouse_handles[i];
if ( curr->is_inside( mouse_pos ) )
{
Logger::writeToLog( " intersection with widget " + String( pointer_sized_int( curr ) ) );
curr->pressed = true;
num_select++;
}
}
// nothing is pressed, create new widget at current position
if (num_select == 0)
{
Logger::writeToLog( " create new widget" );
mouse_handles.add( new MouseHandleRect( mouse_pos ) );
update_curve();
}
}
else if (e.button == SDL_BUTTON_RIGHT)
{
Logger::writeToLog( "right pressed at " + String( e.x ) + ", " + String( e.y ) );
for (int i = 0; i < mouse_handles.size(); i++)
{
MouseHandleRect* curr = mouse_handles[i];
if ( curr->is_inside( mouse_pos ) )
{
Logger::writeToLog( " remove widget " + String( pointer_sized_int( curr ) ) );
mouse_handles.remove( i );
i--;
}
}
update_curve();
}
}
void on_mouse_up( SDL_MouseButtonEvent& e )
{
if (e.button == SDL_BUTTON_LEFT)
{
Logger::writeToLog( "left released" );
for (int i = 0; i < mouse_handles.size(); i++)
mouse_handles[i]->pressed = false;
}
}
#undef main
int main( int argc, char** argv )
{
setup_sdl();
setup_scene();
SceneRenderer renderer;
Mat4f mat_view;
mat_view.set_scale( 2.0f / window_w, -2.0f / window_h, 0.01 );
mat_view.set_translate( -1.0f, 1.0f, 0.0f );
// main loop
while (1)
{
// process events
SDL_Event event{};
bool should_exit = false;
while ( SDL_PollEvent( &event ) )
{
switch (event.type)
{
case SDL_QUIT:
should_exit = true;
break;
case SDL_MOUSEMOTION:
on_mouse_motion( event.motion );
break;
case SDL_MOUSEBUTTONDOWN:
on_mouse_down( event.button );
break;
case SDL_MOUSEBUTTONUP:
on_mouse_up( event.button );
break;
}
if (event.type == SDL_QUIT)
{
should_exit = true;
}
}
if (should_exit) break;
// do render
glClear( GL_COLOR_BUFFER_BIT );
renderer.render( mat_view, Mat4f(), scene );
SDL_GL_SwapWindow( window );
SDL_Delay( 20 );
}
SDL_GL_DeleteContext( context );
SDL_Quit();
return 0;
}
|
#pragma once
#include "Functions.h"
#include "Player.h"
#include "Skeleton.h"
#include "MySFML.h"
using namespace std;
//---------------------------------------------------------------------------------------
class Game
{
Player* player;
vector<GameObject*> staticObjects;
vector<Enemy*> enemies;
Game();
Position placeChecker();
public:
~Game();
static Game& get();
void Draw();
void drawSkelet();
void skeletMove();
void findEnemy();
Player* getPlayer();
};
//---------------------------------------------------------------------------------------
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018-2019 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2019 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include "backend/opencl/runners/tools/OclSharedState.h"
#include "backend/opencl/runners/tools/OclSharedData.h"
#include <cassert>
#include <map>
namespace xmrig {
static std::map<uint32_t, OclSharedData> map;
} // namespace xmrig
xmrig::OclSharedData &xmrig::OclSharedState::get(uint32_t index)
{
return map[index];
}
void xmrig::OclSharedState::release()
{
for (auto &kv : map) {
kv.second.release();
}
map.clear();
}
void xmrig::OclSharedState::start(const std::vector<OclLaunchData> &threads, const Job &job)
{
assert(map.empty());
for (const auto &data : threads) {
auto &sharedData = map[data.device.index()];
++sharedData;
# ifdef XMRIG_ALGO_RANDOMX
if (data.algorithm.family() == Algorithm::RANDOM_X) {
sharedData.createDataset(data.ctx, job, data.thread.isDatasetHost());
}
# endif
}
}
|
#pragma once
#include "../../../Toolbox/Toolbox.h"
#include "Mesh3D.h"
namespace ae
{
class Curve;
/// \ingroup graphics
/// <summary>
/// Give the possibility to draw a parametric curve.
/// </summary>
/// <seealso cref="Mesh3D" />
/// <seealso cref="Drawable" />
/// <seealso cref="Curve" />
class AERO_CORE_EXPORT CurveMesh : public Mesh3D
{
public:
/// <summary>Initialize the curve mesh with the given point count.</summary>
/// <param name="_Curve">The curve to draw.</param>
/// <param name="_PointCount">The number of points to draw.</param>
CurveMesh( const Curve& _Curve, Uint32 _PointCount = 30 );
/// <summary>Set the curve mesh with the given point count.</summary>
/// <param name="_Curve">The curve to draw.</param>
/// <param name="_PointCount">The number of points to draw.</param>
void SetCurve( const Curve& _Curve, Uint32 _PointCount = 30 );
/// /// <summary>Retrieve the number of points to draw.</summary>
/// <returns>The number of points to draw.</returns>
Uint32 GetPointCount() const;
/// <summary>Set the number of points of the curve to draw.</summary>
/// <param name="_PointCount">The number of points to draw.</param>
void SetPointCount( Uint32 _PointCount );
/// <summary>Is the control put in the mesh ?</summary>
/// <returns>True if the control curve is in the mesh, False otherwise.</returns>
Bool IsControlCurveDrawn() const;
/// <summary>Set if the control curve must be put in the mesh.</summary>
/// <param name="_Draw">True to put the control in the mesh, False otherwise.</param>
void SetDrawControlCurve( Bool _Draw );
/// <summary>Is the curve put in the mesh ?</summary>
/// <returns>True if the curve is in the mesh, False otherwise.</returns>
Bool IsCurveDrawn() const;
/// <summary>Set if the curve must be put in the mesh.</summary>
/// <param name="_Draw">True to put the curve in the mesh, False otherwise.</param>
void SetDrawCurve( Bool _Draw );
/// <summary>Get the current curve.</summary>
/// <returns>The current curve.</returns>
const Curve& GetCurve() const;
/// <summary>Update the mesh from the assigned curve.</summary>
void Update();
/// <summary>
/// Function called by the editor.
/// It allows the class to expose some attributes for user editing.
/// Think to call all inherited class function too when overloading.
/// </summary>
void ToEditor() override;
private:
/// <summary>Put the control curve in mesh ?</summary>
Bool m_DrawControlCurve;
/// <summary>Put the interpolated curve in mesh ?</summary>
Bool m_DrawCurve;
/// <summary>Number of points to discretize.</summary>
Uint32 m_PointCounts;
/// <summary>Curve to use when updating the mesh points.</summary>
const Curve* m_Curve;
};
} // ae
|
#include<stdio.h>
#include<stdlib.h>
#include<X11/Xlib.h>
#include <unistd.h>
#include<cmath>
using namespace std;
GC gc;
Display *display;
Window window; //initialization for a window
int screen; //which screen
void initGraph(int width,int height)
{
/* open connection with the server */
display = XOpenDisplay(NULL);
if(display == NULL) {
fprintf(stderr, "cannot open display\n");
exit(1);
}
screen = DefaultScreen(display);
/* set window position */
int x = 0;
int y = 0;
/* border width in pixels */
int border_width = 0;
/* create window */
window = XCreateSimpleWindow(display, RootWindow(display, screen), x, y, width, height, border_width, BlackPixel(display, screen), WhitePixel(display, screen));
/* create graph */
XGCValues values;
long valuemask = 0;
gc = XCreateGC(display, window, valuemask, &values);
//XSetBackground (display, gc, WhitePixel (display, screen));
XSetForeground (display, gc, BlackPixel (display, screen));
XSetBackground(display, gc, 0X0000FF00);
XSetLineAttributes (display, gc, 1, LineSolid, CapRound, JoinRound);
/* map(show) the window */
XMapWindow(display, window);
XSync(display, 0);
/* draw rectangle */
XSetForeground(display,gc,BlackPixel(display,screen));
XFillRectangle(display,window,gc,0,0,width,height);
XFlush(display);
}
void draw(int x,int y)
{
/* draw point */
XSetForeground(display,gc,WhitePixel(display,screen));
XDrawPoint (display, window, gc, x, y);
}
const double PI = 3.14159;
int main(int argc,char *argv[])
{
initGraph(500, 500);
for( int i = 0; i < 100; i++ )
draw(int(200*cos(i/100.0*2*PI))+250, 250+int(200*sin(i/100.0*2*PI)));
for( int i = 0; i < 50; i++)
draw(int(100*cos(i/50.0*2*PI))+250, 250+int(100*sin(i/50.0*2*PI)));
XFlush(display);
sleep(3);
return 0;
}
|
#ifndef wali_wpds_RULE_FUNCTOR_GUARD
#define wali_wpds_RULE_FUNCTOR_GUARD 1
/**
* @author Nicholas Kidd
* @author Akash Lal
*/
#include "wali/Common.hpp"
#include "wali/ref_ptr.hpp"
#include <iostream>
#include <set>
namespace wali
{
namespace wpds
{
class WPDS;
class Wrapper;
class Rule;
class rule_t;
/*! @class RuleFunctor
*
* This functor is used in WPDS::for_each.
* This is a pure virtual class.
*
* @see WPDS
*/
class RuleFunctor
{
public:
virtual ~RuleFunctor() {}
virtual void operator()( rule_t & r ) = 0;
};
/*! @class ConstRuleFunctor
*
* This functor is used in WPDS::for_each.
* This is a pure virtual class.
*
* @see WPDS
*/
class ConstRuleFunctor
{
public:
virtual ~ConstRuleFunctor() {}
virtual void operator()( const rule_t & r ) = 0;
};
/*!
* @class RulePrinter
* Prints rules to constructor param std::ostream o
*/
class RulePrinter : public ConstRuleFunctor
{
std::ostream & os;
public:
RulePrinter( std::ostream & o );
virtual ~RulePrinter();
virtual void operator()( const rule_t & r );
};
/*!
* @class RulePrinter
* Marshalls rules to constructor param std::ostream o
*/
class RuleMarshaller : public ConstRuleFunctor
{
std::ostream & os;
public:
RuleMarshaller( std::ostream & o );
virtual ~RuleMarshaller();
virtual void operator()( const rule_t & r );
};
class RuleDotty : public ConstRuleFunctor
{
std::ostream & os;
bool print_states;
public:
RuleDotty( std::ostream & o, bool _print_states = false );
virtual ~RuleDotty();
virtual void operator()( const rule_t & r );
};
/*!
* @class WpdsStackSymbols
* Gets all stack symbols from the WPDS and classfies them
* as entry and return points, as appropriate
*/
class WpdsStackSymbols : public ConstRuleFunctor
{
public:
std::set< Key > gamma;
std::set< Key > callPoints;
std::set< Key > returnPoints;
std::set< Key > entryPoints;
std::set< Key > pdsStates;
WpdsStackSymbols( );
virtual ~WpdsStackSymbols();
virtual void operator()( const rule_t & r );
private:
void addPoint(Key k, std::set< Key > &s);
};
// @author Amanda Burton
/**
*
* @class WpdsRules
*
* Gets all rules from the WPDS and classifies them as
* push rules, pop rules, and step rules, as appropriate.
*
*/
class WpdsRules: public ConstRuleFunctor
{
public:
std::set< Rule > pushRules;
std::set< Rule > popRules;
std::set< Rule > stepRules;
WpdsRules();
virtual ~WpdsRules();
virtual void operator() (const rule_t & r);
private:
void addRule(Rule r, std::set< Rule > &s);
};
class RuleCopier : public ConstRuleFunctor
{
public:
WPDS& w;
ref_ptr<Wrapper> wrapper;
RuleCopier(WPDS& w,ref_ptr<Wrapper>);
virtual void operator()( const rule_t & r);
};
} // end namespace wpds
} // end namespace wali
#endif // wali_wpds_RULE_FUNCTOR_GUARD
|
// Created on: 1993-01-11
// Created by: CKY / Contract Toubro-Larsen ( Arun MENON )
// Copyright (c) 1993-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 _IGESAppli_LineWidening_HeaderFile
#define _IGESAppli_LineWidening_HeaderFile
#include <Standard.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Real.hxx>
#include <IGESData_IGESEntity.hxx>
class IGESAppli_LineWidening;
DEFINE_STANDARD_HANDLE(IGESAppli_LineWidening, IGESData_IGESEntity)
//! defines LineWidening, Type <406> Form <5>
//! in package IGESAppli
//! Defines the characteristics of entities when they are
//! used to define locations of items.
class IGESAppli_LineWidening : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESAppli_LineWidening();
//! This method is used to set the fields of the class
//! LineWidening
//! - nbPropVal : Number of property values = 5
//! - aWidth : Width of metalization
//! - aCornering : Cornering codes
//! 0 = rounded
//! 1 = squared
//! - aExtnFlag : Extension Flag
//! 0 = No Extension
//! 1 = One-half width extension
//! 2 = Extn set by ExtnVal
//! - aJustifFlag : Justification flag
//! 0 = Center justified
//! 1 = left justified
//! 2 = right justified
//! - aExtnVal : Extension value if aExtnFlag = 2
Standard_EXPORT void Init (const Standard_Integer nbPropVal, const Standard_Real aWidth, const Standard_Integer aCornering, const Standard_Integer aExtnFlag, const Standard_Integer aJustifFlag, const Standard_Real aExtnVal);
//! returns the number of property values
//! is always 5
Standard_EXPORT Standard_Integer NbPropertyValues() const;
//! returns the width of metallization
Standard_EXPORT Standard_Real WidthOfMetalization() const;
//! returns the cornering code
//! 0 = Rounded / 1 = Squared
Standard_EXPORT Standard_Integer CorneringCode() const;
//! returns the extension flag
//! 0 = No extension
//! 1 = One-half width extension
//! 2 = Extension set by theExtnVal
Standard_EXPORT Standard_Integer ExtensionFlag() const;
//! returns the justification flag
//! 0 = Centre justified
//! 1 = Left justified
//! 2 = Right justified
Standard_EXPORT Standard_Integer JustificationFlag() const;
//! returns the Extension Value
//! Present only if theExtnFlag = 2
Standard_EXPORT Standard_Real ExtensionValue() const;
DEFINE_STANDARD_RTTIEXT(IGESAppli_LineWidening,IGESData_IGESEntity)
protected:
private:
Standard_Integer theNbPropertyValues;
Standard_Real theWidth;
Standard_Integer theCorneringCode;
Standard_Integer theExtensionFlag;
Standard_Integer theJustificationFlag;
Standard_Real theExtensionValue;
};
#endif // _IGESAppli_LineWidening_HeaderFile
|
#include "Dribbler.h"
#include "Command.h"
#include "Util.h"
#include <iostream>
Dribbler::Dribbler(int serialId) : serialId(serialId), speed(0), ballDetected(false), ballInDribblerTime(0.0), ballLostTime(-1.0), serial(NULL) {
serial = new Serial();
if (serial->open(serialId) == Serial::OK) {
std::cout << "+ Dribbler found on port '" << serial->getPortName() << "'" << std::endl;
} else {
std::cout << "- Failed to open dribbler serial #" << serialId << " on any of the serial ports" << std::endl;
}
};
Dribbler::~Dribbler() {
if (serial != NULL) {
delete serial;
serial = NULL;
}
}
void Dribbler::setSpeed(int newSpeed) {
speed = newSpeed;
}
void Dribbler::stop() {
speed = 0;
}
void Dribbler::step(double dt) {
if (!serial->isOpen()) {
return;
}
serial->writeln("gb\nwl" + Util::toString(speed));
std::string message;
while (serial->available() > 0) {
message = serial->read();
if (Command::isValid(message)) {
Command cmd = Command::parse(message);
if (cmd.name == "b") {
ballDetected = cmd.params[0] == "1" ? true : false;
}
}
}
if (ballDetected) {
ballInDribblerTime += dt;
if (ballInDribblerTime >= Config::ballInDribblerThreshold) {
ballLostTime = 0.0;
}
} else {
ballLostTime += dt;
if (ballLostTime >= Config::dribblerBallLostThreshold) {
ballInDribblerTime = 0.0;
}
}
}
bool Dribbler::gotBall() const {
//return ballDetected;
if (
ballInDribblerTime >= Config::ballInDribblerThreshold
&& ballLostTime <= Config::dribblerBallLostThreshold
) {
return true;
}
return false;
}
|
#include "material.h"
#include "world.h"
#include "raytracer.h"
PerfectDiffuse::PerfectDiffuse(RGB c)
{
color = c;
}
RGB PerfectDiffuse::Shade(RayTracer * tracer , HitInfo hit )
{
RGB totalcolor;
for(int i=0 ; i < hit.world->lights.size() ; i++)
{
Vec3 inDirection = hit.world->lights[i].pos - hit.HitPoint;
inDirection.fast_normalize();
double diffuseFactor = Dot(inDirection , hit.normal);
if (diffuseFactor < 0)
continue;
if (hit.world->AnyObstacle(hit.HitPoint, hit.world->lights[0].pos))
continue;
totalcolor = totalcolor + hit.world->lights[i].color * color * diffuseFactor;
}
return totalcolor;
}
Phong::Phong()
{
color = colors::Black;
diffuseCoeff = 0;
specular = 0;
specularExponent = 0;
}
Phong::Phong(RGB c , double dc , double s , double se)
{
color = c;
diffuseCoeff = dc;
specular = s;
specularExponent = se;
}
RGB Phong::Shade(RayTracer * tracer , HitInfo hit )
{
RGB totalcolor;
RGB result;
Vec3 inDirection;
double diffuseFactor;
double phongFactor;
for(int i=0;i<hit.world->lights.size();i++)
{
inDirection = hit.world->lights[i].pos - hit.HitPoint;
inDirection.fast_normalize();
diffuseFactor = Dot(inDirection , hit.normal);
if (diffuseFactor < 0)
continue;
if (hit.world->AnyObstacle(hit.HitPoint, hit.world->lights[0].pos))
continue;
result = hit.world->lights[i].color * color * diffuseFactor * diffuseCoeff;
phongFactor = PhongFactor(inDirection, hit.normal, hit.ray.dir * -1 ,specularExponent );
if (phongFactor != 0)
result = result + color * specular * phongFactor;
totalcolor = totalcolor + result;
}
return totalcolor;
}
Reflective::Reflective(RGB materialColor, double diffuse, double specular, double exponent, double Reflectivity)
{
double sum = diffuse + Reflectivity; // Reflecivity + diffuse musi byฤ <= 1
if( sum > 1.0 )
{
diffuse = diffuse / sum;
Reflectivity = Reflectivity / sum;
}
direct.color = materialColor;
direct.diffuseCoeff = diffuse;
direct.specular = specular;
direct.specularExponent = exponent;
reflectivity = Reflectivity;
reflectionColor = materialColor; // Moลผe byc inny kolor
}
RGB Reflective::Shade(RayTracer * tracer, HitInfo hit)
{
Vec3 toCameraDirection = hit.ray.dir.inv();
RGB radiance = direct.Shade(tracer, hit);
Vec3 reflectionDirection = reflect(toCameraDirection, hit.normal);
Ray3 reflectedRay(hit.HitPoint, reflectionDirection);
radiance = radiance + tracer->CalcColor( reflectedRay, hit.Depth) * reflectionColor * reflectivity;
return radiance;
}
double PhongFactor(Vec3 inDirection, Vec3 normal, Vec3 toCameraDirection , double specularExponent)
{
Vec3 reflected = reflect(inDirection, normal);
double cosAngle = Dot(reflected ,toCameraDirection);
if (cosAngle <= 0)
return 0;
return pow(cosAngle, specularExponent);
}
|
#pragma once
#include "AvatarView.h"
#include "EnemyStaticModel.h"
class EnemyGruntView : public AvatarView
{
public:
void initView(AvatarModel* avatarModel);
};
|
#include "graphreader.hh"
#include "stats.hh"
#include "timer.hh"
#include <cassert>
#include <iostream>
#include <string>
using namespace std;
using Mat = vector<vector<int>>;
void ad0(const Mat &m1, const Mat &m2, Mat &res) {
int i = m1.size(); // number of rows in m1
int j = m1[0].size(); // number of cols in m1
int k = m2.size(); // number of rows in m2
int l = m2[0].size(); // number of cols in m2
assert(j == k);
for (int a = 0; a < i; a++)
for (int b = 0; b < l; b++)
for (int c = 0; c < j; c++) {
if (m1[a][c] != numeric_limits<int>::max() &&
m2[c][b] != numeric_limits<int>::max())
res[a][b] = min(res[a][b], m1[a][c] + m2[c][b]);
}
}
void printMat(const vector <int> &vectorData, const vector<int> &vectorCols, const vector<int> &vectorRows) {
for(int i= 0; i < vectorData.size(); i++) {
cout << vectorData[i] << " ";
}
for(int i= 0; i < vectorData.size(); i++) {
cout << vectorCols[i] << " ";
}
for(int i= 0; i < vectorRows.size(); i++) {
cout << vectorRows[i] << " ";
}
}
void benchmark(int times, const string &fileName) {
vector<int> vectorData, vectorData_r;
vector<int> vectorCols, vectorCols_r;
vector<int> vectorRows; vectorCols_r;
readGraph(fileName, vectorData,vectorCols,vectorRows);
//ad0();
printMat(vectorData, vectorCols, vectorRows);
/* Mat r;
r.resize(g.size());
for (int i = 0; i < g.size(); i++)
r[i].resize(g.size(), numeric_limits<int>::max());
ad0(g, g, r);
printMat(r);
*/
}
int main(int argc, char **argv) {
if (argc != 2) {
cerr << "Error!!" << endl;
}
string fileName(argv[1]);
benchmark(1, fileName);
cout <<"Final final no va mas " << endl;
return 0;
}
|
class ItemJerrycanEmpty
{
weight = 1;
};
class ItemJerrycan
{
weight = 10;
};
class ItemFuelcanEmpty
{
weight = 0.5;
};
class ItemFuelcan
{
weight = 5;
};
class ItemFuelBarrel
{
weight = 167;
};
class ItemFuelBarrelEmpty
{
weight = 20;
};
class ItemOilBarrel
{
weight = 140;
};
class ItemOilBarrelEmpty
{
weight = 20;
};
class ItemMethylaminBarrelEmpty
{
weight = 20;
};
class ItemMethylaminBarrel
{
weight = 160;
};
|
#pragma once
#include <iosfwd>
#include <set>
#include <string>
#include <vector>
#include <cppunit/Outputter.h>
namespace CppUnit {
class Exception;
class Test;
class TestFailure;
class TestResultCollector;
}
namespace BeeeOn {
/**
* Plugin to CppUnit that outputs the test results in
* the TAP format:
*
* https://testanything.org/tap-version-13-specification.html
*
* The output is printed after all tests are executed thus
* measuring time of single tests is not possible by the
* target TAP consumer. This is simplifies the implementation
* as the CppUnit has hierachical tests structure.
*/
class TapOutputter : public CppUnit::Outputter {
public:
TapOutputter(CppUnit::TestResultCollector *collector);
TapOutputter(CppUnit::TestResultCollector *collector,
std::ostream &output);
void skip(const std::string &name);
void write() override;
protected:
void reportSuccess(unsigned int id, CppUnit::Test *test);
void reportFailures(unsigned int id, CppUnit::Test *test,
const std::vector<CppUnit::TestFailure *> &fails);
void reportException(const CppUnit::Exception *e);
private:
CppUnit::TestResultCollector *m_collector;
std::set<std::string> m_skip;
std::ostream &m_output;
};
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.